diff --git a/Cargo.lock b/Cargo.lock index 798c159d61..88a9abca04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1035,6 +1035,17 @@ dependencies = [ "winsafe", ] +[[package]] +name = "craft-proof" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +dependencies = [ + "log", + "miniz_oxide 0.9.1", + "toml", + "unicode-normalization", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -6356,6 +6367,13 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "vectorcraft-apischema" +version = "0.21.0" +dependencies = [ + "serde_json", +] + [[package]] name = "vectorcraft-brush" version = "0.21.0" @@ -6463,6 +6481,7 @@ dependencies = [ "cfb", "chrono", "craft-docpath", + "craft-proof", "crc32fast", "flate2", "hayro-jpeg2000", @@ -6480,8 +6499,10 @@ dependencies = [ "ruzstd", "serde", "serde_json", + "skrifa 0.47.0", "thiserror 2.0.21", "vectorcraft-affinity", + "vectorcraft-apischema", "vectorcraft-brush", "vectorcraft-cad", "vectorcraft-color", diff --git a/Cargo.toml b/Cargo.toml index 9de669345f..2c0bf38ec9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637 craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] } craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } @@ -54,6 +55,7 @@ vectorcraft-plugins = { path = "crates/plugins" } vectorcraft-affinity = { path = "crates/affinity" } vectorcraft-scriptcheck = { path = "crates/scriptcheck" } vectorcraft-js = { path = "crates/js" } +vectorcraft-apischema = { path = "crates/apischema" } # foundation kurbo = { version = "0.13", features = ["serde"] } diff --git a/ROADMAP.md b/ROADMAP.md index 1bedf0b95c..e83a01efea 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -15,7 +15,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -83,11 +83,11 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so | Strokes, brushes, width profiles | 88% | 8–15 | | Appearance, transparency, graphic styles, masks | 97% | 1–2 | | Live vector effects | 85% | 4–8 | -| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 | +| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — | | 3D and Materials | ~25% | 30–55 | | Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 | | Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 | -| Symbols, blends, envelopes, Repeat, perspective | 87% | 5–9 | +| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 | | Image Trace, graphs, image tools | 75% | 5–8 | | Layers, artboards, document setup | 78% | 5–8 | | View & navigation | 70% | 9–14 | @@ -131,8 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap 2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h. 3. **Launch and stability on real machines** (G10): 20–35 h. 4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h. -5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h. -6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). +5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Progress log @@ -226,6 +225,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. | | 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. | | 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | | 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index acb665f49e..734f8a0569 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -78,7 +78,7 @@ USAGE: Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and does not take --connect. - vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... + vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants] Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979 (vectorcraft --control 7979), falling back to a headless in-process session. --automation-read-root / --automation-write-root confine the files the agent's commands read @@ -86,8 +86,18 @@ USAGE: DIR, links followed; each may be given more than once, a path inside any of its folders being allowed, and a kind left out grants none of its access. They imply --headless: a running app enforces its own (vectorcraft --control PORT --automation-read-root DIR …). + --allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this session, + so whoever sends the commands can give a plug-in the permissions it lists, and a heavy budget, + with nobody approving them. Without it they are refused, and a plug-in that lists permissions + installs only when its hash is already recorded in grants.json, by a person's approval in the + desktop app or by a grant accepted under this flag. A grant accepted under this flag stays + recorded and counts as approved in later sessions. It implies --headless. It can't be used + with --automation-read-root or --automation-write-root: a server confined to folders has no + plug-in store, so it reads no grants.json, and a plug-in that lists permissions or asks for a + heavy budget does not install there. With VECTORCRAFT_NO_PREFS set there is no store either, + and a grant accepted under this flag lasts for that session only. - vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--allow-plugin-grants] Headless batch: open FILE (any readable format) or start a new document, run commands in order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE is a template, written as file.saveAsTemplate writes it). Raster exports use the document's @@ -97,6 +107,8 @@ USAGE: --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps. Errors name the step, counting from 0 as \"$N\" references do. + --allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this run, as + for mcp. vectorcraft-cli commands Print the command catalogue as JSON. @@ -224,12 +236,22 @@ fn main() -> ExitCode { } /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the -/// ICC profiles loaded and the plug-ins installed (#2168, #2174, #2541), in the folders next to the preferences that the desktop -/// app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there. +/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541) and the custom dictionary's words (#4936), in the folders +/// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply +/// as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); prefs_dir::attach_pdf_preset_store(&mut h.session); + prefs_dir::attach_custom_dictionary(&mut h.session); + h +} + +/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`). +fn accepting_grants(mut h: Headless, allow: bool) -> Headless { + if allow { + h.session.allow_plugin_grants_from_requests(); + } h } @@ -241,6 +263,7 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { } let mut connect: Option = None; let mut headless = false; + let mut allow_grants = false; let (mut read_roots, mut write_roots): (Vec, Vec) = (vec![], vec![]); let mut it = args.iter(); while let Some(a) = it.next() { @@ -252,6 +275,7 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { match flag { "--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?), "--headless" => headless = true, + "--allow-plugin-grants" => allow_grants = true, "--automation-read-root" | "--automation-write-root" => { let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?; if flag == "--automation-read-root" { read_roots.push(dir) } else { write_roots.push(dir) } @@ -262,6 +286,12 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { if headless && connect.is_some() { return Err("use either --connect or --headless".into()); } + if allow_grants && connect.is_some() { + return Err("--allow-plugin-grants applies to the headless server; in a running app a person approves each plug-in".into()); + } + if allow_grants && !(read_roots.is_empty() && write_roots.is_empty()) { + return Err("--allow-plugin-grants can't be used with --automation-read-root or --automation-write-root: a server confined to folders has no plug-in store to record a grant in".into()); + } if safe_mode && connect.is_some() { return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control `".into()); } @@ -276,9 +306,9 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { // Every thread of this process, not only the server's: nothing reaches past the roots. file_access::confine_process(roots.clone()); eprintln!("vectorcraft-cli: files confined: {}", roots.describe()); - Box::new(Headless::with_document().with_automation_roots(Some(roots))) - } else if headless || safe_mode { - Box::new(with_stores(Headless::with_document())) + Box::new(accepting_grants(Headless::with_document().with_automation_roots(Some(roots)), allow_grants)) + } else if headless || safe_mode || allow_grants { + Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants)) } else if let Some(addr) = connect { // Explicit address: fail loudly if the app isn't there. Box::new(Remote::connect(&addr).map_err(|e| format!("cannot connect to {addr}: {e}"))?) @@ -561,6 +591,7 @@ fn run(args: &[String]) -> Result<(), String> { let mut stdin_read = false; let mut scale = None::; let mut ppi = None::; + let mut allow_grants = false; let mut it = args.iter(); while let Some(a) = it.next() { let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}")); @@ -595,6 +626,7 @@ fn run(args: &[String]) -> Result<(), String> { steps.push(Step::Export(val("a file")?)); params_for = None; } + "--allow-plugin-grants" => allow_grants = true, "--scale" | "-s" => { let raw = val("a number")?; scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); @@ -612,7 +644,7 @@ fn run(args: &[String]) -> Result<(), String> { } } - let mut h = with_stores(Headless::new()); + let mut h = accepting_grants(with_stores(Headless::new()), allow_grants); let mut out = std::io::stdout().lock(); // A reader that stopped early (a closed pipe) isn't an error, and the batch goes on: its later // steps (an export…) still run, unprinted. diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 05a5cc5fc6..5bdd2bf631 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -19,6 +19,77 @@ fn empty_dir(dir: std::path::PathBuf) -> std::path::PathBuf { dir } +/// `run` and `mcp --headless` refuse `plugin.install` with this param unless the process was started +/// with `--allow-plugin-grants`. +fn approval_param_needs_the_start_up_flag(key: &str, value: Value) { + let module = vectorcraft_format::base64_encode(include_bytes!("../../../../crates/plugins/tests/fixtures/desaturate.wasm")); + let steps = tmp(&format!("{key}.json")); + std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap(); + let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id()))); + let run = |extra: &[&str]| { + Command::new(BIN).env("VECTORCRAFT_CONFIG_DIR", &config).args(["run", "--commands", steps.to_str().unwrap()]).args(extra).output().unwrap() + }; + let out = run(&[]); + assert!(!out.status.success()); + let shown = String::from_utf8_lossy(&out.stderr).into_owned() + &String::from_utf8_lossy(&out.stdout); + assert!(shown.contains("--allow-plugin-grants"), "{shown}"); + let out = run(&["--allow-plugin-grants"]); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + + let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id()))); + let mcp_install = |extra: &[&str]| -> Value { + let mut child = Command::new(BIN) + .env("VECTORCRAFT_CONFIG_DIR", &mcp_config) + .args(["mcp", "--headless"]) + .args(extra) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + { + let mut stdin = child.stdin.take().unwrap(); + let params = json!({"dataBase64": module, key: value}); + for m in [ + json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}), + json!({"jsonrpc":"2.0","method":"notifications/initialized"}), + json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"run_command","arguments":{"command":"plugin.install","params":params}}}), + ] { + writeln!(stdin, "{m}").unwrap(); + } + } + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + let replies: Vec = String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + replies.into_iter().find(|r| r["id"] == 2).unwrap()["result"].take() + }; + let refused = mcp_install(&[]); + assert_eq!(refused["isError"], true, "without the flag: {refused}"); + assert!(refused["content"][0]["text"].as_str().unwrap().contains("--allow-plugin-grants"), "{refused}"); + let accepted = mcp_install(&["--allow-plugin-grants"]); + assert_eq!(accepted["isError"], false, "with the flag: {accepted}"); +} + +/// `run` and `mcp --headless` refuse `plugin.install`'s `grant` and `allowHeavy` unless the process was +/// started with `--allow-plugin-grants`, which `mcp` won't take with `--connect` or the automation roots. +#[test] +fn plugin_grants_need_the_start_up_flag() { + approval_param_needs_the_start_up_flag("grant", json!(["doc.read"])); + approval_param_needs_the_start_up_flag("allowHeavy", json!(true)); + + let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap(); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server")); + let root = std::env::temp_dir(); + for flag in ["--automation-read-root", "--automation-write-root"] { + let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); + assert!(!out.status.success(), "{flag}"); + assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}"); + } + let usage = Command::new(BIN).arg("help").output().unwrap(); + assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect")); +} + #[test] fn commands_prints_catalogue() { let out = Command::new(BIN).arg("commands").output().unwrap(); @@ -526,7 +597,7 @@ fn exercise_mcp_core( assert!(r["result"]["completion"]["values"].as_array().is_some_and(|v| v.contains(&json!("svg"))), "{r}"); mcp_send(stdin, json!({"jsonrpc":"2.0","id":5,"method":"resources/list","params":{}})); - assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 3)); + assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 4)); mcp_send(stdin, json!({"jsonrpc":"2.0","id":6,"method":"resources/templates/list","params":{}})); assert!(mcp_recv(lines, notes, 6)["result"]["resourceTemplates"].as_array().is_some_and(|v| v.len() >= 4)); diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 4ab382d5cb..dfd9b16719 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -67,7 +67,7 @@ vectorcraft-render = { workspace = true } # with default features off). Pinned exactly: review the diff before bumping. muda = { version = "=0.21.2", default-features = false } objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } # Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd. objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index f47b10e68f..fa0f0dca29 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -95,12 +95,18 @@ impl eframe::App for App { // A ready update installs once the process has exited. The macOS exit below skips // dropping the app, so the helper is started here. self.app.start_pending_update(); + #[cfg(target_os = "macos")] + super::mac_cursor::release(); end_before_teardown(self.frames); } } impl App { fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + #[cfg(target_os = "macos")] + if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) { + super::mac_cursor::release(); + } self.frames = ctx.cumulative_frame_nr(); if let Some(why) = self.graphics_loss.take() { // eframe can't give a window a new device: the user saves and starts again. diff --git a/apps/vectorcraft/src/mac_cursor.rs b/apps/vectorcraft/src/mac_cursor.rs new file mode 100644 index 0000000000..85fea6c78a --- /dev/null +++ b/apps/vectorcraft/src/mac_cursor.rs @@ -0,0 +1,241 @@ +//! AppKit delivery of the UI's existing cursor artwork, independent of canvas presentation. +#![forbid(unsafe_code)] +// Interim #2292: remove when pinned winit correctly handles macOS cursor image and hotspot sizing. + +use egui::{Context, FullOutput, Plugin, ViewportId}; +use objc2::{AllocAnyThread, MainThreadMarker, rc::Retained}; +use objc2_app_kit::{NSApplication, NSBitmapImageRep, NSCursor, NSImage, NSWindow}; +use objc2_foundation::{NSData, NSPoint, NSSize}; +use std::cell::RefCell; +use vectorcraft_ui_egui::cursors::native_request::{self, Bitmap, Key, Request}; + +const CAPACITY: usize = 128; + +fn build(bitmap: &Bitmap) -> Option> { + let one = &bitmap.representations[0]; + let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1])); + let image = NSImage::initWithSize(NSImage::alloc(), size); + for bitmap in &bitmap.representations { + let pixels = image::RgbaImage::from_raw(u32::from(bitmap.size[0]), u32::from(bitmap.size[1]), bitmap.rgba.to_vec())?; + let mut png = std::io::Cursor::new(Vec::new()); + pixels.write_to(&mut png, image::ImageFormat::Png).ok()?; + let rep = NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(png.get_ref()))?; + rep.setSize(size); + image.addRepresentation(&rep); + } + Some(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1])))) +} + +/// The ownership protocol also runs against a headless backend in tests. +trait Backend { + type Window: Clone + PartialEq; + type Cursor: Clone + PartialEq; + fn window(&self) -> Option; + fn enabled(&self, window: &Self::Window) -> bool; + fn suspend(&mut self, window: &Self::Window); + fn restore(&mut self, window: &Self::Window); + fn build(&mut self, request: &Request) -> Option; + fn current(&self) -> Option; + fn set(&mut self, cursor: &Self::Cursor); +} + +struct State { + backend: B, + candidate: Option, + cache: Vec<(Key, Option)>, + // Retain the active object independently of cache eviction. + active: Option<(Key, B::Window, B::Cursor)>, +} + +impl State { + fn new(backend: B) -> Self { + Self { backend, candidate: None, cache: Vec::new(), active: None } + } + + fn begin(&mut self) { + self.candidate = self.backend.window(); + } + + fn release(&mut self) { + self.candidate = None; + if let Some((_, window, _)) = self.active.take() { + self.backend.restore(&window); + } + } + + fn finish(&mut self, request: Option) { + let window = self.candidate.take().filter(|w| self.backend.window().as_ref() == Some(w)); + let (Some(request), Some(window)) = (request, window) else { + self.release(); + return; + }; + if let Some((key, owned, cursor)) = &self.active + && *key == request.key + && *owned == window + { + if self.backend.current().as_ref() != Some(cursor) { + self.backend.set(cursor); + } + return; + } + self.release(); + // Never take another component's suspension (a sheet or native tracking session). + if !self.backend.enabled(&window) { + return; + } + let cursor = if let Some((_, cursor)) = self.cache.iter().find(|(key, _)| *key == request.key) { + cursor.clone() + } else { + let cursor = self.backend.build(&request); + if self.cache.len() >= CAPACITY { + self.cache.clear(); + } + self.cache.push((request.key, cursor.clone())); + cursor + }; + if let Some(cursor) = cursor { + self.backend.suspend(&window); + self.backend.set(&cursor); + self.active = Some((request.key, window, cursor)); + } + } +} + +#[derive(Default)] +struct AppKit { + root: std::sync::Weak, +} +impl Backend for AppKit { + type Window = Retained; + type Cursor = Retained; + fn window(&self) -> Option { + let mtm = MainThreadMarker::new()?; + // Bind the candidate to the host's actual root window without converting raw pointers. + // A floating native panel may be key while egui still has stale root focus input. + let root = self.root.upgrade()?; + if !root.has_focus() || root.is_visible() == Some(false) || root.is_minimized() == Some(true) { + return None; + } + NSApplication::sharedApplication(mtm).keyWindow().filter(|w| w.isVisible() && w.isKeyWindow()) + } + fn enabled(&self, window: &Self::Window) -> bool { + window.areCursorRectsEnabled() + } + fn suspend(&mut self, window: &Self::Window) { + window.disableCursorRects(); + } + fn restore(&mut self, window: &Self::Window) { + window.enableCursorRects(); + window.resetCursorRects(); + // egui-winit may skip an unchanged fallback icon. Rebuild its stored rectangle anyway. + if let Some(view) = window.contentView() { + window.invalidateCursorRectsForView(&view); + } + } + fn build(&mut self, request: &Request) -> Option { + build(&request.bitmap) + } + fn current(&self) -> Option { + Some(NSCursor::currentCursor()) + } + fn set(&mut self, cursor: &Self::Cursor) { + cursor.set(); + } +} + +thread_local! { static STATE: RefCell> = RefCell::new(State::new(AppKit::default())); } + +fn with_state(f: impl FnOnce(&mut State)) { + // All production AppKit access, including restoration, stays on the main thread. + if MainThreadMarker::new().is_some() { + STATE.with(|state| { + if let Ok(mut state) = state.try_borrow_mut() { + f(&mut state); + } + }); + } +} + +/// Also called synchronously when native menu tracking begins and before process teardown. +pub(crate) fn release() { + with_state(State::release); +} + +struct EndedPass { + viewport: ViewportId, + discarded: bool, + request: Option, +} + +struct Delivery { + begin: fn(), + finish: fn(Option), + release: fn(), + tracking: fn() -> bool, + ended: Vec, +} + +impl Plugin for Delivery { + fn debug_name(&self) -> &'static str { + "macOS canvas cursor" + } + fn on_begin_pass(&mut self, ui: &mut egui::Ui) { + native_request::clear(ui.ctx()); + // Floating panels must not acquire or release the main canvas's window. + if ui.ctx().viewport_id() == ViewportId::ROOT { + (self.begin)(); + } + } + fn on_end_pass(&mut self, ui: &mut egui::Ui) { + // egui restores the parent viewport before output_hook. Capture this pass here so + // a floating panel's output cannot consume or release its parent's cursor. + self.ended.push(EndedPass { viewport: ui.ctx().viewport_id(), discarded: ui.ctx().will_discard(), request: native_request::take(ui.ctx()) }); + } + fn input_hook(&mut self, _: &Context, input: &mut egui::RawInput) { + if input.viewport_id == ViewportId::ROOT + && (!input.focused || input.viewports.get(&ViewportId::ROOT).is_some_and(|v| v.minimized == Some(true))) + { + (self.release)(); + } + } + fn output_hook(&mut self, ctx: &Context, output: &mut FullOutput) { + let Some(ended) = self.ended.pop() else { return }; + if ended.viewport != ViewportId::ROOT { + return; + } + if ended.discarded + || (output.platform_output.requested_discard() && output.platform_output.num_completed_passes < ctx.options(|o| o.max_passes.get())) + { + return; + } + let request = ended.request.filter(|r| { + r.viewport == ended.viewport + && r.pass.checked_add(1) == Some(ctx.cumulative_pass_nr_for(ended.viewport)) + && ctx.input(|i| i.focused && i.pointer.hover_pos().is_some()) + && output.platform_output.cursor_icon == r.fallback + && output.platform_output.cursor_image.is_none() + && !(self.tracking)() + }); + // This is BEFORE egui-winit's platform output. In pinned winit, fallback changes update + // the view's stored cursor and invalidate rectangles. Our owned suspension is intended + // to keep that update from replacing the native cursor; native timing needs hand testing. + (self.finish)(request); + } + fn on_exit(&mut self, _: &Context) { + (self.release)(); + } +} + +pub(crate) fn install(ctx: &Context, window: Option<&std::sync::Arc>) { + with_state(|state| state.backend.root = window.map(std::sync::Arc::downgrade).unwrap_or_default()); + ctx.add_plugin(Delivery { + begin: || with_state(State::begin), + finish: |request| with_state(|state| state.finish(request)), + release, + tracking: super::mac_menu::is_tracking, + ended: Vec::new(), + }); +} + +#[cfg(test)] +mod tests; diff --git a/apps/vectorcraft/src/mac_cursor/tests.rs b/apps/vectorcraft/src/mac_cursor/tests.rs new file mode 100644 index 0000000000..648492c4b2 --- /dev/null +++ b/apps/vectorcraft/src/mac_cursor/tests.rs @@ -0,0 +1,236 @@ +use super::*; +use egui::{CursorIcon, RawInput}; +use std::cell::Cell; + +#[derive(Default)] +struct Fake { + window: Option, + suspended: Vec, + current: Option, + sets: usize, + builds: usize, + restores: Vec, + fail: bool, +} +impl Backend for Fake { + type Window = u8; + type Cursor = Key; + fn window(&self) -> Option { + self.window + } + fn enabled(&self, w: &u8) -> bool { + !self.suspended.contains(w) + } + fn suspend(&mut self, w: &u8) { + self.suspended.push(*w); + } + fn restore(&mut self, w: &u8) { + self.suspended.retain(|v| v != w); + self.restores.push(*w); + self.current = None; + } + fn build(&mut self, r: &Request) -> Option { + self.builds += 1; + (!self.fail).then_some(r.key) + } + fn current(&self) -> Option { + self.current + } + fn set(&mut self, cursor: &Key) { + self.current = Some(*cursor); + self.sets += 1; + } +} +fn fake_state() -> State { + State::new(Fake { window: Some(1), ..Default::default() }) +} +fn raw(id: ViewportId, focused: bool) -> RawInput { + let mut input = RawInput { viewport_id: id, focused, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() }; + input.viewports.entry(id).or_default(); + input +} +fn publish(ctx: &Context, scale: f32) { + let mut session = vectorcraft_engine::Session::new(); + let cursor = session.cursor(Default::default(), Default::default(), Default::default()); + let fallback = native_request::request(ctx, cursor, CursorIcon::Default, true, scale); + ctx.set_cursor_icon(fallback); +} +fn request(scale: f32) -> Request { + let ctx = Context::default(); + let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| publish(ui.ctx(), scale)); + native_request::take(&ctx).unwrap() +} +fn deliver(state: &mut State, request: Option) { + state.begin(); + state.finish(request); +} + +#[test] +fn mac_cursor_ownership_deduplicates_reasserts_and_restores() { + let req = request(1.0); + let mut state = fake_state(); + deliver(&mut state, Some(req.clone())); + assert_eq!(state.backend.suspended, [1]); + assert_eq!((state.backend.builds, state.backend.sets), (1, 1)); + deliver(&mut state, Some(req.clone())); + assert_eq!(state.backend.sets, 1); + // Simulate a platform fallback replacing the cursor after finalization. The next pass + // reasserts; this proves the protocol, not AppKit timing or absence of transient flicker. + state.backend.current = None; + deliver(&mut state, Some(req.clone())); + assert_eq!(state.backend.sets, 2); + deliver(&mut state, None); + assert_eq!(state.backend.restores, [1]); + deliver(&mut state, Some(req.clone())); + state.backend.window = None; + deliver(&mut state, Some(req.clone())); + assert!(state.active.is_none()); + state.backend.window = Some(1); + deliver(&mut state, Some(req.clone())); + state.begin(); + state.backend.window = Some(2); + state.finish(Some(req)); + assert!(state.active.is_none(), "never acquire a different key window mid-pass"); + assert_eq!(state.backend.restores, [1, 1, 1]); +} + +#[test] +fn mac_cursor_respects_other_suspensions_failures_and_cache_eviction() { + let mut state = fake_state(); + state.backend.suspended.push(1); + deliver(&mut state, Some(request(1.0))); + assert_eq!(state.backend.builds, 0); + state.release(); + assert_eq!(state.backend.suspended, [1]); + assert!(state.backend.restores.is_empty()); + state.backend.suspended.clear(); + state.backend.fail = true; + for _ in 0..2 { + deliver(&mut state, Some(request(1.0))); + } + assert_eq!(state.backend.builds, 1, "cache failed constructions"); + state.backend.fail = false; + for i in 1..140 { + deliver(&mut state, Some(request(1.0 + i as f32 / 1000.0))); + } + assert!(state.cache.len() <= CAPACITY); + let active = state.active.unwrap(); + state.cache.clear(); + assert_eq!(state.active, Some(active)); + state.release(); + assert!(state.backend.suspended.is_empty()); +} + +thread_local! { + static FAKE: RefCell> = RefCell::new(fake_state()); + static TRACKING: Cell = const { Cell::new(false) }; +} +fn install_fake(ctx: &Context) { + ctx.add_plugin(Delivery { + begin: || FAKE.with(|s| s.borrow_mut().begin()), + finish: |r| FAKE.with(|s| s.borrow_mut().finish(r)), + release: || FAKE.with(|s| s.borrow_mut().release()), + tracking: || TRACKING.with(Cell::get), + ended: Vec::new(), + }); +} +#[test] +fn mac_cursor_plugin_consumes_passes_and_releases_for_menu_focus_and_overrides() { + FAKE.with(|s| *s.borrow_mut() = fake_state()); + TRACKING.with(|t| t.set(false)); + let ctx = Context::default(); + install_fake(&ctx); + install_fake(&ctx); + let root = ViewportId::ROOT; + let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); + FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 1, "one installed plugin consumes the request")); + let _ = headless(&ctx, raw(ViewportId::from_hash_of("floating-panel"), true), |_| {}); + FAKE.with(|s| assert!(s.borrow().active.is_some())); + let _ = headless(&ctx, raw(root, true), |_| {}); + FAKE.with(|s| assert!(s.borrow().active.is_none(), "empty pass hands back even an unchanged Default icon")); + let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); + let _ = headless(&ctx, raw(root, true), |ui| { + publish(ui.ctx(), 1.0); + ui.ctx().set_cursor_icon(CursorIcon::Text); + }); + FAKE.with(|s| assert!(s.borrow().active.is_none(), "changed-icon handback")); + let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); + // The notification calls release without waiting for another UI pass. + TRACKING.with(|t| t.set(true)); + FAKE.with(|s| s.borrow_mut().release()); + FAKE.with(|s| assert!(s.borrow().active.is_none())); + let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); + FAKE.with(|s| assert!(s.borrow().active.is_none())); + TRACKING.with(|t| t.set(false)); + let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); + let _ = headless(&ctx, raw(root, false), |_| {}); + FAKE.with(|s| assert!(s.borrow().active.is_none())); + let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0)); + FAKE.with(|s| assert!(s.borrow().active.is_some())); +} + +#[test] +fn mac_cursor_discarded_pass_does_not_commit_and_installation_does_not_repaint() { + FAKE.with(|s| *s.borrow_mut() = fake_state()); + TRACKING.with(|t| t.set(false)); + let ctx = Context::default(); + install_fake(&ctx); + let mut passes = 0; + let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| { + passes += 1; + if passes == 1 { + publish(ui.ctx(), 1.0); + ui.ctx().request_discard("cursor regression"); + } + }); + assert_eq!(passes, 2); + FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 0)); + let idle = || { + let mut input = raw(ViewportId::ROOT, true); + input.events.clear(); + input.time = Some(ctx.input(|i| i.time) + 0.1); + input + }; + for _ in 0..3 { + let _ = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0)); + } + let out = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0)); + assert!(out.viewport_output[&ViewportId::ROOT].repaint_delay > std::time::Duration::ZERO); +} + +#[test] +fn mac_cursor_appkit_representations_have_pixel_sizes_and_point_hotspots() { + // Only construct and inspect image/cursor objects: no NSApplication, window or cursor.set(). + for scale in [0.75, 1.0, 1.25, 1.5, 2.0] { + let request = request(scale); + let cursor = build(&request.bitmap).unwrap(); + let image = cursor.image(); + let one = &request.bitmap.representations[0]; + let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1])); + assert_eq!(image.size(), size); + assert_eq!(cursor.hotSpot(), NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1]))); + let reps = image.representations(); + assert_eq!(reps.len(), 2); + let mut dimensions: Vec<_> = reps + .iter() + .map(|rep| { + assert_eq!(rep.size(), size); + (rep.pixelsWide(), rep.pixelsHigh()) + }) + .collect(); + dimensions.sort_unstable(); + assert_eq!( + dimensions, + [ + (isize::try_from(one.size[0]).unwrap(), isize::try_from(one.size[1]).unwrap()), + (isize::try_from(one.size[0]).unwrap() * 2, isize::try_from(one.size[1]).unwrap() * 2) + ] + ); + } +} + +fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput { + let mut output = ctx.run_ui(input, draw); + output.textures_delta.clear(); + output +} diff --git a/apps/vectorcraft/src/mac_menu.rs b/apps/vectorcraft/src/mac_menu.rs index 0b94fa03c2..f90e4f7304 100644 --- a/apps/vectorcraft/src/mac_menu.rs +++ b/apps/vectorcraft/src/mac_menu.rs @@ -31,6 +31,10 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole, // asynchronous menu presentation). Keep the native tracking state separate from egui popups. static TRACKING: AtomicBool = AtomicBool::new(false); +pub(crate) fn is_tracking() -> bool { + TRACKING.load(Ordering::Relaxed) +} + fn observe_tracking(ctx: &egui::Context) { static INSTALL: Once = Once::new(); INSTALL.call_once(|| { @@ -41,13 +45,17 @@ fn observe_tracking(ctx: &egui::Context) { let repaint = ctx.clone(); let block = RcBlock::new(move |_: std::ptr::NonNull| { TRACKING.store(tracking, Ordering::Relaxed); + if tracking { + super::mac_cursor::release(); + } // Apply any deferred menu updates as soon as the tracking session ends. if !tracking { repaint.request_repaint(); } }); // SAFETY: these are AppKit's notification names. The notification center retains - // the observer and block for the application's lifetime; callbacks update an atomic and request repaint. + // the observer and block for the application's lifetime; callbacks update tracking, restore + // owned cursor rectangles and request repaint. #[allow(unsafe_code)] unsafe { NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(Some(name), None, None, &block); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index fd062e504c..7e4f245d3e 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -36,6 +36,8 @@ mod logging; #[cfg(all(target_os = "macos", feature = "wgpu"))] mod mac_color_space; #[cfg(target_os = "macos")] +mod mac_cursor; +#[cfg(target_os = "macos")] mod mac_fonts; #[cfg(target_os = "macos")] mod mac_menu; @@ -466,6 +468,8 @@ fn main() -> std::process::ExitCode { // The saved PDF presets live in their own folder (also read by vectorcraft-cli), // which takes over from the copy the preferences file used to hold. prefs_dir::attach_pdf_preset_store(&mut app.session); + // The custom dictionary's words, kept in their own file next to the preferences. + prefs_dir::attach_custom_dictionary(&mut app.session); // Fit the window to its monitor, or put it back where it was (still hidden). let winit_window = cc.winit_window().cloned(); if let Some(w) = &winit_window { @@ -549,6 +553,7 @@ fn main() -> std::process::ExitCode { if !in_window_menus { app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app); } + mac_cursor::install(&cc.egui_ctx, winit_window.as_ref()); } #[cfg(not(target_os = "macos"))] { diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 919a044557..8e64027031 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -57,6 +57,14 @@ pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { } } +/// Keep the custom dictionary (Edit › Spelling › Add, Edit Custom Dictionary) in the +/// `Custom Dictionary.txt` file next to the settings, one word per line, and take in its words. +pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) { + if let Some(path) = store_dir("Custom Dictionary.txt") { + session.attach_custom_dictionary(path); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/contributors/people.toml b/contributors/people.toml index 69c412f8b9..420177ffb6 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -220,3 +220,8 @@ real_name = "Sven Lafebre" [people.kylekanouse] real_name = "Kyle Kanouse" sync_github_name = true + +[people.Hassan1305] +real_name = "Hassan Nawaz Khan" +display_name = "Hassan Nawaz Khan" +sync_github_name = false diff --git a/crates/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/color/src/gradient.rs b/crates/color/src/gradient.rs index 8e947c1436..03d0f5670c 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -456,6 +456,41 @@ impl Gradient { } Some(out) } + /// A gradient whose stops are all CMYK as a ramp of C, M, Y, K and opacity: the stops' own + /// inks, an off-center midpoint halfway between its two stops' inks, and a Perceptual + /// gradient's curve as [`Self::ink_mixes`] mixes the inks. `None` when a stop is in another + /// model, there are no stops, or [`Self::ink_mixes`] gives none for the curve. + fn ink_ramp(&self) -> Option> { + let inks: Vec<[f32; 4]> = self + .stops + .iter() + .map(|s| match s.color { + Color::Cmyk { c, m, y, k } => Some([c, m, y, k]), + _ => None, + }) + .collect::>()?; + if inks.is_empty() { + return None; + } + let entry = |i: usize, w: f32, o: f32| { + let (a, b) = (inks[i], inks.get(i + 1).copied().unwrap_or(inks[i])); + let [c, m, y, k]: [f32; 4] = std::array::from_fn(|n| a[n] + (b[n] - a[n]) * w); + [c, m, y, k, o] + }; + if !self.method.is_classic() { + return Some(Ramp { stops: self.ink_mixes()?.into_iter().map(|(t, i, w, o)| (t, entry(i, w, o))).collect() }); + } + let mut stops = Vec::with_capacity(inks.len()); + for (i, s) in self.stops.iter().enumerate() { + stops.push((s.offset, entry(i, 0.0, s.opacity))); + if let Some(n) = self.stops.get(i + 1) + && (s.midpoint - 0.5).abs() > 1e-3 + { + stops.push((s.offset + (n.offset - s.offset) * s.midpoint, entry(i, 0.5, (s.opacity + n.opacity) / 2.0))); + } + } + Some(Ramp { stops }) + } /// The same ramp the other way round: the stops in reverse order at mirrored offsets, each /// segment's midpoint mirrored with it. pub fn reverse(&mut self) { @@ -895,19 +930,45 @@ impl GradientPaint { fill: bool, rgb: &dyn Fn(&Color) -> [f32; 3], ) -> impl Iterator + use<> { + self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false) + } + /// [`Self::pixels`] of a linear or radial gradient whose stops are all CMYK, as C, M, Y, K + /// and opacity levels mixed from the stops' inks; `None` when a stop is in another model, + /// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`]. + /// Dither's noise adds no ink where the ramp has none. + pub fn ink_pixels(&self, bounds: Rect, area: Rect, cols: u16, rows: u16, fill: bool) -> Option + use<>> { + let ramp = self.gradient.ink_ramp()?; + Some(self.grid(ramp, bounds, area, cols, rows, [0..cols, 0..rows], fill, true)) + } + /// `ramp` sampled at each cell's center in columns `cells[0]` and rows `cells[1]` of the grid, + /// its last channel (opacity) rounded and each other channel with dither's noise, except + /// (`inks`) where that channel is empty. + #[allow(clippy::too_many_arguments)] + fn grid( + &self, + ramp: Ramp, + bounds: Rect, + area: Rect, + cols: u16, + rows: u16, + cells: [std::ops::Range; 2], + fill: bool, + inks: bool, + ) -> impl Iterator + use { let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither); - let ramp = Ramp::new(&self.gradient, rgb); let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1))); let (x0, y0) = (area.x0, area.y0); let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end)); down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| { let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch); let c = ramp.at(geom.param_at(kind, p) as f32); - let level = |k: usize| { - let noise = if dither { dither_noise(i, j, k as u32) } else { 0.0 }; + std::array::from_fn(|k| { + if k + 1 == N { + return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8; + } + let noise = if dither && !(inks && c[k] <= 0.0) { dither_noise(i, j, k as u32) } else { 0.0 }; (c[k].clamp(0.0, 1.0) * 255.0 + noise).round().clamp(0.0, 255.0) as u8 - }; - [level(0), level(1), level(2), (c[3].clamp(0.0, 1.0) * 255.0).round() as u8] + }) }) } } @@ -916,9 +977,9 @@ impl GradientPaint { /// (display RGB, or an ink's coverage): its stops, midpoints and a Perceptual gradient's /// in-between colours as stops (as [`Gradient::expanded_stops`]), each turned into that space /// once, with colour and opacity mixed linearly between them, each on its own (as the renderer's -/// vector gradients mix them). -pub struct Ramp { - stops: Vec<(f32, [f32; 4])>, +/// vector gradients mix them). `N` counts the channels, with opacity last. +pub struct Ramp { + stops: Vec<(f32, [f32; N])>, } impl Ramp { @@ -932,10 +993,13 @@ impl Ramp { .collect(); Self { stops } } +} + +impl Ramp { /// Unpremultiplied colour and opacity at `t`, padded past the ends (transparent black /// without stops). - pub fn at(&self, t: f32) -> [f32; 4] { - let Some(&(t0, first)) = self.stops.first() else { return [0.0; 4] }; + pub fn at(&self, t: f32) -> [f32; N] { + let Some(&(t0, first)) = self.stops.first() else { return [0.0; N] }; // Not after the first stop (or not a number): its colour. if t.partial_cmp(&t0) != Some(std::cmp::Ordering::Greater) { return first; @@ -947,7 +1011,7 @@ impl Ramp { return std::array::from_fn(|k| ca[k] + (cb[k] - ca[k]) * u); } } - self.stops.last().map_or([0.0; 4], |s| s.1) + self.stops.last().map_or([0.0; N], |s| s.1) } } diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 1005b84300..87372a1c24 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -604,3 +604,96 @@ fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() { } assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}"); } + +fn cmyk_stop(offset: f32, c: f32, m: f32, y: f32, k: f32) -> GradientStop { + GradientStop::new(offset, Color::cmyk(c, m, y, k)) +} + +/// The `n` × 1 grid of `g` as a left-to-right linear gradient's ink pixels. +fn ink_row(g: Gradient, n: u16, fill: bool) -> Vec<[u8; 5]> { + let b = Rect::new(0.0, 0.0, f64::from(n), 1.0); + GradientPaint::new(g).ink_pixels(b, b, n, 1, fill).expect("CMYK stops").collect() +} + +#[test] +fn ink_pixels_mix_the_stops_inks_in_cmyk() { + let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0), cmyk_stop(1.0, 0.0, 0.0, 0.0, 1.0)]); + g.stops[1].opacity = 0.5; + let px = ink_row(g.clone(), 10, true); + let at = |x: f32| (x * 255.0).round() as u8; + for (i, p) in px.iter().enumerate() { + let t = (i as f32 + 0.5) / 10.0; + assert_eq!(*p, [at(1.0 - t), 0, 0, at(t), at(1.0 - t * 0.5)], "pixel {i}"); + } + // An off-center midpoint is halfway between the two stops' inks, not a display RGB mix. + g.stops[0].midpoint = 0.25; + let px = ink_row(g.clone(), 4, false); + assert_eq!(&px[0][..4], &[at(0.75), 0, 0, at(0.25)], "halfway to the midpoint"); + assert_eq!(&px[1][..4], &[at(0.5 * 5.0 / 6.0), 0, 0, at(0.5 + 0.5 / 6.0)], "a sixth of the way past it"); + // A hard stop keeps both sides. + let hard = Gradient::new( + GradientKind::Linear, + vec![ + cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0), + cmyk_stop(0.5, 1.0, 0.0, 0.0, 0.0), + cmyk_stop(0.5, 0.0, 1.0, 0.0, 0.0), + cmyk_stop(1.0, 0.0, 1.0, 0.0, 0.0), + ], + ); + let px = ink_row(hard, 4, false); + assert_eq!((&px[1][..4], &px[2][..4]), (&[255, 0, 0, 0][..], &[0, 255, 0, 0][..])); +} + +#[test] +fn ink_pixels_dither_only_the_inks_the_ramp_has() { + let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 0.2, 0.0, 0.0, 0.4), cmyk_stop(1.0, 0.8, 0.0, 0.0, 0.4)]); + g.dither = true; + let noisy = ink_row(g.clone(), 64, true); + let plain = ink_row(g.clone(), 64, false); + assert_ne!(noisy, plain, "a fill has noise, a stroke none"); + for (n, p) in noisy.iter().zip(&plain) { + assert_eq!((n[1], n[2]), (0, 0), "no ink on the empty plates: {n:?}"); + assert!(n[0].abs_diff(p[0]) <= 1 && n[3].abs_diff(p[3]) <= 1, "{n:?} {p:?}"); + assert_eq!(n[4], 255, "opacity has no noise"); + } + assert!(noisy.iter().zip(&plain).any(|(n, p)| n[3] != p[3]), "K gets its own noise"); + assert!(noisy.iter().zip(&plain).any(|(n, p)| (n[0] != p[0]) != (n[3] != p[3])), "the noise differs from channel to channel"); +} + +#[test] +fn ink_pixels_follow_the_perceptual_curve_as_ink_mixes() { + let mut g = Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 0.0, 0.0, 0.0, 0.0), cmyk_stop(1.0, 1.0, 0.0, 0.0, 0.0)]); + g.method = GradientMethod::Perceptual; + let mixes = g.ink_mixes().unwrap(); + let ramp = g.ink_ramp().unwrap(); + assert_eq!(ramp.stops.len(), mixes.len()); + for ((t, ink), (o, i, w, _)) in ramp.stops.iter().zip(&mixes) { + assert_eq!((*t, ink[0]), (*o, if *i == 0 { *w } else { 1.0 }), "cyan at {t}"); + } + let px = ink_row(g, 2, false); + assert!(px[0][0] > 0 && px[0][0] < px[1][0], "{px:?}"); + assert!(px.iter().all(|p| p[1] == 0 && p[2] == 0 && p[3] == 0), "{px:?}"); +} + +#[test] +fn ink_pixels_need_every_stop_in_cmyk() { + let b = Rect::new(0.0, 0.0, 2.0, 1.0); + let with = |stop: GradientStop| GradientPaint::new(Gradient::new(GradientKind::Linear, vec![cmyk_stop(0.0, 1.0, 0.0, 0.0, 0.0), stop])); + assert!(with(cmyk_stop(1.0, 0.0, 0.0, 0.0, 1.0)).ink_pixels(b, b, 2, 1, true).is_some()); + for other in [Color::rgb(1.0, 0.0, 0.0), Color::gray(0.5), Color::lab(50.0, 10.0, 10.0)] { + assert!(with(GradientStop::new(1.0, other)).ink_pixels(b, b, 2, 1, true).is_none(), "{other:?}"); + } + assert!(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![])).ink_pixels(b, b, 2, 1, true).is_none(), "no stops"); +} + +/// A Perceptual curve over the limit of [`Gradient::ink_mixes`] has no inks; a Classic gradient of as many stops does. +#[test] +fn ink_pixels_stop_at_the_ink_mixes_limit() { + let stops: Vec<_> = (0..=MAX_INK_TINTS).map(|i| cmyk_stop(i as f32 / MAX_INK_TINTS as f32, (i % 2) as f32, 0.0, 0.0, 0.0)).collect(); + let classic = Gradient::new(GradientKind::Linear, stops); + let perceptual = Gradient { method: GradientMethod::Perceptual, ..classic.clone() }; + assert!(!perceptual.fits_ink_tints()); + let b = Rect::new(0.0, 0.0, 2.0, 1.0); + assert!(GradientPaint::new(perceptual).ink_pixels(b, b, 2, 1, false).is_none()); + assert!(GradientPaint::new(classic).ink_pixels(b, b, 2, 1, false).is_some()); +} diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index d25be2c419..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; } } @@ -904,12 +905,16 @@ pub struct Spine { cum: Vec, anchors: Vec, closed: bool, - path: PathData, + /// The subpath the spine was flattened from, kept so [`Spine::at_length`] can read the + /// original curves' tangents. Only the first subpath is stored: the others never affect a + /// spine. + subpath: SubPath, } impl Spine { /// Build a spine from the first subpath of `path`: flatten it to a polyline, record cumulative - /// arc lengths, and the arc length at each anchor. + /// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when + /// the first one flattens to fewer than two points (so it has no length to walk). pub fn new(path: &PathData) -> Option { let sp = path.subpaths.first()?; let mut pts: Vec = Vec::new(); @@ -946,7 +951,7 @@ impl Spine { if pts.len() < 2 { return None; } - Some(Self { pts, cum, anchors, closed: sp.closed, path: path.clone() }) + Some(Self { pts, cum, anchors, closed: sp.closed, subpath: sp.clone() }) } /// The spine's flattened length in arc length. pub fn length(&self) -> f64 { @@ -1012,7 +1017,7 @@ impl Spine { /// `Align to Path` jump between chords instead of following the curve smoothly. pub fn at_length(&self, s: f64) -> (Point, f64) { let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 }; - let Some(sp) = self.path.subpaths.first() else { return (self.pts.first().copied().unwrap_or_default(), 0.0) }; + let sp = &self.subpath; let n = sp.segment_count(); let mut start = 0.0; for i in 0..n { 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/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/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..99fb6b03d9 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -1,10 +1,10 @@ //! Where a path's strokes paint, from the path's geometry without building their outlines: the //! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes -//! up to the miter limit, projecting caps and arrowheads. +//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points. use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit}; use vectorcraft_geom::hit::fill_contains; -use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest}; +use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest}; use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2}; use crate::appearance::HEAD_REACH; @@ -101,6 +101,82 @@ fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize, w } +/// Does the curvature of `seg` stay below one over `side` all along it? A curve's first derivative +/// is a mix of its three control differences, and its second a mix of their two differences, which +/// bound the curvature from above. Then the edges of a stroke reaching `side` from it do not fold +/// back, and those edges reach farthest at the ends of `seg` or where its tangent is square to an +/// axis. +fn gentle(seg: &PathSeg, side: f64) -> bool { + let c = seg.to_cubic(); + let d = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2].map(|v| v * 3.0); + let along = unit(d[0] + d[1] + d[2]); + let slowest = d.iter().map(|v| v.dot(along)).fold(f64::INFINITY, f64::min); + let bend = 2.0 * (d[1] - d[0]).hypot().max((d[2] - d[1]).hypot()); + slowest > 0.0 && side * bend < slowest * slowest +} + +/// The box a stroke reaching `side` from `seg` paints across it, from the directions its tangent +/// can take: the tangent is a mix of the nonzero control differences, so when their directions all +/// lie within a quarter turn of the directions' sum, every point across the stroke is in `seg`'s +/// box moved `side` along a normal of one of those directions. `None` when they do not. A handle on +/// its end point adds no direction, so a straight curve with one measures as a line. +fn turning_box(seg: &PathSeg, side: f64) -> Option { + 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 +191,81 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool { impl StrokeLayer { /// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads, - /// or an alignment that depends on whether the path is closed? Else it reaches evenly round it. + /// an alignment that depends on whether the path is closed, or butt caps, which stop at the + /// ends of an open path? Else it reaches evenly round it. fn needs_shape(&self) -> bool { self.join == LineJoin::Miter - || self.cap == LineCap::Square + || self.cap != LineCap::Round || self.start_arrow.is_some() || self.end_arrow.is_some() || self.align != StrokeAlign::Center } - /// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown - /// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of + /// The box this stroke paints along `segs`, the segments with length of an open subpath, when + /// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each + /// joint between segments paints ([`round_join_box`]), a shallow one included. + /// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips + /// are measured apart. A segment in the middle is measured only when its own box grown by + /// `side`, which holds everything it paints, is not inside the box so far. + fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option { + 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 +276,15 @@ impl StrokeLayer { let r = self.head_reach(end); out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r))); } - out.union(bounds.inflate(side_max, side_max)) + even.map_or(out, |e| out.union(e.inflate(side_max, side_max))) + } + + /// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown + /// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of + /// projecting caps and the reach of the arrowheads round their end points. An open subpath + /// with butt caps does not reach past its ends ([`Self::butt_body`]). + pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect { + self.reach_along(bp, bounds, None, true) } /// The tip of the miter spike this stroke paints where segment `b` follows segment `a` in a @@ -176,30 +302,7 @@ impl StrokeLayer { /// every joint of `bp` ([`Self::miter_tip`]) or `None` when there are none, instead of measured /// along `bp`. It measures the projecting caps and arrowheads as [`Self::bounds_on`] does. pub fn bounds_with_tips(&self, bp: &BezPath, bounds: Rect, tips: Option) -> Rect { - let els = bp.elements(); - let mut out = tips.map_or(bounds, |t| bounds.union(t)); - let mut side_max: f64 = 0.0; - // Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere. - let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed); - for (r, closed) in subpaths(bp) { - let side = self.side_reach(closed); - side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side }); - if side <= 0.0 { - continue; - } - if self.cap == LineCap::Square && !closed { - let segs = drawn(&els[r]); - for (at, dir) in ends(&segs).into_iter().flatten() { - let n = Vec2::new(-dir.y, dir.x) * side; - out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n); - } - } - } - for (at, _, end) in head_ends(self, bp) { - let r = self.head_reach(end); - out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r))); - } - out.union(bounds.inflate(side_max, side_max)) + self.reach_along(bp, bounds, tips, false) } /// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and @@ -314,7 +417,7 @@ impl Appearance { } /// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape - /// (miter spikes, projecting caps, arrowheads or an alignment) given by `shaped`. + /// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`. pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect { self.painted_strokes().fold(bounds, |acc, s| { if !s.needs_shape() { @@ -325,6 +428,30 @@ impl Appearance { }) } + /// Does this appearance have a visible butt-capped stroke? + pub fn has_butt_stroke(&self) -> bool { + self.painted_strokes().any(|s| s.cap == LineCap::Butt) + } + + /// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with + /// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The + /// visual box's margin at the stroke's corners there depends on their direction, which a scale + /// out of proportion changes. + pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool { + if !self.has_butt_stroke() { + return false; + } + let slanted = |v: Vec2| { + let d = unit(a * v.to_point() - a * Point::ZERO); + (d.x * d.y).abs() > 1e-9 + }; + let els = bp.elements(); + subpaths(bp) + .into_iter() + .filter(|(_, closed)| !closed) + .any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0)))) + } + /// Does a visible stroke of this appearance along `bp` (filled with `rule`) paint within /// `tol` of `p` ([`StrokeLayer::hits`])? pub fn stroke_hit(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool { @@ -332,6 +459,31 @@ impl Appearance { } } +/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object +/// before it answers yes without looking further. +pub const SLANT_INSTANCES: usize = 4096; + +impl crate::Node { + /// Does a visible butt-capped stroke of this object, of an object in it or of an object in a + /// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment + /// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it + /// answers yes. + pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool { + self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES)) + } + + /// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into. + fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell) -> 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/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..12bc7ec89a 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 { 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..82db95b5b2 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -87,7 +87,7 @@ pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_r pub use solids::{ CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as, - validate_solid, validate_three_d, validate_three_d_params, view_options, + validate_solid, validate_three_d, validate_three_d_at, validate_three_d_params, view_options, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; 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..89f3bba867 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, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; use vectorcraft_three_d::{Edge, Revolve}; +use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, solid_paints, union_bounds}; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; @@ -17,6 +18,13 @@ pub const REVOLVE: &str = "threeD.revolve"; /// thousands of faces took gigabytes; past this the source path is drawn. const MAX_PAINT_COPIES: usize = 256 << 20; +/// The most face and box tests a group's transparent members' faces take together to rejoin their +/// members' last runs; past them each starts a run of its own. +const MAX_OVERLAP_TESTS: usize = 1 << 22; + +/// The width of the stroke around each face that covers the seams between faces. +const SEAM_WIDTH: f64 = 0.75; + /// About the bytes one copy of `paint` takes. fn paint_bytes(paint: &Paint) -> usize { use std::mem::size_of; @@ -60,6 +68,7 @@ pub fn revolve_options(p: &Value) -> Revolve { shade: flag(p, "shade", true), smooth_shading: true, cap_ends: flag(p, "cap", true), + curve_samples: None, } } @@ -67,12 +76,94 @@ pub fn revolve_options(p: &Value) -> Revolve { /// by the evaluator; unsupported source kinds remain unchanged when rendered. pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { validate_revolve_params(p)?; - let path = profile(n).ok_or("Revolve currently requires a path or compound path. Select a profile drawn with the Pen tool.")?; - let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?; - if !path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) { - return Err("Revolve requires at least two anchors".into()); + let effects = &n.appearance.effects; + // The profile is measured before the object's one Revolve, hidden or shown. + let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects); + if is_container(n) { + const EMPTY: &str = "Revolve requires a group holding a shape with at least two anchors"; + let mut shapes = members(n, "Revolve")?; + if !shapes.iter().any(|s| has_two_anchors(&s.path)) { + return Err(EMPTY.into()); + } + reshape_members(n, before, &mut shapes); + let b = union_bounds(&shapes).ok_or(EMPTY)?; + let options = shared_options(&shapes, revolve_options(p))?; + let mut copies = 0; + return shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies)); } - vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ()) + let (path, _) = object_profile(n, "Revolve")?; + if !has_two_anchors(&path) { + return Err("Revolve requires a shape with at least two anchors".into()); + } + let path = geometry(&path, before, &GeomContext::of(n)); + let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; + let paints = solid_paints(n); + check_surface(&path, b, revolve_options(p), surface_item(&paints), &mut 0) +} + +/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of +/// appearance item `target` of `n`. The surfaces of every fill and stroke that carries a Revolve, +/// `target`'s included, share one budget of paint copies, as in [`art`]. A visible object-level +/// Revolve draws in place of those surfaces. +pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { + if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() { + return validate_revolve(n, p); + } + validate_revolve_params(p)?; + const EMPTY: &str = "Revolve requires a shape with at least two anchors"; + let (path, _) = object_profile(n, "Revolve")?; + if !has_two_anchors(&path) { + return Err(EMPTY.into()); + } + let ctx = GeomContext::of(n); + let path = geometry(&path, &n.appearance.effects, &ctx); + let mut copies = 0; + for (i, item) in n.appearance.items.iter().enumerate() { + let effects = item.effects(); + let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && e.id == REVOLVE) }; + let options = match at.and_then(|at| effects.get(at)) { + _ if i == target => revolve_options(p), + Some(fx) if crate::paints(item) => revolve_options(&merged_params(REVOLVE, &fx.params)), + _ => continue, + }; + let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item)); + let b = path.bounds().ok_or(EMPTY)?; + check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?; + } + Ok(()) +} + +fn has_two_anchors(path: &PathData) -> bool { + path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) +} + +/// The bytes the copies of `paint` take on `faces` faces: a face's fill, its shadow and their seam +/// strokes make up to four copies. +fn paint_copies(faces: usize, paint: &Paint) -> usize { + faces.saturating_mul(4).saturating_mul(paint_bytes(paint)) +} + +/// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the +/// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`]. +fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> { + let faces = vectorcraft_three_d::revolve(path, b, options)?; + *copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0))); + if *copies > MAX_PAINT_COPIES { + return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into()); + } + Ok(()) +} + +/// `options` with one number of samples for every curve of `shapes`, the members of one group: the +/// members share Revolve's limits. +fn shared_options(shapes: &[Profile], options: Revolve) -> Result { + let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?; + Ok(Revolve { curve_samples: Some(samples), ..options }) +} + +/// The item whose paint an object's surface takes: its top fill, else its top stroke. +fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> { + items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last()) } /// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`. @@ -87,38 +178,31 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> { Ok(()) } -fn profile(n: &Node) -> Option { - 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 +230,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 +273,7 @@ fn surface( .into_iter() .flat_map(|item| { let AppearanceItem::Fill(fill) = &item else { return vec![item] }; - let mut edge = StrokeLayer::new(fill.paint.clone(), 0.75); + let mut edge = StrokeLayer::new(fill.paint.clone(), SEAM_WIDTH); // Acute face corners must stay within the overlap width. Miter joins // amplify this seam stroke into visible spikes along the silhouette. edge.join = LineJoin::Round; @@ -202,7 +287,16 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some(group) + Some((depths, group)) +} + +/// A surface of one object about the bounds of `path`, built with options derived from `fx`. +/// `copies` is the count [`surface`] adds to. +fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option { + let b = path.bounds()?; + let (paint, opacity, blend) = paint_of(item); + let options = revolve_options(&merged_params(REVOLVE, &fx.params)); + surface(n, path, b, options, fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) } fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint { @@ -237,26 +331,23 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option { /// 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 +365,49 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul Ok(out) } +/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis. +fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, String> { + let index = n + .appearance + .effects + .iter() + .position(|e| e.visible && e.id == REVOLVE) + .ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?; + let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; + let mut shapes = members(n, "Revolve")?; + reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); + let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; + let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let mut out = vec![]; + for s in &shapes { + let Some(item) = surface_item(&s.items) else { continue }; + let (paint, opacity, _) = paint_of(item); + let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?; + crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?; + } + Ok(out) +} + fn art(n: &Node, expand: bool) -> Option { if !has_revolve(n) { return None; } - let path = profile(n)?; + if is_container(n) { + return group_art(n, expand); + } + let (path, _) = profile(n)?; let ctx = GeomContext::of(n); let mut children = vec![]; + let mut copies = 0; let mut remaining = n.appearance.effects.clone(); if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { let fx = n.appearance.effects.get(index)?; let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); // An object's surface uses its top visible fill, falling back to its stroke. - let item = n - .appearance - .items - .iter() - .rev() - .find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i)) - .or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))?; - let (paint, opacity, blend) = paint_of(item); + let paints = solid_paints(n); + let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - children.push(Arc::new(surface(n, &path, fx, paint, opacity, blend, expand)?)); + children.push(Arc::new(object_surface(n, &path, fx, item, expand, &mut copies)?)); // Later geometry acts on the projected art as a whole through container evaluation. remaining = n .appearance @@ -312,9 +424,8 @@ fn art(n: &Node, expand: bool) -> Option { if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); - let (paint, opacity, blend) = paint_of(item); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut art = surface(n, &p, fx, paint, opacity, blend, expand)?; + let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| e.id != REVOLVE).cloned().collect(); children.push(Arc::new(art)); } else { @@ -328,6 +439,244 @@ fn art(n: &Node, expand: bool) -> Option { 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 +844,354 @@ mod tests { assert_eq!(expand_revolve_art(&n).unwrap().children().unwrap()[0], expanded.children().unwrap()[0]); } + /// A closed rectangle `x` to `x + 10` across, filled solid. + fn member(id: u64, x: f64) -> Arc { + 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_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..ab119192c4 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -138,7 +138,7 @@ pub fn inflate_options(p: &Value) -> Inflate { } /// The shape a solid is made from: a path's or a compound path's outline. -fn profile(n: &Node) -> Option<(PathData, FillRule)> { +pub(crate) fn profile(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { NodeKind::Path { path, rule, guide: false, clipping: false, .. } => Some((path.clone(), *rule)), NodeKind::Compound { children, rule } => { @@ -156,7 +156,7 @@ fn profile(n: &Node) -> Option<(PathData, FillRule)> { /// What a 3D effect paints `n` with: its own fills and strokes, else, for type that has none, the /// fill and stroke of its first painted run (its characters' colours). -fn solid_paints(n: &Node) -> Vec { +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; @@ -207,29 +207,52 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; return shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ())); } - let (path, rule) = profile(n).ok_or_else(|| { - format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.") - })?; + let (path, rule) = object_profile(n, label)?; let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; facets(id, &path, rule, b, p).map(|_| ()) } +/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from +/// (empty, or only spaces) is a shape without anchors, and any other object is the wrong kind. +pub(crate) fn object_profile(n: &Node, label: &str) -> Result<(PathData, FillRule), String> { + profile(n).ok_or_else(|| { + if matches!(n.kind, NodeKind::Text(_)) { + format!("{label} requires a shape with at least two anchors") + } else { + format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.") + } + }) +} + +/// A group in a 3D effect's group, or a member of it, whose opacity is below 100% or whose blending +/// mode is not Normal. The members of one group share its `key`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Scope { + pub(crate) key: usize, + pub(crate) opacity: f32, + pub(crate) blend: BlendMode, +} + /// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint -/// it, and the opacity of the objects it is in (1 for the object with the effect itself). -struct Profile { - path: PathData, - rule: FillRule, - items: Vec, - 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)) } @@ -245,15 +268,26 @@ const MAX_MESH_TRIANGLES: usize = 2_000_000; /// effects and painted with its own fills and strokes. Like the effect on a group in the /// reference app, they turn about one shared axis (the centre of their bounds together) rather /// than each about its own. An error names what the group holds that can't become a solid. -fn members(n: &Node, label: &str) -> Result, 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)?; + walk(c, opacity, &scopes, w)?; continue; } let Some((path, rule)) = profile(c) else { @@ -266,19 +300,19 @@ fn members(n: &Node, label: &str) -> Result, String> { }; return Err(format!("{label} on a group needs paths, compound paths and type: release or expand its {what} first.")); }; - if out.len() >= MAX_MEMBERS { + if w.out.len() >= MAX_MEMBERS { return Err(format!("{label} on a group takes at most {MAX_MEMBERS} objects")); } let path = geometry(&path, &c.appearance.effects, &GeomContext::of(c)); if path.bounds().is_some() { - out.push(Profile { path, rule, items: solid_paints(c), opacity }); + w.out.push(Profile { path, rule, items: solid_paints(c), opacity, scopes }); } } Ok(()) } - let mut out = vec![]; - walk(n, 1.0, label, &mut out)?; - Ok(out) + let mut w = Walk { label, out: vec![], keys: 0 }; + walk(n, 1.0, &[], &mut w)?; + Ok(w.out) } /// Can 3D effect `id` (Revolve included, [`is_three_d`]) with parameters `p` draw `n`? Checked @@ -288,6 +322,19 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) } } +/// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of +/// appearance item `item` of `n` (the effects' length for a new effect), or on the object itself +/// when `at` is `None`. A Revolve on a fill or stroke is checked in that item's paint, after the +/// item's geometry effects before it, together with the object's other items that carry a Revolve. +/// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws. +pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { + match at { + Some(_) if is_container(n) => Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()), + Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index), + _ => validate_three_d(n, id, p), + } +} + /// Are 3D effect `id`'s parameter values `p` valid? The checks of [`validate_three_d`] that do not /// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does /// not need to fit. @@ -385,7 +432,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32 /// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before` /// its 3D effect, about the bounds of all of them. -fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) { +pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) { if before.iter().any(|e| e.visible && is_geometry(&e.id)) && let Some(b) = union_bounds(shapes) { @@ -501,7 +548,7 @@ pub fn solid_art(n: &Node) -> Option { 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 +564,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); @@ -680,14 +727,14 @@ fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result 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 363000ca33..ef403dc80b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,6 +21,7 @@ heif = ["dep:heic-rs", "dep:rayon"] [dependencies] # Which paths stored in documents may be opened. craft-docpath = { workspace = true } +craft-proof = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } @@ -39,6 +40,8 @@ vectorcraft-metafile = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } +# The commands' parameter schemas (schemas.rs). +vectorcraft-apischema = { workspace = true } image = { workspace = true } jxl-oxide = { workspace = true } jxl-color = { workspace = true } @@ -85,3 +88,5 @@ zune-jpegxl = { workspace = true } zune-core = { workspace = true } # The JavaScript parser's lexer, compared with the script checker's on the same scripts. vectorcraft-js = { workspace = true } +# A bundled font's own glyph boxes, for the glyph bounds tests. +skrifa = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 6ef4918e16..7c1c9eea49 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; @@ -82,6 +83,7 @@ mod select; pub(crate) mod shaper; pub mod shortcutset; pub(crate) mod slices; +pub mod spelling; mod stroke; mod style; pub mod stylelib; @@ -129,6 +131,9 @@ pub struct CommandSpec { pub run: Run, /// Record in the journal (false for queries and selection-only helpers). pub journal: bool, + /// The parameters' schema: [`Session::execute`] checks the params against it before the + /// command runs, and `params` is the text it writes ([`crate::schemas`]). + pub schema: Option<&'static vectorcraft_apischema::ParamSchema>, } /// Serializable command metadata. @@ -142,11 +147,29 @@ pub struct CommandInfo { pub enabled: bool, #[serde(skip_serializing_if = "Option::is_none")] pub disabled_reason: Option, + /// 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, @@ -155,6 +178,8 @@ impl CommandSpec { params: self.params, enabled: e.is_ok(), disabled_reason: e.err(), + input_schema: schema.as_ref().map(input_schema), + schema, } } } @@ -237,10 +262,17 @@ pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> { macro_rules! cmd { ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, schema: None } }; (query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false } + $crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, schema: None } + }; + // With a parameter schema: `schema: &SCHEMA` after the run function. + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => { + $crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!($id, $label, [$($m),*], $sc, $params, $en, $run) } + }; + (query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => { + $crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!(query $id, $label, [$($m),*], $sc, $params, $en, $run) } }; } pub(crate) use cmd; @@ -321,6 +353,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(expand::specs()); v.extend(attributes::specs()); v.extend(interactivity::specs()); + v.extend(spelling::specs()); v.extend(svgfilter::specs()); v.extend(newart::specs()); v.extend(colortheme::specs()); @@ -352,6 +385,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(actionset::specs()); v.extend(importmatches::specs()); v.extend(addons::specs()); + // Last, so the reference it writes ends with its own section. + v.extend(apiref::specs()); v }) } @@ -368,6 +403,14 @@ pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } +/// [`run_spec`] for a command run outside [`Session::execute`]: with params checked against the +/// command's schema, and the defaults of omitted values filled in, as `execute` does +/// ([`crate::schemas::check`]). +pub(crate) fn run_checked(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + 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/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/appearance.rs b/crates/engine/src/cmd/appearance.rs index be452f6c6d..45b23a0cb1 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's solid fill and stroke for this instance only, as the Eyedropper Options allow, and a sampled gradient or pattern, a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}", has_doc, copy_from ), @@ -1204,11 +1204,10 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { } let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?; // An object of a dynamic symbol instance's art selected with Direct Selection takes the clicked - // object's solid fill and stroke, as the Eyedropper Options allow, for this instance only. A - // gradient or pattern sampled for it, a source that is not a path, compound path or type (a - // symbol instance's own appearance is empty), and options that pick up neither color are - // refused, and the paint defaults stay as they are. A path of a compound path stands for the - // compound path, which holds the paint. + // object's fill and stroke, as the Eyedropper Options allow, for this instance only. A source + // that is not a path, compound path or type (a symbol instance's own appearance is empty) and + // options that pick up neither color are refused, and the paint defaults stay as they are. A + // path of a compound path stands for the compound path, which holds the paint. if !reverse && !append && !defaults_only @@ -1219,11 +1218,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { let src = Arc::new(d.node(super::path::compound_or_self(d, clicked)).ok_or(EngineError::NoNode(clicked))?.clone()); let (fill, stroke) = (super::paint::proxy_paint(&src, false, None), super::paint::proxy_paint(&src, true, None)); let a = attrs.appearance; - if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src) - || !(a.fill.color || a.stroke.color) - || (a.fill.color && !super::paint::part_takes(&fill)) - || (a.stroke.color && !super::paint::part_takes(&stroke)) - { + if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src) || !(a.fill.color || a.stroke.color) { return Err(super::brushsym::part_only()); } super::brushsym::edit_part(s, id, &path, "Eyedropper", |o| { diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 8c225b877b..31639519f0 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 ), diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 53f373a3bd..13b6ab8814 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -272,7 +272,7 @@ pub fn specs() -> Vec { "Select Symbol Instance Part", [], None, - "{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke with a solid color or none, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom with a solid fill and stroke (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused) change that object's fill or stroke for this instance only; gradients and patterns are refused, and so are the commands that change the selected objects without ids (transparency.set, the gradient commands, object.group, edit.cut and edit.clear among them); edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}", + "{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke (solid, none, gradient or pattern), transparency.set with opacity and/or blend, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused; a gradient or pattern fill or stroke is taken) change that object for this instance only; the gradient annotator commands, isolate/knockout on transparency.set, object.group, edit.cut and edit.clear among the commands that change the selected objects without ids are refused; edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}", has_doc, symbol_instance_select_part ), diff --git a/crates/engine/src/cmd/brushsym/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/brushsym/dynamic.rs b/crates/engine/src/cmd/brushsym/dynamic.rs index 89c7c3c522..32edc44f86 100644 --- a/crates/engine/src/cmd/brushsym/dynamic.rs +++ b/crates/engine/src/cmd/brushsym/dynamic.rs @@ -90,10 +90,11 @@ pub(crate) fn edit_part(s: &mut Session, id: NodeId, path: &[u32], label: &str, }) } -/// The refusal of anything but a solid color fill or stroke change while an object of a symbol -/// instance's art is selected ([`selected_part`]), and of selecting any other object of the art. +/// The refusal of a change that is not the fill, stroke, opacity or blend of a path, compound path +/// or type while an object of a symbol instance's art is selected ([`selected_part`]), and of +/// selecting any other object of the art. pub(crate) fn part_only() -> EngineError { - EngineError::Other("Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change".into()) + EngineError::Other("Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change".into()) } pub(super) fn symbol_instance_select_part(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 6d1e7284c9..92d01bb7e9 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 { 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/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/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..80574d2d58 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1063,8 +1063,12 @@ 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); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 297279b64d..9d396edc16 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -280,9 +280,13 @@ 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 targets = appearance_targets(s, p)?; + for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) { let n = s.doc()?.doc.node(target).ok_or(EngineError::NoNode(target))?; - effects::validate_three_d(n, id, &effect.params).map_err(|e| bad(C, e))?; + // A new effect goes after the item's others. + let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten(); + let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len()))); + effects::validate_three_d_at(n, id, &effect.params, on).map_err(|e| bad(C, e))?; if id == effects::REVOLVE && effects::has_revolve(n) { return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead.")); } @@ -589,7 +593,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result { cur.extend(new); } if visible != Some(false) { - effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?; + effects::validate_three_d_at(n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?; } else { // Hidden, the effect draws nothing, so its object need not fit. The values given are // checked, and after a change of 3D type so is every value it keeps. @@ -865,8 +869,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br // keeps it as its only member). Some((image, false)) => Some(rasterfx::replace_with_image(v, image)), image => { - let m = if container && effects::has_solid(&v) { - // A group's or layer's 3D effect: the shaded faces of its members' solids. + let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) { + // A 3D effect on a group or layer, or on type: the shaded faces of its solids. effects::expand_leaf(d, &v, &mut stroke_art) } else if container { // A group's or layer's own fills and strokes become art among its members. diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index e3fca957b8..6604c99a2e 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -193,6 +193,169 @@ fn type_extrudes_as_its_glyphs_and_stays_editable() { assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "the solid follows the edited text"); } +/// #3617: Revolve takes live type and stays type, updating when the text changes, and saves, +/// exports, expands and undoes as one step. +#[test] +fn type_revolves_as_its_glyphs_and_stays_editable() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": "O", "size": 72})).unwrap(); + let id = NodeId(t["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#cc2200"})).unwrap(); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null, "params": {"segments": 16}})).unwrap(); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::Text(_)), "still type"); + let art = effects::revolve_art(&n).expect("a surface of the glyphs"); + let mut tinted = false; + art.walk(&mut |c| { + if let Some([r, g, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) { + tinted |= r > g && r > b; + } + }); + assert!(tinted, "shaded from the characters' red"); + let doc = &s.doc().unwrap().doc; + let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), art, "the same art after a save"); + let meshes = effects::three_d_meshes(&n).unwrap(); + assert_eq!(meshes.len(), 1, "one mesh of every contour of the type"); + s.execute("text.setText", &json!({"ids": [id.0], "text": "OO"})).unwrap(); + assert_ne!(effects::revolve_art(&node(&s, id)).unwrap(), art, "the surface follows the edited text"); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + assert!(!effects::has_revolve(&node(&s, id)), "expanded"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(matches!(node(&s, id).kind, NodeKind::Text(_))); + assert!(effects::has_revolve(&node(&s, id))); + // Extrude & Bevel on type expands the same way. + s.execute("effect.remove", &json!({"index": 0, "ids": [id.0], "item": null})).unwrap(); + s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + assert!(!effects::has_solid(&node(&s, id)), "expanded"); +} + +/// Revolve refuses type with no outlines, and a group with no visible shape, without adding an +/// effect. Extrude & Bevel gives the same reason for empty type. +#[test] +fn revolve_refuses_type_and_groups_without_a_shape() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + for text in ["", " "] { + let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": text, "size": 72})).unwrap(); + let id = NodeId(t["id"].as_u64().unwrap()); + for effect in ["threeD.revolve", "threeD.extrude"] { + let err = s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("at least two anchors"), "{effect}, {text:?}: {err}"); + assert!(node(&s, id).appearance.effects.is_empty()); + } + } + let (mut s, a) = session_with_rect(); + let b = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + for member in [a.0, b] { + s.execute("select.set", &json!({"ids": [member]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + } + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("group holding a shape"), "{err}"); + assert!(node(&s, g).appearance.effects.is_empty()); +} + +/// A Revolve on one fill is checked in that fill's paint, and `effect.setParams` on it as well. +#[test] +fn revolve_on_a_fill_is_checked_in_that_fills_paint() { + use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + use vectorcraft_doc::{AppearanceItem, FillLayer}; + let (mut s, id) = session_with_rect(); + // The paint copies of 100 faces reach the 256 MiB budget: 8 segments stay under, 64 pass it. + let count = (256 << 20) / (4 * 100 * std::mem::size_of::()); + let stops = (0..count).map(|i| GradientStop::new(i as f32 / count as f32, Color::rgb(1.0, 0.0, 0.0))).collect(); + let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + s.edit("fills", |d, _| { + let n = d.node_mut(id).unwrap(); + n.appearance.items = + vec![AppearanceItem::Fill(FillLayer::new(ramp)), AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0))))]; + Ok(()) + }) + .unwrap(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0})).unwrap_err().to_string(); + assert!(err.contains("simplify the gradient"), "{err}"); + assert!(node(&s, id).appearance.items[0].effects().is_empty()); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0, "params": {"segments": 8}})).unwrap(); + let err = s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": 0, "params": {"segments": 128}})).unwrap_err().to_string(); + assert!(err.contains("simplify the gradient"), "{err}"); +} + +/// A hidden Revolve still counts as the object's one Revolve: a second one is refused, and the +/// hidden one can be shown again over the geometry effects after it. +#[test] +fn a_second_revolve_is_refused_over_a_hidden_one() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap(); + s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": false})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [id.0], "item": null})).unwrap(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("one Revolve effect"), "{err}"); + let ids: Vec<_> = node(&s, id).appearance.effects.iter().map(|e| e.id.clone()).collect(); + assert_eq!(ids, ["threeD.revolve", "distort.roughen"]); + s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": true})).unwrap(); + assert!(node(&s, id).appearance.effects[0].visible); +} + +/// Revolve on a group sweeps every member about one axis on the left edge of their bounds, keeps +/// each member's paint, follows an edited member, expands and undoes as one step. +#[test] +fn revolve_on_a_group_shares_one_axis_and_members_stay_editable() { + let (mut s, a) = session_with_rect(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#cc2200"})).unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 50, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [b], "color": "#0022cc"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null, "params": {"segments": 16, "rotationX": 90}})).unwrap(); + assert_eq!(node(&s, g).children().unwrap().len(), 2, "the members stay as they were"); + let art = effects::revolve_art(&node(&s, g)).expect("a surface of the members"); + // The axis is the left edge of both members together (x = 100), so the right member's far + // wall sweeps out to 200 pt from it on either side: x = 300 and x = -100. + let bounds = art.visual_bounds().unwrap(); + assert!((bounds.x1 - 300.0).abs() < 2.0 && (bounds.x0 + 100.0).abs() < 2.0, "{bounds:?}"); + let (mut red, mut blue) = (false, false); + art.walk(&mut |c| { + if let Some([r, _, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) { + red |= r > b; + blue |= b > r; + } + }); + assert!(red && blue, "each member keeps its own paint"); + assert_eq!(effects::three_d_meshes(&node(&s, g)).unwrap().len(), 2, "a mesh for each member"); + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); + assert!(vectorcraft_testkit::svg_shapes(&svg) >= 4, "both members exported as vector faces"); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.move", &json!({"dx": -40, "dy": 0})).unwrap(); + assert_ne!(effects::revolve_art(&node(&s, g)).unwrap(), art, "a moved member reshapes the surface"); + s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap(); + assert!(!effects::has_revolve(&node(&s, g)), "expanded"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(effects::has_revolve(&node(&s, g))); +} + +/// A group holding what can't be swept is refused as a whole, and a clipping group is named. +#[test] +fn revolve_refuses_a_group_with_a_member_it_can_not_sweep() { + let (mut s, a) = session_with_rect(); + let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); + let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [clip.as_u64().unwrap()], "item": null})).unwrap_err().to_string(); + assert!(err.contains("path, compound path, type or group"), "{err}"); + let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [clip, c]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("Revolve on a group") && err.contains("clipping groups"), "{err}"); + assert!(node(&s, g).appearance.effects.is_empty()); +} + /// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is /// stored as the angle that shows the same view, and a later angle replaces an earlier strength. #[test] @@ -581,7 +744,7 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() { let copies = n.children().unwrap(); assert_eq!(copies.len(), 3, "the path and its two copies"); let xs: Vec = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect(); - assert_eq!(xs, vec![100.0, 250.0, 400.0]); + assert_eq!(xs, vec![400.0, 250.0, 100.0], "the original on top"); for c in copies { assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label()); assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0))); @@ -600,10 +763,10 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() { s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); let columns = node(&s, id).children().unwrap().to_vec(); assert_eq!(columns.len(), 3); - for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) { + for (col, x) in columns.iter().zip([400.0, 250.0, 100.0]) { let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label())); let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect(); - assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]); + assert_eq!(ys, vec![(x, 250.0), (x, 100.0)]); assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. }))); } } 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/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(" Cell { } pub(super) fn parse_csv(csv: &str) -> (Vec, Vec, Vec>>) { + let csv = csv.strip_prefix('\u{feff}').unwrap_or(csv); // Records end at line breaks outside quotes; a record is tab-separated if it has a tab outside quotes. let rows: Vec> = split_unquoted(csv, '\n') .into_iter() @@ -169,7 +170,9 @@ pub(super) fn fmt_value(v: f64) -> String { // `{:.0}` prints its exact digits. if v.abs() < 9e18 { format!("{}", v.round() as i64) } else { format!("{v:.0}") } } else { - format!("{:.2}", v).trim_end_matches('0').trim_end_matches('.').to_string() + let s = format!("{:.2}", v).trim_end_matches('0').trim_end_matches('.').to_string(); + // A tiny negative rounds to "-0.00"; show it as plain zero like -0.0. + if s == "-0" { "0".to_string() } else { s } } } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index cc986da63d..650a4275ab 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -14,6 +14,13 @@ fn fmt_value_does_not_saturate_beyond_i64() { assert_eq!(super::fmt_value(2.5), "2.5"); } +#[test] +fn fmt_value_tiny_negative_is_zero() { + assert_eq!(super::fmt_value(-0.004), "0"); + assert_eq!(super::fmt_value(-0.0049), "0"); + assert_eq!(super::fmt_value(-0.006), "-0.01"); +} + fn graph(s: &mut Session, ty: &str) -> NodeId { let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; NodeId( @@ -4198,3 +4205,8 @@ fn character_formats_are_kept_and_bigger_labels_space_out() { } } } + +#[test] +fn csv_leading_byte_order_mark_is_ignored() { + assert_eq!(super::parse_csv("\u{feff}1,2\n3,4"), super::parse_csv("1,2\n3,4")); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index cf7c9b6b2b..25201db87e 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1167,9 +1167,11 @@ fn artboard_fit_art(s: &mut Session, p: &Value) -> 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/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 6d8e82e8d7..c41e9ce290 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. diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index c7bd4ffbfa..ce8029e71b 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -217,13 +217,15 @@ impl Session { /// After a command changed the selection, with New Art Has Basic Appearance on: the fill and /// stroke proxies and the weight take what the selection shows in them, so new art looks like /// it. A paint the selected objects don't share (a "?" proxy) stays as it was, and art without - /// paint (a placed image, whose None would make new art invisible) changes nothing. The - /// template is left alone, and without a stroke to show the weight stays too. + /// paint (a placed image that isn't colorized, whose None would make new art invisible) changes + /// nothing. The template is left alone, and without a stroke to show the weight stays too. pub(crate) fn load_selection_paints(&mut self) { if !self.prefs.new_art_basic { return; } - let has_paint = self.proxy_source(false).is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty()); + let has_paint = self + .proxy_source(false) + .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some()); if !has_paint { return; } 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/paint.rs b/crates/engine/src/cmd/paint.rs index eadf478474..4cc4bbc2e4 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, a solid color or `none` changes that object for this instance only, and a gradient or pattern is refused → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, a solid color or `none` changes that object for this instance only, and a gradient or pattern is refused", + "{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern)", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, transparency ), @@ -487,12 +487,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) s.remember_paint(&paint); return Ok(json!({"objects": ids.len()})); } - // An object of a dynamic symbol instance's art selected with Direct Selection: a solid color or - // none changes that object for this instance only, and anything else is refused. + // An object of a dynamic symbol instance's art selected with Direct Selection: that object's + // fill or stroke changes for this instance only (solid, none, gradient or pattern). if let Some((id, path)) = selected_part_target(s, p, cmd)? { - if !part_takes(&paint) { - return Err(super::brushsym::part_only()); - } super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| { if fill { o.fill = Some(paint.clone()); @@ -620,8 +617,9 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result bool { matches!(paint, Paint::Solid { .. } | Paint::None) } @@ -962,6 +960,46 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( fn transparency(s: &mut Session, p: &Value) -> Result { const C: &str = "transparency.set"; + // An object of a dynamic symbol instance's art selected with Direct Selection: opacity and + // blend change that object for this instance only. Isolate, knockout and Appearance `item` / + // `target` stay refused here (they act on the instance or a stack row). + if p.get("ids").is_none() + && p.get("id").is_none() + && p.get("item").is_none() + && let Some((id, path)) = super::brushsym::selected_part(s)? + { + for key in ["isolate", "knockout", "knockoutShape", "aligned", "target"] { + if p.get(key).is_some() { + return Err(super::brushsym::part_only()); + } + } + if p.get("opacity").is_none() && p.get("blend").is_none() { + return Err(bad(C, "give opacity or blend")); + } + check_numbers(p, &["opacity"], C)?; + let opacity = match p.get("opacity") { + None => None, + Some(Value::Null) => Some(None), + Some(v) => Some(Some(v.as_f64().map(super::opacitymask::percent).ok_or_else(|| bad(C, "opacity must be a number"))?)), + }; + let blend = match p.get("blend") { + None => None, + Some(Value::Null) => Some(None), + Some(b) => { + let name = b.as_str().ok_or_else(|| bad(C, "blend must be a mode name"))?; + Some(Some(BlendMode::parse(name).ok_or_else(|| bad(C, format!("unknown blend mode {b}")))?)) + } + }; + super::brushsym::edit_part(s, id, &path, "Transparency", |o| { + if let Some(op) = opacity { + o.opacity = op; + } + if let Some(b) = blend { + o.blend = b; + } + })?; + return ok(); + } super::opacitymask::refuse_symbol_part_unnamed(s, p)?; let ids = super::opacitymask::transparency_targets(s, p)?; if ids.is_empty() { 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..5d7f935818 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1329,7 +1329,7 @@ pub(super) fn replace_deleted_pieces(d: &mut Document, beside: &mut Beside, orig /// Remove anchors and their incident segments, keeping each surviving stretch as an open path. /// Only a closed path can have a surviving stretch that wraps past the last anchor. -fn without_anchors(sp: SubPath, removed: &BTreeSet) -> 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/plugin.rs b/crates/engine/src/cmd/plugin.rs index c2736d74dc..1cd137bddb 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -11,15 +11,18 @@ //! `document.open` reads (`fileio::plugin_formats`). //! //! A filter may ask for a heavy budget (`Budget::Heavy`: minutes rather than a minute, for routing, -//! packing or simulation). It installs only once the user agrees (`plugin.install {allowHeavy}`), -//! which loading a folder doesn't ask, so folders skip it; the app runs it in the background with -//! Cancel ([`FilterRun`]). +//! packing or simulation). It installs only once a person agrees, which loading a folder doesn't +//! ask, so folders skip it; the app runs it in the background with Cancel ([`FilterRun`]). //! -//! A plug-in whose manifest lists permissions installs once the user grants them -//! (`plugin.install {grant}`, recorded with the module's hash and kept in the plug-in store), and -//! a filter does only what they allow: without `doc.read` it is given no objects, without -//! `doc.write` an output that changes the document is refused, and without `state` it neither -//! reads nor writes the data it keeps with the document. +//! A plug-in whose manifest lists permissions installs once a person grants them (recorded with +//! the module's hash and kept in the plug-in store), and a filter does only what they allow: +//! without `doc.read` it is given no objects, without `doc.write` an output that changes the +//! document is refused, and without `state` it neither reads nor writes the data it keeps with +//! the document. +//! +//! `plugin.install {grant, allowHeavy}` takes effect only with an [`InstallApproval`], which no +//! command can set, or in a session started to accept them from requests +//! ([`Session::allow_plugin_grants_from_requests`]). //! //! A filter or a live effect may add menu commands of its own (its manifest's `commands`). Each //! is the command `plugin..` while the plug-in is installed @@ -41,7 +44,6 @@ //! images or symbol instances of those kinds, to read only: its output must return each of them //! unchanged ([`objects::decode_output_with`]). -use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; @@ -134,9 +136,9 @@ pub struct FilterRun { params: Vec, /// The objects the plug-in is given, and the container new objects go in. inputs: Vec, - /// The type, images and symbol instances among them (a filter that asks for them), as given: - /// its output must return each one unchanged. - read_only: HashMap, + /// The type, images and symbol instances among them (a filter that asks for them): its output + /// must return each one as `input` gives it. These are their places in `input`. + read_only: objects::ReadOnlySpans, parent: Option, /// The document it was made from, and that document's revision then. document: (u64, u64), @@ -270,7 +272,7 @@ impl FilterRun { fn finish(self, s: &mut Session, output: &[u8]) -> Result { let m = self.plugin.manifest(); let may = m.permissions(); - let out = objects::decode_output_with(output, &self.read_only).map_err(err)?; + let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?; if out.document_data.is_some() && !may.contains(&Permission::State) { return Err(not_granted(&m.name, Permission::State)); } @@ -431,6 +433,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { enabled: has_doc, run: unrouted, journal: true, + schema: None, })); made.push(spec); spec @@ -556,6 +559,45 @@ fn grant_param(c: &str, p: &Value) -> Result>> { Ok(Some(out)) } +/// What a person approved for one install: the module they were shown (its id, SHA-256 and the +/// permissions it lists) and whether they agreed to its heavy budget. Only the code that asked the +/// person sets it ([`Session::approve_plugin_install`]); no command can. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstallApproval { + pub id: String, + pub hash: String, + pub permissions: Vec, + pub heavy: bool, +} + +impl InstallApproval { + /// Is `plugin` the module this approval was given for? + fn covers(&self, plugin: &Plugin) -> bool { + let m = plugin.manifest(); + self.id == m.id && self.hash == plugin.hash() && self.permissions.iter().map(String::as_str).eq(permissions::names(&m.permissions())) + } +} + +impl Session { + /// Lets the next `plugin.install` take its `grant` and `allowHeavy`, for the module `approval` + /// describes. Call it only with what a person approved, just before that install. + pub fn approve_plugin_install(&mut self, approval: InstallApproval) { + self.plugin_install_approval = Some(approval); + } + + /// Drops an approval that no install has spent. + pub fn clear_plugin_install_approval(&mut self) { + self.plugin_install_approval = None; + } + + /// Makes `plugin.install` accept `grant` and `allowHeavy` from any request in this session. + /// For the person starting the process (`vectorcraft-cli --allow-plugin-grants`), never for + /// a request. + pub fn allow_plugin_grants_from_requests(&mut self) { + self.plugin_grants_from_requests = true; + } +} + /// Would installing `plugin` take another module's place: one installed with its id and other /// bytes, or, with none installed, the settings and cache the plug-in store keeps for its id? fn takes_over(s: &Session, plugin: &Plugin) -> bool { @@ -565,13 +607,17 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool { } } -/// `plugin.install`: loads and checks the module, refuses one that asks for a heavy budget unless -/// `allowHeavy` says the user agreed, one that lists permissions the user hasn't granted this very -/// module unless `grant` lists them all, one that would take another module's place ([`takes_over`]) -/// unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records the grant with -/// the module's hash, keeps it for the next start and installs it → its `plugin.list` entry. +/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an +/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget +/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this +/// very module unless `grant` lists them all, one that would take another module's place +/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records +/// the grant with the module's hash, keeps it for the next start and installs it → its +/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id. fn install(s: &mut Session, p: &Value) -> Result { const C: &str = "plugin.install"; + // One use: spent whatever this install does. + let approval = s.plugin_install_approval.take(); let replace = match p.get("replace") { None | Some(Value::Null) => None, Some(_) => Some(switch_or(p, "replace", false, C)?), @@ -600,25 +646,38 @@ fn install(s: &mut Session, p: &Value) -> Result { ), )); } - // A heavy plug-in is installed once the user agrees: whoever installs it asks them first. + // `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that. + let approval = approval.filter(|a| a.covers(&plugin)); + if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) { + return Err(bad( + C, + "`grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app", + )); + } + // A heavy plug-in is installed once a person agrees. if plugin.manifest().budget == Budget::Heavy && !allow_heavy { let (minutes, times) = vectorcraft_plugins::heavy_terms(); return Err(bad( C, format!( - "“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees", + "“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants", plugin.manifest().name ), )); } - // A plug-in that lists permissions installs once the user grants them: whoever installs it - // asks them first, unless they already granted this very module all of them. + // A plug-in that lists permissions installs once they are granted, unless a grant recorded for + // this very module already covers all of them. let m = plugin.manifest(); let wanted = m.permissions(); if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) { let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME); let asked = permissions::names(&wanted).join(", "); - return Err(bad(C, format!("“{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees"))); + return Err(bad( + C, + format!( + "“{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants" + ), + )); } // Installed plug-ins stay installed after a restart (#2541). The module is written first and its // grant only once it is there; when the grant can't be written, the store gets the module it @@ -634,6 +693,22 @@ fn install(s: &mut Session, p: &Value) -> Result { s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()); stored = false; } + } else { + // This module takes the id over, so nothing the user approved for the id applies any more. + registry::revoke(&m.id); + // When the write failed, the old stored module stays in the folder and needs its grant at + // the next launch. A grant that can't be removed still approves the old bytes, so the store + // gets the module it held back. When that module can't be read or written back, or there + // was none, no module goes with the grant, and the grant stops counting for this session. A + // grants file that is too large or doesn't hold a list approves nothing, and the new module + // stays; one that can't be opened or read may approve the old bytes once it reads again. + if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) { + let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref())); + stored = !back; + if !back || matches!(previous, Ok(None)) { + s.ignore_stored_grant(&m.id); + } + } } // It gets the settings and cache kept for its id. s.attach_plugin_storage(plugin.id()); @@ -844,19 +919,25 @@ fn remove(s: &mut Session, p: &Value) -> Result { let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); - // Its settings and cache go first: when they can't be moved aside, the plug-in stays installed, - // as it was, and a second `plugin.remove` tries again. - if (installed || stored) - && let Err(e) = s.remove_plugin_storage(id) - { + // Installed again, it asks again. A grant that can't be removed still approves the module, and + // so may a grants file that can't be opened or read. One that is too large or doesn't hold a + // list approves nothing and doesn't stop the removal. + let forget = || s.store_grant(id, None) || !s.holds_plugin_grant(id); + // Its settings and cache are moved aside and its grant removed before anything is deleted: when + // either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove` + // tries again. + let failed = if installed || stored { + s.remove_plugin_storage(id, forget).err().map(|e| e.to_string()) + } else { + (!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string()) + }; + if let Some(e) = failed { if installed { s.attach_plugin_storage(id); } - return Err(EngineError::Other(e.to_string())); + return Err(EngineError::Other(e)); } - // Installed again, it asks again. registry::revoke(id); - s.store_grant(id, None); s.unstore_plugin(id); if !stored && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); @@ -908,7 +989,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, with at most 16 MiB of pixels and 16 MiB of type runs per run (later ones come with pixelsOmitted or truncated); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}", has_doc, run ), @@ -917,7 +998,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (true once the user agreed to a heavy budget: a filter whose manifest asks for one, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (the permissions the user granted: a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; with a plug-in store attached, only the grants kept there count), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry", + "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry", always, install ), @@ -926,7 +1007,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions the user hasn't granted this very module, its bytes included: plugin.install then needs grant) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)", + "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)", always, inspect ), @@ -935,7 +1016,7 @@ pub fn specs() -> Vec { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}", always, remove ), diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 1eadc0a5a8..a0557d2134 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -227,6 +227,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ // Guides & Grid p!("guideColor", "Guides & Grid", "Guides", "Color", color), p!("guideStyle", "Guides & Grid", "Guides", "Style", choice(LINE_STYLE)), + p!("lockGuidesByDefault", "Guides & Grid", "Guides", "Lock Guides by Default", bool), p!("gridColor", "Guides & Grid", "Grid", "Color", color), p!("gridStyle", "Guides & Grid", "Grid", "Style", choice(LINE_STYLE)), p!("gridlineEvery", "Guides & Grid", "Grid", "Gridline every", len(1.0, 16383.0, General)), @@ -437,6 +438,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ // The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink. p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool), p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool), + // The bounding box and the Transform panel measure point type by its glyphs' ink (also in the Transform panel menu). + p!("typeGlyphBounds", "Type", "Glyph Bounds", "Measure Type by Glyph Bounds", bool), // Artboard Options › Global: the canvas darkens the area outside the artboards while the Artboard tool is active. p!("fadeRegionOutsideArtboard", "General", "Artboard Options", "Fade Region Outside Artboard", bool), p!("artboardUpdateWhileDragging", "General", "Artboard Options", "Update While Dragging", bool), @@ -693,10 +696,16 @@ impl Session { let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder; let hyphen_exceptions_changed = p.hyphenation_exceptions != self.prefs.hyphenation_exceptions; let corner_radius_changed = p.corner_radius != self.prefs.corner_radius; + let lock_guides_changed = p.lock_guides_by_default != self.prefs.lock_guides_by_default; if p.trace_presets != self.prefs.trace_presets { self.trace_preset_changes.replaced(); } self.prefs = p; + // Guides & Grid › Lock Guides by Default sets the lock when it changes, the saved value at + // start included. Otherwise the lock stays as View › Guides › Lock Guides left it. + if lock_guides_changed { + self.set_guides_locked(self.prefs.lock_guides_by_default); + } if corner_radius_changed { // General › Corner Radius is the Rounded Rectangle tool's radius (#394): a tool already // made (active, or lent a selection tool for a drag) takes the new value. diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs new file mode 100644 index 0000000000..8ae2a49c29 --- /dev/null +++ b/crates/engine/src/cmd/spelling.rs @@ -0,0 +1,370 @@ +//! Edit → Spelling: the words of the document's type that its dictionaries don't know +//! (`text.spelling.check`) and the words they suggest instead (`text.spelling.suggest`), checked +//! by craft-proof in each run's language +//! ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)). +//! A word is changed with `text.editRange` over the bytes the check gives. Add and Edit Custom +//! Dictionary keep words in the custom dictionary (`text.spelling.dictionary`, `addWord`, +//! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All +//! (`text.spelling.ignoreAll`) skips a word in the active document only. + +use std::collections::BTreeSet; +use std::ops::Range; +use std::sync::atomic::{AtomicU64, Ordering}; + +use craft_proof::{IssueKind, Options, ProofLang}; +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject}; + +use super::menucmds::whole_or; +use super::typemenu::{all_texts, text_ids}; +use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param}; + +/// Most unknown words one check lists; past it the result says `more`. +pub const MAX_WORDS: usize = 10_000; + +/// Most suggestions one word gets. +pub const MAX_SUGGESTIONS: u64 = 20; + +/// Longest word suggestions are looked for, in bytes: the search costs more with the length. +const MAX_WORD_LEN: usize = 128; + +/// The Edit › Spelling commands. +pub fn specs() -> Vec { + vec![ + cmd!( + query "text.spelling.check", + "Check Spelling", + [], + None, + "{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one", + has_doc, + check + ), + cmd!( + query "text.spelling.suggest", + "Spelling Suggestions", + [], + None, + "{word, max?: 1..20 (default 5), lang?: language tag (default English)} the words the dictionary of lang suggests instead of word, best first → {suggestions: [word…]}", + has_doc, + suggest + ), + cmd!( + query "text.spelling.dictionary", + "Edit Custom Dictionary", + [], + None, + "{} the words of the custom dictionary, sorted (lower case, as they are kept) → {words: [word…]}", + always, + dictionary + ), + cmd!( + query "text.spelling.addWord", + "Add to Custom Dictionary", + [], + None, + "{word} adds word (one word, at most 64 characters; kept in lower case) to the custom dictionary, which every language's check takes as right, and saves it → {word, added: bool (false: it was there already)}", + always, + add_word + ), + cmd!( + query "text.spelling.removeWord", + "Delete from Custom Dictionary", + [], + None, + "{word} deletes word from the custom dictionary and saves it (an error when it isn't there) → {word}", + always, + remove_word + ), + cmd!( + query "text.spelling.changeWord", + "Change in Custom Dictionary", + [], + None, + "{word, to} replaces word in the custom dictionary with to and saves it (an error when word isn't there) → {word: to}", + always, + change_word + ), + cmd!( + query "text.spelling.ignoreAll", + "Ignore All", + [], + None, + "{word} the active document's spelling checks skip word from now on, until it closes (not saved, not undoable) → {word}", + has_doc, + ignore_all + ), + ] +} + +/// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked +/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them. +fn check(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.check"; + // Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than + // a check of the whole document. + let ids = match p.get("ids").filter(|v| !v.is_null()) { + Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)), + None => all_texts(&s.doc()?.doc), + }; + let st = s.doc()?; + let mut words = vec![]; + let mut more = false; + for id in ids { + let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue }; + let text = t.plain_text(); + let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len()); + for m in found { + let Some(word) = text.get(m.range.clone()) else { continue }; + words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() })); + } + if cut { + more = true; + break; + } + } + Ok(json!({ "words": words, "more": more })) +} + +/// One word of a type object its dictionaries don't know ([`misspellings`]). +#[derive(Clone, Debug, PartialEq)] +pub struct Misspelling { + /// The word's bytes in the object's [`TextObject::plain_text`]. + pub range: Range, + /// The language it was checked in. + pub lang: ProofLang, +} + +/// The words of `t` its dictionaries don't know, in text order: each run checked in its +/// language, each paragraph on its own, leaving out the words in `ignored` (a document's Ignore +/// All words). At most `max` of them; the flag says the list was cut short there. What +/// `text.spelling.check` lists for one object, and what Auto Spell Check underlines. +pub fn misspellings(t: &TextObject, ignored: &BTreeSet, max: usize) -> (Vec, bool) { + let text = t.plain_text(); + // Each run in its own language, at its bytes of the plain text. + let mut spans: Vec<(Range, ProofLang)> = Vec::with_capacity(t.runs.len()); + let mut at = 0; + for r in &t.runs { + let end = at + r.text.len(); + spans.push((at..end, ProofLang::from_tag(r.style.language.as_deref()))); + at = end; + } + let opts = Options::default(); + let mut found = vec![]; + // craft-proof checks one paragraph at a time (its language detection reads the paragraph), + // and the check stops at the paragraph where the list fills up rather than proofing the rest + // of the text. + let mut para_start = 0; + for para in text.split('\n') { + let para_end = para_start + para.len(); + let para_spans: Vec<(Range, ProofLang)> = spans + .iter() + .filter_map(|(r, lang)| { + let (a, b) = (r.start.max(para_start), r.end.min(para_end)); + (a < b).then(|| (a - para_start..b - para_start, *lang)) + }) + .collect(); + for issue in craft_proof::check_text_with(para, ¶_spans, &opts, false, false) { + if issue.kind != IssueKind::Spelling { + continue; + } + let (start, end) = (para_start + issue.start, para_start + issue.end); + let Some(word) = text.get(start..end) else { continue }; + if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) { + continue; + } + if found.len() == max { + return (found, true); + } + found.push(Misspelling { range: start..end, lang: issue.lang }); + } + // Past the paragraph and its `\n`. + para_start = para_end + 1; + } + (found, false) +} + +/// Goes up each time the custom dictionary may have changed: an add, delete or change (saved or +/// not, since a save takes in the words another window saved), and a dictionary file attached. +static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0); + +/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be +/// out of date (Auto Spell Check checks the type again). +pub fn dictionary_generation() -> u64 { + DICTIONARY_GENERATION.load(Ordering::Relaxed) +} + +fn dictionary_changed() { + DICTIONARY_GENERATION.fetch_add(1, Ordering::Relaxed); +} + +/// `ids` sorted back to front, as the document paints them: by their index paths, which are in +/// paint order. +fn in_paint_order(d: &Document, mut ids: Vec) -> Vec { + let paths = d.index_paths(ids.iter().copied()); + ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b))); + ids +} + +/// `text.spelling.suggest`: up to `max` of the words the dictionary of `lang` suggests for `word`. +fn suggest(_s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.suggest"; + let word = str_param(p, "word").map(str::trim).filter(|w| !w.is_empty()).ok_or_else(|| bad(C, "missing `word`"))?; + let max = whole_or(p, "max", 5, C)?; + if !(1..=MAX_SUGGESTIONS).contains(&max) { + return Err(bad(C, format!("`max` must be 1 to {MAX_SUGGESTIONS}"))); + } + if word.len() > MAX_WORD_LEN { + return Ok(json!({ "suggestions": [] })); + } + let lang = ProofLang::from_tag(str_param(p, "lang")); + // `max` is at most MAX_SUGGESTIONS, so it fits. + let suggestions = craft_proof::suggest_in(word, usize::try_from(max).unwrap_or(5), lang); + Ok(json!({ "suggestions": suggestions })) +} + +/// `p`'s `key` as a custom-dictionary word (trimmed, lower case), or an error naming what it must be. +fn word_param(p: &Value, key: &str, command: &str) -> Result { + let w = str_param(p, key).ok_or_else(|| bad(command, format!("missing `{key}`")))?; + craft_proof::custom_word(w) + .ok_or_else(|| bad(command, format!("`{key}` must be one word of at most {} characters", craft_proof::MAX_CUSTOM_WORD_CHARS))) +} + +/// Largest custom dictionary file taken in, in bytes: craft-proof reads no more of one (its +/// `MAX_CUSTOM_FILE_BYTES`), so a larger file would lose its other words when written back. +pub const MAX_DICTIONARY_FILE_BYTES: u64 = 1_000_000; + +/// Whether the custom dictionary file at `path` can be written over without losing words: it is +/// missing (a first save creates it), or a file that can be read whole. Otherwise why not. +fn dictionary_file_readable(path: &std::path::Path) -> std::result::Result<(), String> { + match std::fs::metadata(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.to_string()), + Ok(m) if !m.is_file() => Err("it isn't a file".into()), + Ok(m) if m.len() > MAX_DICTIONARY_FILE_BYTES => Err(format!("it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes")), + Ok(_) => { + // Read it whole, as craft-proof will: a file that opens but then can't be read would + // read as no words there. + use std::io::Read; + let mut bytes = Vec::new(); + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + file.take(MAX_DICTIONARY_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > MAX_DICTIONARY_FILE_BYTES { + return Err(format!("it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes")); + } + Ok(()) + } + } +} + +/// After a failed save took a command's change back: take in the words the file holds again, so +/// a word another window saved meanwhile, which the change had added too, stays. +fn retake_file_words(s: &Session) { + if let Some(path) = s.dictionary_file.as_deref().filter(|p| dictionary_file_readable(p).is_ok()) { + craft_proof::load_user_dictionary(path); + } +} + +/// Write the custom dictionary to its file when the session has one, leaving out `removed`. A file +/// that is there but can't be read whole is left alone rather than written over with only the +/// words read. On an error the caller takes its own change back, so memory and file agree. +fn save_dictionary(s: &Session, removed: &[String], command: &str) -> Result<()> { + let Some(path) = &s.dictionary_file else { return Ok(()) }; + if let Err(why) = dictionary_file_readable(path) { + return Err(bad(command, format!("the custom dictionary {} can't be read ({why}), so it is left as it is", path.display()))); + } + craft_proof::save_user_dictionary(path, removed) + .map_err(|e| bad(command, format!("the custom dictionary couldn't be saved to {}: {e}", path.display()))) +} + +/// `text.spelling.dictionary`: the custom dictionary's words. +fn dictionary(_s: &mut Session, _p: &Value) -> Result { + Ok(json!({ "words": craft_proof::user_dictionary() })) +} + +/// `text.spelling.addWord`: Add, and Edit Custom Dictionary's Add. +fn add_word(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.addWord"; + let word = word_param(p, "word", C)?; + let added = !craft_proof::user_dictionary().contains(&word); + craft_proof::add_word(&word); + let saved = save_dictionary(s, &[], C); + dictionary_changed(); + saved.inspect_err(|_| { + // Only this command's word: words the save took in from the file stay. + if added { + craft_proof::remove_word(&word); + retake_file_words(s); + } + })?; + Ok(json!({ "word": word, "added": added })) +} + +/// `text.spelling.removeWord`: Edit Custom Dictionary's Delete. +fn remove_word(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.removeWord"; + let word = word_param(p, "word", C)?; + if !craft_proof::remove_word(&word) { + return Err(bad(C, format!("`{word}` isn't in the custom dictionary"))); + } + let saved = save_dictionary(s, std::slice::from_ref(&word), C); + dictionary_changed(); + saved.inspect_err(|_| craft_proof::add_word(&word))?; + Ok(json!({ "word": word })) +} + +/// `text.spelling.changeWord`: Edit Custom Dictionary's Change. +fn change_word(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.changeWord"; + let word = word_param(p, "word", C)?; + let to = word_param(p, "to", C)?; + if !craft_proof::user_dictionary().contains(&word) { + return Err(bad(C, format!("`{word}` isn't in the custom dictionary"))); + } + if word == to { + let saved = save_dictionary(s, &[], C); + dictionary_changed(); + saved?; + return Ok(json!({ "word": to })); + } + let to_is_new = !craft_proof::user_dictionary().contains(&to); + craft_proof::remove_word(&word); + craft_proof::add_word(&to); + let saved = save_dictionary(s, std::slice::from_ref(&word), C); + dictionary_changed(); + saved.inspect_err(|_| { + if to_is_new { + craft_proof::remove_word(&to); + retake_file_words(s); + } + craft_proof::add_word(&word); + })?; + Ok(json!({ "word": to })) +} + +/// `text.spelling.ignoreAll`: Ignore All, for the active document. +fn ignore_all(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.ignoreAll"; + let word = word_param(p, "word", C)?; + // Not a change to the document, so its revision stays: a tool edit computed meanwhile still + // applies (`command_sweep`'s check of commands that don't wait for one). + s.doc_mut()?.spelling_ignored.insert(word.clone()); + Ok(json!({ "word": word })) +} + +impl Session { + /// Keep the custom dictionary in the file at `path` (the desktop app's, beside its + /// preferences), and take in the words already there. A missing file reads as no words and is + /// created by the first save. A file that is there but can't be read whole is logged and left + /// as it is: changes to the dictionary are refused rather than written over it. + pub fn attach_custom_dictionary(&mut self, path: std::path::PathBuf) { + match dictionary_file_readable(&path) { + Ok(()) => { + craft_proof::load_user_dictionary(&path); + } + Err(why) => log::warn!("not reading the custom dictionary {}: {why}; it is left as it is", path.display()), + } + self.dictionary_file = Some(path); + dictionary_changed(); + } +} diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index a2c4b0bdb8..1e74eb4563 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -2,7 +2,7 @@ //! of symbols the library panel shows. A library is a document holding the symbols with the //! resources they use (nested symbols, patterns, swatches, brushes, graphic styles, images) and //! their Symbol Options; saved, it is a native `.vectorcraft` file, which File › Open also opens. -//! The built-in library is generated here ([`BUILTIN`]); User Defined ones are the `.vectorcraft` +//! The built-in libraries are generated here ([`BUILTIN`]); User Defined ones are the `.vectorcraft` //! files in the user library folder ([`Libraries`]), and Other Library… loads the symbols of any //! document VectorCraft opens. `symbol.addFromLibrary` copies symbols into the document; //! `symbol.saveLibrary` writes the document's. @@ -12,7 +12,7 @@ use std::sync::{Arc, LazyLock}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice}; use vectorcraft_geom::{Affine, Point, Rect, shapes}; use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size}; @@ -154,7 +154,10 @@ pub struct BuiltinSymbolLibrary { } /// The built-in symbol libraries, in menu order: original art generated in code. -pub const BUILTIN: &[BuiltinSymbolLibrary] = &[BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes }]; +pub const BUILTIN: &[BuiltinSymbolLibrary] = &[ + BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes }, + BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames }, +]; /// Built-in library `id`, made once. fn builtin_library(id: &str) -> Option> { @@ -194,6 +197,30 @@ fn basic_shapes() -> SymbolLibrary { SymbolLibrary { name: "Basic Shapes".into(), doc } } +/// UI Frames: panel, button and bar HUD chrome with default 9-slice guides (original art). +fn ui_frames() -> SymbolLibrary { + // Heights keep default 9-slice (0.25) past each corner radius so a vertical resize + // stretches only the flat middle, not the curves. + let frames = [ + ("Panel", Rect::new(-48.0, -36.0, 48.0, 36.0), 10.0, "#2b3340", "#8aa0b8"), + ("Button", Rect::new(-36.0, -18.0, 36.0, 18.0), 8.0, "#3a6ea5", "#d7e6f5"), + ("Bar", Rect::new(-56.0, -24.0, 56.0, 24.0), 10.0, "#1f6b4a", "#b7e0c9"), + ]; + let mut doc = Document::new(100.0, 100.0); + for (name, rect, radius, fill_hex, edge_hex) in frames { + let fill = Color::from_hex(fill_hex).unwrap_or(Color::BLACK); + let edge = Color::from_hex(edge_hex).unwrap_or(Color::BLACK); + let id = doc.alloc_id(); + let art = Node::path(id, shapes::rounded_rectangle(rect, radius), Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.5)); + let Ok((art, size, _)) = normalize(art) else { continue }; + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(&mut doc, name, Some(size)); + doc.set_symbol_nine_slice(name, Some(SymbolNineSlice::default())); + } + doc.title = "UI Frames".into(); + SymbolLibrary { name: "UI Frames".into(), doc } +} + /// An instance of symbol `name` (what the resource gathering follows). fn instance(name: &str) -> Node { Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) 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..a4fe337626 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -304,6 +304,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); t.cached_baselines = lay.baselines(); + t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); } /// [`refresh_bounds`] for a document that is opening: the first frame takes the layout @@ -315,6 +316,7 @@ pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); t.cached_baselines = lay.baselines(); + t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); vectorcraft_text::keep_layout(t, stamp, lay); } diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 0b0ea10420..8d40002b3d 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -718,7 +718,9 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, /// The text objects Find and Replace and Find Next reach: on visible, unlocked layers, and not /// inside a hidden or locked group, which hides or locks what it holds as a layer does (#5900). -fn all_texts(d: &Document) -> Vec { +/// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint +/// order: the text Find and Replace and Check Spelling go through. +pub(crate) fn all_texts(d: &Document) -> Vec { fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec) { if !n.visible || n.locked { return; 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/doc_state.rs b/crates/engine/src/doc_state.rs index e70bf5c2d8..736b873d06 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -58,6 +58,9 @@ pub struct DocState { /// View Opacity Mask (Alt-click the mask thumbnail): the masked object whose mask the canvas /// shows alone, in greyscale, while that mask is edited (see [`DocState::shown_mask`]). pub mask_view: Option, + /// Check Spelling's Ignore All: the words (as craft-proof keys them, lower case) a spelling + /// check of this document skips. Kept while the document is open: not saved, not undoable. + pub spelling_ignored: std::collections::BTreeSet, /// View → Show Transparency Grid, per document (saved view state, not undoable). pub transparency_grid: bool, /// The format Save writes ([`cmd::fileio::SAVE_FORMATS`]): the one the document was opened @@ -109,6 +112,8 @@ pub struct DocState { pub opened_by: Option>, /// 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 @@ -121,10 +126,25 @@ struct EmptyArtboards { any: bool, } +/// Whether an unlocked artboard of those asked about has art that Fit to Artwork Bounds fits it +/// to, with what was measured: the document (held as [`EmptyArtboards::doc`] holds it), the +/// artboards, and the generations of what the measure reads outside the document. One is kept for +/// each open document, and its weak reference keeps the measured document's allocation (not its +/// contents) until the next measure or until the document closes. +#[derive(Clone, Debug)] +struct ArtToFit { + doc: std::sync::Weak, + 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); @@ -288,6 +308,7 @@ impl DocState { uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), opened_as_tab: true, mask_view: None, + spelling_ignored: Default::default(), transparency_grid, format: "vectorcraft", save_options: Default::default(), @@ -305,6 +326,7 @@ impl DocState { last_perspective: None, opened_by: file_access::current(), empty_artboards: Default::default(), + art_to_fit: Default::default(), } } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, @@ -319,6 +341,38 @@ impl DocState { } last.any } + /// Whether an unlocked artboard of `indices` has art that Fit to Artwork Bounds fits it to. A + /// menu asks on every frame it is open, and measuring builds the solids of 3D effects, so the + /// answer is kept for this version of the document and those artboards, and a change of the + /// selection or the view keeps it. It is measured again when what the measure reads outside the + /// document changes: the installed plug-ins, whose effects draw art, and the installed fonts, + /// which set the bounds of all type. + pub fn any_art_to_fit(&self, indices: &[usize]) -> bool { + self.any_art_to_fit_with(indices, (vectorcraft_plugins::registry::revision(), vectorcraft_text::FontDb::global().generation())) + } + /// [`Self::any_art_to_fit`], with `outside` the generations of the plug-ins and the fonts. + pub(crate) fn any_art_to_fit_with(&self, indices: &[usize], outside: (u64, u64)) -> bool { + // Measuring runs renderer and plug-in code; should it ever ask again while measuring, it + // is measured without being kept rather than borrowed twice. + let Ok(mut last) = self.art_to_fit.try_borrow_mut() else { + let mut r = vectorcraft_render::Renderer::new(); + return indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some()); + }; + if let Some(k) = last.as_ref() + && std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) + && k.indices == indices + && k.outside == outside + { + return k.any; + } + #[cfg(test)] + ART_TO_FIT_MEASURES.with(|c| c.set(c.get() + 1)); + // One renderer measures every artboard: each object once. + let mut r = vectorcraft_render::Renderer::new(); + let any = indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some()); + *last = Some(ArtToFit { doc: Arc::downgrade(&self.doc), indices: indices.to_vec(), outside, any }); + any + } /// Unsaved changes: the document differs from the saved one (selection changes and changes that /// are not edits to save don't count, [`DocState::same_content`]). pub fn is_dirty(&self) -> bool { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b6e404e8b1..eaa0e7b574 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; @@ -148,15 +149,28 @@ pub struct Session { /// Where the saved PDF presets are kept, one file each; `None`: only for the session /// ([`Session::attach_pdf_preset_store`]). pdf_preset_dir: Option, + /// The custom dictionary file Edit › Spelling › Add and Edit Custom Dictionary save to; `None`: + /// the words are kept only for the process ([`Session::attach_custom_dictionary`]). + dictionary_file: Option, /// Where the ICC profiles `color.loadProfile` loads are kept; `None`: only for the process /// ([`Session::attach_profile_store`]). profile_dir: Option, /// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process /// ([`Session::attach_plugin_store`]). plugin_dir: Option, + /// The plug-in ids whose grant in the plug-in store should be gone but could not be removed: + /// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful + /// [`Session::store_grant`] for the id takes it out. + ignored_plugin_grants: std::sync::Mutex>, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option, + /// What a person approved for the next `plugin.install` ([`Session::approve_plugin_install`]); + /// that install spends it, whatever it does. + plugin_install_approval: Option, + /// `plugin.install` takes `grant` and `allowHeavy` from any request + /// ([`Session::allow_plugin_grants_from_requests`]). + plugin_grants_from_requests: bool, /// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved. pub recent_urls: Vec, /// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]). diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d3b0345264..603fa9028a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -41,6 +41,12 @@ pub struct Prefs { /// Align panel menu › Align to Glyph Bounds › Area Text: the same for area type, instead of /// its frame. pub align_glyph_bounds_area: bool, + /// Preferences › Type › Glyph Bounds › Measure Type by Glyph Bounds (also in the Transform + /// panel menu): the bounding box, the Transform panel's, Control bar's and Properties panel's X, + /// Y, W and H, and `object.setBounds` measure each point type object selected as an object (not + /// inside a selected group) by the ink of its glyphs instead of its em box + /// ([`crate::Session::bounds_measure`]). + pub type_glyph_bounds: bool, /// Artboard Options › Fade Region Outside Artboard: while the Artboard tool is active, the /// canvas draws everything outside the artboards darker, the pasteboard and the art on it. pub fade_region_outside_artboard: bool, @@ -114,6 +120,8 @@ pub struct Prefs { // Guides & Grid pub guide_color: String, pub guide_style: String, + /// Lock Guides by Default: the app starts with View › Guides › Lock Guides on. + pub lock_guides_by_default: bool, pub grid_color: String, pub grid_style: String, pub gridline_every: f64, @@ -370,6 +378,7 @@ impl Default for Prefs { use_preview_bounds: false, align_glyph_bounds_point: false, align_glyph_bounds_area: false, + type_glyph_bounds: false, fade_region_outside_artboard: true, artboard_update_while_dragging: true, display_print_size: false, @@ -421,6 +430,7 @@ impl Default for Prefs { identify_objects_by: s("objectName"), guide_color: s("#4affff"), guide_style: s("lines"), + lock_guides_by_default: false, grid_color: s("#c8c8c8"), grid_style: s("lines"), gridline_every: 72.0, 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/session/documents.rs b/crates/engine/src/session/documents.rs index 64f451adc9..208088a4cd 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -80,9 +80,13 @@ impl Session { brush_libraries: Default::default(), libraries: Default::default(), pdf_preset_dir: None, + dictionary_file: None, profile_dir: None, plugin_dir: None, + ignored_plugin_grants: Default::default(), plugin_output: None, + plugin_install_approval: None, + plugin_grants_from_requests: false, recent_urls: vec![], trace_preset_changes: Default::default(), ui_language: None, diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 1a60c21019..81c839068e 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -60,6 +60,11 @@ impl Session { if !self.replaying { self.check_params(id, params)?; } + // A command with a parameter schema runs only with params that pass it, and with the + // defaults of omitted values filled in; the journal keeps the params as given. Saved steps + // keep their keys the schema doesn't name, as above. + let checked = crate::schemas::check(spec, params, self.replaying)?; + let run_params = checked.as_ref().unwrap_or(params); // Objects given as `id` (where it stands for `ids` of one) or as `ids` beside it are checked // before anything else: a malformed one, or one naming no object, is an error under this // command's id, never the selection in its place. `effect.apply {id: "stylize.dropShadow"}` @@ -126,7 +131,7 @@ impl Session { if let Some(ids) = &select_first { s.execute("select.set", &serde_json::json!({ "ids": ids }))?; } - let r = cmd::run_spec(s, spec, params); + let r = cmd::run_spec(s, spec, run_params); if r.is_err() && let Some((uid, selection, layer)) = selected_before && let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid) diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index dcf7edadf9..ae98bdf4fa 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -28,7 +28,7 @@ //! The files are untrusted input like any other: sizes and counts are capped, a file that does not //! parse is skipped with a log record, and every write is atomic. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -62,6 +62,8 @@ pub const DISABLED_FILE: &str = "disabled.json"; pub const DISABLED_LOCK: &str = "disabled.lock"; /// The file in the plug-in store that holds the permissions the user granted. const GRANTS_FILE: &str = "grants.json"; +/// The error of a `plugin.remove` that can't remove the plug-in's grant from [`GRANTS_FILE`]. +pub(crate) const GRANT_NOT_REMOVED: &str = "the plug-in's grant can't be removed from the plug-in store"; /// The largest grants file read. const MAX_GRANTS_FILE: u64 = 1 << 20; /// The folder in the plug-in store that holds each plug-in's settings and cache. @@ -110,15 +112,21 @@ fn list_files(dir: &Path, ext: &str) -> Vec { /// The content of `path` when it is at most `max` bytes; the file is never read past `max`. pub(crate) fn read_capped(path: &Path, max: u64) -> Result, String> { - let file = std::fs::File::open(path).map_err(|e| e.to_string())?; - let mut bytes = vec![]; - file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?; if bytes.len() as u64 > max { return Err(too_large(max)); } Ok(bytes) } +/// The first `max + 1` bytes of `path` at most, so that a result longer than `max` shows the file is +/// over its cap. +fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { + let mut bytes = vec![]; + std::fs::File::open(path)?.take(max + 1).read_to_end(&mut bytes)?; + Ok(bytes) +} + /// What a file over its cap is told (a detail after the file's name, in the log or an error). fn too_large(max: u64) -> String { format!("larger than {max} bytes") @@ -168,13 +176,21 @@ fn lock_disabled(_: &Path) -> Option { None } -/// Remove `dir/file`; a file that isn't there is what was wanted. -fn take(dir: &Path, file: &str) { +#[cfg(test)] +thread_local! { + /// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume. + pub(crate) static PUT_BACK_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted. +fn take(dir: &Path, file: &str) -> bool { let path = dir.join(file); - if let Err(e) = std::fs::remove_file(&path) - && e.kind() != std::io::ErrorKind::NotFound - { - log::warn!("can't remove {}: {e}", path.display()); + match std::fs::remove_file(&path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + log::warn!("can't remove {}: {e}", path.display()); + false + } + _ => true, } } @@ -283,6 +299,9 @@ impl Session { let disabled = read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); safe_mode::set_disabled(disabled); + if self.plugin_dir.as_ref() != Some(&dir) { + self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } self.plugin_dir = Some(dir); self.load_stored_plugins(); } @@ -291,15 +310,18 @@ impl Session { /// disabled (matched by file name, which is made from the id). The launch marker names each /// file while it loads. A module that doesn't load, and one that lists permissions the grants /// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and - /// stays in the folder with its grant. + /// stays in the folder with its grant. A grant for an id whose stored module lists no + /// permissions is forgotten; one that can't be removed from the grants file doesn't count for + /// the rest of the session ([`Session::plugin_approver`]). pub fn load_stored_plugins(&mut self) { let Some(dir) = self.plugin_dir.clone() else { return }; if safe_mode::active() { return; } - let grants = stored_grants(&dir); + let grants = self.counted_grants(&dir); let limits = vectorcraft_plugins::Limits::default(); let mut left = MAX_PLUGIN_STORE; + let mut asks_nothing = BTreeSet::new(); for path in list_files(&dir, PLUGIN_EXT) { if left == 0 { log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together"); @@ -325,6 +347,7 @@ impl Session { let m = plugin.manifest(); match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) { Some(g) => { + asks_nothing.remove(&m.id); vectorcraft_plugins::registry::grant(g.clone()); vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id)); vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())); @@ -335,12 +358,24 @@ impl Session { } } Ok(plugin) => { + asks_nothing.insert(plugin.id().to_string()); vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id())); vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())); } Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), } } + let kept = read_grants(&dir); + for id in &asks_nothing { + vectorcraft_plugins::registry::revoke(id); + let named = match &kept { + Ok(file) => file.names(id), + Err(e) => e.unread, + }; + if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) { + self.ignore_stored_grant(id); + } + } } /// Write the disabled plug-ins saved for the next launch to the plug-in folder → whether they @@ -379,7 +414,8 @@ impl Session { /// Whether `plugin` installs without asking the user: it lists no permissions, or this very /// module (its id and SHA-256) was granted every one it lists, in the grants of the attached - /// plug-in store when there is one ([`grant_covers`]), else in this process's + /// plug-in store when there is one ([`grant_covers`]), not counting a grant that should be gone + /// and could not be removed ([`Session::ignore_stored_grant`]), else in this process's /// ([`vectorcraft_plugins::registry::approved`]). pub(crate) fn plugin_approved(&self, plugin: &vectorcraft_plugins::Plugin) -> bool { self.plugin_approver()(plugin) @@ -388,7 +424,7 @@ impl Session { /// [`Session::plugin_approved`] for many plug-ins: reads the store's grants once, when it is /// made, and checks each plug-in against them. pub(crate) fn plugin_approver(&self) -> impl Fn(&vectorcraft_plugins::Plugin) -> bool + use<> { - let grants = self.plugin_dir.as_deref().map(stored_grants); + let grants = self.plugin_dir.as_deref().map(|dir| self.counted_grants(dir)); move |plugin| { let m = plugin.manifest(); match &grants { @@ -398,6 +434,15 @@ impl Session { } } + /// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session + /// doesn't count ([`Session::ignore_stored_grant`]). + fn counted_grants(&self, dir: &Path) -> BTreeMap { + let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()); + let mut grants = stored_grants(dir); + grants.retain(|id, _| !ignored.contains(id)); + grants + } + /// Write the module `bytes` of the plug-in `id` to the store → whether they went there (`false` /// without a folder). pub(crate) fn store_plugin(&self, id: &str, bytes: &[u8]) -> bool { @@ -417,12 +462,15 @@ impl Session { } /// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a - /// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. - pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) { + /// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the + /// store now holds `previous`. + pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool { + #[cfg(test)] + if PUT_BACK_FAILS.get() { + return false; + } match previous { - Some(bytes) => { - self.store_plugin(id, bytes); - } + Some(bytes) => self.store_plugin(id, bytes), None => self.unstore_plugin(id), } } @@ -438,13 +486,29 @@ impl Session { /// are written back as they were, except one for `id`. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now - /// holds what was asked (`false` without a folder). + /// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts + /// again ([`Session::ignore_stored_grant`]). pub(crate) fn store_grant(&self, id: &str, grant: Option) -> bool { + let done = self.write_grant(id, grant); + if done { + self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id); + } + done + } + + /// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next + /// succeeds for it or another store is attached: for a grant that should be gone and could not + /// be removed, which would otherwise approve the bytes it covers. + pub(crate) fn ignore_stored_grant(&self, id: &str) { + self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string()); + } + + fn write_grant(&self, id: &str, grant: Option) -> bool { let Some(dir) = &self.plugin_dir else { return false }; let mut file = match read_grants(dir) { Ok(file) => file, Err(e) => { - log::warn!("not updating the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); return false; } }; @@ -460,8 +524,7 @@ impl Session { let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); if entries.is_empty() { - take(dir, GRANTS_FILE); - return true; + return take(dir, GRANTS_FILE); } // The file is read back only up to its cap: written compactly when pretty-printed is larger, // and not at all when that is too. @@ -475,11 +538,20 @@ impl Session { } } - /// Remove the plug-in `id` from the store. - pub(crate) fn unstore_plugin(&self, id: &str) { - if let Some(dir) = &self.plugin_dir { - take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id))); - } + /// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this + /// version can't use ([`GrantsFile::names`]). `true` when the grants file can't be opened or + /// read, because it may name `id` once it reads again; `false` without a folder, and when the + /// file is too large or doesn't hold a list. + pub(crate) fn holds_plugin_grant(&self, id: &str) -> bool { + self.plugin_dir.as_deref().is_some_and(|dir| match read_grants(dir) { + Ok(file) => file.names(id), + Err(e) => e.unread, + }) + } + + /// Remove the plug-in `id` from the store → whether its file is gone (`false` without a folder). + pub(crate) fn unstore_plugin(&self, id: &str) -> bool { + self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)))) } /// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without @@ -500,10 +572,15 @@ impl Session { /// Delete the settings and cache of plug-in `id` from the store, and stop keeping any for it. /// The folder is first renamed out of the way (`.removed`), and that fails, leaving it /// as it was, when the rename does; what the deletion then leaves stays under that name, with a - /// log record. A later call for the id tries to delete it again. - pub(crate) fn remove_plugin_storage(&self, id: &str) -> Result<(), StorageError> { + /// log record. A later call for the id tries to delete it again. `forget` runs once the folder is + /// out of the way, before anything is deleted: when it returns `false`, the folder is renamed + /// back and this fails. + pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> { + let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string()); vectorcraft_plugins::registry::set_storage(id, None); - let Some(dir) = &self.plugin_dir else { return Ok(()) }; + let Some(dir) = &self.plugin_dir else { + return if forget() { Ok(()) } else { Err(not_forgotten()) }; + }; let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let path = plugin_data_dir(dir, id); // Every storage handed out for the folder, including those runs still hold, is closed once @@ -518,6 +595,9 @@ impl Session { let data = dir.join(PLUGIN_DATA_DIR); if is_link(&data) { log::warn!("{} is a link: the plug-in settings and cache it leads to are left", data.display()); + if !forget() { + return Err(not_forgotten()); + } close(); return Ok(()); } @@ -530,6 +610,14 @@ impl Session { Err(e) => return Err(StorageError::Io(format!("{}: {e}", path.display()))), Ok(()) => {} } + if !forget() { + if std::fs::symlink_metadata(&aside).is_ok() + && let Err(e) = std::fs::rename(&aside, &path) + { + log::warn!("can't move {} back: {e}", aside.display()); + } + return Err(not_forgotten()); + } close(); if std::fs::symlink_metadata(&aside).is_ok() && let Err(e) = std::fs::remove_dir_all(&aside) @@ -960,16 +1048,36 @@ struct GrantsFile { other: Vec, } +impl GrantsFile { + /// Whether the file has an entry for the plug-in `id`, usable by this version or not. + fn names(&self, id: &str) -> bool { + self.grants.contains_key(id) || self.other.iter().any(|e| e.get("id").and_then(serde_json::Value::as_str) == Some(id)) + } +} + +/// Why the grants file of a plug-in store gave no grants. +struct GrantsError { + /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is + /// too large or doesn't hold a list, and approves nothing. + unread: bool, + /// The detail for a log record. + why: String, +} + /// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too /// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an /// invalid id, is kept in [`GrantsFile::other`] with a log record. -fn read_grants(dir: &Path) -> Result { +fn read_grants(dir: &Path) -> Result { let path = dir.join(GRANTS_FILE); - if !path.exists() { - return Ok(GrantsFile::default()); + let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(GrantsFile::default()), + Err(e) => return Err(GrantsError { unread: true, why: e.to_string() }), + }; + if bytes.len() as u64 > MAX_GRANTS_FILE { + return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } - let entries = - read_capped(&path, MAX_GRANTS_FILE).and_then(|bytes| serde_json::from_slice::>(&bytes).map_err(|e| e.to_string()))?; + let entries = serde_json::from_slice::>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?; let mut file = GrantsFile::default(); let mut first_error = None; for entry in entries { @@ -997,7 +1105,7 @@ fn stored_grants(dir: &Path) -> BTreeMap file.grants, Err(e) => { - log::warn!("skipping the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); BTreeMap::new() } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 742d7a3ac0..6063feab45 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -158,6 +158,7 @@ mod simplify_part; mod slices; mod smartguides; mod smooth_path; +mod spelling; mod store; mod strokegeom; mod strokegradient; @@ -185,6 +186,7 @@ mod transformfx; mod transparencygrid; mod trap; mod typearea; +mod typeglyphbounds; mod typescale; mod typeundo; mod units; diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 467dd40524..158cf21ad0 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"); diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index 2dba3f6e00..c71014eb1c 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -173,6 +173,22 @@ fn blend_recolors_a_colorized_gray_image_without_alpha() { assert_eq!(colorize(&s, middle), Some(Paint::solid(Color::rgb(0.5, 0.5, 0.5)))); } +/// A colorized image shows a fill and no stroke, so selecting it loads them for new art as any +/// object without a stroke does (the weight stays). +#[test] +fn selecting_a_colorized_image_gives_new_art_its_fill_and_no_stroke() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 5.0})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(s.paint.fill.color().map(|c| c.to_hex()), Some("#336699".into())); + assert_eq!((s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, 5.0)); +} + #[test] fn fill_proxy_invert_recolors_a_colorized_gray_image_and_undo_restores_it() { let mut s = session(); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 7a05a58964..c0946a465d 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2698,19 +2698,15 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() { assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1), (0, 2)].into()); s.execute("edit.copy", &json!({})).unwrap(); assert_eq!(pasted(&mut s), [2]); - // Cut takes the segment between them. The two surviving runs of an ordinary path - // become independent objects, and this path keeps the first run (#3380). + // Cut takes the two anchors out of the path, as Clear does (#6361): each side keeps one + // anchor, which makes no path, so nothing is left. s.execute("edit.undo", &json!({})).unwrap(); let original = path(&s, id); let picked = s.doc().unwrap().selection.clone(); s.execute("edit.cut", &json!({})).unwrap(); let left = paths(&s); - assert_eq!(left.len(), 2); - assert_eq!(left[0].0, id); - assert!(left.iter().all(|(_, p)| p.subpaths.len() == 1 && !p.subpaths[0].closed)); - assert_eq!(left[0].1.subpaths[0].anchors, original.subpaths[0].anchors[..2]); - assert_eq!(left[1].1.subpaths[0].anchors, original.subpaths[0].anchors[2..]); - assert_eq!(s.doc().unwrap().selection.objects, left.iter().map(|(id, _)| *id).collect::>()); + 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/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index b946f7192a..eab2f30675 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1,7 +1,7 @@ //! Dynamic symbols (#4938): an instance changes the appearance of objects in its symbol's art and //! stays linked; editing the symbol keeps those changes, Reset and Break Link handle them. Direct -//! Selection picks one path, compound path or type object of an instance's art, and a solid color -//! Fill or Stroke changes it. +//! Selection picks one path, compound path or type object of an instance's art, and Fill, Stroke, +//! opacity and blend change it for that instance. use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; @@ -51,8 +51,9 @@ fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] { const RED: [u8; 4] = [255, 0, 0, 255]; const BLUE: [u8; 4] = [0, 0, 255, 255]; -/// The refusal of anything but a solid fill or stroke on a picked object says so. -const REFUSED: &str = "solid color fill and stroke"; +/// The refusal of a change that is not fill, stroke, opacity or blend on a picked path, compound +/// path or type (or of selecting any other kind of object) says so. +const REFUSED: &str = "fill, stroke, opacity and blend"; #[test] fn a_dynamic_instance_paints_one_object_its_own_way_and_stays_linked() { @@ -655,8 +656,7 @@ fn commands_on_the_selection_leave_a_picked_objects_instance_alone() { ("object.repeat.release", json!({})), ("object.intertwine.release", json!({})), ("object.objectsOnPath.expand", json!({})), - ("transparency.set", json!({"opacity": 50})), - ("transparency.set", json!({"blend": "multiply"})), + ("transparency.set", json!({"opacity": 50, "isolate": true})), ("transparency.releaseOpacityMask", json!({})), ("transparency.setOpacityMask", json!({"invert": true, "clip": false})), ("transparency.disableOpacityMask", json!({})), @@ -858,38 +858,30 @@ fn a_press_on_an_image_of_the_art_is_refused_and_moves_nothing() { assert_eq!(overrides(&s, inst), 0); } -/// A gradient or pattern for a picked object is refused and changes nothing, new art's paint -/// included. An object that shows a gradient takes a solid color. +/// A gradient or pattern for a picked object is stored on the instance; Invert, Complement and the +/// gradient annotator stay refused. An object that shows a gradient takes a solid color. #[test] -fn gradients_and_patterns_on_a_picked_object_are_refused() { +fn gradients_and_patterns_on_a_picked_object_are_taken() { let mut s = session(); let inst = pair(&mut s, "dynamic"); let g = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}); s.execute("swatch.new", &json!({"name": "Ramp", "gradient": g})).unwrap(); let tile = square(&mut s, 150.0); s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Dots", "edit": false})).unwrap(); - // An object to sample a gradient from. let far = square(&mut s, 150.0); s.execute("paint.setFill", &json!({"ids": [far.0], "gradient": g})).unwrap(); s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); - let undo = undo_steps(&s); - let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone()); - for (cmd, p) in [ - ("paint.setFill", json!({"gradient": g})), - ("paint.setStroke", json!({"gradient": g})), - ("paint.setFill", json!({"gradient": g, "span": "selection"})), - ("paint.setFill", json!({"swatch": "Ramp"})), - ("paint.setFill", json!({"swatch": "Dots"})), - ("appearance.copyFrom", json!({"source": far.0})), - ] { - let e = s.execute(cmd, &p).unwrap_err().to_string(); - assert!(e.contains(REFUSED), "{cmd} {p}: {e}"); - } - assert_eq!((overrides(&s, inst), undo_steps(&s)), (0, undo), "nothing changes"); - assert_eq!((&s.paint.fill, &s.paint.stroke), (&fill, &stroke), "new art keeps its paint"); - // An object whose art has a gradient takes a solid color; Invert, Complement and selecting one - // of its stops are refused. - s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": {"gradient": g}})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": g})).unwrap(); + assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_)))); + s.execute("paint.setStroke", &json!({"gradient": g})).unwrap(); + assert!(matches!(node(&s, inst).extras().symbol_overrides[0].stroke, Some(Paint::Gradient(_)))); + s.execute("paint.setFill", &json!({"swatch": "Ramp"})).unwrap(); + assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_)))); + s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap(); + assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Pattern { .. }))); + s.execute("appearance.copyFrom", &json!({"source": far.0})).unwrap(); + assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_)))); + // Invert, Complement and selecting a stop are refused on a gradient. for cmd in ["paint.invert", "paint.complement"] { let e = s.execute(cmd, &json!({"stroke": false})).unwrap_err().to_string(); assert!(e.contains(REFUSED), "{cmd}: {e}"); @@ -902,10 +894,8 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() { assert_eq!(s.selected_stop(), None); s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); assert_eq!(pixel(&s, 80, 30), RED); - // The Eyedropper's options can leave the gradient out: the fill stays. s.execute("appearance.copyFrom", &json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}}}})).unwrap(); assert_eq!(pixel(&s, 80, 30), RED); - // Options that pick up neither color leave nothing to change, so the click is refused. let (undo, fill) = (undo_steps(&s), s.paint.fill.clone()); let neither = json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}, "stroke": {"color": false}}}}); let e = s.execute("appearance.copyFrom", &neither).unwrap_err().to_string(); @@ -913,6 +903,26 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() { assert_eq!((undo_steps(&s), &s.paint.fill), (undo, &fill), "nothing changes"); } +#[test] +fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + assert_eq!(node(&s, inst).extras().symbol_overrides[0].opacity, Some(0.5)); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + let o = node(&s, inst).extras().symbol_overrides[0].clone(); + assert_eq!(o.opacity, Some(0.5)); + assert_eq!(o.blend, Some(vectorcraft_color::BlendMode::Multiply)); + // A static symbol's instance refuses selectPart, so transparency.set acts on the instance whole. + let mut t = session(); + let static_inst = pair(&mut t, "static"); + t.execute("select.set", &json!({"ids": [static_inst.0]})).unwrap(); + t.execute("transparency.set", &json!({"opacity": 40})).unwrap(); + assert!(node(&t, static_inst).extras().symbol_overrides.is_empty()); + assert!((node(&t, static_inst).opacity - 0.4).abs() < 1e-6); +} + #[test] fn select_part_refuses_hidden_and_locked_objects_of_the_art() { let mut s = session(); 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/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1bc75a82a4..e59f764574 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -3687,6 +3687,40 @@ fn ruler_guides_and_lock() { assert!(s.execute("guide.remove", &json!({"index": 0})).is_err()); } +/// While guides are locked, a guide dragged out of a ruler and `guide.add` still make new guides, +/// each in one undo step and not selected. The ruler guides and guide paths in the document, the +/// new guides included, can't be selected, moved or deleted. +#[test] +fn new_guides_can_be_made_while_guides_are_locked() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let path = guide_path(&mut s, 300.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let n = undo_len(&s); + s.ruler_guide(true, &PointerEvent::new(PointerKind::Drag, 153.0, 30.0), true, v).unwrap(); + s.ruler_guide(true, &PointerEvent::new(PointerKind::Up, 153.0, 30.0), true, v).unwrap(); + assert_eq!(guides(&s), [(false, 50.0), (true, 153.0)]); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "New Guide"); + assert_eq!(s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap()["index"], 2); + assert_eq!(guides(&s).len(), 3); + assert_eq!(selected_guides(&s), Vec::::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/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/plugins.rs b/crates/engine/src/tests/plugins.rs index 4025927297..a705f05b9b 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -26,7 +26,15 @@ fn install_wat(s: &mut Session, src: &str) -> Value { install(s, &wat::parse_str(src).unwrap()) } +/// A session started to take `grant` and `allowHeavy` from requests, as most tests here install. fn session() -> Session { + let mut s = strict_session(); + s.allow_plugin_grants_from_requests(); + s +} + +/// A session as MCP and the CLI have by default: `grant` and `allowHeavy` need an approval. +fn strict_session() -> Session { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); s @@ -1338,6 +1346,506 @@ fn a_grant_covers_only_the_module_that_was_approved() { run(&mut s, "plugin.remove", json!({"id": exempt})); } +/// Installing a module that lists no permissions under a granted id forgets the grant, so the +/// formerly approved bytes need a new approval. A refused install leaves the grant, and a module +/// that lists permissions keeps replacing it as before. +#[test] +fn a_module_without_permissions_ends_the_grant_of_its_id() { + use vectorcraft_plugins::permissions::sha256_hex; + let mut s = session(); + let id = "test.engine.permissions.replaced"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let granted = || vectorcraft_plugins::registry::granted(id).map(|g| g.hash); + for permissions in ["null", "[]"] { + let plain = vectorcraft_format::base64_encode(&asking(id, permissions, &empty)); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true})); + // Refused installs change nothing. + let e = s.execute("plugin.install", &json!({"dataBase64": plain, "hash": "0".repeat(64), "replace": true})).unwrap_err().to_string(); + assert!(e.contains("SHA-256 `hash`"), "{e}"); + let e = s.execute("plugin.install", &json!({"dataBase64": plain, "replace": false})).unwrap_err().to_string(); + assert!(e.contains("already installed"), "{e}"); + let e = s.execute("plugin.install", &json!({"dataBase64": plain})).unwrap_err().to_string(); + assert!(e.contains("`replace: true`"), "{e}"); + assert_eq!(granted(), Some(sha256_hex(&approved)), "{permissions}: a refused install leaves the grant"); + + run(&mut s, "plugin.install", json!({"dataBase64": plain, "replace": true})); + assert_eq!(granted(), None, "{permissions}"); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "{permissions}"); + let e = s.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); + assert!(e.contains("`grant`"), "{permissions}: {e}"); + assert!(!vectorcraft_plugins::registry::get(id).unwrap().manifest().asks_permissions(), "{permissions}: the module installed stays"); + } + // With no module installed under the id, the grant ends the same way. + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true})); + vectorcraft_plugins::registry::remove(id); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "null", &empty))})); + assert_eq!(granted(), None); + // A module that lists permissions records its own grant. + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true})); + assert_eq!(granted(), Some(sha256_hex(&approved))); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// In a plug-in store, a module that lists no permissions removes only its own id's entry from +/// `grants.json`, and the formerly approved bytes need a new approval after a restart. A store +/// that holds such a module and a grant for its id has that grant forgotten when it is attached. +#[test] +fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { + use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + let folder = crate::tests_links::Folder::new("plugin-store-stale-grant"); + let id = "test.engine.permissions.storedstale"; + let other = "test.engine.permissions.storedother"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let other_wasm = asking(other, r#"["doc.read"]"#, &empty); + let grants = folder.0.join("grants.json"); + let ids = || -> Vec { + serde_json::from_slice::>(&std::fs::read(&grants).unwrap()) + .unwrap() + .iter() + .map(|e| e["id"].as_str().unwrap().to_string()) + .collect() + }; + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&other_wasm), "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + assert_eq!(ids().len(), 2); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + assert_eq!(ids(), vec![other.to_string()], "only this id's entry goes"); + assert!(vectorcraft_plugins::registry::granted(id).is_none()); + assert!(vectorcraft_plugins::registry::granted(other).is_some(), "the other plug-in's grant stays"); + + vectorcraft_plugins::registry::remove(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert_eq!(run(&mut next, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true); + + // A grant the store already holds for an id whose stored module lists no permissions. + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}); + std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap(); + vectorcraft_plugins::registry::remove(id); + let mut third = session(); + third.attach_plugin_store(folder.0.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the module that lists nothing still loads"); + assert_eq!(ids(), vec![other.to_string()]); + assert!(vectorcraft_plugins::registry::get(other).is_some()); + + // So does an entry this version can't read, and a grant held only by the process. + let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]}); + std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap(); + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&approved), permissions: vec![Permission::DocRead] }); + let mut fourth = session(); + fourth.attach_plugin_store(folder.0.clone()); + assert_eq!(ids(), vec![other.to_string()]); + assert!(vectorcraft_plugins::registry::granted(id).is_none()); + run(&mut fourth, "plugin.remove", json!({"id": id})); + run(&mut fourth, "plugin.remove", json!({"id": other})); +} + +/// A module listing no permissions that can't be written to the plug-in store leaves the stored +/// module in place, so `grants.json` keeps the grant that module needs at the next launch. +#[test] +fn a_failed_store_write_of_a_module_without_permissions_keeps_the_stored_grant() { + let folder = crate::tests_links::Folder::new("plugin-store-failed-write-plain"); + let id = "test.engine.permissions.storefail"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); + let before = std::fs::read(&grants).unwrap(); + let file = s.stored_plugin_file(id).unwrap(); + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir(&file).unwrap(); + + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + assert_eq!(std::fs::read(&grants).unwrap(), before, "the grant stays with the module left in the store"); + assert!(vectorcraft_plugins::registry::granted(id).is_none(), "the process runs the module that lists nothing"); + + std::fs::remove_dir(&file).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A module listing no permissions whose id's grant can't be removed from `grants.json` doesn't stay +/// in the store, so the grant and the module it covers stay together. It does stay when the module +/// before it can't be read back, and when the grants file is too large or doesn't hold a list and so +/// approves nothing. +#[test] +fn a_grant_that_cannot_be_removed_keeps_the_stored_module() { + let folder = crate::tests_links::Folder::new("plugin-store-failed-forget"); + let id = "test.engine.permissions.forgetfail"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let plain = asking(id, "null", &empty); + let replace = json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + // An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which + // makes the rewritten file larger than the 1 MiB that is read. + let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + + run(&mut s, "plugin.install", replace.clone()); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + assert!(vectorcraft_plugins::registry::granted(id).is_none(), "the process runs the module that lists nothing"); + + let oversized = vectorcraft_plugins::Limits::default().max_module_bytes as u64 + 1; + std::fs::File::options().write(true).open(&file).unwrap().set_len(oversized).unwrap(); + run(&mut s, "plugin.install", replace.clone()); + assert_eq!(std::fs::read(&file).unwrap(), plain, "a module that can't be read back can't be put back"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + let inspect = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); + assert_eq!(run(&mut s, "plugin.inspect", inspect)["needsApproval"], true, "the grant left behind stops counting"); + + std::fs::write(&file, &approved).unwrap(); + std::fs::write(&grants, b"not a list").unwrap(); + run(&mut s, "plugin.install", replace.clone()); + assert_eq!(std::fs::read(&file).unwrap(), plain, "a grants file that isn't a list approves nothing"); + + std::fs::write(&file, &approved).unwrap(); + std::fs::write(&grants, vec![b' '; (1 << 20) + 1]).unwrap(); + run(&mut s, "plugin.install", replace); + assert_eq!(std::fs::read(&file).unwrap(), plain, "a grants file over its size limit approves nothing"); + + std::fs::remove_file(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grant that can't be removed stops counting for the session when the module it covers can't be +/// written back either: the store holds the new module, and the old bytes would otherwise install +/// without approval. +#[test] +fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() { + let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back"); + let id = "test.engine.permissions.failedputback"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + + crate::store::PUT_BACK_FAILS.set(true); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + crate::store::PUT_BACK_FAILS.set(false); + assert_eq!(std::fs::read(&file).unwrap(), plain, "the store keeps the new module"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "the grant left behind stops counting"); + let refused = s.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); + assert!(refused.contains("doc.read"), "{refused}"); + + std::fs::remove_file(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// An entry of `grants.json` that this version can't use is kept for a version that can, so when it +/// can't be removed, neither `plugin.remove` nor a replacing module gets past it. +#[test] +fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() { + let folder = crate::tests_links::Folder::new("plugin-store-failed-remove-other"); + let id = "test.engine.permissions.removeother"; + let empty = json!({"objects": []}); + let first = asking(id, "null", &empty); + let second = asking(id, "[]", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first)})); + let file = s.stored_plugin_file(id).unwrap(); + let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]}); + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed"); + assert_eq!(std::fs::read(&file).unwrap(), first, "the store keeps the module"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&second), "replace": true})); + assert_eq!(std::fs::read(&file).unwrap(), first, "the store gets its module back"); + + std::fs::write(&grants, serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert!(!grants.exists(), "the removal takes the entry out of the file"); +} + +/// A grant that can't be removed when no module is stored for its id has no module to go with, so +/// it stops counting for the session. +#[test] +fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() { + let folder = crate::tests_links::Folder::new("plugin-store-grant-no-module"); + let id = "test.engine.permissions.forgetnomodule"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + std::fs::remove_file(&file).unwrap(); + + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + assert!(!std::path::Path::new(&file).exists(), "the store keeps no module"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true); + + std::fs::remove_file(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for +/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load. +/// A grant recorded later counts again, and another store starts with nothing ignored. +#[test] +fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-load-forget"); + let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other"); + let id = "test.engine.permissions.loadforget"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let needs_approval = json!({"dataBase64": approved_data}); + let grants = folder.0.join("grants.json"); + let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); + let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); + + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + vectorcraft_plugins::registry::remove(id); + let mut next = session(); + next.attach_plugin_store(folder.0.clone()); + assert_eq!(std::fs::read(&grants).unwrap(), full, "the load can't rewrite the file"); + assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], true); + let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); + assert!(refused.contains("doc.read"), "{refused}"); + + std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + next.attach_plugin_store(elsewhere.0.clone()); + assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); + + // A directory at the file's path gives a read error on every platform. + std::fs::remove_file(&grants).unwrap(); + std::fs::create_dir(&grants).unwrap(); + vectorcraft_plugins::registry::remove(id); + let mut third = session(); + third.attach_plugin_store(folder.0.clone()); + std::fs::remove_dir(&grants).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count"); + + // Attaching the same store again, with no stored module to try the removal for, keeps it out. + let file = third.stored_plugin_file(id).unwrap(); + std::fs::remove_file(&file).unwrap(); + third.attach_plugin_store(folder.0.clone()); + assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the same store's grant stays out"); + + // A later load in the session doesn't count it either, for the bytes it covers. + std::fs::write(&file, &approved).unwrap(); + vectorcraft_plugins::registry::remove(id); + third.load_stored_plugins(); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded"); + + run(&mut third, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true})); + assert_eq!(run(&mut third, "plugin.inspect", needs_approval)["needsApproval"], false, "the user granted it again"); + run(&mut third, "plugin.remove", json!({"id": id})); +} + +/// A grants file that can't be opened or read may name the old module once it reads again, so +/// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the +/// file's path gives a read error on every platform. +#[test] +fn a_grants_file_that_cannot_be_read_keeps_the_grant_and_the_module_it_covers() { + let folder = crate::tests_links::Folder::new("plugin-store-unread-grants"); + let id = "test.engine.permissions.unreadgrants"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + let recorded = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + std::fs::create_dir(&grants).unwrap(); + + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); + + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"], "replace": true})); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed"); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store keeps the module"); + + std::fs::remove_dir(&grants).unwrap(); + std::fs::write(&grants, &recorded).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert!(!grants.exists(), "the file reads again and the grant goes"); +} + +/// `plugin.remove` returns an error and keeps the plug-in when its grant can't be removed from +/// `grants.json`; a second one tries again. A grants file that doesn't hold a list doesn't stop it. +#[test] +fn a_grant_that_cannot_be_removed_stops_plugin_remove() { + let folder = crate::tests_links::Folder::new("plugin-store-failed-remove"); + let id = "test.engine.permissions.removefail"; + let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let approved_data = vectorcraft_format::base64_encode(&approved); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + let recorded = std::fs::read(&grants).unwrap(); + // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. + let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); + let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + std::fs::write(&grants, &full).unwrap(); + let data = crate::store::plugin_data_dir(&folder.0, id); + std::fs::create_dir_all(&data).unwrap(); + std::fs::write(data.join("settings.json"), b"{}").unwrap(); + + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed"); + assert!(vectorcraft_plugins::registry::granted(id).is_some(), "it keeps its grant"); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store keeps the module the grant covers"); + assert_eq!(std::fs::read(&grants).unwrap(), full); + assert!(data.join("settings.json").is_file(), "it keeps its settings"); + + // Settings that can't be moved aside leave the grant recorded. A file at the aside path stops + // the move on Unix, and a file held open in the folder stops it on Windows. + std::fs::write(&grants, &recorded).unwrap(); + let mut aside = data.clone().into_os_string(); + aside.push(".removed"); + let aside = std::path::PathBuf::from(aside); + std::fs::write(&aside, b"in the way").unwrap(); + #[cfg(windows)] + let held = { + use std::os::windows::fs::OpenOptionsExt; + std::fs::File::options().read(true).share_mode(1).open(data.join("settings.json")).unwrap() + }; + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err()); + #[cfg(windows)] + drop(held); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays while the settings do"); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + let _ = std::fs::remove_file(&aside); + + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert!(!grants.exists(), "the second removal forgets the grant"); + + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + std::fs::write(&grants, b"not a list").unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "a grants file that isn't a list approves nothing"); + assert!(!std::path::Path::new(&file).exists()); +} + +/// Windows keeps a file another program holds open without delete sharing, so the last grant can't +/// be removed by deleting `grants.json`. +#[cfg(windows)] +#[test] +fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { + use std::os::windows::fs::OpenOptionsExt; + const FILE_SHARE_READ: u32 = 1; + let folder = crate::tests_links::Folder::new("plugin-store-held-grants"); + let id = "test.engine.permissions.heldgrants"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let plain = asking(id, "null", &empty); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); + let file = s.stored_plugin_file(id).unwrap(); + + let held = std::fs::File::options().read(true).share_mode(FILE_SHARE_READ).open(&grants).unwrap(); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); + drop(held); + assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); + assert!(grants.exists()); + + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in folder that leaves a module listing no permissions under an id forgets the process's +/// grant for it, unless a later file in the folder leaves a granted module there. A grant kept in +/// the plug-in store stays, with the stored module it covers. +#[test] +fn a_plugin_folder_ends_the_process_grant_of_an_id_it_replaces() { + let mut s = session(); + let id = "test.engine.permissions.folderstale"; + let empty = json!({"objects": []}); + let approved = asking(id, r#"["doc.read"]"#, &empty); + let approved_data = vectorcraft_format::base64_encode(&approved); + let plain = asking(id, "null", &empty); + let dir = crate::tests_links::Folder::new("plugin-folder-stale-grant"); + std::fs::write(dir.0.join("a-plain.wasm"), &plain).unwrap(); + std::fs::write(dir.0.join("b-approved.wasm"), &approved).unwrap(); + let path = json!({"path": dir.0.display().to_string()}); + run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + + let r = run(&mut s, "plugin.reload", path.clone()); + assert_eq!(r["failed"], json!([]), "{r}"); + assert!(vectorcraft_plugins::registry::granted(id).is_some(), "the granted module is the one left"); + + std::fs::remove_file(dir.0.join("b-approved.wasm")).unwrap(); + let r = run(&mut s, "plugin.reload", path.clone()); + assert_eq!(r["loaded"], json!([id]), "{r}"); + assert!(vectorcraft_plugins::registry::granted(id).is_none()); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true); + run(&mut s, "plugin.remove", json!({"id": id})); + + let store = crate::tests_links::Folder::new("plugin-folder-stale-grant-store"); + let mut stored = session(); + stored.attach_plugin_store(store.0.clone()); + run(&mut stored, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); + let grants = store.0.join("grants.json"); + let recorded = std::fs::read(&grants).unwrap(); + run(&mut stored, "plugin.reload", path); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the store still holds the module its grant covers"); + assert_eq!(run(&mut stored, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false); + run(&mut stored, "plugin.remove", json!({"id": id})); +} + /// A stored module whose bytes changed is skipped at the next start and stays in the store with its /// grant, and the original bytes load again. A stored grant whose hash is malformed covers nothing. /// With a store attached, a matching grant held only by the process doesn't count. @@ -1639,6 +2147,69 @@ fn read_only_kind_field_and_omission_refuse_without_undo() { assert!(e.contains("`inputs` needs `api` 2"), "{e}"); } +/// A run past its memory budget fails before the plug-in starts, with the document and undo +/// history as they were: a read-only object whose other fields don't fit, a path and a compound +/// path that don't fit, and parameters past the input's half of the cap, with objects selected or +/// with none. The module has one page of memory, the most it may have, so a run that started would +/// report that the plug-in ran out of memory instead. +#[test] +fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeKind}; + use vectorcraft_geom::FillRule; + use vectorcraft_plugins::{Limits, Plugin, registry}; + let id = "test.engine.inputs.budget"; + let params: Vec = (0..9).map(|i| format!(r#""p{i}":{{"type":"string","maxLength":4096}}"#)).collect(); + let manifest = format!( + r#"{{"id":"{id}","name":"Budget","kind":"filter","api":2,"permissions":["doc.read","doc.write"],"inputs":["type"],"params":{{{}}}}}"#, + params.join(",") + ); + let module = wat::parse_str(tpl::module(&manifest, "unreachable", "", 1)).unwrap(); + // One page of memory: the input and the parameters share 32 KiB. + registry::install(Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap()); + let mut s = session(); + let small = rect(&mut s, 10.0, "#ff0000"); + let long = rect(&mut s, 30.0, "#00ff00"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap()); + let mut compound = NodeId(0); + s.edit("Set up", |d, _| { + d.node_mut(t).unwrap().name = Some("n".repeat(40_000)); + let points: Vec = (0..4_000).map(|i| Point::new(f64::from(i), 0.0)).collect(); + let outline = PathData::single(SubPath::polyline(&points, false)); + if let NodeKind::Path { path, .. } = &mut d.node_mut(long).unwrap().kind { + *path = outline.clone(); + } + let member = Node::path(d.alloc_id(), outline, Appearance::default()); + let n = Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: FillRule::NonZero }); + let layer = d.layers[0].id; + compound = d.insert(Some(layer), usize::MAX, n).unwrap(); + Ok(()) + }) + .unwrap(); + let padding: Value = (0..9).map(|i| (format!("p{i}"), json!("x".repeat(4096)))).collect::>().into(); + let too_large = "memory budget (the selection is too large to hand over)"; + let named = format!("memory budget (object {} needs", t.0); + let with_padding = |ids: Vec| { + let mut p = padding.clone(); + p["id"] = json!(id); + p["ids"] = json!(ids); + p + }; + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + for (p, says) in [ + (json!({"id": id, "ids": [t.0]}), named.as_str()), + (json!({"id": id, "ids": [long.0]}), too_large), + (json!({"id": id, "ids": [compound.0]}), too_large), + (with_padding(vec![small.0]), too_large), + (with_padding(vec![]), too_large), + ] { + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{says}: {e}"); + assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{says}"); + } + assert!(registry::remove(id)); +} + /// What the user granted is kept in the plug-in store with the module: the next session installs /// the plug-in again without asking. A stored plug-in that lists permissions nobody granted it is /// skipped, even when another store granted it, and so is one in the Additional Plug-ins Folder @@ -1979,6 +2550,132 @@ fn a_level_2_filter_installs_with_progress_granted_and_reports_to_the_caller() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// An approval of the module `wasm` with id `id`, its `permissions` and, if `heavy`, its budget. +fn approval(id: &str, wasm: &[u8], permissions: &[&str], heavy: bool) -> crate::cmd::plugin::InstallApproval { + crate::cmd::plugin::InstallApproval { + id: id.into(), + hash: vectorcraft_plugins::permissions::sha256_hex(wasm), + permissions: permissions.iter().map(|p| p.to_string()).collect(), + heavy, + } +} + +/// In a session that wasn't started to accept them, `grant` and `allowHeavy` are refused whichever +/// way the command runs, a batch included, until an approval covers the module, its id, SHA-256 and +/// permissions. An approval is spent by the first install, whatever it does. A hash already approved +/// still installs. +#[test] +fn a_request_cannot_grant_what_only_a_person_approves() { + let mut s = strict_session(); + let id = "test.engine.approval"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let refused = "take effect only in a session started with --allow-plugin-grants"; + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string(); + assert!(e.contains(refused), "{e}"); + let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string(); + assert!(e.contains("approve them in the desktop app") && e.contains("--allow-plugin-grants"), "{e}"); + let batch = json!({"commands": [{"command": "plugin.install", "params": {"dataBase64": data, "grant": ["doc.read"]}}]}); + let e = s.execute("command.batch", &batch).unwrap_err().to_string(); + assert!(e.contains(refused), "a batch can't grant: {e}"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + + // Approved for other bytes, for another id or for other permissions: refused, and spent. + let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"name": "x"}]})); + for wrong in [ + approval(id, &other, &["doc.read"], false), + approval("test.engine.approval.other", &wasm, &["doc.read"], false), + approval(id, &wasm, &["doc.read", "state"], false), + ] { + s.approve_plugin_install(wrong); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string(); + assert!(e.contains(refused), "{e}"); + } + assert!(vectorcraft_plugins::registry::get(id).is_none()); + + // The approval for this module installs it once. + s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false)); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm))); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string(); + assert!(e.contains(refused), "the approval was spent: {e}"); + // A hash already approved installs without one. + run(&mut s, "plugin.install", json!({"dataBase64": data})); + run(&mut s, "plugin.remove", json!({"id": id})); + + // A refused install spends the approval too. + s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false)); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"], "hash": "0"})).unwrap_err().to_string(); + assert!(e.contains("SHA-256"), "{e}"); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string(); + assert!(e.contains(refused), "{e}"); + // So does one refused for its params. + s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false)); + s.execute("plugin.install", &json!({"dataBase64": data, "grant": "doc.read"})).unwrap_err(); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string(); + assert!(e.contains(refused), "{e}"); + + // The heavy budget needs its own agreement. + let heavy_id = "test.engine.approval.heavy"; + let heavy_wasm = heavy(heavy_id, 1); + let heavy_data = vectorcraft_format::base64_encode(&heavy_wasm); + let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data, "allowHeavy": true})).unwrap_err().to_string(); + assert!(e.contains(refused), "{e}"); + // Without a `permissions` list it has the ones its kind implies. + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": heavy_data})); + let implied: Vec<&str> = inspected["permissions"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + s.approve_plugin_install(approval(heavy_id, &heavy_wasm, &implied, false)); + let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data, "allowHeavy": true})).unwrap_err().to_string(); + assert!(e.contains(refused), "an approval without the heavy budget doesn't cover it: {e}"); + let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data})).unwrap_err().to_string(); + assert!(e.contains("approve it in the desktop app"), "{e}"); + s.approve_plugin_install(approval(heavy_id, &heavy_wasm, &implied, true)); + run(&mut s, "plugin.install", json!({"dataBase64": heavy_data, "allowHeavy": true})); + run(&mut s, "plugin.remove", json!({"id": heavy_id})); + + // A session started to accept them takes them from requests. + s.allow_plugin_grants_from_requests(); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A module a person approved in the desktop app, recorded in the store's `grants.json`, installs +/// from another session with that store and no flag and no `grant`. Other bytes under its id are +/// refused there, with or without `grant`. +#[test] +fn a_module_approved_in_the_app_installs_from_a_strict_session_with_its_store() { + let folder = crate::tests_links::Folder::new("plugin-approval-store"); + let id = "test.engine.approval.store"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let mut desktop = strict_session(); + desktop.attach_plugin_store(folder.0.clone()); + desktop.approve_plugin_install(approval(id, &wasm, &["doc.read"], false)); + run(&mut desktop, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert!(std::fs::read_to_string(folder.0.join("grants.json")).unwrap().contains(id), "recorded in the store"); + + // Another process starts with an empty registry and the store's grants. + let forget = || { + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + }; + forget(); + let mut headless = strict_session(); + headless.attach_plugin_store(folder.0.clone()); + forget(); + run(&mut headless, "plugin.install", json!({"dataBase64": data})); + assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm))); + + let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"name": "x"}]})); + let other_data = vectorcraft_format::base64_encode(&other); + let e = headless.execute("plugin.install", &json!({"dataBase64": other_data, "replace": true})).unwrap_err().to_string(); + assert!(e.contains("approve them in the desktop app"), "{e}"); + let e = headless.execute("plugin.install", &json!({"dataBase64": other_data, "replace": true, "grant": ["doc.read"]})).unwrap_err().to_string(); + assert!(e.contains("take effect only in a session started with --allow-plugin-grants"), "{e}"); + assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm))); + run(&mut headless, "plugin.remove", json!({"id": id})); +} + /// A filter run the caller cancels (MCP's `notifications/cancelled`, the app's Cancel) stops between /// two slices of its budget and changes nothing. #[test] @@ -2441,7 +3138,7 @@ fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() { assert_eq!(st.set_cache_entry("tile", b"again", m), Err(StorageError::Unavailable)); assert!(!dir.exists()); assert_eq!(upper.setting("k0", m).unwrap(), Some(b"upper".to_vec())); - s.remove_plugin_storage(upper_id).unwrap(); + s.remove_plugin_storage(upper_id, || true).unwrap(); } /// Files larger than the storage reads are not read: a settings file larger than 1 MiB, although @@ -2624,7 +3321,7 @@ fn removing_a_plugin_drops_its_settings_from_memory() { let mut m = Meter::unlimited(); assert_eq!(st.setting("zoom", &mut m).unwrap(), Some(b"hello".to_vec())); assert_eq!(m.used(), bytes.len() as u64, "read from the file"); - s.remove_plugin_storage(id).unwrap(); + s.remove_plugin_storage(id, || true).unwrap(); } /// The cache's total stays in memory while the cache folder keeps its time; a write and a clear 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/spelling.rs b/crates/engine/src/tests/spelling.rs new file mode 100644 index 0000000000..eca38d8e65 --- /dev/null +++ b/crates/engine/src/tests/spelling.rs @@ -0,0 +1,329 @@ +//! Edit → Spelling (`text.spelling.check`, `text.spelling.suggest`): the unknown words of the +//! document's type, at the bytes `text.editRange` changes, each in its run's language. + +use serde_json::{Value, json}; + +use crate::cmd::spelling::MAX_DICTIONARY_FILE_BYTES; +use crate::*; + +/// 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(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +/// Runs a command that must succeed and gives its result. +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap() +} + +/// New point type at (10, `y`) holding `t`. +fn text(s: &mut Session, y: f64, t: &str) -> NodeId { + NodeId(run(s, "text.create", json!({"x": 10, "y": y, "text": t}))["id"].as_u64().unwrap()) +} + +/// The unknown words a check lists: (id, start, end, word). +fn unknown(s: &mut Session, p: Value) -> Vec<(u64, u64, u64, String)> { + let r = run(s, "text.spelling.check", p); + assert_eq!(r["more"], false); + r["words"] + .as_array() + .unwrap() + .iter() + .map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["end"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string())) + .collect() +} + +#[test] +fn check_lists_unknown_words_at_the_bytes_edit_range_changes() { + let mut s = session(); + // "—" is three bytes, so the unknown word starts at byte 12, not character 10. Punctuation, + // not a word, so the result doesn't depend on which dictionary is built in. + let t = text(&mut s, 50.0, "drawing — qzxvw tools"); + assert_eq!(unknown(&mut s, json!({})), [(t.0, 12, 17, "qzxvw".to_string())]); + let w = &run(&mut s, "text.spelling.check", json!({}))["words"][0]; + assert_eq!(w["lang"], "en", "text with no language is checked in English"); + // Change: the bytes the check gave, as one undo step. + run(&mut s, "text.editRange", json!({"id": t.0, "start": 12, "end": 17, "insert": "vector"})); + assert_eq!(unknown(&mut s, json!({})), []); + run(&mut s, "edit.undo", json!({})); + assert_eq!(unknown(&mut s, json!({})).len(), 1, "undo brings the word back"); +} + +#[test] +fn check_goes_through_visible_unlocked_type_in_paint_order_or_the_ids_given() { + let mut s = session(); + let a = text(&mut s, 50.0, "first qzxvw"); + let b = text(&mut s, 100.0, "second wvxzq"); + let hidden = text(&mut s, 150.0, "hidden qqzzx"); + let locked = text(&mut s, 200.0, "locked zzqqx"); + run(&mut s, "object.hide", json!({"ids": [hidden.0]})); + run(&mut s, "object.lock", json!({"ids": [locked.0]})); + let ids: Vec = unknown(&mut s, json!({})).iter().map(|w| w.0).collect(); + assert_eq!(ids, [a.0, b.0], "hidden and locked type are left out"); + assert_eq!(unknown(&mut s, json!({"ids": [b.0]})), [(b.0, 7, 12, "wvxzq".to_string())]); + assert_eq!(unknown(&mut s, json!({"ids": null})).len(), 2, "null ids is the default"); + let both = [(a.0, 6, 11, "qzxvw".to_string()), (b.0, 7, 12, "wvxzq".to_string())]; + assert_eq!(unknown(&mut s, json!({"ids": [b.0, a.0]})), both, "given ids are listed in paint order too"); + for ids in [json!(b.0), json!("all"), json!({"id": b.0}), json!([-1]), json!(["x"]), json!([999_999])] { + assert!(s.execute("text.spelling.check", &json!({"ids": ids})).is_err(), "malformed ids {ids} is refused"); + } +} + +#[test] +fn a_language_without_a_dictionary_marks_nothing() { + let mut s = session(); + let t = text(&mut s, 50.0, "qzxvw"); + run(&mut s, "text.setFormat", json!({"ids": [t.0], "language": "German"})); + assert_eq!(unknown(&mut s, json!({})), [], "German has no spelling dictionary in craft-proof"); +} + +#[test] +fn suggest_offers_dictionary_words() { + let mut s = session(); + let r = run(&mut s, "text.spelling.suggest", json!({"word": "drawng"})); + let got: Vec<&str> = r["suggestions"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).collect(); + assert!(got.len() <= 5, "five at most by default: {got:?}"); + assert!(got.contains(&"drawing"), "{got:?}"); + assert_eq!(run(&mut s, "text.spelling.suggest", json!({"word": "drawng", "max": 1}))["suggestions"].as_array().unwrap().len(), 1); + assert!(s.execute("text.spelling.suggest", &json!({})).is_err(), "a word is required"); + assert!(s.execute("text.spelling.suggest", &json!({"word": " "})).is_err(), "a blank word is refused"); + for max in [json!(0), json!(21), json!(-1), json!("3")] { + assert!(s.execute("text.spelling.suggest", &json!({"word": "drawng", "max": max})).is_err(), "max {max}"); + } +} + +#[test] +fn each_paragraph_is_checked_on_its_own_at_the_bytes_of_the_whole_text() { + let mut s = session(); + // Read as one block, the Vietnamese first paragraph would make the whole text Vietnamese, + // which has no dictionary, and the English typo below it would go unmarked. + let vi = "Cảm ơn những người bạn"; + let t = text(&mut s, 50.0, &format!("{vi}\ndrawing qzxvw tools")); + let at = vi.len() + 1 + "drawing ".len(); + assert_eq!(unknown(&mut s, json!({})), [(t.0, at as u64, at as u64 + 5, "qzxvw".to_string())]); +} + +// The custom dictionary is craft-proof's, shared by the whole process, so each test below uses +// made-up words of its own: tests running at the same time never see each other's. + +/// The words a check of the whole active document lists. +fn marked(s: &mut Session) -> Vec { + unknown(s, json!({})).into_iter().map(|w| w.3).collect() +} + +#[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"]); + // Kept in lower case, so the capitalized word is right too. + let r = run(&mut s, "text.spelling.addWord", json!({"word": " Zqvwkx "})); + assert_eq!((r["word"].as_str(), r["added"].as_bool()), (Some("zqvwkx"), Some(true))); + assert_eq!(marked(&mut s), Vec::::new()); + assert_eq!(run(&mut s, "text.spelling.addWord", json!({"word": "zqvwkx"}))["added"], false, "already there"); + let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone(); + assert!(words.as_array().unwrap().contains(&json!("zqvwkx")), "{words}"); + // Another document's check takes it as right too. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + text(&mut s, 50.0, "zqvwkx"); + assert_eq!(marked(&mut s), Vec::::new()); + run(&mut s, "text.spelling.removeWord", json!({"word": "ZQVWKX"})); + assert_eq!(marked(&mut s), ["zqvwkx"]); + let e = s.execute("text.spelling.removeWord", &json!({"word": "zqvwkx"})).unwrap_err().to_string(); + assert!(e.contains("isn't in the custom dictionary"), "{e}"); +} + +#[test] +fn a_changed_word_replaces_the_old_one() { + let _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"})); + assert_eq!(marked(&mut s), ["xkvzqb"]); + assert_eq!(run(&mut s, "text.spelling.changeWord", json!({"word": "xkvzqa", "to": "Xkvzqb"}))["word"], "xkvzqb"); + assert_eq!(marked(&mut s), ["xkvzqa"]); + let e = s.execute("text.spelling.changeWord", &json!({"word": "xkvzqa", "to": "x"})).unwrap_err().to_string(); + assert!(e.contains("isn't in the custom dictionary"), "{e}"); + run(&mut s, "text.spelling.removeWord", json!({"word": "xkvzqb"})); +} + +#[test] +fn the_custom_dictionary_file_is_read_and_kept_up_to_date() { + let _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(); + let mut s = session(); + s.attach_custom_dictionary(file.clone()); + text(&mut s, 50.0, "kqzvwx vkqzwx"); + assert_eq!(marked(&mut s), ["vkqzwx"], "the file's word is right; its line of three words is skipped"); + run(&mut s, "text.spelling.addWord", json!({"word": "vkqzwx"})); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.lines().any(|l| l == "kqzvwx") && saved.lines().any(|l| l == "vkqzwx"), "{saved}"); + run(&mut s, "text.spelling.changeWord", json!({"word": "kqzvwx", "to": "kqzvwy"})); + run(&mut s, "text.spelling.removeWord", json!({"word": "vkqzwx"})); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.lines().any(|l| l == "kqzvwy"), "{saved}"); + assert!(!saved.lines().any(|l| l == "kqzvwx" || l == "vkqzwx"), "changed and deleted words are gone from the file: {saved}"); + run(&mut s, "text.spelling.removeWord", json!({"word": "kqzvwy"})); +} + +#[test] +fn ignore_all_skips_a_word_in_the_active_document_only() { + let _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"})); + assert_eq!(marked(&mut s), ["vqzxkw"], "every occurrence, whatever its case"); + let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone(); + assert!(!words.as_array().unwrap().contains(&json!("wqzxkv")), "not added to the custom dictionary"); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + text(&mut s, 50.0, "wqzxkv"); + assert_eq!(marked(&mut s), ["wqzxkv"], "another document still marks it"); +} + +#[test] +fn custom_dictionary_commands_refuse_what_isnt_one_word() { + let _one_at_a_time = dictionary_lock(); + let mut s = session(); + let long = "q".repeat(65); + for (id, p) in [ + ("text.spelling.addWord", json!({})), + ("text.spelling.addWord", json!({"word": " "})), + ("text.spelling.addWord", json!({"word": "two words"})), + ("text.spelling.addWord", json!({"word": long})), + ("text.spelling.addWord", json!({"word": 5})), + ("text.spelling.removeWord", json!({})), + ("text.spelling.changeWord", json!({"word": "qzx"})), + ("text.spelling.changeWord", json!({"word": "qzx", "to": "a b"})), + ("text.spelling.ignoreAll", json!({"word": "a\tb"})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p} is refused"); + } + let mut empty = Session::new(); + assert!(empty.execute("text.spelling.ignoreAll", &json!({"word": "qzx"})).is_err(), "Ignore All needs a document"); + assert!(empty.execute("text.spelling.dictionary", &json!({})).is_ok(), "the dictionary is the app's"); +} + +/// Whether the custom dictionary holds `word`. +fn in_dictionary(s: &mut Session, word: &str) -> bool { + run(s, "text.spelling.dictionary", json!({}))["words"].as_array().unwrap().contains(&json!(word)) +} + +#[test] +fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() { + let _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. + let folder = dir.join("Custom Dictionary.txt"); + std::fs::create_dir_all(&folder).unwrap(); + let big = dir.join("big.txt"); + let words = "qkzvxw\n".repeat((MAX_DICTIONARY_FILE_BYTES / 7 + 2) as usize); + std::fs::write(&big, &words).unwrap(); + for path in [folder.clone(), big.clone()] { + let mut s = session(); + s.attach_custom_dictionary(path.clone()); + let e = s.execute("text.spelling.addWord", &json!({"word": "zkqvxw"})).unwrap_err().to_string(); + assert!(e.contains("can't be read"), "{}: {e}", path.display()); + assert!(!in_dictionary(&mut s, "zkqvxw"), "the refused word isn't kept either"); + } + assert!(folder.is_dir()); + assert_eq!(std::fs::read_to_string(&big).unwrap(), words, "the large file is as it was"); +} + +#[test] +fn a_change_that_cant_be_saved_is_taken_back() { + let _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"); + let folder = dir.join("Custom Dictionary.txt"); + std::fs::create_dir_all(&folder).unwrap(); + let mut failing = session(); + failing.attach_custom_dictionary(folder); + assert!(failing.execute("text.spelling.removeWord", &json!({"word": "wkqzvx"})).is_err()); + assert!(in_dictionary(&mut s, "wkqzvx"), "a delete that wasn't saved leaves the word"); + assert!(failing.execute("text.spelling.changeWord", &json!({"word": "wkqzvx", "to": "wkqzvy"})).is_err()); + assert!(in_dictionary(&mut s, "wkqzvx") && !in_dictionary(&mut s, "wkqzvy"), "a change that wasn't saved leaves the old word"); + run(&mut s, "text.spelling.removeWord", json!({"word": "wkqzvx"})); +} + +#[cfg(unix)] +#[test] +fn a_word_another_window_saved_stays_when_this_save_fails() { + 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"); + std::fs::write(&file, "").unwrap(); + let mut s = session(); + s.attach_custom_dictionary(file.clone()); + // Another window saves a word this session hasn't taken in, then the folder can't be written: + // the save reads the file, takes the word in, and fails writing. + std::fs::write(&file, "zvkqxw\n").unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o500)).unwrap(); + let probe = dir.join("probe"); + let writable = std::fs::write(&probe, "").is_ok(); + let r = (!writable).then(|| s.execute("text.spelling.addWord", &json!({"word": "zvkqxw"}))); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + let Some(r) = r else { + // Run as root, the folder stays writable: there is no failing save to check. + return; + }; + assert!(r.is_err(), "{r:?}"); + assert!(in_dictionary(&mut s, "zvkqxw"), "the word in the file stays, though this Add was taken back"); + run(&mut s, "text.spelling.removeWord", json!({"word": "zvkqxw"})); +} + +/// `misspellings` finds in one type object what the check lists for it, stops at the most it is +/// asked for and says so, and leaves out the Ignore All words it is given. +#[test] +fn misspellings_of_one_object_are_what_the_check_lists() { + use crate::cmd::spelling::misspellings; + let mut s = session(); + let id = text(&mut s, 50.0, "the Vqzrtwx cat\nsat Wzqrvtx Xqrzvtw"); + let listed: Vec<_> = unknown(&mut s, json!({"ids": [id.0]})).into_iter().map(|(_, a, b, _)| a as usize..b as usize).collect(); + let st = s.doc().unwrap(); + let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(id).map(|n| n.kind.clone()) else { panic!("type") }; + let none = Default::default(); + let (found, cut) = misspellings(&t, &none, 10); + assert_eq!((found.iter().map(|m| m.range.clone()).collect::>(), cut), (listed.clone(), false)); + assert!(found.iter().all(|m| m.lang.tag() == "en"), "{found:?}"); + let (first, cut) = misspellings(&t, &none, 2); + assert_eq!((first.iter().map(|m| m.range.clone()).collect::>(), cut), (listed[..2].to_vec(), true)); + let ignored = std::collections::BTreeSet::from(["wzqrvtx".to_string()]); + let (found, _) = misspellings(&t, &ignored, 10); + assert_eq!(found.iter().map(|m| m.range.clone()).collect::>(), [listed[0].clone(), listed[2].clone()]); +} + +/// Each change to the custom dictionary moves its generation on, whether it is saved or not, so +/// 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(); + let mut moved = |s: &mut Session, id: &str, p: Value| { + let _ = s.execute(id, &p); + let now = dictionary_generation(); + let on = now > last; + last = now; + on + }; + assert!(moved(&mut s, "text.spelling.addWord", json!({"word": "Gqzvrtx"})), "add"); + assert!(moved(&mut s, "text.spelling.changeWord", json!({"word": "gqzvrtx", "to": "hqzvrtx"})), "change"); + assert!(moved(&mut s, "text.spelling.removeWord", json!({"word": "hqzvrtx"})), "delete"); +} diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index 6a93b80a3d..31ceb24341 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -251,11 +251,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 226fe830af..42909da1c7 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -84,8 +84,12 @@ 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(), 1, "{libs:?}"); + assert_eq!(libs.len(), 2, "{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")) + ); 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"]); @@ -95,6 +99,32 @@ fn the_builtin_library_is_original_art_generated_in_code() { assert!(s.execute("symbol.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn ui_frames_symbols_carry_default_nine_slice_when_added() { + let mut s = session(); + let lib = run(&mut s, "symbol.library", json!({"library": "ui-frames"})); + let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Panel", "Button", "Bar"]); + let mut placed = Vec::new(); + for (i, name) in names.iter().enumerate() { + let r = run( + &mut s, + "symbol.addFromLibrary", + json!({"library": "ui-frames", "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), Some(vectorcraft_doc::SymbolNineSlice::default()), "{name} should have default 9-slice guides"); + } + assert!(matches!( + d.node(NodeId(placed[0])).map(|n| &n.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Panel" + )); +} + #[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/typeglyphbounds.rs b/crates/engine/src/tests/typeglyphbounds.rs new file mode 100644 index 0000000000..9fd8e400b4 --- /dev/null +++ b/crates/engine/src/tests/typeglyphbounds.rs @@ -0,0 +1,325 @@ +//! 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)); +} + +#[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..e818c36862 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, diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index bba6247c75..424f30cdd7 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2415,6 +2415,64 @@ proptest! { let text = type42_composite_eps(&font, gid); survive("damaged Type 42 glyphs", || vectorcraft_eps::import(text.as_bytes()).ok().map(|r| r.document))?; } + + /// CID-keyed fonts with hostile CMaps (codespace ranges of any length, mappings past them) + /// and Type 0 CIDFonts with damaged binary data (offset table, charstrings, subroutine table, + /// any FDBytes and GDBytes), shown with any bytes: drawn, measured and outlined, or refused. + #[test] + fn eps_cid_fonts_never_panic( + space in prop::collection::vec((prop::collection::vec(any::(), 0..6), prop::collection::vec(any::(), 0..6)), 0..4), + cids in prop::collection::vec((prop::collection::vec(any::(), 1..5), any::()), 0..6), + data in prop::collection::vec(any::(), 0..200), + fd_bytes in 0u8..6, + gd_bytes in 0u8..6, + len_iv in -2i8..8, + shown in prop::collection::vec(any::(), 0..24), + ) { + let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); + let ranges: String = space.iter().map(|(lo, hi)| format!("<{}> <{}>\n", hex(lo), hex(hi))).collect(); + let maps: String = cids.iter().map(|(c, cid)| format!("<{}> <{}> {cid}\n", hex(c), hex(c))).collect(); + let text = format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n\ + /CIDInit /ProcSet findresource begin 20 dict begin /CIDFontName /F def /CIDFontType 0 def\n\ + /FDArray [4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 4 dict dup begin /lenIV {len_iv} def\n\ + /SubrMapOffset 3 def /SDBytes 2 def /SubrCount 4 def end def currentdict end] def\n\ + /CIDMapOffset 0 def /FDBytes {fd_bytes} def /GDBytes {gd_bytes} def /CIDCount 40 def\n\ + (Hex) {} StartData\n{}\n\ + /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /M def\n\ + {} begincodespacerange\n{ranges}endcodespacerange\n{} begincidrange\n{maps}endcidrange\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /C /M [/F] composefont 40 scalefont setfont 10 20 moveto <{}> show <{}> stringwidth pop pop\n\ + 10 60 moveto <{}> true charpath fill\nshowpage\n%%EOF\n", + data.len(), hex(&data), space.len(), cids.len(), hex(&shown), hex(&shown), hex(&shown) + ); + survive("hostile CID-keyed fonts", || vectorcraft_eps::import(text.as_bytes()).ok().map(|r| r.document))?; + } + + /// Embedded Type 1 fonts whose encrypted part is damaged or hostile (any bytes, binary or + /// hexadecimal), shown, measured and outlined: drawn, or left out. + #[test] + fn eps_type1_programs_never_panic( + part in prop::collection::vec(any::(), 0..400), + hex in any::(), + shown in prop::collection::vec(any::(), 0..12), + ) { + let hexed = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); + // Bytes that would end the part early are left out, as `cleartomark` ends it. + let part: Vec = part.into_iter().filter(|b| *b != b'c').collect(); + let mut bytes = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n\ + 12 dict begin /FontName /T1 def /FontType 1 def /FontMatrix [0.001 0 0 0.001 0 0] def /FontBBox [0 0 1000 1000] def\n\ + /Encoding StandardEncoding def currentdict end currentfile eexec\n" + .to_vec(); + if hex { + bytes.extend(hexed(&part).into_bytes()); + } else { + bytes.extend(part); + } + bytes.extend(format!("\n{}\ncleartomark\n/T1 findfont 40 scalefont setfont 10 20 moveto <{}> show <{}> stringwidth pop pop\n\ + 10 60 moveto <{}> true charpath fill\nshowpage\n%%EOF\n", "0".repeat(512), hexed(&shown), hexed(&shown), hexed(&shown)).into_bytes()); + survive("hostile Type 1 programs", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?; + } } /// The TrueType font [`type42_composite_eps`] carries. diff --git a/crates/engine/tests/it/copy_direct_selection.rs b/crates/engine/tests/it/copy_direct_selection.rs index 957d778299..c2713befe5 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] diff --git a/crates/engine/tests/plugin_clear_cache.rs b/crates/engine/tests/plugin_clear_cache.rs index 74ba69d644..7a323390c9 100644 --- a/crates/engine/tests/plugin_clear_cache.rs +++ b/crates/engine/tests/plugin_clear_cache.rs @@ -40,6 +40,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() { std::fs::create_dir_all(&folder).unwrap(); let ids = ["test.clearcache.a", "test.clearcache.b"]; let mut s = Session::new(); + s.allow_plugin_grants_from_requests(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); s.attach_plugin_store(folder.clone()); for id in ids { diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 79d66bb636..0bc8615d6f 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -695,6 +695,7 @@ proptest! { prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME); } let mut s = rich_session(); + s.allow_plugin_grants_from_requests(); let module = wat::parse_str(tpl::returning(&text, r#"{"objects":[]}"#)).unwrap(); let data = vectorcraft_format::base64_encode(&module); let r = catch_quiet(|| { @@ -862,6 +863,7 @@ proptest! { prop_assert!(kinds.is_empty() || (man.asks_permissions() && reads), "{}", text); } let mut s = rich_session(); + s.allow_plugin_grants_from_requests(); let module = wat::parse_str(tpl::module(&text, tpl::ECHO, "", 1)).unwrap(); let data = vectorcraft_format::base64_encode(&module); let grant = json!(["doc.read", "doc.write", "state", "effect.render", "export.write"]); @@ -915,6 +917,7 @@ proptest! { let _ = std::fs::remove_dir_all(&store.0); let folder = store.0.clone(); let mut s = Session::new(); + s.allow_plugin_grants_from_requests(); s.attach_plugin_store(folder.clone()); let storing = |id: &str| format!(r#"{{"id":"{id}","name":"F","kind":"filter","api":2,"permissions":["settings","cache"]}}"#); let grant = json!(["settings", "cache"]); 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/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 7fe54fb53e..878ec6bf59 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -204,6 +204,7 @@ fn a_disabled_plug_in_whose_new_grant_cant_be_stored_stays_disabled() { let _f = fresh(); let dir = tmp_dir("reinstall-no-grant"); let mut s = launch(&dir); + s.allow_plugin_grants_from_requests(); let manifest = r#"{"id":"test.sm.g","name":"Test","version":"1","kind":"filter","permissions":["doc.read"]}"#; let module = |out: &str| vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(manifest, out)).unwrap()); s.execute("plugin.install", &json!({"dataBase64": module(r#"{"objects":[]}"#), "grant": ["doc.read"]})).unwrap(); @@ -217,6 +218,37 @@ fn a_disabled_plug_in_whose_new_grant_cant_be_stored_stays_disabled() { let _ = std::fs::remove_dir_all(&dir); } +/// A stored module that lists no permissions and isn't read, because it is disabled or Safe Mode is +/// on, leaves the grant for its id in the store. The load that reads it forgets the grant. +#[test] +fn a_stored_module_that_is_not_read_keeps_the_grant_for_its_id() { + let _f = fresh(); + let dir = tmp_dir("unread-grant"); + let id = "test.sm.unread"; + let mut s = launch(&dir); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter(id))})).unwrap(); + let grants = dir.join("grants.json"); + let entry = serde_json::to_vec(&json!([{"id": id, "hash": "0".repeat(64), "permissions": ["doc.read"]}])).unwrap(); + std::fs::write(&grants, &entry).unwrap(); + + s.execute("plugin.setEnabled", &json!({"id": id, "enabled": false})).unwrap(); + let mut s = launch(&dir); + assert!(!installed(id), "the disabled module is skipped"); + assert_eq!(std::fs::read(&grants).unwrap(), entry, "a disabled module keeps the grant"); + + s.execute("plugin.setEnabled", &json!({"id": id, "enabled": true})).unwrap(); + vectorcraft_engine::cmd::plugin::start_in_safe_mode(); + let mut s = launch(&dir); + assert!(!installed(id), "Safe Mode loads nothing"); + assert_eq!(std::fs::read(&grants).unwrap(), entry, "Safe Mode keeps the grant"); + + safe_mode::set_active(None); + vectorcraft_engine::cmd::plugin::load_prefs_folder(&mut s); + assert!(installed(id)); + assert!(!grants.exists(), "the load that reads the module forgets the grant"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A launch where the stored plug-in `id` stopped while loading: it is installed, then disabled by /// its stored file alone (as Disable and Continue saves it), and the next launch skips it. fn stored_plug_in_disabled_by_file(dir: &std::path::Path, id: &str) -> Session { diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index bc41feb7a9..0a5799ddf9 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -35,6 +35,7 @@ mod ai; mod ate; +mod cid; mod data; mod graphics; mod interp; @@ -44,11 +45,14 @@ mod obj; mod preview; mod shading; mod text; +mod type1; mod type42; #[cfg(test)] mod tests; #[cfg(test)] +mod tests_cid; +#[cfg(test)] mod tests_composite; #[cfg(test)] mod tests_fontnames; @@ -60,13 +64,17 @@ mod tests_illustrator; mod tests_images; #[cfg(test)] mod tests_native; +#[cfg(test)] +mod tests_type1; +#[cfg(test)] +mod tests_type42; use std::collections::HashSet; use std::sync::Arc; use vectorcraft_color::Paint; use vectorcraft_color::swatch::{REGISTRATION, Swatch}; -use vectorcraft_doc::{ColorMode, Document, LayerColor, Node}; +use vectorcraft_doc::{ColorMode, Document, LayerColor, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect}; use graphics::{GState, Out}; @@ -90,6 +98,12 @@ const LETTER: [f64; 4] = [0.0, 0.0, 612.0, 792.0]; /// Largest page side read (points). const MAX_SIDE: f64 = 1e5; +/// The start of the warning that type was set in fonts that aren't available, before ": " and +/// their families: PDF import's words, as type in those fonts comes in the same way. +pub(crate) const MISSING_FONTS_NOTE: &str = "fonts that aren't available show in the fallback font until they are"; +/// Most families named in that warning. +const MAX_MISSING_FONTS: usize = 64; + /// A read file. #[derive(Debug)] pub struct Imported { @@ -257,8 +271,46 @@ pub fn import_trusting(bytes: &[u8], editing_data: bool, trust: bool) -> Result< /// [`import_trusting`], with the names in the editing copy that aren't UTF-8 (layers, objects, /// artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables -/// and data sets) read in `names`. +/// and data sets) read in `names`. The type of the document it gives that is set in families that +/// aren't available shows in the fallback font, and a warning names them. pub fn import_names(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncoding) -> Result { + let mut r = read_names(bytes, editing_data, trust, names)?; + let missing = missing_fonts(&r.document); + if !missing.is_empty() { + r.warnings.push(format!("{MISSING_FONTS_NOTE}: {}", missing.join(", "))); + } + Ok(r) +} + +/// The families of the type in `d` (its layers and its symbols) that aren't available, each once +/// in the order the type comes, at most [`MAX_MISSING_FONTS`]: the document's, whether its type +/// came from the page or from an editing copy, and none for type only measured or outlined. +fn missing_fonts(d: &Document) -> Vec { + let db = vectorcraft_text::FontDb::global(); + let mut checked: HashSet = HashSet::new(); + let mut missing: Vec = Vec::new(); + let mut add = |n: &Node| { + let NodeKind::Text(t) = &n.kind else { return }; + for run in &t.runs { + let family = run.style.font_family.as_str(); + if missing.len() >= MAX_MISSING_FONTS || family.is_empty() || checked.contains(family) { + continue; + } + checked.insert(family.to_string()); + if db.find_family(family).is_none() { + missing.push(family.to_string()); + } + } + }; + d.walk(&mut add); + for s in &d.symbols { + s.art.walk(&mut add); + } + missing +} + +/// [`import_names`] before the type's fonts are checked. +fn read_names(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncoding) -> Result { let ps = program(bytes)?; let dsc = Dsc::read(ps); // A legacy `.ai` VectorCraft wrote: its prolog prints the art plainly (gradients flat, no 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/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/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/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..473a070794 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -279,6 +279,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 +373,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..19cd6fa279 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). diff --git a/crates/eps/src/import/cid.rs b/crates/eps/src/import/cid.rs new file mode 100644 index 0000000000..e2ad169f79 --- /dev/null +++ b/crates/eps/src/import/cid.rs @@ -0,0 +1,971 @@ +//! CID-keyed fonts (PLRM 3rd ed., §5.11): CMaps built with the operators of the `CIDInit` +//! procedure set (and the predefined `Identity-H` and `Identity-V`), `composefont`, Type 0 +//! fonts with `FMapType` 9 that map a show string's codes through their CMap to CIDs, and the +//! glyphs of the CIDFonts they select: Type 0 CIDFonts (Type 1 charstrings in the binary data +//! `StartData` reads, or in a `GlyphDirectory`: PLRM 3rd ed., §5.11.3, and Adobe Technical Note +//! #5014, "Adobe CMap and CIDFont Files Specification") and Type 2 CIDFonts (TrueType glyphs in +//! `sfnts`, picked through `CIDMap`). CIDs carry no characters: the glyphs are drawn from the +//! font's outlines, as a composite font's are. + +use std::rc::Rc; + +use skrifa::raw::ps::cff::CffFontRef; +use skrifa::raw::ps::cff::index::Index; +use skrifa::raw::ps::cs::{CharstringContext, CharstringKind, CommandSink, NopFilterSink, TransformSink}; +use skrifa::raw::ps::error::Error as CsError; +use skrifa::raw::types::{Fixed, GlyphId}; +use vectorcraft_geom::BezPath; + +use super::interp::{Interp, matrix_obj}; +use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err}; + +/// Most codespace ranges, character and notdef mappings a CMap may hold. +const MAX_RANGES: usize = 1 << 16; +/// Most bytes of glyph data a Type 0 CIDFont may carry. +const MAX_GLYPH_DATA: usize = 64 << 20; +/// Most CMaps whose mappings are kept read between shows. +const MAX_CMAPS: usize = 8; +/// Longest code a codespace range may give (PLRM 3rd ed., §5.11.5: the bytes of an integer). +const MAX_CODE: usize = 4; + +/// The CMap entries the CIDInit operators fill: codespace ranges (`[lo hi …]`, strings), and +/// character and notdef mappings to CIDs (`[lo hi cid font …]`, the codes as strings). +const CODESPACE: &str = "CodeSpaceRange"; +const CIDS: &str = "CIDRange"; +const NOTDEFS: &str = "NotDefRange"; +/// Mappings to a base font's character codes or glyph names (`[lo hi dst font …]`: `dst` a +/// string, a name, or an array of them, one a code). +const BASES: &str = "BFRange"; + +/// The mappings of the CMaps shown with so far, by their character mapping, codespace, notdef +/// mapping and base-font mapping arrays, the most recent last. +pub(super) type CMaps = Vec<([Option>; 4], Rc)>; + +/// A CMap's mappings, read from its dictionary. +pub(super) struct CMap { + /// Codespace ranges: each byte's bounds. + space: Vec>, + /// Character mappings (code length, first code, last code, first CID, font), latest first. + cids: Vec<(usize, u32, u32, u32, usize)>, + /// Notdef mappings, latest first. + notdefs: Vec<(usize, u32, u32, u32, usize)>, + /// Mappings to base-font codes or glyph names (code length, first code, last code, what + /// the first code maps to, font), latest first. + bases: Vec<(usize, u32, u32, Obj, usize)>, +} + +/// What a code maps to in a base font (`beginbfchar`, `beginbfrange`). +#[derive(Clone)] +pub(super) enum Base { + Code(u8), + Name(Rc), +} + +/// A character of an `FMapType` 9 font: its code's descendant font and CID, and the notdef +/// mapping's CID for when that font has no glyph for it. +pub(super) struct CidChar { + pub font: usize, + pub cid: u32, + pub notdef: Option, + /// The base-font code or glyph name a `bfchar` or `bfrange` mapping gives it, instead of a + /// CID. + pub base: Option, +} + +impl CMap { + /// The mappings of CMap dictionary `d`. + fn read(d: &Dict) -> Self { + let items = |k: &str| d.get(&Key::name(k)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default(); + let bytes = |o: &Obj| match o { + Obj::Str(s) => Some(s.to_vec()), + _ => None, + }; + let space = items(CODESPACE) + .as_chunks::<2>() + .0 + .iter() + .filter_map(|[lo, hi]| { + let (lo, hi) = (bytes(lo)?, bytes(hi)?); + (!lo.is_empty() && lo.len() == hi.len() && lo.len() <= MAX_CODE).then(|| lo.into_iter().zip(hi).collect()) + }) + .collect(); + let maps = |k: &str| -> Vec<(usize, u32, u32, u32, usize)> { + items(k) + .as_chunks::<4>() + .0 + .iter() + .rev() + .filter_map(|[lo, hi, cid, font]| { + let (lo, hi) = (bytes(lo)?, bytes(hi)?); + let cid = cid.as_num().filter(|c| (0.0..=f64::from(u32::MAX)).contains(c))? as u32; + let font = font.as_num().filter(|f| (0.0..=255.0).contains(f))? as usize; + (!lo.is_empty() && lo.len() == hi.len() && lo.len() <= MAX_CODE).then(|| (lo.len(), code(&lo), code(&hi), cid, font)) + }) + .collect() + }; + let bases = items(BASES) + .as_chunks::<4>() + .0 + .iter() + .rev() + .filter_map(|[lo, hi, dst, font]| { + let (lo, hi) = (bytes(lo)?, bytes(hi)?); + let font = font.as_num().filter(|f| (0.0..=255.0).contains(f))? as usize; + (!lo.is_empty() && lo.len() == hi.len() && lo.len() <= MAX_CODE).then(|| (lo.len(), code(&lo), code(&hi), dst.clone(), font)) + }) + .collect(); + Self { space, cids: maps(CIDS), notdefs: maps(NOTDEFS), bases } + } + + /// The characters of show string `s` (PLRM 3rd ed., §5.11.5 "CMap Mapping" and "Handling + /// Undefined Characters"), and how many ranges and mappings were compared to find them. It + /// stops once that passes `limit` (the characters found so far, and the work done). + pub fn decode(&self, s: &[u8], limit: u64) -> (Vec, u64) { + let mut out = Vec::with_capacity(s.len() / 2); + let mut work = 0u64; + let mut i = 0; + while let Some(rest) = s.get(i..).filter(|r| !r.is_empty() && work <= limit) { + let matched = (1..=MAX_CODE.min(rest.len())).find(|&n| { + work += self.space.len() as u64; + self.space.iter().any(|r| r.len() == n && fits(r, rest)) + }); + let n = match matched { + Some(n) => n, + // An invalid code: as many bytes as the best partly matching range's codes. + None => self.partial(rest), + }; + let n = n.clamp(1, rest.len()); + let c = code(rest.get(..n).unwrap_or_default()); + let find = |maps: &[(usize, u32, u32, u32, usize)], work: &mut u64| { + let at = maps.iter().position(|m| m.0 == n && (m.1..=m.2).contains(&c)); + *work += at.map_or(maps.len(), |k| k + 1) as u64; + at.and_then(|k| maps.get(k)).map(|m| (m.4, m.3.saturating_add(c - m.1), m.3)) + }; + let notdef = find(&self.notdefs, &mut work).map(|(_, _, base)| base); + let at = self.bases.iter().position(|m| m.0 == n && (m.1..=m.2).contains(&c)); + work += at.map_or(self.bases.len(), |k| k + 1) as u64; + let base = at.and_then(|k| self.bases.get(k)).and_then(|m| Some((m.4, base_of(&m.3, c - m.1)?))); + out.push(match (matched.is_some(), find(&self.cids, &mut work), base) { + (true, Some((font, cid, _)), _) => CidChar { font, cid, notdef, base: None }, + (true, None, Some((font, base))) => CidChar { font, cid: 0, notdef: None, base: Some(base) }, + // No character mapping: the notdef mapping's CID, else font 0's CID 0. + _ => match find(&self.notdefs, &mut work) { + Some((font, _, base)) if matched.is_some() => CidChar { font, cid: base, notdef: None, base: None }, + _ => CidChar { font: 0, cid: 0, notdef: None, base: None }, + }, + }); + i += n; + } + (out, work) + } + + /// How many bytes an invalid code at the start of `rest` takes: the length of the codes of + /// the range matching the most of its first bytes (the shortest of those), or of the + /// shortest range when none matches its first byte. + fn partial(&self, rest: &[u8]) -> usize { + let prefix = |r: &[(u8, u8)]| r.iter().zip(rest).take_while(|((lo, hi), b)| (lo..=hi).contains(b)).count(); + let best = self.space.iter().map(|r| prefix(r)).max().unwrap_or(0); + let pick = self.space.iter().filter(|r| best == 0 || prefix(r) == best).map(Vec::len).min(); + pick.unwrap_or(1) + } +} + +/// What the code `k` codes after the first of a base-font mapping to `dst` maps to: a string's +/// code with its last byte that much higher, the `k`th of an array of codes and names, or a +/// name (TN #5099, `beginbfrange`). +fn base_of(dst: &Obj, k: u32) -> Option { + match dst { + // An array's elements are read as codes and names only: an array may hold itself, so + // reading its arrays in turn could recurse without end. + Obj::Array { items, .. } => base_of_leaf(items.borrow().get(usize::try_from(k).ok()?)?, 0), + _ => base_of_leaf(dst, k), + } +} + +/// [`base_of`] for a string or a name. +fn base_of_leaf(dst: &Obj, k: u32) -> Option { + match dst { + Obj::Str(s) => { + let last = u32::from(s.len().checked_sub(1).and_then(|i| s.get(i))?).checked_add(k)?; + Some(Base::Code(u8::try_from(last).ok()?)) + } + Obj::Name(n) if k == 0 => Some(Base::Name(n.clone())), + _ => None, + } +} + +/// Does code `bytes` (as long as `range`, at least) start in codespace range `range`? +fn fits(range: &[(u8, u8)], bytes: &[u8]) -> bool { + range.len() <= bytes.len() && range.iter().zip(bytes).all(|((lo, hi), b)| (lo..=hi).contains(&b)) +} + +/// The number a code's bytes make, the first byte highest. +fn code(bytes: &[u8]) -> u32 { + bytes.iter().take(MAX_CODE).fold(0u32, |c, b| c << 8 | u32::from(*b)) +} + +/// The number `n` bytes at `at` of `data` make, the first byte highest. +fn number(data: &[u8], at: usize, n: usize) -> Option { + let bytes = data.get(at..at.checked_add(n)?)?; + (n <= 8).then(|| bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b))) +} + +/// How a predefined Unicode CMap's codes encode their characters. +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Unicode { + /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. + Utf16, + Utf8, + /// Four bytes, the high byte first. + Utf32, +} + +/// The encoding of predefined Unicode CMap `name` and whether it is vertical: one of Adobe's +/// public CMap resources whose name says its codes are Unicode: `Uni` and a character +/// collection, then `-UCS2`, `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), +/// then `-H` or `-V` (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: +/// ). +pub(super) fn unicode_cmap(name: &str) -> Option<(Unicode, bool)> { + let (rest, dir) = name.rsplit_once('-')?; + let vertical = match dir { + "H" => false, + "V" => true, + _ => return None, + }; + let rest = rest.strip_suffix("-HW").unwrap_or(rest); + let (collection, form) = rest.rsplit_once('-')?; + if !(collection.len() > 3 && collection.starts_with("Uni") && !collection.contains('-')) { + return None; + } + let form = match form { + "UCS2" | "UTF16" => Unicode::Utf16, + "UTF8" => Unicode::Utf8, + "UTF32" => Unicode::Utf32, + _ => return None, + }; + Some((form, vertical)) +} + +/// The characters show string `s` encodes in Unicode form `form` (invalid codes left out). +pub(super) fn unicode_text(s: &[u8], form: Unicode) -> String { + match form { + Unicode::Utf16 => { + let units = s.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b)); + char::decode_utf16(units).filter_map(Result::ok).collect() + } + Unicode::Utf8 => String::from_utf8_lossy(s).chars().filter(|c| *c != char::REPLACEMENT_CHARACTER).collect(), + Unicode::Utf32 => s.as_chunks::<4>().0.iter().filter_map(|b| char::from_u32(u32::from_be_bytes(*b))).collect(), + } +} + +/// A predefined Identity CMap: two-byte codes, each the CID of its own value; vertical for +/// `Identity-V`. +pub(super) fn identity(name: &str, vertical: bool) -> Obj { + let full = || Obj::string(vec![0xff, 0xff]); + let zero = || Obj::string(vec![0, 0]); + let mut d = Dict::new(); + d.insert(Key::name("CMapName"), Obj::name(name)); + d.insert(Key::name("CMapType"), Obj::Int(1)); + d.insert(Key::name("WMode"), Obj::Int(i64::from(vertical))); + d.insert(Key::name(CODESPACE), Obj::array(vec![zero(), full()])); + d.insert(Key::name(CIDS), Obj::array(vec![zero(), full(), Obj::Int(0), Obj::Int(0)])); + Obj::dict(d) +} + +impl Interp<'_> { + /// `composefont` and the operators of the `CIDInit` and `FontSetInit` procedure sets. + pub fn cid_op(&mut self, op: Op) -> Res { + use Op::*; + match op { + // A CMap's mappings take font 0 until its own `usefont` (Adobe Technical Note #5014). + BeginCMap => self.cmap_font = 0, + EndCMap | EndRearrangedFont => {} + BeginCodeSpaceRange | BeginBfChar | BeginBfRange | BeginCidChar | BeginCidRange | BeginNotDefChar | BeginNotDefRange => { + self.pop_int()?; + self.push(Obj::Mark)?; + } + EndCodeSpaceRange => { + let items = self.pop_mark_items()?; + if items.len() % 2 != 0 || !items.iter().all(|o| matches!(o, Obj::Str(_))) { + return ps_err("typecheck", "endcodespacerange"); + } + self.cmap_append(CODESPACE, items)?; + } + EndCidChar | EndCidRange | EndNotDefChar | EndNotDefRange => { + let items = self.pop_mark_items()?; + let per = if matches!(op, EndCidChar | EndNotDefChar) { 2 } else { 3 }; + if items.len() % per != 0 { + return ps_err("rangecheck", op.name()); + } + let mut out = Vec::with_capacity(items.len() / per * 4); + for m in items.chunks_exact(per) { + let (lo, hi, cid) = match m { + [lo, cid] => (lo, lo, cid), + [lo, hi, cid] => (lo, hi, cid), + _ => return ps_err("rangecheck", op.name()), + }; + if !(matches!(lo, Obj::Str(_)) && matches!(hi, Obj::Str(_)) && cid.as_num().is_some()) { + return ps_err("typecheck", op.name()); + } + out.extend([lo.clone(), hi.clone(), cid.clone(), Obj::Int(self.cmap_font)]); + } + self.cmap_append(if matches!(op, EndCidChar | EndCidRange) { CIDS } else { NOTDEFS }, out)?; + } + // Mappings to character codes or names in base fonts (TN #5099, §§3.3 and 4). + EndBfChar | EndBfRange => { + let items = self.pop_mark_items()?; + let per = if op == EndBfChar { 2 } else { 3 }; + if items.len() % per != 0 { + return ps_err("rangecheck", op.name()); + } + let mut out = Vec::with_capacity(items.len() / per * 4); + for m in items.chunks_exact(per) { + let (lo, hi, dst) = match m { + [lo, dst] => (lo, lo, dst), + [lo, hi, dst] => (lo, hi, dst), + _ => return ps_err("rangecheck", op.name()), + }; + if !(matches!(lo, Obj::Str(_)) && matches!(hi, Obj::Str(_)) && matches!(dst, Obj::Str(_) | Obj::Name(_) | Obj::Array { .. })) { + return ps_err("typecheck", op.name()); + } + out.extend([lo.clone(), hi.clone(), dst.clone(), Obj::Int(self.cmap_font)]); + } + self.cmap_append(BASES, out)?; + } + UseFont => { + let n = self.pop_int()?; + self.cmap_font = n.clamp(0, 255); + } + UseCMap => { + let name = self.pop()?; + let parent = self.find_cmap(&name)?; + let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", "usecmap".into()))?; + for k in [CODESPACE, CIDS, NOTDEFS, BASES] { + // Both arrays are copied into a new one: charged by its size first, as + // `cmap_append` charges its copy, so `usecmap` of a large CMap in a loop runs + // out of the budgets instead of the memory. + let len = |c: &DictRef| c.borrow().get(&Key::name(k)).and_then(|a| a.items().map(|i| i.len())).unwrap_or(0); + let n = len(&parent).saturating_add(len(&d)); + if n > MAX_RANGES * 4 { + return Err(PsError::Limit("a CMap has too many mappings")); + } + self.alloc(n.saturating_mul(std::mem::size_of::()))?; + self.spend_bytes(n.saturating_mul(std::mem::size_of::()))?; + let theirs = parent.borrow().get(&Key::name(k)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default(); + let ours = d.borrow().get(&Key::name(k)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default(); + // The parent's mappings first: the CMap's own come later and win. + let all: Vec = theirs.into_iter().chain(ours).collect(); + if all.len() > MAX_RANGES * 4 { + return Err(PsError::Limit("a CMap has too many mappings")); + } + self.insert(&d, Key::name(k), Some(Obj::array(all)))?; + } + let w = parent.borrow().get(&Key::name("WMode")).cloned(); + if let Some(w) = w + && !d.borrow().contains_key(&Key::name("WMode")) + { + self.insert(&d, Key::name("WMode"), Some(w))?; + } + } + BeginRearrangedFont => { + self.pop()?; + self.pop()?; + } + BeginUseMatrix => { + self.pop_int()?; + } + EndUseMatrix => { + self.pop()?; + } + StartData => self.start_data()?, + ComposeFont => self.compose_font()?, + _ => return ps_err("undefined", op.name()), + } + Ok(()) + } + + /// The operands down to the mark that a `begin…` operator pushed. + fn pop_mark_items(&mut self) -> Res> { + let at = self.stack.iter().rposition(|o| matches!(o, Obj::Mark)).ok_or(PsError::Ps("unmatchedmark", String::new()))?; + self.spend((self.stack.len() - at) as u64)?; + let items = self.stack.split_off(at + 1); + self.stack.pop(); + Ok(items) + } + + /// `items` added to the CMap being defined (the current dictionary) under `key`. + fn cmap_append(&mut self, key: &str, items: Vec) -> Res { + let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", key.into()))?; + let mut all = d.borrow().get(&Key::name(key)).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default(); + if all.len().saturating_add(items.len()) > MAX_RANGES * 4 { + return Err(PsError::Limit("a CMap has too many mappings")); + } + self.alloc(items.len() * std::mem::size_of::())?; + // The mappings so far are copied too: a CMap of many small blocks pays for each copy. + self.spend_bytes(all.len().saturating_mul(std::mem::size_of::()))?; + all.extend(items); + self.insert(&d, Key::name(key), Some(Obj::array(all))) + } + + /// CMap `name` (a name, or a CMap dictionary itself). + pub(super) fn find_cmap(&mut self, name: &Obj) -> Res { + if let Obj::Dict(d) = name { + return Ok(d.clone()); + } + let key = name.key().ok_or(PsError::Ps("typecheck", "CMap".into()))?; + if let Some(Obj::Dict(d)) = self.instances(&Obj::name("CMap"))?.borrow().get(&key) { + return Ok(d.clone()); + } + let text = name.text().map(|t| t.to_string()).unwrap_or_default(); + match unicode_cmap(&text) { + Some((_, vertical)) => { + let mut d = Dict::new(); + d.insert(Key::name("CMapName"), Obj::name(&text)); + d.insert(Key::name("CMapType"), Obj::Int(1)); + d.insert(Key::name("WMode"), Obj::Int(i64::from(vertical))); + Ok(DictRef::new(d)) + } + None => Err(PsError::Ps("undefinedresource", text)), + } + } + + /// CIDFont `name` (a name, or a dictionary itself): one the program defined, in the CIDFont + /// category or as a font, else a CIDFont of that name without glyphs (its glyphs show + /// nothing). + pub(super) fn find_cid_font(&mut self, name: &Obj) -> Res { + if let Obj::Dict(d) = name { + return Ok(d.clone()); + } + let key = name.key().ok_or(PsError::Ps("typecheck", "composefont".into()))?; + if let Some(Obj::Dict(d)) = self.instances(&Obj::name("CIDFont"))?.borrow().get(&key) { + return Ok(d.clone()); + } + if let Some(Obj::Dict(d)) = self.fonts.borrow().get(&key) { + return Ok(d.clone()); + } + let mut d = Dict::new(); + d.insert(Key::name("CIDFontName"), key.obj()); + d.insert(Key::name("CIDFontType"), Obj::Int(0)); + d.insert(Key::name("FontType"), Obj::Int(9)); + d.insert(Key::name("FontMatrix"), matrix_obj(vectorcraft_geom::Affine::scale(0.001))); + Ok(DictRef::new(d)) + } + + /// `key cmap [fonts] composefont font`: a Type 0 font with `FMapType` 9 over `cmap` and the + /// CIDFonts (or fonts) named, defined as a font (PLRM 3rd ed., `composefont` in chapter 8). + fn compose_font(&mut self) -> Res { + let fonts = self.pop()?; + let cmap = self.pop()?; + let key = self.pop()?.key().ok_or(PsError::Ps("typecheck", "composefont".into()))?; + let names = fonts.items().map(|i| i.to_vec()).ok_or(PsError::Ps("typecheck", "composefont".into()))?; + let cmap = self.find_cmap(&cmap)?; + let mut deps = Vec::with_capacity(names.len()); + for n in &names { + deps.push(Obj::Dict(self.find_cid_font(n)?)); + } + let font = self.composed(key, cmap, deps); + self.push(Obj::Dict(font)) + } + + /// The Type 0 font `key` with `FMapType` 9 over CMap `cmap` and descendants `deps`, defined + /// as a font. + pub(super) fn composed(&mut self, key: Key, cmap: DictRef, deps: Vec) -> DictRef { + let mut d = Dict::new(); + d.insert(Key::name("FontName"), key.obj()); + d.insert(Key::name("FontType"), Obj::Int(0)); + d.insert(Key::name("FMapType"), Obj::Int(9)); + d.insert(Key::name("FontMatrix"), matrix_obj(vectorcraft_geom::Affine::IDENTITY)); + d.insert(Key::name("Encoding"), Obj::array((0..deps.len() as i64).map(Obj::Int).collect())); + d.insert(Key::name("FDepVector"), Obj::array(deps)); + if let Some(w) = cmap.borrow().get(&Key::name("WMode")).cloned() { + d.insert(Key::name("WMode"), w); + } + d.insert(Key::name("CMap"), Obj::Dict(cmap)); + let font = DictRef::new(d); + self.fonts.borrow_mut().insert(key, Obj::Dict(font.clone())); + font + } + + /// `StartData`: `(Binary) n StartData` in a Type 0 CIDFont file reads its binary data section + /// (`n` bytes after the space that ends the name, or `n` bytes in hexadecimal for `(Hex)`) + /// into the CIDFont's `GlyphData`, defines the CIDFont (the current dictionary) as a resource + /// and ends it and the CIDInit dictionary under it (Adobe Technical Note #5014, §4.3). A + /// FontSet's `/name n StartData` (Compact Font Format data: PLRM 3rd ed., §5.8.1) defines its + /// CID-keyed fonts as CIDFonts (see [`Self::font_set`]); its other fonts are set as type by + /// name. + fn start_data(&mut self) -> Res { + // Glyph data is often larger than the most other operators take (`pop_count`). + let n = self.pop_int()?; + let kind = self.pop()?; + let f = self.running.last().cloned().unwrap_or_else(|| Rc::new(std::cell::RefCell::new(super::data::Stream::Current))); + if n < 0 { + return ps_err("rangecheck", "StartData"); + } + let n = usize::try_from(n).unwrap_or(usize::MAX); + if n > MAX_GLYPH_DATA { + return Err(PsError::Limit("a font's data is too large")); + } + self.alloc(n)?; + self.spend((n / 256) as u64)?; + let hex = match &kind { + Obj::Str(s) => s.to_vec() == b"Hex", + _ => false, + }; + let data = if hex { + let d = self.read_hex(&f, n)?; + // The data can end with the `>` of a hexadecimal string. + self.skip_hex_end(&f)?; + d + } else { + self.read(&f, n)? + }; + if !matches!(kind, Obj::Str(_)) { + return self.font_set(data); + } + let d = self.dicts.last().cloned().ok_or(PsError::Ps("dictstackunderflow", "StartData".into()))?; + self.insert(&d, Key::name("GlyphData"), Some(Obj::string(data)))?; + // A Type 0 CIDFont without a matrix of its own: the 1000-unit glyph space of Type 1 + // fonts, and each FDArray matrix scaled to it (PLRM 3rd ed., §5.11.3). + // The changes go through the journal, so `restore` undoes them as it does the program's. + if !d.borrow().contains_key(&Key::name("FontMatrix")) { + self.insert(&d, Key::name("FontMatrix"), Some(matrix_obj(vectorcraft_geom::Affine::scale(0.001))))?; + let fds = d.borrow().get(&Key::name("FDArray")).and_then(|a| a.items().map(|i| i.to_vec())).unwrap_or_default(); + for fd in fds { + if let Obj::Dict(fd) = fd { + let m = fd.borrow().get(&Key::name("FontMatrix")).and_then(|o| o.items().and_then(|i| super::interp::matrix_of(&i.borrow()))); + if let Some(m) = m { + self.insert(&fd, Key::name("FontMatrix"), Some(matrix_obj(vectorcraft_geom::Affine::scale(1000.0) * m)))?; + } + } + } + } + let name = d.borrow().get(&Key::name("CIDFontName")).and_then(Obj::key); + if let Some(k) = name { + self.instances(&Obj::name("CIDFont"))?.borrow_mut().insert(k, Obj::Dict(d.clone())); + } + if self.dicts.len() > 3 && self.dicts.last().is_some_and(|t| t.same(&d)) { + self.dicts.pop(); + let cid_init = self.instances(&Obj::name("ProcSet"))?.borrow().get(&Key::name("CIDInit")).cloned(); + if let (Some(Obj::Dict(p)), Some(top)) = (cid_init, self.dicts.last()) + && top.same(&p) + && self.dicts.len() > 3 + { + self.dicts.pop(); + } + } + Ok(()) + } + + /// The CID-keyed fonts of FontSet data `data` (Compact Font Format: Adobe Technical Note + /// #5176, a top DICT with `ROS`), each defined as a Type 0 CIDFont of its name in the CFF's + /// Name INDEX, in glyph space of its units an em, whose glyphs are its Type 2 charstrings + /// picked by the CIDs its charset gives them. + fn font_set(&mut self, data: Vec) -> Res { + let data: Rc<[u8]> = data.into(); + for index in 0..MAX_FONT_SET { + let Ok(font) = CffFontRef::new_cff(&data, index, None) else { break }; + let Some(name) = font.metadata().and_then(|m| m.name().map(str::to_string)) else { continue }; + if !font.is_cid() || self.cff.len() >= MAX_CFF { + continue; + } + let upem = f64::from(font.upem()); + let upem = if upem.is_finite() && upem >= 1.0 { upem } else { 1000.0 }; + let mut d = Dict::new(); + d.insert(Key::name("CIDFontName"), Obj::name(&name)); + d.insert(Key::name("CIDFontType"), Obj::Int(0)); + d.insert(Key::name("FontType"), Obj::Int(9)); + d.insert(Key::name("FontMatrix"), matrix_obj(vectorcraft_geom::Affine::scale(1.0 / upem))); + let d = DictRef::new(d); + self.instances(&Obj::name("CIDFont"))?.borrow_mut().insert(Key::name(&name), Obj::Dict(d.clone())); + self.cff.push((d, Rc::new(Cff::new(data.clone(), index)))); + } + Ok(()) + } + + /// The mappings of CMap dictionary `d` (read once while it stays the same). + pub(super) fn cmap(&mut self, d: &DictRef) -> Res> { + let array = |k: &str| d.borrow().get(&Key::name(k)).and_then(|a| a.items().cloned()); + let key = [array(CIDS), array(CODESPACE), array(NOTDEFS), array(BASES)]; + let same = |a: &Option>, b: &Option>| match (a, b) { + (Some(a), Some(b)) => a.same(b), + (None, None) => true, + _ => false, + }; + if let Some((_, m)) = self.cmaps.iter().find(|(k, _)| k.iter().zip(&key).all(|(a, b)| same(a, b))) { + return Ok(m.clone()); + } + let m = Rc::new(CMap::read(&d.borrow())); + self.spend((m.cids.len() + m.space.len() + m.notdefs.len() + m.bases.len()) as u64)?; + if self.cmaps.len() >= MAX_CMAPS { + self.cmaps.remove(0); + } + self.cmaps.push((key, m.clone())); + Ok(m) + } + + /// Glyph `cid` of CIDFont `font`: its outline in the CIDFont's glyph space and its width + /// there, or `None` when the font has no glyph for it (or isn't a CIDFont with glyphs). + pub(super) fn cid_glyph(&mut self, font: &DictRef, cid: u32) -> Res> { + let (kind, count) = { + let f = font.borrow(); + let num = |k: &str| f.get(&Key::name(k)).and_then(Obj::as_num); + (num("CIDFontType"), num("CIDCount")) + }; + if count.is_some_and(|c| f64::from(cid) >= c) { + return Ok(None); + } + let glyph = match kind { + Some(2.0) => self.cid_type2(font, cid)?, + Some(0.0) => self.cid_type0(font, cid)?, + _ => None, + }; + // Widths from the font's `Metrics` override the glyph's own (PLRM 3rd ed., §5.9.2). + Ok(glyph.map(|(outline, w)| { + let m = font.borrow().get(&Key::name("Metrics")).cloned(); + let w = match m { + Some(Obj::Dict(m)) => match m.borrow().get(&Key::Int(i64::from(cid))) { + Some(o) => match o.as_num() { + Some(v) => v, + None => o + .items() + .and_then(|i| match i.len() { + 2 => i.get(1).and_then(|v| v.as_num()), + 4 => i.get(2).and_then(|v| v.as_num()), + _ => None, + }) + .unwrap_or(w), + }, + None => w, + }, + _ => w, + }; + (outline, if w.is_finite() { w } else { 0.0 }) + })) + } + + /// Glyph `cid` of a Type 2 CIDFont: the TrueType glyph its `CIDMap` gives it (a string, or + /// strings, of `GDBytes`-byte glyph indices by CID; a dictionary; or an integer added to the + /// CID: PLRM 3rd ed., §5.11.3), its width in ems. + fn cid_type2(&mut self, font: &DictRef, cid: u32) -> Res> { + let Some(data) = self.type42_data(font)? else { return Ok(None) }; + let gid = { + let f = font.borrow(); + let gd = f.get(&Key::name("GDBytes")).and_then(Obj::as_num).filter(|n| (1.0..=4.0).contains(n)).map_or(2, |n| n as usize); + match f.get(&Key::name("CIDMap")) { + None => Some(u64::from(cid)), + Some(Obj::Int(off)) => u64::try_from(i64::from(cid).saturating_add(*off)).ok(), + Some(Obj::Dict(d)) => d.borrow().get(&Key::Int(i64::from(cid))).and_then(Obj::as_num).filter(|g| *g >= 0.0).map(|g| g as u64), + Some(Obj::Str(s)) => (cid as usize).checked_mul(gd).and_then(|at| number(&s.borrow(), at, gd)), + Some(Obj::Array { items, .. }) => { + // The strings one after another, each a whole number of entries. + let Some(mut at) = (cid as usize).checked_mul(gd) else { return Ok(None) }; + let mut found = None; + for s in items.borrow().iter() { + let Obj::Str(s) = s else { continue }; + let s = s.borrow(); + let len = s.len() - s.len() % gd; + if at < len { + found = number(&s, at, gd); + break; + } + at -= len; + } + found + } + Some(_) => None, + } + }; + let Some(gid) = gid.and_then(|g| u32::try_from(g).ok()).filter(|g| *g <= u32::from(u16::MAX)) else { return Ok(None) }; + if gid == 0 && cid != 0 { + return Ok(None); + } + Ok(super::type42::glyph(&data.data, gid)) + } + + /// Glyph `cid` of a Type 0 CIDFont: the Type 1 charstring its `GlyphDirectory` entry or + /// its binary data section's offset table gives it, run with the subroutines of its + /// FDArray dictionary's `Private` dictionary, in the FDArray dictionary's glyph space under + /// the CIDFont's; its width in the CIDFont's glyph space. + fn cid_type0(&mut self, font: &DictRef, cid: u32) -> Res> { + if let Some(cff) = self.cff.iter().find(|(k, _)| k.same(font)).map(|(_, c)| c.clone()) { + self.spend(64)?; + let read = cff.gids_read().is_some(); + let glyph = cff.glyph(cid); + self.spend(cff.take_work())?; + // Reading the charset visits each of its glyphs. + if !read { + self.spend(cff.gids_read().unwrap_or(0) as u64)?; + } + return Ok(glyph); + } + let f = font.borrow(); + let num = |k: &str, default: f64| f.get(&Key::name(k)).and_then(Obj::as_num).unwrap_or(default); + let fd_bytes = num("FDBytes", 0.0); + let gd_bytes = num("GDBytes", 0.0); + if !(0.0..=4.0).contains(&fd_bytes) || !(0.0..=4.0).contains(&gd_bytes) { + return Ok(None); + } + let (fd_bytes, gd_bytes) = (fd_bytes as usize, gd_bytes as usize); + let data: Option> = match f.get(&Key::name("GlyphData")) { + Some(Obj::Str(s)) => Some(s.clone()), + _ => None, + }; + // The FDArray index and the charstring. + let found: Option<(usize, Vec)> = match f.get(&Key::name("GlyphDirectory")) { + Some(dir @ (Obj::Array { .. } | Obj::Dict(_))) => { + let entry = match dir { + Obj::Dict(d) => d.borrow().get(&Key::Int(i64::from(cid))).cloned(), + _ => dir.items().and_then(|i| i.get(cid as usize)), + }; + match entry { + Some(Obj::Str(s)) => { + let s = s.to_vec(); + let fd = number(&s, 0, fd_bytes).unwrap_or(0) as usize; + Some((fd, s.get(fd_bytes..).unwrap_or_default().to_vec())) + } + _ => None, + } + } + _ => data.as_ref().and_then(|data| { + let data = data.borrow(); + let map = num("CIDMapOffset", 0.0); + if !(0.0..=data.len() as f64).contains(&map) { + return None; + } + let at = (map as usize).checked_add((cid as usize).checked_mul(fd_bytes + gd_bytes)?)?; + let fd = if fd_bytes == 0 { 0 } else { number(&data, at, fd_bytes)? as usize }; + let start = number(&data, at + fd_bytes, gd_bytes)? as usize; + let end = number(&data, at + 2 * fd_bytes + gd_bytes, gd_bytes)? as usize; + Some((fd, data.get(start..end)?.to_vec())) + }), + }; + let Some((fd, charstring)) = found.filter(|(_, c)| !c.is_empty()) else { return Ok(None) }; + let Some(Obj::Dict(fd)) = f.get(&Key::name("FDArray")).and_then(|a| a.items().and_then(|i| i.get(fd))) else { return Ok(None) }; + drop(f); + let fd = fd.borrow(); + let fdm = fd + .get(&Key::name("FontMatrix")) + .and_then(|o| o.items().and_then(|i| super::interp::matrix_of(&i.borrow()))) + .unwrap_or(vectorcraft_geom::Affine::IDENTITY); + let Some(Obj::Dict(private)) = fd.get(&Key::name("Private")).cloned() else { return Ok(None) }; + drop(fd); + let len_iv = private.borrow().get(&Key::name("lenIV")).and_then(Obj::as_num).unwrap_or(4.0); + let subrs = self.cid_subrs(&private, data.as_ref(), len_iv)?; + self.spend((charstring.len() as u64).saturating_add(64))?; + let charstring = decrypt(&charstring, len_iv); + let (glyph, work) = type1_glyph(&charstring, &subrs); + // The subroutines it ran, which the evaluator limits for each glyph, not for the file. + self.spend(work)?; + let Some((outline, width)) = glyph else { return Ok(None) }; + let mut outline = outline; + outline.apply_affine(fdm); + let w = fdm * vectorcraft_geom::Point::new(width, 0.0) - fdm * vectorcraft_geom::Point::ZERO; + Ok(Some((outline, w.x))) + } + + /// The subroutines of a Type 0 CIDFont's FDArray `Private` dictionary `private`, decrypted + /// with `len_iv`: its `Subrs` array, else the subroutine table of the CIDFont's binary data + /// `data` (Adobe Technical Note #5014). Read once while they stay the same, and counted + /// against the budgets before they are copied. + fn cid_subrs(&mut self, private: &DictRef, data: Option<&Shared>, len_iv: f64) -> Res>>> { + let same_data = |d: &Option>| match (d, data) { + (Some(a), Some(b)) => a.same(b), + (None, None) => true, + _ => false, + }; + if let Some(i) = self.cid_subrs.iter().position(|(p, d, _)| p.same(private) && same_data(d)) { + let hit = self.cid_subrs.remove(i); + let subrs = hit.2.clone(); + self.cid_subrs.push(hit); + return Ok(subrs); + } + let p = private.borrow(); + // Each subroutine's bytes: a string of `Subrs`, or a range of the binary data. + let strings: Option>>> = match p.get(&Key::name("Subrs")) { + Some(Obj::Array { items, .. }) => Some( + items + .borrow() + .iter() + .map(|s| match s { + Obj::Str(s) => Some(s.clone()), + _ => None, + }) + .collect(), + ), + _ => None, + }; + let mut ranges: Vec> = Vec::new(); + if strings.is_none() { + let num = |k: &str| p.get(&Key::name(k)).and_then(Obj::as_num).filter(|n| *n >= 0.0); + if let (Some(map), Some(sd), Some(count), Some(data)) = (num("SubrMapOffset"), num("SDBytes"), num("SubrCount"), data) { + let data = data.borrow(); + let (map, sd, count) = (map as usize, (sd as usize).min(4), (count as usize).min(MAX_RANGES)); + for i in 0..count { + let at = map.saturating_add(i.saturating_mul(sd)); + let range = number(&data, at, sd).zip(number(&data, at.saturating_add(sd), sd)); + ranges.push(range.map(|(a, b)| (a as usize, b as usize)).filter(|(a, b)| a <= b && *b <= data.len())); + } + } + } + drop(p); + let total = match &strings { + Some(strings) => strings.iter().flatten().fold(0usize, |t, s| t.saturating_add(s.len())), + None => ranges.iter().flatten().fold(0usize, |t, (a, b)| t.saturating_add(b - a)), + }; + if total > MAX_GLYPH_DATA { + return Err(PsError::Limit("a font's subroutines are too large")); + } + self.alloc(total)?; + self.spend_bytes(total)?; + self.spend((strings.as_ref().map_or(ranges.len(), Vec::len) / 16) as u64)?; + let subrs: Vec> = match (&strings, data) { + (Some(strings), _) => strings.iter().map(|s| s.as_ref().map(|s| decrypt(&s.borrow(), len_iv)).unwrap_or_default()).collect(), + (None, Some(data)) => { + let data = data.borrow(); + ranges.iter().map(|r| r.and_then(|(a, b)| data.get(a..b)).map(|s| decrypt(s, len_iv)).unwrap_or_default()).collect() + } + (None, None) => vec![], + }; + let subrs = Rc::new(subrs); + if self.cid_subrs.len() >= MAX_SUBR_SETS { + self.cid_subrs.remove(0); + } + self.cid_subrs.push((private.clone(), data.cloned(), subrs.clone())); + Ok(subrs) + } +} + +/// Most fonts read from one FontSet. +const MAX_FONT_SET: u32 = 64; +/// Most CIDFonts read from FontSets. +const MAX_CFF: usize = 256; + +/// A CID-keyed font in Compact Font Format data: the data and the font's index in it, and the +/// glyph its charset gives each CID (read when first asked). +pub(super) struct Cff { + data: Rc<[u8]>, + index: u32, + gids: std::cell::OnceCell>, + /// The charstring bytes glyphs entered, not yet charged. + work: std::cell::Cell, +} + +impl Cff { + pub(super) fn new(data: Rc<[u8]>, index: u32) -> Self { + Self { data, index, gids: std::cell::OnceCell::new(), work: std::cell::Cell::new(0) } + } + + /// Whether the CID-to-glyph map has been read, and the glyphs it holds. + fn gids_read(&self) -> Option { + self.gids.get().map(std::collections::HashMap::len) + } + + /// Glyph `cid`: the glyph the charset gives that CID, drawn from its Type 2 charstring with + /// the subroutines and widths of its FDSelect subfont, in font units; `None` when the font + /// has no glyph for it. + pub(super) fn glyph(&self, cid: u32) -> Option<(BezPath, f64)> { + let font = CffFontRef::new_cff(&self.data, self.index, None).ok()?; + // The charset read once into a map, instead of searched for each glyph. + let gids = self.gids.get_or_init(|| font.charset().map(|c| c.iter().map(|(g, sid)| (sid.to_u16(), g)).collect()).unwrap_or_default()); + let gid = *gids.get(&u16::try_from(cid).ok()?)?; + if gid.to_u32() == 0 && cid != 0 { + return None; + } + let sub = font.subfont(font.subfont_index(gid)?, &[]).ok()?; + // Run as `CffFontRef::draw` does, through the counting context, so the subroutines a + // glyph enters (up to a million operations each time) are paid for. + let subrs = match sub.subrs_offset() { + 0 => Index::Empty, + at => Index::new(self.data.get(at as usize..)?, false).ok()?, + }; + let charstrings = font.charstrings().clone(); + let data = charstrings.get(gid.to_u32() as usize)?; + let ctx = (&self.data[..], &charstrings, font.global_subrs(), &subrs); + let mut pen = super::type42::Pen(BezPath::new(), 1.0); + let transform = font.transform(&sub, None); + let mut filter = NopFilterSink::new(&mut pen); + let mut sink = TransformSink::new(&mut filter, transform); + let (w, work) = super::type1::evaluate(&ctx, data, &mut sink); + self.work.set(self.work.get().saturating_add(work)); + let w = w.ok()?.map(|w| w + sub.nominal_width()).or(sub.default_width()); + let w = w.map_or(0.0, |w| f64::from(transform.transform_h_metric(w).to_f32().max(0.0))); + Some((pen.0, if w.is_finite() { w } else { 0.0 })) + } + + /// The charstring bytes entered since the last call (see [`super::type1::evaluate`]). + pub(super) fn take_work(&self) -> u64 { + self.work.take() + } +} + +/// Most FDArray dictionaries whose subroutines are kept decrypted between glyphs. +const MAX_SUBR_SETS: usize = 32; + +/// The decrypted subroutines of FDArray `Private` dictionaries, by the dictionary and the +/// CIDFont's binary data (see [`Interp::cid_subrs`]), the most recently used last. +pub(super) type CidSubrs = Vec<(DictRef, Option>, Rc>>)>; + +/// Type 1 charstring `data` decrypted (the charstring key 4330, the first `len_iv` bytes +/// dropped: Adobe Type 1 Font Format, §7.2); as it is when `len_iv` is negative. +pub(super) fn decrypt(data: &[u8], len_iv: f64) -> Vec { + if len_iv < 0.0 { + return data.to_vec(); + } + let mut r: u16 = 4330; + let plain = data.iter().map(|&c| { + let p = c ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + p + }); + plain.skip(len_iv.min(64.0) as usize).collect() +} + +/// The outline (glyph space) and width of decrypted Type 1 charstring `data`, with +/// subroutines `subrs`, or `None` when it can't be run; and the bytes of the charstrings it +/// entered (see [`super::type1::evaluate`]). +pub(super) fn type1_glyph(data: &[u8], subrs: &[Vec]) -> (Option<(BezPath, f64)>, u64) { + let ctx = Type1 { subrs }; + let mut sink = Sink(BezPath::new()); + let (w, work) = super::type1::evaluate(&ctx, data, &mut sink); + (w.ok().map(|w| (sink.0, w.map_or(0.0, |w| f64::from(w.to_f32())))), work) +} + +/// What a Type 1 charstring runs with: its font's subroutines (no `seac` accents: a CIDFont's +/// glyphs have no names to build them from). +struct Type1<'a> { + subrs: &'a [Vec], +} + +impl CharstringContext for Type1<'_> { + fn kind(&self) -> CharstringKind { + CharstringKind::Type1 + } + fn seac_components(&self, base: i32, _accent: i32) -> Result<[&[u8]; 2], CsError> { + Err(CsError::InvalidSeacCode(base)) + } + fn global_subr(&self, _index: i32) -> Result<&[u8], CsError> { + Err(CsError::MissingSubroutines) + } + fn subr(&self, index: i32) -> Result<&[u8], CsError> { + usize::try_from(index).ok().and_then(|i| self.subrs.get(i)).map(Vec::as_slice).ok_or(CsError::MissingSubroutines) + } +} + +/// A charstring's path, in glyph space. +struct Sink(BezPath); + +impl CommandSink for Sink { + fn move_to(&mut self, x: Fixed, y: Fixed) { + self.0.move_to((f64::from(x.to_f32()), f64::from(y.to_f32()))); + } + fn line_to(&mut self, x: Fixed, y: Fixed) { + self.0.line_to((f64::from(x.to_f32()), f64::from(y.to_f32()))); + } + fn curve_to(&mut self, cx0: Fixed, cy0: Fixed, cx1: Fixed, cy1: Fixed, x: Fixed, y: Fixed) { + let p = |a: Fixed, b: Fixed| (f64::from(a.to_f32()), f64::from(b.to_f32())); + self.0.curve_to(p(cx0, cy0), p(cx1, cy1), p(x, y)); + } + fn close(&mut self) { + self.0.close_path(); + } +} diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 4397a0e230..33f394482a 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -196,7 +196,7 @@ impl Interp<'_> { } /// Up to `n` bytes of file `f`. - fn read(&mut self, f: &Rc>, n: usize) -> Res> { + pub(in super::super) fn read(&mut self, f: &Rc>, n: usize) -> Res> { self.materialize(f)?; Ok(match &mut *f.borrow_mut() { Stream::Current => { @@ -236,7 +236,7 @@ impl Interp<'_> { } /// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). - fn read_hex(&mut self, f: &Rc>, n: usize) -> Res> { + pub(in super::super) fn read_hex(&mut self, f: &Rc>, n: usize) -> Res> { let mut out = Vec::with_capacity(n); let mut high: Option = None; while out.len() < n { @@ -250,6 +250,31 @@ impl Interp<'_> { Ok(out) } + /// Skip the whitespace and the `>` that end hexadecimal data in `f`, if a `>` is next: the + /// rest is left unread. + pub(in super::super) fn skip_hex_end(&mut self, f: &Rc>) -> Res { + self.materialize(f)?; + let blank = |b: &u8| b.is_ascii_whitespace() || *b == 0; + match &mut *f.borrow_mut() { + Stream::Current => { + let rest = self.lex.data(); + let n = rest.iter().take_while(|b| blank(b)).count(); + if rest.get(n) == Some(&b'>') { + self.lex.advance(n + 1); + } + } + Stream::Buf { data, pos, .. } => { + let rest = data.get(*pos..).unwrap_or_default(); + let n = rest.iter().take_while(|b| blank(b)).count(); + if rest.get(n) == Some(&b'>') { + *pos += n + 1; + } + } + Stream::Pending { .. } => {} + } + Ok(()) + } + /// Read bytes `got` into string `s` and push the part of `s` they fill. fn fill(&mut self, s: Shared, got: &[u8]) -> Res { if !s.write(0, got) { @@ -451,6 +476,10 @@ impl Interp<'_> { continue; } let want = step.min(n - o.len()); + // The bytes of this read's own copy of a procedure's string: counted while it + // lives, released once it is appended (the string itself is the program's, and + // stays counted as long as the program can hold it). + let mut copied = 0; let chunk = match src { Source::File(f) => self.read(f, want)?, // A string gives its bytes over and over. @@ -462,26 +491,31 @@ impl Interp<'_> { self.call(p.clone())?; let s = self.pop_str()?.to_vec(); self.alloc(s.len())?; + copied = s.len(); s } }; *e = chunk.is_empty(); o.extend_from_slice(chunk.get(..chunk.len().min(n - o.len())).unwrap_or_default()); + drop(chunk); + self.unalloc(copied); } } Ok(out) } - /// `file eexec`: an encrypted font program follows in `file`. It is skipped there, up to the - /// `cleartomark` that ends it (type is drawn in the app's fonts, by name): the font - /// dictionary it would complete is defined as it is. + /// `file eexec`: an encrypted font program follows in `file`. It isn't run: it is skipped + /// there, up to the `cleartomark` that ends it, and the font dictionary it would complete is + /// defined as it is, with the glyphs the Type 1 font parser reads from it (see `type1`). fn eexec(&mut self) -> Res { let src = self.pop()?; + let mut font = None; if let Some(Obj::Dict(d)) = self.stack.last().cloned() { let name = d.borrow().get(&Key::name("FontName")).cloned(); if let Some(k) = name.and_then(|n| n.key()) { self.pop()?; - self.fonts.borrow_mut().insert(k, Obj::Dict(d)); + self.fonts.borrow_mut().insert(k, Obj::Dict(d.clone())); + font = Some(d); } } // `currentfile eexec`: the program's own file or the file being run. A string operand @@ -492,15 +526,31 @@ impl Interp<'_> { }; self.materialize(&f)?; let missing = || PsError::Ps("ioerror", "eexec".into()); - match &mut *f.borrow_mut() { + // The encrypted part, for the font's glyphs (a font's, of a size that can be read). + // Copied only when the font can still be kept (it is dropped otherwise). + let room = font.is_some() && self.type1_room(); + let keep = |part: &[u8]| (room && part.len() <= super::super::type1::MAX_PROGRAM).then(|| part.to_vec()); + let (encrypted, scanned) = match &mut *f.borrow_mut() { Stream::Buf { data, pos, .. } => { - let at = find(data.get(*pos..).unwrap_or_default(), b"cleartomark").ok_or_else(missing)?; + let rest = data.get(*pos..).unwrap_or_default(); + let at = find(rest, b"cleartomark").ok_or_else(missing)?; + let part = keep(rest.get(..at).unwrap_or_default()); *pos += at; + (part, at) } _ => { - let at = find(self.lex.data(), b"cleartomark").ok_or_else(missing)?; + let rest = self.lex.data(); + let at = find(rest, b"cleartomark").ok_or_else(missing)?; + let part = keep(rest.get(..at).unwrap_or_default()); self.lex.advance(at); + (part, at) } + }; + // The search for `cleartomark` read the part: charged by its length (as `search` is), so `eexec` on a + // large reusable file in a loop runs out of the budget. + self.spend((scanned / 64) as u64)?; + if let (Some(d), Some(part)) = (font, encrypted) { + self.attach_type1(&d, &part)?; } self.push(Obj::Mark) } @@ -549,12 +599,16 @@ impl Interp<'_> { } return Ok(None); } + // Interleaved data is read into this decoder's own buffers, split into the two images' + // samples: those stop counting once both are decoded (their pixels still count). + let mut charged = 0; if interleave != 3.0 { let src = image.sources.first().cloned().ok_or(PsError::Ps("undefined", "DataSource".into()))?; let (pixels, samples) = if interleave == 2.0 { let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n)); let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h)); self.alloc(total)?; + charged = total; let raw = self.source_bytes(&src, total.min(MAX_DATA))?; by_rows(&raw, (mrow, stencil.h), (drow, image.h)) } else { @@ -562,15 +616,21 @@ impl Interp<'_> { stencil.bpc = image.bpc; (stencil.w, stencil.h) = (image.w, image.h); let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8); - self.alloc(row.saturating_mul(image.h))?; - let raw = self.source_bytes(&src, row.saturating_mul(image.h).min(MAX_DATA))?; + charged = row.saturating_mul(image.h); + self.alloc(charged)?; + let raw = self.source_bytes(&src, charged.min(MAX_DATA))?; by_samples(&raw, image.w, image.h, n, image.bpc) }; stencil.sources = vec![Source::Str(pixels)]; image.sources = vec![Source::Str(samples)]; } - let Some(mut img) = self.decode_image(image)? else { return Ok(None) }; - let Some(m) = self.decode_image(stencil)? else { return Ok(Some(img)) }; + let decoded = match self.decode_image(image) { + Ok(Some(img)) => self.decode_image(stencil).map(|m| Some((img, m))), + other => other.map(|_| None), + }; + self.unalloc(charged); + let Some((mut img, m)) = decoded? else { return Ok(None) }; + let Some(m) = m else { return Ok(Some(img)) }; let (w, h, mw, mh) = (img.w as usize, img.h as usize, m.w as usize, m.h as usize); for (i, px) in img.rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { let (x, y) = (i % w, i / w); @@ -689,7 +749,11 @@ impl Interp<'_> { return ps_err("rangecheck", "DataSource"); } let plane = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA).ok_or(PsError::Limit("decoded data is too large"))?; - self.alloc(plane.saturating_mul(sources.len()))?; + // The sample planes are this decoder's own and live only while the image is decoded: they + // stop counting once it is (the pixels made from them still count). What the data source + // procedures allocate is the program's and stays counted. + let plane_bytes = plane.saturating_mul(sources.len()); + self.alloc(plane_bytes)?; let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?; for p in &mut planes { p.resize(row * s.h, 0); @@ -766,6 +830,8 @@ impl Interp<'_> { rgba.extend([rgb[0], rgb[1], rgb[2], if masked { 0 } else { 255 }]); } } + drop(planes); + self.unalloc(plane_bytes); Ok(Some(Pixels { w: s.w as u32, h: s.h as u32, rgba, inks, matrix: s.matrix })) } diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index d3d9c2bdd0..4920b1d66d 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -79,6 +79,19 @@ pub(crate) struct Interp<'a> { /// The `sfnts` arrays whose TrueType data has been counted against [`MAX_MEMORY`]: a font /// read again after it left `type42` doesn't count again. pub type42_counted: HashSet>, + /// The mappings of the CMaps shown with so far, by their range arrays (see `cid`), the most + /// recent last. + pub cmaps: super::cid::CMaps, + /// The Type 1 fonts read from the encrypted part of their programs, by the `CharStrings` + /// dictionary given to their font dictionaries (see `type1`). + pub type1: Vec<(DictRef, Rc)>, + /// The CIDFonts a FontSet's Compact Font Format data defined, by their dictionaries: the + /// data and the font's index in it (see `cid`). + pub cff: Vec<(DictRef, Rc)>, + /// The decrypted subroutines of Type 0 CIDFonts (see `cid`). + pub cid_subrs: super::cid::CidSubrs, + /// The font number `usefont` gave the CMap mappings that follow. + pub cmap_font: i64, pub g: GState, pub saved: Vec, pub out: Out, @@ -101,7 +114,7 @@ pub(crate) struct Fault { } /// The TrueType data of Type 42 fonts by their `sfnts` array (see [`Interp::type42`]). -pub(crate) type Type42Cache = Vec<(Shared, Option>>)>; +pub(crate) type Type42Cache = Vec<(Shared, Option>)>; /// Most procedure names a [`Fault`] keeps. const FAULT_PROCS: usize = 3; @@ -137,7 +150,7 @@ impl<'a> Interp<'a> { let encodings = new_dict(); { let mut d = system.borrow_mut(); - for (op, name) in Op::ALL { + for (op, name) in Op::ALL.iter().filter(|(op, _)| !Op::PROCSET.contains(op)) { d.insert(Key::name(name), Obj::Op(*op)); } for name in ["StandardEncoding", "ISOLatin1Encoding"] { @@ -155,6 +168,21 @@ impl<'a> Interp<'a> { let resources = new_dict(); resources.borrow_mut().insert(Key::name("Category"), Obj::dict(categories)); resources.borrow_mut().insert(Key::name("Encoding"), Obj::Dict(encodings)); + // The procedure sets that build CMaps and CIDFonts (CIDInit) and font sets (FontSetInit), + // and the predefined Identity CMaps. + let cid_init: Dict = Op::PROCSET.iter().map(|op| (Key::name(op.name()), Obj::Op(*op))).collect(); + let font_set_init = Dict::from([(Key::name("StartData"), Obj::Op(Op::StartData))]); + resources.borrow_mut().insert( + Key::name("ProcSet"), + Obj::dict(Dict::from([(Key::name("CIDInit"), Obj::dict(cid_init)), (Key::name("FontSetInit"), Obj::dict(font_set_init))])), + ); + resources.borrow_mut().insert( + Key::name("CMap"), + Obj::dict(Dict::from([ + (Key::name("Identity-H"), super::cid::identity("Identity-H", false)), + (Key::name("Identity-V"), super::cid::identity("Identity-V", true)), + ])), + ); let fonts = new_dict(); system.borrow_mut().insert(Key::name("FontDirectory"), Obj::Dict(fonts.clone())); for name in ["GlobalFontDirectory", "SharedFontDirectory"] { @@ -199,6 +227,11 @@ impl<'a> Interp<'a> { fault: None, glyph_width: None, type42: vec![], + cmaps: vec![], + type1: vec![], + cff: vec![], + cid_subrs: vec![], + cmap_font: 0, type42_counted: HashSet::new(), g, saved: vec![], @@ -367,6 +400,12 @@ impl<'a> Interp<'a> { Ok(()) } + /// Stop counting `bytes` the program no longer holds: buffers an operator made for itself and + /// freed before it returned. Never for what the program's own procedures allocated. + pub(crate) fn unalloc(&mut self, bytes: usize) { + self.allocated = self.allocated.saturating_sub(bytes); + } + fn tick(&mut self) -> Res { self.spend(1) } @@ -377,6 +416,11 @@ impl<'a> Interp<'a> { self.spend((n / 256) as u64) } + /// The operations left in the budget (`max_ops`). + pub fn ops_left(&self) -> u64 { + self.max_ops.saturating_sub(self.ops) + } + /// Count `ops` operations' worth of work against the budget (`max_ops`): what an operator that costs /// far more than one operation (laying out type) does in a loop has to end too. pub fn spend(&mut self, ops: u64) -> Res { @@ -1395,7 +1439,7 @@ impl<'a> Interp<'a> { /// Put `v` under `k` in `d` (`None`: remove it), within [`MAX_ALLOC`] entries; while a `save` /// is open the old value is kept for `restore`. - fn insert(&mut self, d: &DictRef, k: Key, v: Option) -> Res { + pub fn insert(&mut self, d: &DictRef, k: Key, v: Option) -> Res { let old = { let mut dm = d.borrow_mut(); if v.is_some() && dm.len() >= MAX_ALLOC && !dm.contains_key(&k) { @@ -1425,6 +1469,21 @@ impl<'a> Interp<'a> { }) } + /// Is `o` the standard encoding (`Some(false)`) or the ISO Latin-1 encoding (`Some(true)`) + /// of systemdict, whose names here are all `.notdef`? + pub fn standard_encoding(&self, o: &Obj) -> Option { + let items = o.items()?; + let s = self.system.borrow(); + let is = |k: &str| s.get(&Key::name(k)).and_then(Obj::items).is_some_and(|e| e.same(items)); + if is("StandardEncoding") { + Some(false) + } else if is("ISOLatin1Encoding") { + Some(true) + } else { + None + } + } + /// The instances of `category`: `FontDirectory` for fonts. pub fn instances(&mut self, category: &Obj) -> Res { if category.text().as_deref() == Some("Font") { Ok(self.fonts.clone()) } else { self.category(category) } diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 5dd918fb51..eaa50b6bbf 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -1,7 +1,7 @@ use super::layers::closed_where_ends_meet; use super::slots::{ Content, MAX_PAIRS, OUTLINE_REACH, PAGE_TYPE_LEFT_OUT, PAGE_TYPE_UNCHECKED, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, - words, + word_pieces, words, }; use super::{Affine, Arc, Node, NodeId, NodeKind, Point, Rect, Story, TextKind}; @@ -283,9 +283,10 @@ fn plain_text(n: &Node) -> String { if let NodeKind::Text(t) = &n.kind { t.plain_text() } else { String::new() } } -/// The words of the page's text object `o`, each as its [`spelling`], the empty ones left out. +/// The words of the page's text object `o` (see [`word_pieces`]), each as its [`spelling`], the +/// empty ones left out. fn object_words(o: &[Arc]) -> Vec { - o.iter().flat_map(|n| plain_text(n).split_whitespace().map(spelling).collect::>()).filter(|w| !w.is_empty()).collect() + o.iter().flat_map(|n| word_pieces(&plain_text(n)).map(spelling).collect::>()).filter(|w| !w.is_empty()).collect() } /// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws, diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index f0cda3088a..bce43140d1 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -446,7 +446,21 @@ pub(super) fn letters(s: &str) -> String { /// the page draws a right-to-left paragraph's words in the order they show (" 120.5 mm " as /// "mm 120.5"), its text object keeps them in the order they are typed. pub(super) fn words(s: &str) -> Vec { - s.split_whitespace().map(letters).filter(|w| !w.is_empty()).collect() + word_pieces(s).map(letters).filter(|w| !w.is_empty()).collect() +} + +/// The words of `s`, split at spaces and at private-use characters too. The page's type names a +/// font's ligature glyph that has no character of its own (`uniE028`, the Adobe Glyph List +/// specification's `uniXXXX` names: ) by a +/// private-use character, where its text object has the letters ("Qual\u{E028}y" for +/// "Quality"): what is around it is compared, each piece as a word. +pub(super) fn word_pieces(s: &str) -> impl Iterator { + s.split(|c: char| c.is_whitespace() || private_use(c)).filter(|w| !w.is_empty()) +} + +/// Is `c` in one of Unicode's private use areas (Unicode Standard §23.5)? +fn private_use(c: char) -> bool { + matches!(u32::from(c), 0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD) } /// Does `n` hold type that is where `story` lays one of its lines out: the line, or a piece of it diff --git a/crates/eps/src/import/obj.rs b/crates/eps/src/import/obj.rs index ddf4858c82..2b3ae92c73 100644 --- a/crates/eps/src/import/obj.rs +++ b/crates/eps/src/import/obj.rs @@ -21,6 +21,11 @@ impl DictRef { note(Made::Dict(Rc::downgrade(&d))); Self(d) } + + /// Is `o` this very dictionary? + pub fn same(&self, o: &Self) -> bool { + Rc::ptr_eq(&self.0, &o.0) + } } /// An array or a dictionary a program made. @@ -443,6 +448,16 @@ macro_rules! ops { /// Every operator with its name (`systemdict`). pub const ALL: &'static [(Op, &'static str)] = &[$((Op::$v, $n)),*]; + /// The operators of the CIDInit procedure set (PLRM 3rd ed., §5.11.4), found through + /// it rather than systemdict. + pub const PROCSET: &'static [Op] = &[ + Op::BeginCMap, Op::EndCMap, Op::UseCMap, Op::BeginCodeSpaceRange, Op::EndCodeSpaceRange, Op::UseFont, + Op::BeginBfChar, Op::EndBfChar, Op::BeginBfRange, Op::EndBfRange, Op::BeginCidChar, Op::EndCidChar, + Op::BeginCidRange, Op::EndCidRange, Op::BeginNotDefChar, Op::EndNotDefChar, Op::BeginNotDefRange, + Op::EndNotDefRange, Op::BeginRearrangedFont, Op::EndRearrangedFont, Op::BeginUseMatrix, Op::EndUseMatrix, + Op::StartData, + ]; + pub fn name(self) -> &'static str { match self { $(Op::$v => $n),* } } @@ -542,6 +557,15 @@ ops! { SetVmThreshold = "setvmthreshold", VmReclaim = "vmreclaim", StartJob = "startjob", CurrentObjectFormat = "currentobjectformat", Revision = "revision", SerialNumber = "serialnumber", Read = "read", FilePosition = "fileposition", SetFilePosition = "setfileposition", DeleteFile = "deletefile", RenameFile = "renamefile", Run = "run", + // CID-keyed fonts: `composefont`, and the operators of the CIDInit procedure set (CMaps and + // `StartData`, which FontSetInit has too), which aren't in systemdict (see `Op::PROCSET`). + ComposeFont = "composefont", BeginCMap = "begincmap", EndCMap = "endcmap", UseCMap = "usecmap", + BeginCodeSpaceRange = "begincodespacerange", EndCodeSpaceRange = "endcodespacerange", UseFont = "usefont", + BeginBfChar = "beginbfchar", EndBfChar = "endbfchar", BeginBfRange = "beginbfrange", EndBfRange = "endbfrange", + BeginCidChar = "begincidchar", EndCidChar = "endcidchar", BeginCidRange = "begincidrange", EndCidRange = "endcidrange", + BeginNotDefChar = "beginnotdefchar", EndNotDefChar = "endnotdefchar", BeginNotDefRange = "beginnotdefrange", + EndNotDefRange = "endnotdefrange", BeginRearrangedFont = "beginrearrangedfont", EndRearrangedFont = "endrearrangedfont", + BeginUseMatrix = "beginusematrix", EndUseMatrix = "endusematrix", StartData = "StartData", // User paths. UFill = "ufill", UEoFill = "ueofill", UStroke = "ustroke", UAppend = "uappend", UPath = "upath", SetBBox = "setbbox", } diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 70e69dae1f..f4edc0ac8f 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -737,7 +737,7 @@ fn embedded_font_programs_are_skipped() { let r = read(&program); let NodeKind::Text(t) = &objects(&r.document)[0].kind else { panic!("{program}: {:?}", r.warnings) }; assert_eq!(t.runs[0].style.font_family, "My Font"); - assert!(r.warnings.is_empty(), "{program}: {:?}", r.warnings); + assert!(program_warnings(&r.warnings).is_empty(), "{program}: {:?}", r.warnings); } } @@ -833,12 +833,18 @@ fn device_settings_are_accepted_and_change_nothing() { } /// Check that `body` draws one square, blue: it sets blue when what it checks holds, else red. +/// `warnings` without the note naming fonts that aren't available: which those are depends on the +/// fonts installed where the tests run, not on the program. +pub(super) fn program_warnings(warnings: &[String]) -> Vec<&String> { + warnings.iter().filter(|w| !w.starts_with(super::MISSING_FONTS_NOTE)).collect() +} + fn blue(body: &str) { let r = read(&format!("{body} 10 10 80 80 rectfill")); let o = objects(&r.document); assert_eq!(o.len(), 1, "{body}: {:?}", r.warnings); assert_eq!(fill(&o[0]), Some(&Paint::solid(Color::rgb(0.0, 0.0, 1.0))), "{body}"); - assert!(r.warnings.is_empty(), "{body}: {:?}", r.warnings); + assert!(program_warnings(&r.warnings).is_empty(), "{body}: {:?}", r.warnings); } /// Check that PostScript `cond` leaves `true`. @@ -983,8 +989,8 @@ fn intervals_share_their_arrays_and_strings() { fn resourceforall_enumerates_matching_names() { // #234. blue("(*) { pop } 128 string /Category resourceforall 0 0 1 setrgbcolor"); - let count = |template: &str| format!("/n 0 def ({template}) {{ pop /n n 1 add def }} 128 string /ProcSet resourceforall n"); - let define = "[/Foo /Fop /Bar /F*x] { 1 dict /ProcSet defineresource pop } forall"; + let count = |template: &str| format!("/n 0 def ({template}) {{ pop /n n 1 add def }} 128 string /Form resourceforall n"); + let define = "[/Foo /Fop /Bar /F*x] { 1 dict /Form defineresource pop } forall"; check(&format!("{define} {} 4 eq", count("*"))); check(&format!("{define} {} 2 eq", count("Fo?"))); check(&format!("{define} {} 3 eq", count("F*"))); @@ -992,10 +998,10 @@ fn resourceforall_enumerates_matching_names() { check(&format!("{define} {} 0 eq", count("Q*"))); check(&format!("{define} {} 1 eq", count("*a*"))); // Each name is copied into the scratch string; exit stops. - check(&format!("{define} /last () def (B*) {{ dup length string copy /last exch def }} 8 string /ProcSet resourceforall last (Bar) eq")); - check(&format!("{define} /n 0 def (*) {{ pop /n n 1 add def exit }} 8 string /ProcSet resourceforall n 1 eq")); + check(&format!("{define} /last () def (B*) {{ dup length string copy /last exch def }} 8 string /Form resourceforall last (Bar) eq")); + check(&format!("{define} /n 0 def (*) {{ pop /n n 1 add def exit }} 8 string /Form resourceforall n 1 eq")); // A scratch string too small for the names, as the prolog probes it. - check(&format!("{define} {{ (*) {{ pop }} 2 string /ProcSet resourceforall }} stopped")); + check(&format!("{define} {{ (*) {{ pop }} 2 string /Form resourceforall }} stopped")); check("/n 0 def (Gen*) { pop /n n 1 add def } 16 string /Category resourceforall n 1 eq"); } @@ -1264,6 +1270,15 @@ fn shading_functions_in_shared_arrays_stop_at_the_limits() { assert!(r.warnings.iter().any(|w| w.contains("the program runs too long")), "{:?}", r.warnings); } +/// Type only measured (`stringwidth`) or drawn as outlines (`charpath`) adds no type to the +/// document, so its font isn't named as one that shows in the fallback font. +#[test] +fn fonts_only_measured_or_outlined_are_not_named_as_missing() { + let r = read("/Nowhere-Bold 12 selectfont (Hi) stringwidth pop pop newpath 10 10 moveto (Hi) true charpath fill 10 10 80 80 rectfill"); + assert!(!objects(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Text(_)))); + assert!(!r.warnings.iter().any(|w| w.starts_with(super::MISSING_FONTS_NOTE)), "{:?}", r.warnings); +} + #[test] fn cshow_runs_its_procedure_for_each_character() { check("/n 0 def { pop pop pop /n n 1 add def } (abc) cshow n 3 eq"); @@ -1436,6 +1451,31 @@ fn the_planes_of_multi_source_images_are_charged() { assert!(r.warnings.iter().any(|w| w.contains("too much memory")), "{:?}", r.warnings); } +/// The planes an image is decoded from, and the decoder's copies of the strings a procedure gives +/// to fill them, stop counting against the memory budget once the image is decoded: they are freed +/// then. A procedure that hands back one large buffer for every image (1 MiB here, for a one-pixel +/// image) charged the whole buffer each time, and a file of many images came in as its preview. +#[test] +fn an_images_transient_data_is_not_charged_after_it() { + let body = "/buf 1048576 string def\n1100 { 1 1 8 [1 0 0 1 0 0] { buf } image } repeat\n"; + let r = import(&eps(body)).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("too much memory")), "{:?}", r.warnings); + let mut images = 0; + r.document.walk(|n| images += usize::from(matches!(n.kind, NodeKind::Image(_)))); + assert_eq!(images, 1100); +} + +/// What a data source procedure allocates stays counted, whatever image it fills: a procedure +/// that keeps each new string (in an array here) still runs into the memory budget, however small +/// the images it fills are. +#[test] +fn strings_a_data_source_keeps_stay_charged() { + let body = "/keep 1100 array def /i 0 def\n\ + 1100 { 1 1 8 [1 0 0 1 0 0] { keep i 1048576 string put keep i get /i i 1 add def } image } repeat\n"; + let r = import(&eps(body)).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("too much memory")), "{:?}", r.warnings); +} + /// #3568: a single sample plane over the data limit is refused. #[test] fn an_oversized_image_plane_is_refused() { diff --git a/crates/eps/src/import/tests_cid.rs b/crates/eps/src/import/tests_cid.rs new file mode 100644 index 0000000000..2b01b2b4f2 --- /dev/null +++ b/crates/eps/src/import/tests_cid.rs @@ -0,0 +1,644 @@ +//! CID-keyed fonts (PLRM 3rd ed., §5.11): CMaps built with the CIDInit procedure set's +//! operators, `composefont`, `FMapType` 9 fonts mapping codes to CIDs, Type 0 CIDFonts (Type 1 +//! charstrings in the binary data `StartData` reads: Adobe Technical Note #5014) and Type 2 +//! CIDFonts (TrueType glyphs through `CIDMap`). The CIDFonts are written from scratch: Type 0 +//! glyphs are hand-made charstrings (Adobe Type 1 Font Format, chapter 6), Type 2 glyphs come +//! from the bundled Source Sans 3. + +use vectorcraft_doc::NodeKind; + +use super::tests::{all, bounds, check}; +use super::tests_composite::{glyph, sfnts}; +use crate::import::import; + +/// A Type 1 charstring number (Adobe Type 1 Font Format, §6.2). +fn num(v: i32) -> Vec { + match v { + -107..=107 => vec![(v + 139) as u8], + 108..=1131 => vec![((v - 108) / 256 + 247) as u8, ((v - 108) % 256) as u8], + -1131..=-108 => vec![((-v - 108) / 256 + 251) as u8, ((-v - 108) % 256) as u8], + _ => [vec![255], v.to_be_bytes().to_vec()].concat(), + } +} + +/// A charstring from numbers and commands (`hsbw` 13, `rmoveto` 21, `rlineto` 5, `closepath` +/// 9, `callsubr` 10, `return` 11, `endchar` 14). +fn cs(parts: &[(&[i32], u8)]) -> Vec { + parts.iter().flat_map(|(args, op)| args.iter().flat_map(|a| num(*a)).chain([*op])).collect() +} + +/// `plain` encrypted with the charstring key and 4 leading bytes (Adobe Type 1 Font Format, §7). +fn encrypt(plain: &[u8]) -> Vec { + let mut r: u16 = 4330; + [0u8; 4] + .iter() + .chain(plain) + .map(|&p| { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + c + }) + .collect() +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +/// A Type 0 CIDFont `/TestCID` with three CIDs: 0 an empty glyph 500 wide; 1 a square (100 to +/// 500 across, 500 high) 600 wide, its charstring plain (FDArray dictionary 0, `lenIV` -1); 2 a +/// triangle (500 across, 400 high) 500 wide drawn by a subroutine, encrypted (dictionary 1, +/// `lenIV` 4). The binary data section, written in hexadecimal when `hex_data`. +fn cid_font(hex_data: bool) -> Vec { + let empty = cs(&[(&[0, 500], 13), (&[], 14)]); + let square = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]); + let triangle = encrypt(&cs(&[(&[0, 500], 13), (&[0], 10), (&[], 14)])); + let subr = encrypt(&cs(&[(&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)])); + // The offset table: FDArray index (1 byte) and offset (2 bytes) of CIDs 0 to 2 and the end. + let table = 4 * 3; + let offsets = [table, table + empty.len(), table + empty.len() + square.len(), table + empty.len() + square.len() + triangle.len()]; + let mut data = vec![]; + for (fd, at) in [0u8, 0, 1, 0].iter().zip(offsets) { + data.push(*fd); + data.extend_from_slice(&(at as u16).to_be_bytes()); + } + data.extend(empty); + data.extend(square); + data.extend(triangle); + let mut out = format!( + "/CIDInit /ProcSet findresource begin\n20 dict begin\n/CIDFontName /TestCID def /CIDFontType 0 def\n\ + /CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Shapes) def /Supplement 0 def end def\n\ + /FontBBox [0 0 1000 1000] def\n/FDArray [\n\ + 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end\n\ + 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV 4 def /Subrs [<{}>] def end def currentdict end\n\ + ] def\n/CIDMapOffset 0 def /FDBytes 1 def /GDBytes 2 def /CIDCount 3 def\n", + hex(&subr) + ) + .into_bytes(); + if hex_data { + out.extend(format!("(Hex) {} StartData\n{}>\n", data.len(), hex(&data)).into_bytes()); + } else { + out.extend(format!("(Binary) {} StartData ", data.len()).into_bytes()); + out.extend(data); + out.push(b'\n'); + } + out +} + +/// CMap `/Test-H`: one-byte codes 00–7F and two-byte codes 8000–FFFF; A and B are CIDs 1 and 2, +/// <8001> CID 2, and codes 00–1F without a character take CID 1 as their notdef. +const CMAP: &str = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\ + /CMapName /Test-H def /CMapType 1 def /WMode 0 def\n\ + 2 begincodespacerange <00> <7f> <8000> endcodespacerange\n\ + 1 begincidrange <41> <42> 1 endcidrange\n1 begincidchar <8001> 2 endcidchar\n\ + 1 beginnotdefrange <00> <1f> 1 endnotdefrange\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /TestFont /Test-H [/TestCID] composefont pop\n"; + +/// `body` after the CIDFont and the CMap, as an EPS file. +fn program(hex_data: bool, body: &str) -> Vec { + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + [head, cid_font(hex_data), CMAP.as_bytes().to_vec(), format!("{body}\nshowpage\n%%EOF\n").into_bytes()].concat() +} + +fn paths(r: &crate::Imported) -> Vec { + all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| bounds(n)).collect() +} + +#[test] +fn type0_cidfonts_draw_their_charstrings_through_the_cmap() { + for hex_data in [false, true] { + let r = import(&program(hex_data, "/TestFont 50 selectfont 10 20 moveto (AB) show")).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(!all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Text(_)))); + let p = paths(&r); + assert_eq!(p.len(), 2, "{p:?}"); + // The square, 100 to 500 units across at 50 pt an em; the triangle 600 units on. + let (sq, tri) = (p[0], p[1]); + assert!((sq.x0 - 15.0).abs() < 0.01 && (sq.width() - 20.0).abs() < 0.01 && (sq.height() - 25.0).abs() < 0.01, "{sq:?}"); + assert!((sq.y1 - 80.0).abs() < 0.01, "{sq:?}"); + assert!((tri.x0 - 40.0).abs() < 0.01 && (tri.width() - 25.0).abs() < 0.01 && (tri.height() - 20.0).abs() < 0.01, "{tri:?}"); + } +} + +/// Codes take as many bytes as their codespace range says; codes without a character take their +/// notdef mapping's CID, else CID 0 (PLRM 3rd ed., §5.11.5). +#[test] +fn codes_map_by_their_codespace_with_notdef_fallbacks() { + let fonts = String::from_utf8(cid_font(true)).unwrap() + CMAP; + let width = |s: &str, w: f64| check(&format!("{fonts} /TestFont 50 selectfont {s} stringwidth pop {w} sub abs 0.01 lt")); + width("(AB)", 55.0); + // A two-byte code mapped by a character mapping. + width("<8001>", 25.0); + // A two-byte code (one character) without a mapping: CID 0. + width("<9041>", 25.0); + // A one-byte code with a notdef mapping: CID 1. + width("<01>", 30.0); +} + +/// `usecmap` brings in another CMap's ranges and mappings; the CMap's own come after them. +#[test] +fn usecmap_takes_the_parents_mappings() { + let r = import(&program( + true, + "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /Test-H usecmap /CMapName /Child def\n\ + 1 begincidchar <43> 2 endcidchar endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /Child2 /Child [/TestCID] composefont 50 scalefont setfont 10 20 moveto (AC) show", + )) + .unwrap(); + let p = paths(&r); + assert_eq!(p.len(), 2, "{p:?}"); + assert!((p[1].x0 - 40.0).abs() < 0.01 && (p[1].height() - 20.0).abs() < 0.01, "{p:?}"); +} + +/// A Type 2 CIDFont with Source Sans 3's glyphs: CIDs 1 and 2 are H and I. +fn cid2_font(cid_map: &str) -> String { + format!( + "20 dict begin /CIDFontName /TestCID2 def /CIDFontType 2 def /FontType 11 def /FontMatrix [1 0 0 1 0 0] def\n\ + /CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Latin) def /Supplement 0 def end def\n\ + /FontBBox [0 0 1 1] def /CIDCount 3 def /GDBytes 2 def /CIDMap {cid_map} def\n\ + /sfnts [\n{}] def CIDFontName currentdict end /CIDFont defineresource pop\n", + sfnts() + ) +} + +#[test] +fn type2_cidfonts_draw_their_truetype_glyphs_through_cidmap() { + let (h, wh) = glyph('H'); + let (i, wi) = glyph('I'); + for cid_map in [format!("<0000{h:04x}{i:04x}>"), format!("[<0000{h:04x}> <{i:04x}>]")] { + let body = format!("{}/T2 /Identity-H [/TestCID2] composefont 50 scalefont setfont 10 20 moveto <00010002> show", cid2_font(&cid_map)); + let r = super::tests::read(&body); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let p = paths(&r); + assert_eq!(p.len(), 2, "{cid_map}: {p:?}"); + let (bh, bi) = (p[0], p[1]); + assert!(bh.x0 > 10.0 && bh.x0 < 18.0 && bh.height() > 25.0 && bh.height() < 40.0, "{bh:?}"); + assert!(bi.x0 > 10.0 + 50.0 * wh - 1.0 && bi.x1 < 10.0 + 50.0 * (wh + wi), "{bi:?}"); + } +} + +/// `Identity-V`: each glyph an em below the one before (writing mode 1). +#[test] +fn identity_v_sets_glyphs_downwards() { + let (h, _) = glyph('H'); + let (i, _) = glyph('I'); + let body = format!( + "{}/T2V /Identity-V [/TestCID2] composefont 40 scalefont setfont 50 90 moveto <00010002> show", + cid2_font(&format!("<0000{h:04x}{i:04x}>")) + ); + let p = paths(&super::tests::read(&body)); + assert_eq!(p.len(), 2, "{p:?}"); + // Document y runs down: the I is 40 pt (an em) below the H. + assert!((p[1].y1 - p[0].y1 - 40.0).abs() < 0.5, "{p:?}"); + check(&format!( + "{}/T2V /Identity-V [/TestCID2] composefont 40 scalefont setfont (\\000\\001\\000\\002) stringwidth -80 sub abs 0.01 lt exch abs 0.01 lt and", + cid2_font("0") + )); +} + +/// A CIDFont the file doesn't carry draws nothing, an em a character, and says so. +#[test] +fn cidfonts_the_file_lacks_draw_nothing_with_a_warning() { + let r = super::tests::read( + "/X /Identity-H [/NotInFile] composefont 50 scalefont setfont 10 20 moveto <00410042> show 0 0 1 setrgbcolor currentpoint 5 5 rectfill", + ); + let p = paths(&r); + assert_eq!(p.len(), 1, "{p:?}"); + // The point moved two ems along. + assert!((p[0].x0 - 110.0).abs() < 0.01, "{p:?}"); + assert!(r.warnings.iter().any(|w| w.contains("CID-keyed")), "{:?}", r.warnings); +} + +/// The CIDInit operators are found through the procedure set, not systemdict. +#[test] +fn cidinit_operators_are_not_in_systemdict() { + check("systemdict /begincmap known not /CIDInit /ProcSet findresource /begincmap known and systemdict /composefont known and"); +} + +/// A CFF INDEX (Adobe Technical Note #5176, §5) of `items`, with 2-byte offsets. +fn cff_index(items: &[Vec]) -> Vec { + let mut out = (items.len() as u16).to_be_bytes().to_vec(); + if items.is_empty() { + return out; + } + out.push(2); + let mut at = 1u16; + out.extend(at.to_be_bytes()); + for i in items { + at += i.len() as u16; + out.extend(at.to_be_bytes()); + } + out.extend(items.iter().flatten()); + out +} + +/// A CFF DICT operand as a 5-byte integer (TN #5176, Table 3), so offsets don't change its size. +fn cff_int(v: i32) -> Vec { + [vec![29], v.to_be_bytes().to_vec()].concat() +} + +/// A Type 2 charstring (Adobe Technical Note #5177) from numbers, each a 3-byte integer +/// (`28`), and operators (`rmoveto` 21, `rlineto` 5, `endchar` 14). +fn cs2(parts: &[(&[i16], u8)]) -> Vec { + parts.iter().flat_map(|(args, op)| args.iter().flat_map(|a| [vec![28], a.to_be_bytes().to_vec()].concat()).chain([*op])).collect() +} + +/// A CID-keyed CFF font `/CffCID` (TN #5176, §18): glyph 0 `.notdef`, glyph 1 CID 1 a square +/// (100 to 500 across, 500 high) 600 wide, glyph 2 CID 7 a triangle (500 across, 400 high) 500 +/// wide (the first number of a charstring its width, `nominalWidthX` 0). +fn cid_cff() -> Vec { + let glyphs = vec![ + cs2(&[(&[0], 14)]), + cs2(&[(&[600, 100, 0], 21), (&[400, 0, 0, 500, -400, 0], 5), (&[], 14)]), + cs2(&[(&[500, 0, 0], 21), (&[500, 0, -250, 400], 5), (&[], 14)]), + ]; + let header = vec![1, 0, 4, 2]; + let names = cff_index(&[b"CffCID".to_vec()]); + let strings = cff_index(&[b"Test".to_vec(), b"Shapes".to_vec()]); + let global = cff_index(&[]); + // The top DICT: ROS (12 30), CIDCount (12 34), charset (15), CharStrings (17), FDArray + // (12 36), FDSelect (12 37), each offset a 5-byte integer. + let top = |charset: i32, strings_at: i32, fd_array: i32, fd_select: i32| -> Vec { + [ + cff_int(391), + cff_int(392), + cff_int(0), + vec![12, 30], + cff_int(8), + vec![12, 34], + cff_int(charset), + vec![15], + cff_int(strings_at), + vec![17], + cff_int(fd_array), + vec![12, 36], + cff_int(fd_select), + vec![12, 37], + ] + .concat() + }; + let top_len = cff_index(&[top(0, 0, 0, 0)]).len(); + let charset_at = header.len() + names.len() + top_len + strings.len() + global.len(); + // Format 0: the CIDs of glyphs 1 and 2. + let charset = vec![0, 0, 1, 0, 7]; + let fd_select_at = charset_at + charset.len(); + let fd_select = vec![0, 0, 0, 0]; + let strings_at = fd_select_at + fd_select.len(); + let char_strings = cff_index(&glyphs); + let private_at = strings_at + char_strings.len(); + // defaultWidthX (20) and nominalWidthX (21) 0. + let private = [cff_int(0), vec![20], cff_int(0), vec![21]].concat(); + let fd_array_at = private_at + private.len(); + let fd = [cff_int(private.len() as i32), cff_int(private_at as i32), vec![18]].concat(); + let fd_array = cff_index(&[fd]); + let top = cff_index(&[top(charset_at as i32, strings_at as i32, fd_array_at as i32, fd_select_at as i32)]); + [header, names, top, strings, global, charset, fd_select, char_strings, private, fd_array].concat() +} + +/// A FontSet holding CID-keyed Compact Font Format data (PLRM 3rd ed., §5.8.1, `StartData`; +/// TN #5176) defines its CIDFont, whose glyphs are drawn by their CIDs. +#[test] +fn cff_fontsets_draw_their_cidfonts_glyphs() { + let data = cid_cff(); + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let set = + [format!("/FontSetInit /ProcSet findresource begin\n/CffCID {} StartData ", data.len()).into_bytes(), data, b"\nend\n".to_vec()].concat(); + let body = "/CffFont /Identity-H [/CffCID] composefont 50 scalefont setfont 10 20 moveto <00010007> show\n\ + (\\000\\001\\000\\007) stringwidth pop 55 sub abs 0.01 lt { 0 0 5 5 rectfill } if\nshowpage\n%%EOF\n"; + let r = import(&[head, set, body.as_bytes().to_vec()].concat()).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let p = paths(&r); + assert_eq!(p.len(), 3, "{p:?}"); + let (sq, tri) = (p[0], p[1]); + assert!((sq.x0 - 15.0).abs() < 0.01 && (sq.width() - 20.0).abs() < 0.01 && (sq.height() - 25.0).abs() < 0.01, "{sq:?}"); + assert!((tri.x0 - 40.0).abs() < 0.01 && (tri.width() - 25.0).abs() < 0.01 && (tri.height() - 20.0).abs() < 0.01, "{tri:?}"); +} + +/// Damaged FontSet data (each byte of the CFF data changed, in turn) is read as fonts or as +/// nothing, never a crash. +#[test] +fn damaged_cff_fontsets_never_panic() { + let data = cid_cff(); + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let body = b"/CffFont /Identity-H [/CffCID] composefont 50 scalefont setfont 10 20 moveto <000100070002> show showpage\n%%EOF\n".to_vec(); + for at in 0..data.len() { + for v in [0u8, 0x7f, 0xff, data[at].wrapping_add(1)] { + let mut d = data.clone(); + d[at] = v; + let set = + [format!("/FontSetInit /ProcSet findresource begin\n/CffCID {} StartData ", d.len()).into_bytes(), d, b"\nend\n".to_vec()].concat(); + let _ = import(&[head.clone(), set, body.clone()].concat()); + } + } +} + +/// A CMap mapping two-byte codes to base fonts' codes and glyph names (`beginbfchar`, +/// `beginbfrange`, `usefont`: Adobe Technical Note #5099, "Building CMap Files for CID-Keyed +/// Fonts"): font 0 a Type 42 font that carries Source Sans 3, font 1 a font found by name. +const BF_CMAP: &str = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\ + /CMapName /TestBF-H def /CMapType 1 def /WMode 0 def\n\ + 1 begincodespacerange <0000> endcodespacerange\n\ + 0 usefont 1 beginbfchar <0001> <01> endbfchar 1 beginbfrange <0002> <0003> [/g2 /g1] endbfrange\n\ + 1 usefont 1 beginbfrange <0010> <0012> <41> endbfrange\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n"; + +#[test] +fn cmaps_map_codes_to_base_fonts_codes_and_glyph_names() { + let (h, wh) = glyph('H'); + let (i, wi) = glyph('I'); + // `/Plain42`: codes 1 and 2 are glyphs g1 (H) and g2 (I); g2 is also named outside the encoding. + let plain = format!( + "10 dict begin /FontName /Plain42 def /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /FontBBox [0 0 1 1] def /PaintType 0 def\n\ + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 1 /g1 put\n\ + /CharStrings 3 dict def CharStrings begin /.notdef 0 def /g1 {h} def /g2 {i} def end\n\ + /sfnts [\n{}] def FontName currentdict end definefont pop\n", + sfnts() + ); + let body = format!("{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 50 scalefont setfont 10 20 moveto <000100020003> show"); + let r = super::tests::read(&body); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let p = paths(&r); + assert_eq!(p.len(), 3, "{p:?}"); + // H, I, H, each its own width along. + assert!(p[0].x0 > 10.0 && p[0].x0 < 18.0, "{p:?}"); + assert!(p[1].x0 > 10.0 + 50.0 * wh - 1.0 && p[1].x1 < 10.0 + 50.0 * (wh + wi), "{p:?}"); + assert!(p[2].x0 > 10.0 + 50.0 * (wh + wi) && (p[2].width() - p[0].width()).abs() < 0.01, "{p:?}"); + // Codes to a font found by name set its characters as type. + let body = format!("{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 20 scalefont setfont 10 20 moveto <001000110012> show"); + let r = super::tests::read(&body); + let text: String = all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(text, "ABC"); +} + +/// A CID-keyed font over a predefined Unicode CMap the file doesn't define, its CIDFont only +/// named: the codes say their characters, set as type in the font of the CIDFont's name, +/// whether found as `CIDFont-CMap` or composed. +#[test] +fn named_cidfonts_over_unicode_cmaps_set_their_characters_as_type() { + let texts = |r: &crate::Imported| -> Vec { + all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((**t).clone()), + _ => None, + }) + .collect() + }; + let r = super::tests::read("/Ryumin-Light-UniJIS-UCS2-H findfont 20 scalefont setfont 10 20 moveto <4e2d0041> show"); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + let t = texts(&r); + assert_eq!(t.len(), 1, "{:?}", all(&r.document)); + assert_eq!(t[0].plain_text(), "\u{4e2d}A"); + assert_eq!((t[0].runs[0].style.font_family.as_str(), t[0].runs[0].style.size), ("Ryumin", 20.0)); + let r = super::tests::read("/X /UniGB-UTF8-H [/NotInFile] composefont 20 scalefont setfont 10 20 moveto (\\344\\270\\255A) show"); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::(), "\u{4e2d}A"); + // The point moves past the type. + check("/Ryumin-Light-UniJIS-UCS2-H findfont 20 scalefont setfont <00410042> stringwidth pop dup 5 gt exch 40 lt and"); +} + +/// A Type 2 CIDFont the file carries (its glyph space one unit an em), over a Unicode CMap the +/// file doesn't define, sets its characters as type at the font's size, not a thousand times it. +#[test] +fn type2_cidfonts_over_unicode_cmaps_set_type_at_their_size() { + let r = + super::tests::read(&format!("{}/X /UniGB-UCS2-H [/TestCID2] composefont 20 scalefont setfont 10 20 moveto <4e2d0041> show", cid2_font("0"))); + let sizes: Vec = all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.runs[0].style.size * t.xf.determinant().abs().sqrt()), + _ => None, + }) + .collect(); + assert!(!sizes.is_empty() && sizes.iter().all(|s| (s - 20.0).abs() < 0.5), "{sizes:?} {:?}", r.warnings); +} + +/// A code a base-font CMap doesn't map, in a base font, is that font's code 0 (`.notdef`): it +/// moves the point by that glyph's width, not by a thousand ems, and the font isn't missing. +#[test] +fn unmapped_codes_in_base_fonts_take_their_notdef() { + let plain = format!( + "10 dict begin /FontName /Plain42 def /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /FontBBox [0 0 1 1] def /PaintType 0 def\n\ + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for\n\ + /CharStrings 1 dict def CharStrings begin /.notdef 0 def end\n\ + /sfnts [\n{}] def FontName currentdict end definefont pop\n", + sfnts() + ); + check(&format!( + "{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 50 scalefont setfont <0009> stringwidth pop dup 0 gt exch 100 lt and" + )); + let r = super::tests::read(&format!( + "{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 50 scalefont setfont 10 20 moveto <0009> show 0 0 10 10 rectfill" + )); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// A CMap's mappings take font 0 until its own `usefont`, whatever font number an earlier CMap +/// ended with (Adobe Technical Note #5014). +#[test] +fn each_cmap_starts_at_font_0() { + let r = import(&program( + true, + "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Two-H def\n\ + 1 begincodespacerange <00> endcodespacerange 1 usefont 1 begincidchar <41> 1 endcidchar\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /One-H def\n\ + 1 begincodespacerange <00> endcodespacerange 1 begincidrange <41> <42> 1 endcidrange\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /One /One-H [/TestCID] composefont 50 scalefont setfont 10 20 moveto (AB) show", + )) + .unwrap(); + assert_eq!(paths(&r).len(), 2, "{:?}", r.warnings); +} + +/// A Type 0 CIDFont with a matrix of its own (its FDArray matrices map 1000 units to an em): +/// vertical type moves an em a character, not a thousand. +#[test] +fn cidfonts_with_their_own_matrix_move_an_em_a_character() { + let font = String::from_utf8(cid_font(true)).unwrap().replace("/CIDFontType 0 def", "/CIDFontType 0 def /FontMatrix [1 0 0 1 0 0] def"); + check(&format!( + "{font}{CMAP} /V /Identity-V [/TestCID] composefont 40 scalefont setfont (\\000\\001\\000\\002) stringwidth -80 sub abs 0.01 lt exch abs 0.01 lt and" + )); +} + +/// `restore` undoes the matrices `StartData` gives a CIDFont and its FDArray dictionaries, as +/// it undoes the program's own changes. +#[test] +fn restore_undoes_the_matrices_start_data_sets() { + let font = String::from_utf8(cid_font(true)).unwrap().replacen( + "4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end", + "fd0", + 1, + ); + check(&format!( + "/fd0 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end def\n\ + /sv save def\n{font}\nsv restore fd0 /FontMatrix get 0 get 0.001 sub abs 1e-9 lt" + )); +} + +/// Notdef mappings added to a CMap that was already shown with take effect (its mappings are +/// read again). +#[test] +fn notdef_mappings_added_later_are_read() { + let fonts = String::from_utf8(cid_font(true)).unwrap() + CMAP; + check(&format!( + "{fonts} /TestFont 50 selectfont <21> stringwidth pop pop\n\ + /CIDInit /ProcSet findresource begin /Test-H /CMap findresource begin 1 beginnotdefrange <20> <2f> 1 endnotdefrange end end\n\ + <21> stringwidth pop 30 sub abs 0.01 lt" + )); +} + +/// A CMap built of many small blocks pays for copying its mappings at each block. +#[test] +fn many_small_cmap_blocks_run_out_of_the_budget() { + super::tests::runs_out_of_budget("/CIDInit /ProcSet findresource begin 12 dict begin begincmap { 1 begincidchar <41> 1 endcidchar } loop"); +} + +/// A CIDFont's subroutines are decrypted once, not again for every glyph: measuring a glyph of +/// a font with 10 MB of them in a loop ends within the budget. +#[test] +fn cidfont_subroutines_are_read_once() { + let font = String::from_utf8(cid_font(true)).unwrap(); + let at = font.find("/Subrs [<").unwrap() + "/Subrs [".len(); + let font = format!( + "{}{} 0 1 9998 {{ pop 1000 string }} for{}", + &font[..at], + &font[at..font[at..].find(']').unwrap() + at], + &font[font[at..].find(']').unwrap() + at..] + ); + super::tests::runs_out_of_budget(&format!("{font}{CMAP} /TestFont 50 selectfont {{ (B) stringwidth pop pop }} loop")); +} + +/// Binary data larger than most operators' counts (4 MB) is read: CJK CIDFonts carry more. +#[test] +fn start_data_reads_more_than_4_mb() { + let mut font = cid_font(false); + let marker = b"(Binary) "; + let at = font.windows(marker.len()).position(|w| w == marker).unwrap(); + let rest = font.split_off(at); + let len_end = rest.iter().skip(marker.len()).position(|b| *b == b' ').unwrap() + marker.len(); + let n: usize = std::str::from_utf8(&rest[marker.len()..len_end]).unwrap().parse().unwrap(); + let data_at = len_end + " StartData ".len(); + let mut data = rest[data_at..data_at + n].to_vec(); + data.resize(5_000_000, 0); + font.extend(format!("(Binary) {} StartData ", data.len()).into_bytes()); + font.extend(data); + font.push(b'\n'); + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let r = import(&[head, font, CMAP.as_bytes().to_vec(), b"/TestFont 50 selectfont 10 20 moveto (AB) show\nshowpage\n%%EOF\n".to_vec()].concat()) + .unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(paths(&r).len(), 2); +} + +/// Decoding a string through a CMap with many mappings counts against the operation budget. +#[test] +fn decoding_through_a_large_cmap_runs_out_of_the_budget() { + // A CIDFont the file doesn't carry: its glyphs cost nothing, so the decoding is what counts. + super::tests::runs_out_of_budget( + "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Big-H def\n\ + 2 begincodespacerange <00> <7f> <8000> endcodespacerange\n\ + 16000 begincidrange 0 1 15999 { /i exch def 2 string dup 0 i 256 idiv 128 add put dup 1 i 256 mod put dup 1 } for endcidrange\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /Big /Big-H [/NotInFile] composefont 50 scalefont setfont /s 1000 string def { s stringwidth pop pop } loop", + ); +} + +/// A CID-keyed font's glyphs are grouped under the font's name: a CID stands for no character. +#[test] +fn cid_glyph_groups_take_the_fonts_name() { + let r = import(&program(true, "/TestFont 50 selectfont 10 20 moveto (AB) show")).unwrap(); + let names: Vec<_> = all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Group { .. })).map(|n| n.name.clone()).collect(); + assert_eq!(names, [Some("TestFont".to_string())]); +} + +/// One show of a long string through a CMap with many mappings stops at the operation budget, +/// not after decoding the whole string. +#[test] +fn one_long_show_through_a_large_cmap_runs_out_of_the_budget() { + super::tests::runs_out_of_budget( + "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Big-H def\n\ + 2 begincodespacerange <00> <7f> <8000> endcodespacerange\n\ + /mk { 0 1 15999 { /i exch def 2 string dup 0 i 256 idiv 128 add put dup 1 i 256 mod put dup 1 } for } def\n\ + 16000 begincidrange mk endcidrange 16000 begincidrange mk endcidrange 16000 begincidrange mk endcidrange 16000 begincidrange mk endcidrange\n\ + 16000 beginnotdefrange mk endnotdefrange 16000 beginnotdefrange mk endnotdefrange 16000 beginnotdefrange mk endnotdefrange 16000 beginnotdefrange mk endnotdefrange\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /Big /Big-H [/NotInFile] composefont 50 scalefont setfont 4000000 string stringwidth pop pop", + ); +} + +/// The evaluator limits each glyph, not the file: measuring a glyph whose subroutines (1 to 8 +/// each calling the next four times) run a quarter of a million operations in a loop ends within +/// the operation budget. +#[test] +fn cid_glyphs_measured_in_a_loop_run_out_of_the_budget() { + let font = String::from_utf8(cid_font(true)).unwrap(); + let at = font.find("/Subrs [<").unwrap() + "/Subrs [".len(); + let end = font[at..].find(']').unwrap() + at; + let mut subrs = vec![encrypt(&cs(&[(&[1], 10), (&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)]))]; + for k in 1..=8 { + subrs.push(encrypt(&cs(&[(&[k + 1], 10), (&[k + 1], 10), (&[k + 1], 10), (&[k + 1], 10), (&[], 11)]))); + } + subrs.push(encrypt(&cs(&[(&[], 11)]))); + let list: String = subrs.iter().map(|s| format!("<{}> ", hex(s))).collect(); + let font = format!("{}{list}{}", &font[..at], &font[end..]); + check(&format!("{font}{CMAP} /TestFont 50 selectfont (B) stringwidth pop 25 sub abs 0.01 lt")); + super::tests::runs_out_of_budget(&format!("{font}{CMAP} /TestFont 50 selectfont {{ (B) stringwidth pop pop }} loop")); +} + +/// Setting type over a Unicode CMap copies the composite font for every string: the copy is +/// charged by the font's size, so a font with a huge number of keys shown in a loop runs out of +/// the operation budget. +#[test] +fn unicode_type_in_a_huge_font_in_a_loop_runs_out_of_the_budget() { + super::tests::runs_out_of_budget( + "/Ryumin-Light-UniJIS-UCS2-H findfont dup length 200000 add dict copy dup begin 0 1 199999 { dup def } for end\n\ + /Huge exch definefont 20 scalefont setfont { <0041> stringwidth pop pop } loop", + ); +} + +/// A `beginbfrange` destination array that holds itself is read without recursing into it (an +/// array element that is an array maps nothing), so showing its code is no crash. +#[test] +fn a_bfrange_array_holding_itself_is_no_crash() { + let body = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Self-H def\n\ + 1 begincodespacerange <00> endcodespacerange\n\ + /a 1 array def a 0 a put 1 beginbfrange <00> <00> a endbfrange\n\ + endcmap CMapName currentdict /CMap defineresource pop end end\n\ + /S /Self-H [/Helvetica] composefont 20 scalefont setfont 10 20 moveto <00> show 0 0 10 10 rectfill"; + let r = super::tests::read(body); + assert_eq!(paths(&r).len(), 1, "{:?}", r.warnings); +} + +/// Drawing a glyph of a FontSet's CIDFont counts the charstring bytes it enters, as Type 1 +/// glyphs do, so glyphs that run long (nested subroutines) are paid for by the `show` that +/// draws them, not a flat amount. +#[test] +fn cff_glyphs_count_the_charstrings_they_run() { + let cff = super::cid::Cff::new(std::rc::Rc::from(cid_cff()), 0); + assert!(cff.glyph(1).is_some()); + assert!(cff.take_work() > 0); + assert_eq!(cff.take_work(), 0); +} + +/// `usecmap` copies the parent's mappings into new arrays: the copies count against the memory +/// budget, so keeping the CMaps made from a large one in a loop stops with an error instead of +/// growing without bound. +#[test] +fn usecmap_copies_count_against_the_memory_budget() { + let r = import(&super::tests::eps( + "0 0 10 10 rectfill /CIDInit /ProcSet findresource begin 12 dict begin begincmap\n\ + 1 begincodespacerange <0000> endcodespacerange\n\ + 0 1 599 { pop 100 begincidrange 0 1 99 { pop <0000> <0001> 0 } for endcidrange } for\n\ + endcmap /Big currentdict /CMap defineresource pop end end\n\ + /CIDInit /ProcSet findresource begin { 12 dict begin /Big usecmap currentdict end } loop", + )) + .unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("too much memory")), "{:?}", r.warnings); +} diff --git a/crates/eps/src/import/tests_composite.rs b/crates/eps/src/import/tests_composite.rs index ddf86acc56..e682ce10ec 100644 --- a/crates/eps/src/import/tests_composite.rs +++ b/crates/eps/src/import/tests_composite.rs @@ -11,10 +11,10 @@ use vectorcraft_doc::NodeKind; use super::tests::{all, bounds, fill, read}; -const FONT: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); +pub(super) const FONT: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); /// The glyph index of `c` in [`FONT`] and its advance width in ems. -fn glyph(c: char) -> (u32, f64) { +pub(super) fn glyph(c: char) -> (u32, f64) { let font = FontRef::new(FONT).unwrap(); let gid = font.charmap().map(c).unwrap(); let upem = f64::from(font.metrics(Size::unscaled(), LocationRef::default()).units_per_em); @@ -24,7 +24,7 @@ fn glyph(c: char) -> (u32, f64) { /// `sfnts` strings of [`FONT`]: the first of odd length, ending in a padding byte that isn't part /// of the font, the rest split at even lengths. -fn sfnts() -> String { +pub(super) fn sfnts() -> String { let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::(); let mut out = format!("<{}00>\n", hex(&FONT[..20000])); for chunk in FONT[20000..].chunks(40000) { @@ -251,3 +251,16 @@ fn unreadable_type42_data_read_again_runs_out_of_the_budget() { /Comp findfont 50 scalefont setfont {{ ({s}) stringwidth pop pop }} loop" )); } + +/// Characters that map to no glyph (an empty `FDepVector`) cost nothing to draw, but finding that +/// out reads the whole string: a `loop` showing, measuring or outlining a long string of them runs +/// out of the operation budget instead of stalling the import. +#[test] +fn unmapped_composite_characters_in_a_loop_run_out_of_the_budget() { + let font = "16 dict begin /FontName /Comp def /FontType 0 def /FontMatrix [1 0 0 1 0 0] def /FMapType 2 def\n\ + /Encoding [0] def /FDepVector [] def FontName currentdict end definefont pop\n\ + /Comp findfont 50 scalefont setfont /s 100000 string def"; + for body in ["{ 0 0 moveto s show } loop", "{ s stringwidth pop pop } loop", "{ newpath 0 0 moveto s false charpath } loop"] { + super::tests::runs_out_of_budget(&format!("{font} {body}")); + } +} diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index a9bb8cf279..13f979f9f8 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -215,7 +215,7 @@ fn text_and_its_strokes_come_from_the_page_into_the_layer_of_its_text_object() { assert_eq!(kinds(&r.document.layers[0]), ["path"]); // The text and the path of its stroke, where the text object is (no group of their own). assert_eq!(kinds(&r.document.layers[1]), ["text", "path"], "{:?}", r.warnings); - assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); } /// A point type object in the legacy format (`To` … `TO`), as an EPS saved for Illustrator 10 @@ -245,6 +245,25 @@ fn type_in_the_legacy_format_is_the_layers_own_and_the_page_has_text() { assert!(r.warnings.iter().any(|w| w.starts_with("1 text objects of the page are outlines on the layers")), "{:?}", r.warnings); } +/// The warning about fonts that aren't available names the fonts of the type the document keeps, +/// wherever it came from: type the editing copy sets in a font that isn't available is named +/// though the page sets it in one that is, and type only the page sets in such a font is not. +#[test] +fn the_missing_fonts_warning_names_the_fonts_of_the_documents_type() { + let page = |font: &str| format!("{}\n0 0 0 1 setcmykcolor /{font} findfont 12 scalefont setfont 10 50 moveto (Hi) show", page_square(10, 10)); + // `legacy_text` in `font`. + let words = |font: &str| format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_{font} 12 Tf\n(Hi) Tx\nTO"); + for (on_page, in_copy, named) in [("Inter-Regular", "Nowhere-Bold", Some("Nowhere")), ("Nowhere-Bold", "Inter-Regular", None)] { + let art = native(&(layer("Art", true, &square(10, 10)) + &layer("Words", true, &words(in_copy)))); + let r = import(&eps(&page(on_page), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Words"], "{:?}", r.warnings); + assert_eq!(text_of(&r.document.layers[1]).len(), 1, "{:?}", r.warnings); + let notes: Vec<&String> = r.warnings.iter().filter(|w| w.starts_with(super::MISSING_FONTS_NOTE)).collect(); + let want: Vec = named.iter().map(|f| format!("{}: {f}", super::MISSING_FONTS_NOTE)).collect(); + assert_eq!(notes, want.iter().collect::>(), "page {on_page}, editing copy {in_copy}: {:?}", r.warnings); + } +} + #[test] fn a_damaged_editing_copy_leaves_the_page() { // Not ASCII85, ASCII85 of something that isn't Zstandard, Zstandard of something that isn't art. @@ -4661,6 +4680,22 @@ fn a_small_label_of_the_page_in_no_text_object_is_noted() { assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings); } +/// A ligature the page shows by a glyph its font's encoding names `uniE028` (a private-use +/// character, without the letters it stands for) is the letters of its text object: the page's type +/// has one, and nothing is noted as left out. +#[test] +fn a_ligature_glyph_without_letters_is_matched_to_its_text_object() { + let doc = text_document(&[("Quality here\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont dup length dict copy \ + dup /Encoding StandardEncoding 256 array copy dup 127 /uniE028 put put /Lig exch definefont \ + 14 scalefont setfont 58.5 61.5 moveto (Qual\\177y here) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("so it is left out")), "{:?}", r.warnings); + assert_eq!(text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect::>(), ["Quality here"], "{:?}", r.warnings); +} + /// A line break inside a paragraph (`\x03` in the text document) stays a line break in it. #[test] fn a_soft_return_is_a_line_break_in_its_paragraph() { @@ -5187,7 +5222,7 @@ fn envelope_options_keep_the_source_text_hidden_under_its_outlined_appearance() } }); assert_eq!(texts, [("CHONKYCATS".to_string(), false)], "{:?}", r.warnings); - assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); } /// A live envelope that draws a little apart from its drawn art, in layers that already differ diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs new file mode 100644 index 0000000000..5399042908 --- /dev/null +++ b/crates/eps/src/import/tests_type1.rs @@ -0,0 +1,251 @@ +//! Type 1 fonts embedded in the file: their encrypted part (`eexec`) is read for their glyphs +//! (Adobe Type 1 Font Format, chapters 6 and 7), so their type keeps the font's own widths, and +//! glyphs that stand for no character are drawn from their outlines. The font here is written +//! from scratch: two square and triangle glyphs in hand-made charstrings. + +use vectorcraft_doc::{NodeKind, TextObject}; + +use super::tests::{all, bounds, check, program_warnings, read}; +use crate::import::import; + +/// A Type 1 charstring number (§6.2). +fn num(v: i32) -> Vec { + match v { + -107..=107 => vec![(v + 139) as u8], + 108..=1131 => vec![((v - 108) / 256 + 247) as u8, ((v - 108) % 256) as u8], + -1131..=-108 => vec![((-v - 108) / 256 + 251) as u8, ((-v - 108) % 256) as u8], + _ => [vec![255], v.to_be_bytes().to_vec()].concat(), + } +} + +/// A charstring (`hsbw` 13, `rmoveto` 21, `rlineto` 5, `closepath` 9, `endchar` 14). +fn cs(parts: &[(&[i32], u8)]) -> Vec { + parts.iter().flat_map(|(args, op)| args.iter().flat_map(|a| num(*a)).chain([*op])).collect() +} + +/// `plain` encrypted with key `r` after 4 leading bytes (§7.1: 55665 for the encrypted part, +/// 4330 for charstrings). +fn encrypt(plain: &[u8], mut r: u16) -> Vec { + [0u8; 4] + .iter() + .chain(plain) + .map(|&p| { + let c = p ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + c + }) + .collect() +} + +/// Font `/TestOne`: A a square (100 to 500 across, 500 high) 600 wide, B a triangle (500 +/// across, 400 high) 500 wide, and the triangle again under the name `g1`, which says nothing, +/// at code 67 (C). Its encoding is `encoding` (a PostScript expression); its encrypted part +/// written in hexadecimal when `hex`. +fn font(encoding: &str, hex: bool) -> Vec { + font_with(encoding, hex, &[], None) +} + +/// [`font`] with subroutines `subrs` and, when given, charstring `a` for A. +fn font_with(encoding: &str, hex: bool, subrs: &[Vec], a: Option>) -> Vec { + let square = a.unwrap_or_else(|| cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)])); + let triangle = cs(&[(&[0, 500], 13), (&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 14)]); + let notdef = cs(&[(&[0, 250], 13), (&[], 14)]); + let mut private = b"dup /Private 8 dict dup begin\n/RD {string currentfile exch readstring pop} executeonly def\n\ + /ND {noaccess def} executeonly def\n/NP {noaccess put} executeonly def\n/lenIV 4 def\n/password 5839 def\n\ + /MinFeature {16 16} def\n" + .to_vec(); + private.extend(format!("/Subrs {} array\n", subrs.len()).into_bytes()); + for (i, subr) in subrs.iter().enumerate() { + let e = encrypt(subr, 4330); + private.extend(format!("dup {i} {} RD ", e.len()).into_bytes()); + private.extend(e); + private.extend(b" NP\n"); + } + private.extend(b"readonly def\n2 index /CharStrings 4 dict dup begin\n"); + for (name, glyph) in [(".notdef", ¬def), ("A", &square), ("B", &triangle), ("g1", &triangle)] { + let e = encrypt(glyph, 4330); + private.extend(format!("/{name} {} RD ", e.len()).into_bytes()); + private.extend(e); + private.extend(b" ND\n"); + } + private.extend(b"end\nend\nreadonly put\nnoaccess put\ndup /FontName get exch definefont pop\nmark currentfile closefile\n"); + let encrypted = encrypt(&private, 55665); + let mut out = format!( + "%!FontType1-1.0: TestOne 001\n12 dict begin\n/FontName /TestOne def /FontType 1 def /PaintType 0 def\n\ + /FontMatrix [0.001 0 0 0.001 0 0] readonly def /FontBBox {{0 0 1000 1000}} readonly def\n\ + /Encoding {encoding} def\ncurrentdict end\ncurrentfile eexec\n" + ) + .into_bytes(); + if hex { + for line in encrypted.chunks(32) { + out.extend(line.iter().map(|b| format!("{b:02x}")).collect::().into_bytes()); + out.push(b'\n'); + } + } else { + out.extend(encrypted); + out.push(b'\n'); + } + for _ in 0..8 { + out.extend(b"0".repeat(64)); + out.push(b'\n'); + } + out.extend(b"cleartomark\n"); + out +} + +/// The font's own encoding: A, B and `g1` at codes 65 to 67. +const OWN: &str = "256 array 0 1 255 {1 index exch /.notdef put} for dup 65 /A put dup 66 /B put dup 67 /g1 put readonly"; + +fn texts(r: &crate::Imported) -> Vec { + all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((**t).clone()), + _ => None, + }) + .collect() +} + +fn program(encoding: &str, hex: bool, body: &str) -> crate::Imported { + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + import(&[head, font(encoding, hex), format!("{body}\nshowpage\n%%EOF\n").into_bytes()].concat()).unwrap() +} + +#[test] +fn embedded_type1_type_keeps_the_fonts_widths() { + for hex in [true, false] { + let r = program(OWN, hex, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show"); + assert!(program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + let t = texts(&r); + assert_eq!(t.len(), 1, "{:?}", all(&r.document)); + assert_eq!(t[0].plain_text(), "AB"); + assert_eq!(t[0].runs[0].style.font_family, "Test One"); + // B starts where A's 600 units end, whatever the font laid out. + let o: Vec = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t[0]).glyphs.iter().map(|g| g.origin.x).collect(); + assert!((o[1] - o[0] - 30.0).abs() < 0.05, "{o:?}"); + } +} + +/// Type in an embedded font whose family isn't available keeps the font's name and shows in the +/// fallback font, and the import says so as PDF import does: each such family once, in the order +/// its type comes. A family that is available isn't named. +#[test] +fn type_in_fonts_that_arent_available_is_named_in_a_warning() { + let r = program( + OWN, + false, + "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show 10 60 moveto (BA) show \ + /Nowhere-Bold 12 selectfont 10 80 moveto (x) show /Inter-Regular 12 selectfont 10 90 moveto (y) show", + ); + assert_eq!(texts(&r).iter().map(|t| t.runs[0].style.font_family.as_str()).collect::>(), ["Test One", "Test One", "Nowhere", "Inter"]); + // PDF import's words. + assert_eq!(r.warnings, ["fonts that aren't available show in the fallback font until they are: Test One, Nowhere"]); +} + +#[test] +fn embedded_type1_fonts_measure_and_outline_their_glyphs() { + let fonts = String::from_utf8(font(OWN, true)).unwrap(); + check(&format!("{fonts} /TestOne findfont 50 scalefont setfont (AB) stringwidth pop 55 sub abs 0.01 lt")); + check(&format!( + "{fonts} /TestOne findfont 50 scalefont setfont newpath 10 20 moveto (A) true charpath pathbbox 45 sub abs 0.01 lt \ + exch 35 sub abs 0.01 lt and exch 20 sub abs 0.01 lt and exch 15 sub abs 0.01 lt and" + )); + check(&format!("{fonts} /TestOne findfont /CharStrings get /A known")); +} + +/// A glyph whose name says no character (`g1`) is drawn from the font. +#[test] +fn embedded_type1_glyphs_without_a_character_are_drawn() { + let r = program(OWN, true, "/TestOne findfont 50 scalefont setfont 10 20 moveto (C) show"); + assert!(texts(&r).is_empty()); + let paths: Vec<_> = all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| bounds(n)).collect(); + assert_eq!(paths.len(), 1); + assert!((paths[0].x0 - 10.0).abs() < 0.01 && (paths[0].width() - 25.0).abs() < 0.01 && (paths[0].height() - 20.0).abs() < 0.01, "{paths:?}"); +} + +/// A font in the standard encoding takes the standard names of its codes (PLRM 3rd ed., +/// Appendix E.5), so its glyphs and widths are found. +#[test] +fn standard_encoding_fonts_find_their_glyphs() { + let fonts = String::from_utf8(font("StandardEncoding", true)).unwrap(); + check(&format!("{fonts} /TestOne findfont 50 scalefont setfont (AB) stringwidth pop 55 sub abs 0.01 lt")); + let r = read(&format!("{fonts} /TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show")); + assert_eq!(texts(&r)[0].plain_text(), "AB"); +} + +/// A font found by name (its program not in the file), re-encoded with glyph names at other +/// codes, sets the characters its names say, not its codes read as Latin-1. +#[test] +fn named_fonts_set_the_characters_their_glyph_names_say() { + let r = read( + "/Helvetica findfont dup length dict begin { 1 index /FID ne { def } { pop pop } ifelse } forall\n\ + /Encoding 256 array 0 1 255 { 1 index exch /.notdef put } for dup 1 /H put dup 2 /i put dup 3 /eacute put def\n\ + currentdict end /Helv-Re exch definefont pop /Helv-Re 20 selectfont 10 20 moveto (\\001\\002\\003) show", + ); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::(), "Hié"); +} + +/// A font whose encoding is a copy of `StandardEncoding` (a different array, so not known as the +/// standard encoding) still finds each code's glyph by its character's name, not `.notdef`. +#[test] +fn copied_standard_encodings_find_their_glyphs() { + let fonts = String::from_utf8(font("StandardEncoding 256 array copy", true)).unwrap(); + check(&format!("{fonts} /TestOne findfont 50 scalefont setfont (AB) stringwidth pop 55 sub abs 0.01 lt")); + let r = read(&format!("{fonts} /TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show")); + assert_eq!(texts(&r)[0].plain_text(), "AB"); +} + +/// Subroutines 1 to 8 each calling the one below four times (`callsubr` 10, `return` 11), and +/// A a square drawn after calling subroutine 8: a few bytes that run some 260,000 operations. +fn heavy_font() -> String { + let mut subrs = vec![cs(&[(&[], 11)])]; + for k in 1..=8 { + subrs.push(cs(&[(&[k - 1], 10), (&[k - 1], 10), (&[k - 1], 10), (&[k - 1], 10), (&[], 11)])); + } + let a = cs(&[(&[0, 600], 13), (&[8], 10), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]); + String::from_utf8(font_with(OWN, true, &subrs, Some(a))).unwrap() +} + +/// Running a glyph's charstrings counts the bytes of every subroutine call, for the operation +/// budget; and the glyph still draws. +#[test] +fn running_a_type1_glyph_counts_its_subroutine_calls() { + let program = heavy_font(); + let at = program.find("eexec\n").unwrap() + "eexec\n".len(); + let font = super::type1::parse(&program.as_bytes()[at..]).unwrap(); + let gid = font.font.glyph_names().find(|(_, n)| *n == "A").unwrap().0.to_u32(); + let font = super::type1::Embedded::Type1(std::rc::Rc::new(font)); + let (outline, w) = font.glyph(gid).unwrap(); + assert!((w - 0.6).abs() < 1e-9 && !outline.elements().is_empty(), "{w}"); + let work = font.take_work(); + assert!(work > 4u64.pow(8), "{work}"); + assert_eq!(font.take_work(), 0); + check(&format!("{program} /TestOne findfont 50 scalefont setfont (A) stringwidth pop 30 sub abs 0.01 lt")); +} + +/// The evaluator limits each glyph, not the file: measuring a glyph whose subroutines run a +/// quarter of a million operations in a loop ends within the operation budget. +#[test] +fn type1_glyphs_measured_in_a_loop_run_out_of_the_budget() { + super::tests::runs_out_of_budget(&format!("{} /TestOne findfont 50 scalefont setfont {{ (A) stringwidth pop pop }} loop", heavy_font())); +} + +/// One long string of a costly glyph pays for each glyph as it is measured: a million copies of +/// the glyph above stop at the operation budget after a few hundred, instead of all running first. +#[test] +fn a_long_string_of_type1_glyphs_runs_out_of_the_budget() { + super::tests::runs_out_of_budget(&format!( + "{} /TestOne findfont 50 scalefont setfont /s 1000000 string def 0 1 999999 {{ s exch 65 put }} for s stringwidth pop pop", + heavy_font() + )); +} + +/// `eexec`'s search for `cleartomark` reads the encrypted part: on a large reusable file in a +/// loop it runs out of the operation budget instead of reading megabytes a pass for free. +#[test] +fn eexec_on_a_large_file_in_a_loop_runs_out_of_the_budget() { + super::tests::runs_out_of_budget( + "/s 4000000 string def s 3999980 (cleartomark) putinterval /f s /ReusableStreamDecode filter def\n\ + { f resetfile f eexec cleartomark } loop", + ); +} diff --git a/crates/eps/src/import/tests_type42.rs b/crates/eps/src/import/tests_type42.rs new file mode 100644 index 0000000000..21399afe70 --- /dev/null +++ b/crates/eps/src/import/tests_type42.rs @@ -0,0 +1,278 @@ +//! Plain Type 42 fonts (TrueType fonts in PostScript, Adobe Technical Note #5012, "The Type 42 +//! Font Format Specification") that carry their TrueType font: each code's character from its +//! glyph name, or from the glyph its `CharStrings` name gives when the name says nothing +//! (`/g12`); its width from the font's own metrics; glyphs that stand for no character drawn +//! from the font's outlines. Spacing from the show operators (PLRM 3rd ed., §5.1.4 and the +//! `ashow`, `widthshow` and `xshow` entries of chapter 8) is kept on live type as tracking. The +//! fonts are written from scratch around the bundled Source Sans 3. + +use skrifa::{FontRef, MetadataProvider}; +use vectorcraft_doc::{NodeKind, TextObject}; + +use super::tests::{all, read}; +use super::tests_composite::{FONT, glyph, sfnts}; + +/// A program defining Type 42 font `/Plain42` whose `Encoding` gives codes 1 to `names.len()` +/// glyph names `/g1`, `/g2`… mapped through `CharStrings` to the glyph of each of `glyphs`. +fn font(glyphs: &[u32]) -> String { + let mut enc = String::new(); + let mut strings = String::new(); + for (i, g) in glyphs.iter().enumerate() { + enc.push_str(&format!("Encoding {} /g{} put ", i + 1, i + 1)); + strings.push_str(&format!("/g{} {g} def ", i + 1)); + } + format!( + "10 dict begin /FontName /Plain42 def /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /FontBBox [0 0 1 1] def /PaintType 0 def\n\ + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for {enc}\n\ + /CharStrings {} dict def CharStrings begin /.notdef 0 def {strings} end\n\ + /sfnts [\n{}] def FontName currentdict end definefont pop\n", + glyphs.len() + 1, + sfnts() + ) +} + +fn texts(r: &crate::Imported) -> Vec { + all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((**t).clone()), + _ => None, + }) + .collect() +} + +/// Where each glyph of `t` starts along its baseline (text space). +fn origins(t: &TextObject) -> Vec { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| g.origin.x).collect() +} + +#[test] +fn glyph_names_that_say_nothing_read_the_fonts_character_map() { + let (h, _) = glyph('H'); + let (i, _) = glyph('I'); + let r = read(&format!("{}/Plain42 findfont 40 scalefont setfont 10 20 moveto (\\001\\002) show", font(&[h, i]))); + let t = texts(&r); + assert_eq!(t.len(), 1, "{:?}", all(&r.document)); + assert_eq!(t[0].plain_text(), "HI"); + assert_eq!(t[0].runs[0].style.font_family, "Plain42"); +} + +#[test] +fn a_glyph_name_says_its_character_whatever_its_code() { + // The Euro by its name at code 128, where Latin-1 has a control code. + // A standard encoding name says its character too (`hyphen`), not one the font's character + // map also maps to its glyph (the soft hyphen). + let (e, _) = glyph('€'); + let (h, _) = glyph('-'); + let program = font(&[e, h]) + .replace("Encoding 1 /g1 put", "Encoding 128 /Euro put") + .replace("/g1 ", "/Euro ") + .replace("Encoding 2 /g2 put", "Encoding 45 /hyphen put") + .replace("/g2 ", "/hyphen "); + let r = read(&format!("{program}/Plain42 findfont 40 scalefont setfont 10 20 moveto (\\200-) show")); + assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::(), "€-"); +} + +/// A glyph of the bundled font with an outline that the character map doesn't reach (an +/// alternate form) and whose name says no character. +fn alternate_glyph() -> u32 { + let f = FontRef::new(FONT).unwrap(); + let mapped: std::collections::HashSet = f.charmap().mappings().map(|(_, g)| g.to_u32()).collect(); + let names = f.glyph_names(); + (1..f.glyph_names().num_glyphs()) + .find(|g| !mapped.contains(g) && super::text::glyph_char(names.get(skrifa::GlyphId::new(*g)).unwrap().as_str()) == '\u{2022}') + .and_then(|g| { + // One with an outline. + let (o, _) = super::type42::glyph(FONT, g)?; + (!o.elements().is_empty()).then_some(g) + }) + .unwrap() +} + +#[test] +fn glyphs_that_stand_for_no_character_are_drawn_from_the_font() { + let alt = alternate_glyph(); + let (h, _) = glyph('H'); + let r = read(&format!("{}/Plain42 findfont 40 scalefont setfont 10 20 moveto (\\001\\002) show", font(&[h, alt]))); + assert!(texts(&r).is_empty()); + let paths = all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).count(); + assert_eq!(paths, 2); +} + +#[test] +fn the_fonts_own_widths_space_its_type_and_move_the_point() { + let (h, wh) = glyph('H'); + let (i, wi) = glyph('I'); + let f = font(&[h, i]); + let check = |cond: String| super::tests::check(&format!("{f} /Plain42 findfont 50 scalefont setfont {cond}")); + check(format!("(\\001\\002) stringwidth pop {} sub abs 0.01 lt", 50.0 * (wh + wi))); + check(format!("gsave nulldevice 10 20 moveto (\\001\\002) show currentpoint grestore pop {} sub abs 0.01 lt", 10.0 + 50.0 * (wh + wi))); + check("gsave nulldevice 10 20 moveto (\\001\\002) [30 7] xshow currentpoint grestore pop 47 sub abs 0.01 lt".into()); + check("newpath 10 20 moveto (\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into()); +} + +/// `xshow` and `ashow` put each character where they say: the type's tracking makes up the +/// difference from its font's advances. +#[test] +fn show_operators_space_live_type_with_tracking() { + let (h, wh) = glyph('H'); + let (i, _) = glyph('I'); + let f = font(&[h, i, h]); + let r = read(&format!("{f}/Plain42 findfont 50 scalefont setfont 10 20 moveto (\\001\\002\\003) [40 25 10] xshow")); + let t = texts(&r); + assert_eq!(t.len(), 1); + assert_eq!(t[0].plain_text(), "HIH"); + let o = origins(&t[0]); + assert!((o[1] - o[0] - 40.0).abs() < 0.05 && (o[2] - o[1] - 25.0).abs() < 0.05, "{o:?}"); + let r = read(&format!("{f}/Plain42 findfont 50 scalefont setfont 10 20 moveto 6 0 (\\001\\002) ashow")); + let o = origins(&texts(&r)[0]); + assert!((o[1] - o[0] - (50.0 * wh + 6.0)).abs() < 0.05, "{o:?}"); +} + +/// A font found by name (its program isn't in the file) keeps the installed font's spacing, +/// plus what the show operator adds. +#[test] +fn named_fonts_take_the_show_operators_spacing() { + let r = read("/Helvetica findfont 20 scalefont setfont 10 20 moveto (AB) [30 0] xshow"); + let t = texts(&r); + assert_eq!(t[0].plain_text(), "AB"); + let o = origins(&t[0]); + assert!((o[1] - o[0] - 30.0).abs() < 0.05, "{o:?}"); + // Plain `show` keeps a single run with no tracking. + let r = read("/Helvetica findfont 20 scalefont setfont 10 20 moveto (AB) show"); + let t = texts(&r); + assert!(t[0].runs.len() == 1 && t[0].runs[0].style.tracking == 0.0, "{:?}", t[0].runs); +} + +/// `kshow` runs its procedure between each two characters with their codes (PLRM 3rd ed., +/// `kshow`): where it moves the current point, the next character follows (kept on live type as +/// tracking), and what it draws is drawn over the type. +#[test] +fn kshow_procedures_kern_live_type() { + let (h, wh) = glyph('H'); + let (i, wi) = glyph('I'); + let f = font(&[h, i, h]); + // Only the pair of codes 1 then 2 is kerned, 20 units. + let kern = "{ exch 1 eq exch 2 eq and { 20 0 rmoveto } if }"; + let r = read(&format!("{f}/Plain42 findfont 50 scalefont setfont 10 20 moveto {kern} (\\001\\002\\003) kshow")); + let t = texts(&r); + assert_eq!(t.len(), 1, "{:?}", all(&r.document)); + assert_eq!(t[0].plain_text(), "HIH"); + let o = origins(&t[0]); + assert!((o[1] - o[0] - (50.0 * wh + 20.0)).abs() < 0.05, "{o:?}"); + assert!((o[2] - o[1] - 50.0 * wi).abs() < 0.05, "{o:?}"); + let check = |cond: String| super::tests::check(&format!("{f} /Plain42 findfont 50 scalefont setfont {cond}")); + check(format!( + "gsave nulldevice 10 20 moveto {kern} (\\001\\002\\003) kshow currentpoint grestore pop {} sub abs 0.01 lt", + 10.0 + 50.0 * (2.0 * wh + wi) + 20.0 + )); + // A font found by name kerns the same way. + let r = read("/Helvetica findfont 20 scalefont setfont 10 20 moveto { pop pop -3 0 rmoveto } (HIH) kshow"); + let t = texts(&r); + let plain = read("/Helvetica findfont 20 scalefont setfont 10 20 moveto (HIH) show"); + let (o, p) = (origins(&t[0]), origins(&texts(&plain)[0])); + assert!((o[1] - o[0] - (p[1] - p[0] - 3.0)).abs() < 0.05 && (o[2] - o[1] - (p[2] - p[1] - 3.0)).abs() < 0.05, "{o:?} {p:?}"); + // A procedure that draws: a square after the type, over it. + let r = read("/Helvetica findfont 20 scalefont setfont 10 20 moveto { pop pop currentpoint 2 2 rectfill } (AB) kshow"); + let kinds: Vec = all(&r.document) + .iter() + .filter(|n| matches!(n.kind, NodeKind::Text(_) | NodeKind::Path { .. })) + .map(|n| matches!(n.kind, NodeKind::Text(_))) + .collect(); + assert_eq!(kinds, [true, false]); +} + +/// Characters the installed font would join in a ligature (`fi`) keep the places the file gives +/// each of them: the type is set without ligatures and each character's tracking is its own. +#[test] +fn characters_a_ligature_would_join_keep_their_places() { + // Each character at its own width in the bundled Source Sans 3, as a PDF converter writes them. + let (_, wf) = glyph('f'); + let (_, wi) = glyph('i'); + let (f, i) = (50.0 * wf, 50.0 * wi); + let r = read(&format!("/SourceSans3-Regular findfont 50 scalefont setfont 10 20 moveto (fit) [{f} {i} 0] xshow")); + let t = texts(&r); + assert_eq!(t[0].plain_text(), "fit"); + let o = origins(&t[0]); + assert_eq!(o.len(), 3, "{o:?}"); + assert!((o[1] - o[0] - f).abs() < 0.05 && (o[2] - o[1] - i).abs() < 0.05, "{o:?} {f} {i}"); +} + +/// A move that is finite in user space but not along the type's baseline (a font matrix +/// squashed a thousandfold) is an `undefinedresult`, not a tracking that isn't a number. +#[test] +fn moves_too_large_for_the_baseline_are_refused() { + let r = read("0 0 10 10 rectfill /Helvetica findfont [0.001 0 0 50 0 0] makefont setfont 10 20 moveto (A\\001) [1e307 -1e307] xshow"); + assert!(texts(&r).iter().all(|t| t.runs.iter().all(|r| r.style.tracking.is_finite())), "{:?}", texts(&r)); + assert!(r.warnings.iter().any(|w| w.contains("undefinedresult")), "{:?}", r.warnings); +} + +/// Moves that overflow (two `1e308` numbers in `xshow`) in type drawn from the font's outlines +/// are an `undefinedresult` before anything is painted, as for live type: no glyph lands at +/// infinity. +#[test] +fn outline_moves_that_overflow_are_refused() { + let alt = alternate_glyph(); + let (h, _) = glyph('H'); + let r = read(&format!( + "0 0 10 10 rectfill {}/Plain42 findfont 40 scalefont setfont 10 20 moveto (\\001\\002\\001) [1e308 1e308 0] xshow", + font(&[h, alt]) + )); + assert!(r.warnings.iter().any(|w| w.contains("undefinedresult")), "{:?}", r.warnings); + assert_eq!(all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).count(), 1, "{:?}", all(&r.document)); +} + +/// Reading a font's character map counts the mappings it visits, once, for the operation +/// budget. +#[test] +fn reading_the_character_map_counts_its_mappings() { + let f = super::type42::Font::new(FONT.to_vec()); + let (h, _) = glyph('H'); + assert_eq!(f.char_of(h), Some('H')); + let n = f.take_char_map_work(); + assert!(n > 100, "{n}"); + f.char_of(h); + assert_eq!(f.take_char_map_work(), 0); +} + +/// A glyph named for a symbol font's private-use code (`uniF041`) stands for no character, as +/// when the character map maps only that code to it, so it's drawn from the font's outline; +/// other names still say their character. +#[test] +fn private_use_glyph_names_stand_for_no_character() { + use super::type42::post_name_char; + assert_eq!(post_name_char("uniF041"), None); + assert_eq!(post_name_char("uF0FF"), None); + assert_eq!(post_name_char("uni00AD"), None); + assert_eq!(post_name_char("uniF100"), Some('\u{F100}')); + assert_eq!(post_name_char("uni20AC"), Some('€')); + assert_eq!(post_name_char("A"), Some('A')); + assert_eq!(post_name_char("bullet"), Some('\u{2022}')); + assert_eq!(post_name_char("g12"), None); +} + +/// A glyph the character map doesn't reach is looked up by its glyph name once: the first lookup +/// counts for the operation budget, a second one is remembered (a miss too). +#[test] +fn glyph_name_lookups_are_counted_once() { + let f = super::type42::Font::new(FONT.to_vec()); + let alt = alternate_glyph(); + let first = f.char_of(alt); + f.take_char_map_work(); + // The character map was read by the first call; the name lookup is remembered. + let g = FontRef::new(FONT).unwrap().glyph_names().num_glyphs() + 5; + assert_eq!(f.char_of(g), None); + assert!(f.take_char_map_work() > 0); + assert_eq!(f.char_of(g), None); + assert_eq!(f.char_of(alt), first); + assert_eq!(f.take_char_map_work(), 0); +} + +/// Control codes (a new string's zeros) set no type but are still read: showing or measuring a +/// long string of them in a loop runs out of the operation budget. +#[test] +fn control_codes_in_a_loop_run_out_of_the_budget() { + for body in ["{ s stringwidth pop pop } loop", "{ 0 0 moveto s show } loop"] { + super::tests::runs_out_of_budget(&format!("/Helvetica findfont 10 scalefont setfont /s 1000000 string def {body}")); + } +} diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index d0b68bbf5c..5868aa9228 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -11,9 +11,11 @@ use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, Point, Vec2}; use vectorcraft_text::TextLayout; +use super::cid::Base; use super::graphics::MAX_APART; use super::interp::{Interp, matrix_obj, matrix_of}; use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, ps_err}; +use super::type1::Embedded; /// The font a program uses before it sets one. const DEFAULT_FONT: &str = "Helvetica"; @@ -168,12 +170,14 @@ impl Interp<'_> { ResourceForAll => self.resource_for_all()?, Show | AShow | WidthShow | AWidthShow | XShow | YShow | XYShow | KShow => { let (s, spacing) = self.show_operands(op)?; - if let Some(glyphs) = self.composite_glyphs(&s) { + if let Some((text, font)) = self.unicode_type(&s)? { + self.show_unicode(&text, &font)?; + } else if let Some(glyphs) = self.composite_glyphs(&s)? { self.show_composite(&glyphs, &spacing)?; } else { match self.type3_font() { Some(font) => self.show_type3(&font, &s, &spacing)?, - None => self.show(&s)?, + None => self.show_plain(&s, &spacing)?, } } } @@ -229,6 +233,7 @@ impl Interp<'_> { }; self.push(Obj::Dict(font))?; } + op if op == ComposeFont || Op::PROCSET.contains(&op) => self.cid_op(op)?, _ => return ps_err("undefined", op.name()), } Ok(()) @@ -277,14 +282,26 @@ impl Interp<'_> { /// How far `s` moves the current point (user space). fn width_of(&mut self, s: &[u8]) -> Res { - if let Some(glyphs) = self.composite_glyphs(s) { + if let Some((text, font)) = self.unicode_type(s)? { + let saved = self.g.font.replace(font); + let r = self.set_text(&text, Point::ZERO).map(|t| t.2); + self.g.font = saved; + return r; + } + if let Some(glyphs) = self.composite_glyphs(s)? { let mut w = Vec2::ZERO; for g in &glyphs { w += self.composite_glyph(g, Point::new(w.x, w.y), Draw::No)?; } return Ok(w); } - let Some(font) = self.type3_font() else { return Ok(self.set_type(s, Point::ZERO)?.2) }; + let Some(font) = self.type3_font() else { + if let Some((_, glyphs)) = self.type42_plain(s)? { + let (_, f1) = self.font()?; + return Ok(glyphs.iter().map(|g| f1 * Point::new(g.width, 0.0) - f1 * Point::ZERO).sum()); + } + return Ok(self.set_type(s, Point::ZERO)?.2); + }; let mut w = Vec2::ZERO; for &code in s { w += self.type3_glyph(&font, Glyph::Code(code), Point::new(w.x, w.y), false)?; @@ -300,11 +317,7 @@ impl Interp<'_> { let w = self.type3_glyph(font, Glyph::Code(code), at, true)?; let d = spacing.advance(i, i64::from(code), w); self.g.cur = Some(self.xf() * (at + d)); - if let (Spacing::Kern(p), Some(next)) = (spacing, s.get(i + 1)) { - self.push(Obj::Int(i64::from(code)))?; - self.push(Obj::Int(i64::from(*next)))?; - self.call(p.clone())?; - } + self.kern(spacing, s, i, at + d)?; } let text: String = s.iter().map(|b| char::from(*b)).filter(|c| !c.is_control()).collect(); self.group_glyphs(start, &text); @@ -381,12 +394,23 @@ impl Interp<'_> { self.out.push(group, &clips); } - /// The font named `k`: one the program defined, else a font of that name. + /// The font named `k`: one the program defined; else, for a name `CIDFont-CMap` whose CMap + /// is a predefined Unicode CMap, the CID-keyed font of those two (the usual name of a + /// CID-keyed font, as `composefont` makes them: PLRM 3rd ed., chapter 8); else a font of + /// that name. fn find_font(&mut self, k: &Obj) -> Res { let key = k.key().ok_or(PsError::Ps("typecheck", "findfont".into()))?; if let Some(Obj::Dict(d)) = self.fonts.borrow().get(&key) { return Ok(d.clone()); } + let text = k.text().map(|t| t.to_string()).unwrap_or_default(); + let split = + text.match_indices('-').map(|(i, _)| i).find(|&i| i > 0 && super::cid::unicode_cmap(text.get(i + 1..).unwrap_or_default()).is_some()); + if let Some((cid_font, cmap)) = split.and_then(|i| Some((text.get(..i)?, text.get(i + 1..)?))) { + let cmap = self.find_cmap(&Obj::name(cmap))?; + let dep = self.find_cid_font(&Obj::name(cid_font))?; + return Ok(self.composed(key, cmap, vec![Obj::Dict(dep)])); + } let mut d = Dict::new(); d.insert(Key::name("FontName"), key.obj()); d.insert(Key::name("FontType"), Obj::Int(1)); @@ -421,10 +445,41 @@ impl Interp<'_> { /// `s` (read as Latin-1) set in the current font at user point `at`: point type placed there, /// its layout in text space, and how far it moves the current point (user space). fn set_type(&mut self, s: &[u8], at: Point) -> Res<(TextObject, TextLayout, Vec2)> { + // Every byte is read, also the control codes left out of the type (a new string's zeros). + self.spend(s.len() as u64)?; + let text: String = self.named_chars(s).into_iter().filter(|c| !c.is_control()).collect(); + self.set_text(&text, at) + } + + /// The character each code of `s` stands for in the current font (one found by name, whose + /// program isn't in the file): the one its glyph name says (the standard encodings by their + /// codes' names), else the code read as Latin-1. + fn named_chars(&self, s: &[u8]) -> Vec { + let Some(font) = self.g.font.clone() else { return s.iter().map(|b| char::from(*b)).collect() }; + let f = font.borrow(); + let standard = f.get(&Key::name("Encoding")).and_then(|e| self.standard_encoding(e)); + s.iter() + .map(|&code| { + let mut name = glyph_name(&f, code); + if &*name == ".notdef" + && let Some(iso) = standard + { + name = Rc::from(standard_name(code, iso)); + } + match &*name { + ".notdef" => char::from(code), + n => named_char(code, n).unwrap_or(char::from(code)), + } + }) + .collect() + } + + /// [`Self::set_type`] for the characters `text`. + fn set_text(&mut self, text: &str, at: Point) -> Res<(TextObject, TextLayout, Vec2)> { // Laying out type costs about as much as 300 operations, and 64 more a character // (measured), so `{ (a) stringwidth pop pop } loop` or `cshow` on a long string ends // within the budget like any other loop instead of running for minutes. - self.spend((s.len() as u64).saturating_mul(64).saturating_add(300))?; + self.spend((text.len() as u64).saturating_mul(64).saturating_add(300))?; let (name, f1) = self.font()?; // Text space (y down, `size` points an em) onto the document. let m = self.xf() * Affine::translate(at.to_vec2()) * f1; @@ -435,10 +490,9 @@ impl Interp<'_> { let (family, font_style) = family_style(&name); // The available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". let font_family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); - let text: String = s.iter().map(|b| char::from(*b)).filter(|c| !c.is_control()).collect(); let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; let style = CharStyle { font_family, font_style, size, fill, stroke: Paint::None, ..CharStyle::default() }; - let mut t = TextObject::point(Point::ZERO, &text, style); + let mut t = TextObject::point(Point::ZERO, text, style); let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); t.xf = m * Affine::scale_non_uniform(1.0 / size, -1.0 / size); t.cached_bounds = Some(layout.bounds); @@ -448,19 +502,223 @@ impl Interp<'_> { /// `show`: point type at the current point, which moves past it. fn show(&mut self, s: &[u8]) -> Res { + self.show_plain(s, &Spacing::Plain) + } + + /// `s` shown in a font that isn't a Type 3 or composite font, spaced as `spacing` says: point + /// type at the current point, which moves past it as far as the file says, each character + /// where the file puts it. A Type 42 font that carries its TrueType font gives each code its + /// character (by its glyph name, else the character its glyph stands for in the font's own + /// character map) and its glyph's width; type in a font found by name is spaced by the + /// installed font's advances. Where the file's spacing differs from the advances of the + /// installed (or fallback) font, each character's tracking makes up the difference, so type + /// in a font that isn't installed keeps the file's line lengths and justified lines don't + /// drift, as PDF import does. Glyphs that stand for no character are drawn from the font's + /// outlines (the whole string, as one group). + fn show_plain(&mut self, s: &[u8], spacing: &Spacing) -> Res { + // Every code gets a move, also the control codes left out of the type. + self.spend(s.len() as u64)?; let at = self.user_point()?; - let (t, _, adv) = self.set_type(s, at)?; - if !self.g.paint.is_none() && !t.plain_text().trim().is_empty() { - let clips = self.g.clips.clone(); - self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); + let (_, f1) = self.font()?; + let plain = self.type42_plain(s)?; + if let Some((data, glyphs)) = &plain + && glyphs.iter().any(|g| g.ch.is_none() && g.gid != 0) + { + return self.show_type42_outlines(data, glyphs, s, spacing, at, f1); } - self.g.cur = Some(self.xf() * (at + adv)); + // Each code's character, if it has one that shows (control codes don't). + let chars: Vec> = match &plain { + Some((_, glyphs)) => glyphs.iter().map(|g| g.ch).collect::>(), + None => self.named_chars(s).into_iter().map(Some).collect(), + } + .into_iter() + .map(|c| c.filter(|c| !c.is_control())) + .collect(); + let text: String = chars.iter().flatten().collect(); + let (mut t, mut layout, _) = self.set_text(&text, at)?; + let size = t.runs.first().map_or(1.0, |r| r.style.size); + let starts: Vec = text.char_indices().map(|(b, _)| b).collect(); + // The file places each character's glyph: where the layout joins characters in a + // ligature, the type is set without ligatures, so each character has its own advance. + let glyph_starts: std::collections::HashSet = layout.glyphs.iter().map(|g| g.byte).collect(); + if starts.iter().any(|b| !glyph_starts.contains(b)) { + for run in &mut t.runs { + run.style.features.push("-liga".into()); + } + layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + t.cached_bounds = Some(layout.bounds); + } + // Each character's advance in the layout (text space). + let mut natural = vec![0.0; starts.len()]; + for g in &layout.glyphs { + if let Some(n) = starts.binary_search(&g.byte).ok().and_then(|k| natural.get_mut(k)) { + *n += g.advance; + } + } + // Each code's move (user space) and that move in text space, along the baseline and across. + let em = |x: f64| f1 * Point::new(x, 0.0) - f1 * Point::ZERO; + let inv = f1.inverse(); + let mut moves = Vec::with_capacity(s.len()); + let mut k = 0; + // What `kshow`'s procedure draws goes after the type. + let start = self.out.drawn.len(); + let mut pen = at; + for (i, (&code, c)) in s.iter().zip(&chars).enumerate() { + let own = match &plain { + Some((_, glyphs)) => glyphs.get(i).map_or(0.0, |g| g.width), + None if c.is_some() => natural.get(k).copied().unwrap_or(0.0) / size, + None => 0.0, + }; + k += usize::from(c.is_some()); + let mut d = spacing.advance(i, i64::from(code), em(own)); + d += self.kern(spacing, s, i, pen + d)?; + pen += d; + let e = inv * Point::new(d.x, d.y) - inv * Point::ZERO; + if ![d.x, d.y, e.x * size, e.y * size].iter().all(|v| v.is_finite()) { + return ps_err("undefinedresult", "a show"); + } + moves.push((d, e.x * size, e.y * size)); + } + let total: Vec2 = moves.iter().map(|m| m.0).sum(); + if !(total.x.is_finite() && total.y.is_finite()) { + return ps_err("undefinedresult", "a show"); + } + let across = moves.iter().any(|m| m.2.abs() > size * 1e-3); + // Nothing shows on the null device (`nulldevice`, a Type 3 glyph only measured). + let painted = !self.g.paint.is_none() && !self.g.null; + if across { + // Moves across the baseline (`yshow`, `xyshow`): each character where the file puts it. + let mut pen = at; + for ((d, ..), c) in moves.iter().zip(&chars) { + if let Some(c) = c + && painted + && !c.is_whitespace() + { + let (t, ..) = self.set_text(c.encode_utf8(&mut [0; 4]), pen)?; + let clips = self.g.clips.clone(); + self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); + } + pen += *d; + } + } else if painted && !text.trim().is_empty() { + // The moves of codes before the first character move the type; those of codes after + // a character, before the next, are that character's. + let mut lead = Vec2::ZERO; + let mut target: Vec = Vec::with_capacity(natural.len()); + for ((d, along, _), c) in moves.iter().zip(&chars) { + match (c, target.last_mut()) { + (Some(_), _) => target.push(*along), + (None, Some(last)) => *last += along, + (None, None) => lead += *d, + } + } + let tracking: Vec = target + .iter() + .zip(&natural) + // Hundredths of a thousandth of an em: no drift along a line, no noise in the panels. + .map(|(want, has)| (((want - has) / size * 1000.0).clamp(-1000.0, 10000.0) * 100.0).round() / 100.0) + .collect(); + if tracking.iter().any(|t| *t != 0.0) + && let Some(run) = t.runs.first().cloned() + { + let mut runs: Vec = Vec::new(); + for (c, tr) in text.chars().zip(&tracking) { + match runs.last_mut() { + Some(last) if last.style.tracking == *tr => last.text.push(c), + _ => runs.push(vectorcraft_doc::TextRun { + text: c.to_string(), + style: CharStyle { tracking: *tr, ..run.style.clone() }, + inline: run.inline.clone(), + }), + } + } + t.runs = runs; + t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds); + } + if lead != Vec2::ZERO { + t.xf = Affine::translate(self.xf() * Point::new(lead.x, lead.y) - self.xf() * Point::ZERO) * t.xf; + } + let clips = self.g.clips.clone(); + if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some() + && let Some(after) = self.out.drawn.get_mut(start..) + { + after.rotate_right(1); + } + } + self.g.cur = Some(self.xf() * (at + total)); + Ok(()) + } + + /// `kshow` between character `i` of `s` and the next: its procedure run with the two codes + /// and the current point at user point `pen` (PLRM 3rd ed., `kshow`: the procedure may + /// change the current point, as kerning does) → how far it moved the point (user space). + /// Nothing for other show operators or after the last character. + fn kern(&mut self, spacing: &Spacing, s: &[u8], i: usize, pen: Point) -> Res { + let (Spacing::Kern(p), Some(&code), Some(&next)) = (spacing, s.get(i), s.get(i + 1)) else { return Ok(Vec2::ZERO) }; + self.g.cur = Some(self.xf() * pen); + self.push(Obj::Int(i64::from(code)))?; + self.push(Obj::Int(i64::from(next)))?; + self.call(p.clone())?; + Ok(self.user_point()? - pen) + } + + /// `s` in a Type 42 font, some of whose glyphs stand for no character, drawn from the font's + /// outlines at the current point (one group), spaced as `spacing` says. + fn show_type42_outlines(&mut self, data: &Embedded, glyphs: &[Plain], s: &[u8], spacing: &Spacing, at: Point, f1: Affine) -> Res { + // The moves, checked before anything is painted: moves that overflow (two `1e308` + // numbers in `xshow`) are an error, as in `show_plain`, not glyphs at infinity. + let mut pen = at; + for (i, (g, &code)) in glyphs.iter().zip(s).enumerate() { + pen += spacing.advance(i, i64::from(code), f1 * Point::new(g.width, 0.0) - f1 * Point::ZERO); + if !(pen.x.is_finite() && pen.y.is_finite()) { + return ps_err("undefinedresult", "a show"); + } + } + let start = self.out.drawn.len(); + let mut text = String::new(); + let mut pen = at; + for (i, (g, &code)) in glyphs.iter().zip(s).enumerate() { + let glyph = data.glyph(g.gid); + self.spend(data.take_work())?; + if let Some(outline) = glyph.map(|o| o.0) { + self.type42_paint(outline, pen, f1, Draw::Fill)?; + } + let d = spacing.advance(i, i64::from(code), f1 * Point::new(g.width, 0.0) - f1 * Point::ZERO); + // `kshow`'s procedure moves the point as it runs, so its moves are checked as they come. + let d = d + self.kern(spacing, s, i, pen + d)?; + pen += d; + if !(pen.x.is_finite() && pen.y.is_finite()) { + return ps_err("undefinedresult", "a show"); + } + text.push(g.ch.unwrap_or('\u{2022}')); + } + self.g.cur = Some(self.xf() * pen); + self.group_glyphs(start, &text); + Ok(()) + } + + /// Glyph outline `outline` (glyph space) under font matrix `fm` at user point `at`: filled, or + /// added to the current path (`charpath`). + fn type42_paint(&mut self, mut outline: vectorcraft_geom::BezPath, at: Point, fm: Affine, paint: Draw) -> Res { + // Measuring a glyph reads its outline too, so `stringwidth` in a loop pays for it. + self.spend((outline.elements().len() as u64).saturating_add(16))?; + if paint == Draw::No { + return Ok(()); + } + outline.apply_affine(self.xf() * Affine::translate(at.to_vec2()) * fm); + if paint == Draw::Fill { + return self.fill_path(outline, vectorcraft_geom::FillRule::NonZero); + } + if self.g.path.elements().len().saturating_add(outline.elements().len()) > super::graphics::MAX_PATH { + return Err(PsError::Limit("a path has too many points")); + } + self.g.path.extend(outline); Ok(()) } /// `charpath`: the glyph outlines of `s` added to the path. fn char_path(&mut self, s: &[u8]) -> Res { - if let Some(glyphs) = self.composite_glyphs(s) { + if let Some(glyphs) = self.composite_glyphs(s)? { for g in &glyphs { let at = self.user_point()?; let w = self.composite_glyph(g, at, Draw::Path)?; @@ -468,6 +726,20 @@ impl Interp<'_> { } return Ok(()); } + if let Some((data, glyphs)) = self.type42_plain(s)? { + let (_, f1) = self.font()?; + let mut pen = self.user_point()?; + for g in &glyphs { + let glyph = data.glyph(g.gid); + self.spend(data.take_work())?; + if let Some((outline, _)) = glyph { + self.type42_paint(outline, pen, f1, Draw::Path)?; + } + pen += f1 * Point::new(g.width, 0.0) - f1 * Point::ZERO; + } + self.g.cur = Some(self.xf() * pen); + return Ok(()); + } let at = self.user_point()?; let (t, layout, adv) = self.set_type(s, at)?; for g in &layout.glyphs { @@ -520,14 +792,19 @@ impl Spacing { } } -/// A character of a composite font: the descendant font that draws it, its code there, and the -/// composite font's matrix (over the descendant's own). +/// A character of a composite font: the descendant font that draws it, its code there (its last +/// byte for a CID), its CID and the notdef mapping's (`FMapType` 9), the composite font's matrix +/// (over the descendant's own) and whether it is set vertically (`WMode` 1). struct Mapped { font: DictRef, /// The byte that picked the descendant (the font number). pick: u8, code: u8, + /// The glyph name a CMap maps the character to, when the font's encoding has no code for it. + name: Option>, + cid: Option<(u32, Option)>, outer: Affine, + vertical: bool, } /// What drawing a glyph does with it. @@ -553,23 +830,51 @@ fn font_matrix(f: &Dict, default: f64) -> Affine { /// Font `f`'s glyph units in its matrix's space: Type 1 glyphs are in 1000-unit space; a Type 42 /// font's glyph space is one unit an em (its FontMatrix, usually the identity, is already the -/// em's). +/// em's). A CIDFont's em is the glyph units its matrix makes one unit of text space: one for a +/// Type 2 CIDFont, its units an em for one from a FontSet's Compact Font Format data. fn units(f: &Dict) -> f64 { - if font_type(f) == Some(42.0) { 1.0 } else { 1000.0 } + if font_type(f) == Some(42.0) { + return 1.0; + } + if let Some(kind) = f.get(&Key::name("CIDFontType")).and_then(Obj::as_num) { + let default = if kind == 2.0 { 1.0 } else { 0.001 }; + let scale = font_matrix(f, default).determinant().abs().sqrt(); + return if scale.is_finite() && scale > 1e-9 { 1.0 / scale } else { 1.0 / default }; + } + 1000.0 } impl Interp<'_> { /// The characters of `s` in the current font when it is a composite font with the 8/8 mapping /// (`FMapType` 2: a byte picking the descendant through `Encoding` and `FDepVector`, then the - /// code in it: PLRM 3rd ed., §5.10.1 "Type 0 Font Dictionaries"); `None` for other fonts and - /// mappings, which are set as type in the font of the composite font's name. - fn composite_glyphs(&self, s: &[u8]) -> Option> { - let font = self.g.font.clone()?; - let f = font.borrow(); - if font_type(&f) != Some(0.0) || f.get(&Key::name("FMapType")).and_then(Obj::as_num) != Some(2.0) { - return None; + /// code in it: PLRM 3rd ed., §5.10.1 "Type 0 Font Dictionaries") or a CMap (`FMapType` 9: + /// codes mapped to a descendant and a CID, §5.11.5); `None` for other fonts and mappings, + /// which are set as type in the font of the composite font's name. + fn composite_glyphs(&mut self, s: &[u8]) -> Res>> { + let Some(font) = self.g.font.clone() else { return Ok(None) }; + let map = { + let f = font.borrow(); + if font_type(&f) != Some(0.0) { + return Ok(None); + } + f.get(&Key::name("FMapType")).and_then(Obj::as_num) + }; + if map == Some(9.0) { + return self.cid_chars(&font, s).map(Some); } - let (encoding, fonts) = (f.get(&Key::name("Encoding"))?.items()?.clone(), f.get(&Key::name("FDepVector"))?.items()?.clone()); + if map != Some(2.0) { + return Ok(None); + } + // The scan visits every byte pair, also those that map to no glyph and so cost nothing + // further: charged by the string's length first, so a long string of unmapped characters + // shown in a loop runs out of the budget. + self.spend(s.len() as u64)?; + let f = font.borrow(); + let (Some(encoding), Some(fonts)) = + (f.get(&Key::name("Encoding")).and_then(|e| e.items().cloned()), f.get(&Key::name("FDepVector")).and_then(|e| e.items().cloned())) + else { + return Ok(None); + }; let (encoding, fonts) = (encoding.borrow(), fonts.borrow()); let outer = font_matrix(&f, 1.0); let mut out = Vec::with_capacity(s.len() / 2); @@ -579,10 +884,104 @@ impl Interp<'_> { if let Some(Obj::Dict(d)) = index.and_then(|i| fonts.get(i as usize)) && font_type(&d.borrow()) != Some(0.0) { - out.push(Mapped { font: d.clone(), pick, code, outer }); + out.push(Mapped { font: d.clone(), pick, code, name: None, cid: None, outer, vertical: false }); } } - Some(out) + Ok(Some(out)) + } + + /// The characters of `s` in `FMapType` 9 font `font`: its CMap's codes, each a CID in the + /// descendant `FDepVector` gives its font number (PLRM 3rd ed., §5.11.5). + fn cid_chars(&mut self, font: &DictRef, s: &[u8]) -> Res> { + let (cmap, fonts, outer, wmode) = { + let f = font.borrow(); + let fonts = f.get(&Key::name("FDepVector")).and_then(|e| e.items().map(|i| i.to_vec())).unwrap_or_default(); + let wmode = f.get(&Key::name("WMode")).and_then(Obj::as_num); + (f.get(&Key::name("CMap")).cloned(), fonts, font_matrix(&f, 1.0), wmode) + }; + let Some(Obj::Dict(cmap)) = cmap else { return Ok(vec![]) }; + let vertical = wmode.or_else(|| cmap.borrow().get(&Key::name("WMode")).and_then(Obj::as_num)) == Some(1.0); + let map = self.cmap(&cmap)?; + // Decoding stops when it would pass the budget left, which `spend` then reports. + let (chars, work) = map.decode(s, self.ops_left().saturating_mul(64)); + // Each code is compared with the CMap's ranges and mappings until one matches. + self.spend((s.len() as u64).saturating_add(work / 64))?; + Ok(chars + .into_iter() + .filter_map(|c| match (fonts.get(c.font), c.base) { + // A base font's code, or its glyph name (at the code its encoding gives it, if any). + (Some(Obj::Dict(d)), Some(Base::Code(code))) => { + Some(Mapped { font: d.clone(), pick: 0, code, name: None, cid: None, outer, vertical }) + } + (Some(Obj::Dict(d)), Some(Base::Name(name))) => { + let code = encoded(&d.borrow(), &name); + let name = code.is_none().then_some(name); + Some(Mapped { font: d.clone(), pick: 0, code: code.unwrap_or(0), name, cid: None, outer, vertical }) + } + // A code without a mapping in a base font (not a CIDFont): its code 0, the + // `.notdef` glyph CID 0 stands for in a CIDFont. + (Some(Obj::Dict(d)), None) if !d.borrow().contains_key(&Key::name("CIDFontType")) => { + Some(Mapped { font: d.clone(), pick: 0, code: 0, name: None, cid: None, outer, vertical }) + } + (Some(Obj::Dict(d)), None) => { + Some(Mapped { font: d.clone(), pick: 0, code: (c.cid & 0xff) as u8, name: None, cid: Some((c.cid, c.notdef)), outer, vertical }) + } + _ => None, + }) + .collect()) + } + + /// The characters of `s` and the font to set them in when the current font is a CID-keyed + /// font over a predefined Unicode CMap the file doesn't define (`UniJIS-UCS2-H`), whose + /// mappings to CIDs aren't known: its codes say the characters, set as type in the font of + /// its CIDFont's name. + fn unicode_type(&mut self, s: &[u8]) -> Res> { + let Some((text, font, name)) = self.unicode_parts(s) else { return Ok(None) }; + // The composite font is copied under the CIDFont's name for every string: charged by + // its size, so a huge font dictionary shown in a loop runs out of the budget. + let entries = font.borrow().len(); + self.spend(entries as u64)?; + let mut named = font.borrow().clone(); + named.insert(Key::name("FontName"), name); + Ok(Some((text, DictRef::new(named)))) + } + + /// The text, the composite font and the CIDFont's name of [`Self::unicode_type`]. + fn unicode_parts(&self, s: &[u8]) -> Option<(String, DictRef, Obj)> { + let font = self.g.font.clone()?; + let f = font.borrow(); + if font_type(&f) != Some(0.0) || f.get(&Key::name("FMapType")).and_then(Obj::as_num) != Some(9.0) { + return None; + } + let Some(Obj::Dict(cmap)) = f.get(&Key::name("CMap")) else { return None }; + let cmap = cmap.borrow(); + // A CMap the file built has mappings of its own. + if cmap.contains_key(&Key::name("CodeSpaceRange")) { + return None; + } + let (form, _) = super::cid::unicode_cmap(&cmap.get(&Key::name("CMapName")).and_then(Obj::text)?)?; + let Some(Obj::Dict(dep)) = f.get(&Key::name("FDepVector")).and_then(|v| v.items()?.get(0)) else { return None }; + let name = { + let d = dep.borrow(); + d.get(&Key::name("CIDFontName")).or_else(|| d.get(&Key::name("FontName"))).cloned()? + }; + Some((super::cid::unicode_text(s, form), font.clone(), name)) + } + + /// `text` set as point type at the current point in font `font` (see + /// [`Self::unicode_type`]), which moves past it. + fn show_unicode(&mut self, text: &str, font: &DictRef) -> Res { + let at = self.user_point()?; + let saved = self.g.font.replace(font.clone()); + let r = self.set_text(text, at); + self.g.font = saved; + let (t, _, adv) = r?; + if !self.g.paint.is_none() && !self.g.null && !text.trim().is_empty() { + let clips = self.g.clips.clone(); + self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); + } + self.g.cur = Some(self.xf() * (at + adv)); + Ok(()) } /// The characters of a composite font shown at the current point, spaced as `spacing` says. @@ -596,7 +995,8 @@ impl Interp<'_> { // times 256 plus its code (PLRM 3rd ed., `widthshow` in chapter 8). let d = spacing.advance(i, i64::from(g.pick) * 256 + i64::from(g.code), w); self.g.cur = Some(self.xf() * (at + d)); - let c = code_char(&g.font.borrow(), g.code); + // A CID stands for no character (its code is only the CID's low byte). + let c = if g.cid.is_some() { '\u{2022}' } else { g.name.as_deref().map_or_else(|| code_char(&g.font.borrow(), g.code), glyph_char) }; if c != '\u{2022}' { text.push(c); } @@ -618,29 +1018,25 @@ impl Interp<'_> { let f = g.font.borrow(); font_type(&f) == Some(3.0) && (f.contains_key(&Key::name("BuildGlyph")) || f.contains_key(&Key::name("BuildChar"))) }; - if builds { - return self.type3_glyph_in(&g.font, Glyph::Code(g.code), at, paint == Draw::Fill, g.outer); + if let Some((cid, notdef)) = g.cid { + return self.cid_glyph_at(g, cid, notdef, at, paint); } - let fm = g.outer * font_matrix(&g.font.borrow(), 1.0); - if let Some((outline, advance)) = self.type42_glyph(&g.font, g.code)? { - // Measuring a glyph reads its outline too, so `stringwidth` in a loop pays for it. - self.spend((outline.elements().len() as u64).saturating_add(16))?; - if paint != Draw::No { - let mut p = outline; - p.apply_affine(self.xf() * Affine::translate(at.to_vec2()) * fm); - if paint == Draw::Fill { - self.fill_path(p, vectorcraft_geom::FillRule::NonZero)?; - } else { - if self.g.path.elements().len().saturating_add(p.elements().len()) > super::graphics::MAX_PATH { - return Err(PsError::Limit("a path has too many points")); - } - self.g.path.extend(p); - } - } + if builds { + let glyph = g.name.clone().map_or(Glyph::Code(g.code), Glyph::Name); + return self.type3_glyph_in(&g.font, glyph, at, paint == Draw::Fill, g.outer); + } + // An em of the descendant's glyphs: a Type 42 font's matrix maps ems, a Type 1 font's + // its 1000-unit glyph space. + let fm = { + let f = g.font.borrow(); + if units(&f) == 1.0 { g.outer * font_matrix(&f, 1.0) } else { g.outer * font_matrix(&f, 0.001) * Affine::scale(units(&f)) } + }; + if let Some((outline, advance)) = self.type42_glyph(&g.font, g.code, g.name.as_deref())? { + self.type42_paint(outline, at, fm, paint)?; return Ok(fm * Point::new(advance, 0.0) - fm * Point::ZERO); } // Set as type in the descendant's font, under the composite font's matrix. - let c = code_char(&g.font.borrow(), g.code); + let c = g.name.as_deref().map_or_else(|| code_char(&g.font.borrow(), g.code), |n| named_char(0, n).unwrap_or('\u{2022}')); let Ok(byte) = u8::try_from(u32::from(c)) else { return Ok(Vec2::ZERO) }; // Scaling the descendant copies its dictionary for every character: charged by its size, // so a huge font dictionary shown in a loop runs out of the budget. @@ -662,62 +1058,230 @@ impl Interp<'_> { r } - /// Glyph `code` of Type 42 font `font` from the TrueType font it carries: its outline and - /// width in its glyph space (ems), or `None` when it isn't a Type 42 font with one. - fn type42_glyph(&mut self, font: &DictRef, code: u8) -> Res> { - let (sfnts, gid) = { + /// Glyph `cid` of CIDFont `g.font` at user point `at` (else the notdef mapping's glyph, else + /// CID 0's) → its width (user space), or its vertical displacement in writing mode 1 (the + /// glyph's origin then half its width left of the point and 0.88 em above it, and the next + /// one an em below it, the defaults ISO 32000-1 §9.7.4.3 gives CIDFonts without vertical + /// metrics). A CIDFont the file doesn't carry draws nothing, an em wide. + fn cid_glyph_at(&mut self, g: &Mapped, cid: u32, notdef: Option, at: Point, paint: Draw) -> Res { + let (em, fm) = { + let f = g.font.borrow(); + // Without a matrix, Type 2 CIDFonts, like Type 42 fonts, are in ems; Type 0 in + // 1000-unit space. With one, an em is the glyph units it makes one unit of text space. + let default = if f.get(&Key::name("CIDFontType")).and_then(Obj::as_num) == Some(2.0) { 1.0 } else { 0.001 }; + let m = font_matrix(&f, default); + let scale = m.determinant().abs().sqrt(); + let em = if scale.is_finite() && scale > 1e-9 { 1.0 / scale } else { 1.0 / default }; + (em, g.outer * m) + }; + let mut glyph = self.cid_glyph(&g.font, cid)?; + for other in [notdef, Some(0)].into_iter().flatten() { + if glyph.is_none() { + glyph = self.cid_glyph(&g.font, other)?; + } + } + let (outline, w) = match glyph { + Some(g) => g, + None => { + self.out.warn(MISSING_CID_FONT); + (vectorcraft_geom::BezPath::new(), em) + } + }; + if g.vertical { + self.type42_paint(outline, at, fm * Affine::translate((-w / 2.0, -0.88 * em)), paint)?; + return Ok(fm * Point::new(0.0, -em) - fm * Point::ZERO); + } + self.type42_paint(outline, at, fm, paint)?; + Ok(fm * Point::new(w, 0.0) - fm * Point::ZERO) + } + + /// Glyph `code` (or the glyph named `name`) of font `font` from the font program it carries + /// (a Type 42 or Type 1 font): its outline and width in ems, or `None` when it carries none. + fn type42_glyph(&mut self, font: &DictRef, code: u8, name: Option<&str>) -> Res> { + let Some(data) = self.embedded(font)? else { return Ok(None) }; + let standard = font.borrow().get(&Key::name("Encoding")).and_then(|e| self.standard_encoding(e)); + let gid = match name { + Some(n) => { + let f = font.borrow(); + char_string(&f, n).or_else(|| named_char(0, n).and_then(|c| data.gid_of(c))).or_else(|| char_string(&f, ".notdef")).unwrap_or(0) + } + None => type42_code(&font.borrow(), &data, code, standard).1, + }; + // Reading the font's character map (once) visits each of its mappings; running a Type 1 + // glyph's charstrings is paid for by their bytes. + self.spend(data.take_work())?; + self.spend(64)?; + let glyph = data.glyph(gid); + self.spend(data.take_work())?; + Ok(glyph) + } + + /// The codes of `s` in the current font when it is a font that carries its font program (a + /// Type 42 font's TrueType font, a Type 1 font's encrypted part), not a descendant of a + /// composite font: the font program, and each code's glyph. + fn type42_plain(&mut self, s: &[u8]) -> Res)>> { + let Some(font) = self.g.font.clone() else { return Ok(None) }; + let Some(data) = self.embedded(&font)? else { return Ok(None) }; + self.spend((s.len() as u64).saturating_mul(16))?; + let f = font.borrow(); + let standard = f.get(&Key::name("Encoding")).and_then(|e| self.standard_encoding(e)); + let mut glyphs = Vec::with_capacity(s.len()); + for &code in s { + let (ch, gid) = type42_code(&f, &data, code, standard); + let width = data.advance(gid); + // Reading the font's character map (once) visits each of its mappings; measuring a + // Type 1 glyph runs its charstrings. Paid for code by code, so that a long string of + // a costly glyph stops at the budget instead of running every glyph first. + self.spend(data.take_work())?; + glyphs.push(Plain { ch, gid, width }); + } + drop(f); + Ok(Some((data, glyphs))) + } + + /// The font program font `font` carries: a Type 42 font's TrueType font, or the Type 1 font + /// read from its encrypted part (see `type1`). + fn embedded(&mut self, font: &DictRef) -> Res> { + if let Some(d) = self.type42_data(font)? { + return Ok(Some(Embedded::TrueType(d))); + } + let strings = match font.borrow().get(&Key::name("CharStrings")) { + Some(Obj::Dict(d)) if font_type(&font.borrow()) == Some(1.0) => d.clone(), + _ => return Ok(None), + }; + Ok(self.type1.iter().find(|(k, _)| k.same(&strings)).map(|(_, f)| Embedded::Type1(f.clone()))) + } + + /// Whether another embedded Type 1 font can still be kept (see [`Self::attach_type1`]). + pub(super) fn type1_room(&self) -> bool { + self.type1.len() < MAX_TYPE1 + } + + /// Give font dictionary `d` the glyphs of the Type 1 font whose encrypted part is + /// `encrypted`: a `CharStrings` dictionary naming each glyph's index, by which it is drawn. + pub(super) fn attach_type1(&mut self, d: &DictRef, encrypted: &[u8]) -> Res { + if self.type1.len() >= MAX_TYPE1 { + return Ok(()); + } + self.alloc(encrypted.len())?; + self.spend((encrypted.len() / 256) as u64)?; + let Some(font) = super::type1::parse(encrypted) else { return Ok(()) }; + // Its charstrings are kept a second time, to be run here. + self.alloc(font.size())?; + let strings: Dict = font.font.glyph_names().map(|(g, n)| (Key::name(n), Obj::Int(i64::from(g.to_u32())))).collect(); + let strings = DictRef::new(strings); + d.borrow_mut().insert(Key::name("CharStrings"), Obj::Dict(strings.clone())); + self.type1.push((strings, Rc::new(font))); + Ok(()) + } + + /// The TrueType font Type 42 font `font` carries (read once for each `sfnts` array), or + /// `None` when it isn't a Type 42 font with one. + pub(super) fn type42_data(&mut self, font: &DictRef) -> Res>> { + let sfnts = { let f = font.borrow(); - if font_type(&f) != Some(42.0) { + // Type 42 fonts and Type 2 CIDFonts (FontType 11) carry TrueType fonts. + let cid2 = f.get(&Key::name("CIDFontType")).and_then(Obj::as_num) == Some(2.0); + if font_type(&f) != Some(42.0) && !cid2 { return Ok(None); } let Some(Obj::Array { items: sfnts, .. }) = f.get(&Key::name("sfnts")).cloned() else { return Ok(None) }; - let name = glyph_name(&f, code); - let strings = f.get(&Key::name("CharStrings")).and_then(|c| match c { - Obj::Dict(d) => Some(d.clone()), - _ => None, - }); - let gid = strings - .and_then(|d| { - let d = d.borrow(); - d.get(&Key::name(&name)).or_else(|| d.get(&Key::name(".notdef"))).and_then(Obj::as_num) - }) - .filter(|g| (0.0..=f64::from(u16::MAX)).contains(g)) - .map_or(0, |g| g as u32); - (sfnts, gid) + sfnts }; // The least recently used font goes first: a hit moves to the end. - let data = match self.type42.iter().position(|(k, _)| k.same(&sfnts)) { - Some(i) => { - let hit = self.type42.remove(i); - let data = hit.1.clone(); - self.type42.push(hit); - data - } - None => { - // Joining the strings visits each element and copies its bytes, whether or not - // the font can then be read: charged first, as other bulk copies are. - let (elements, bytes) = super::type42::font_size(&sfnts.borrow()); - self.spend_bytes(bytes)?; - self.spend((elements / 16) as u64)?; - // Fonts whose data can't be read are kept too, so they are copied only once. - let data = super::type42::font_data(&sfnts.borrow()).map(Rc::new); - if let Some(d) = &data - && self.type42_counted.insert(sfnts.clone()) - { - self.alloc(d.len())?; - } - if self.type42.len() >= MAX_TYPE42 { - self.type42.remove(0); - } - self.type42.push((sfnts, data.clone())); - data - } - }; - let Some(data) = data else { return Ok(None) }; - Ok(super::type42::glyph(&data, gid)) + if let Some(i) = self.type42.iter().position(|(k, _)| k.same(&sfnts)) { + let hit = self.type42.remove(i); + let data = hit.1.clone(); + self.type42.push(hit); + return Ok(data); + } + // Joining the strings visits each element and copies its bytes, whether or not the font + // can then be read: charged first, as other bulk copies are. + let (elements, bytes) = super::type42::font_size(&sfnts.borrow()); + self.spend_bytes(bytes)?; + self.spend((elements / 16) as u64)?; + // Fonts whose data can't be read are kept too, so they are copied only once. + let data = super::type42::font_data(&sfnts.borrow()).map(|d| Rc::new(super::type42::Font::new(d))); + if let Some(d) = &data + && self.type42_counted.insert(sfnts.clone()) + { + self.alloc(d.data.len())?; + } + if self.type42.len() >= MAX_TYPE42 { + self.type42.remove(0); + } + self.type42.push((sfnts, data.clone())); + Ok(data) } } +/// A character code of a font carrying its program: the character it stands for (`None` when +/// neither its glyph name nor the font says), its glyph and the glyph's width (ems). +struct Plain { + ch: Option, + gid: u32, + width: f64, +} + +/// The glyph index `CharStrings` gives glyph name `name` in Type 42 font `f`. +fn char_string(f: &Dict, name: &str) -> Option { + let Some(Obj::Dict(d)) = f.get(&Key::name("CharStrings")) else { return None }; + d.borrow().get(&Key::name(name)).and_then(Obj::as_num).filter(|g| (0.0..=f64::from(u16::MAX)).contains(g)).map(|g| g as u32) +} + +/// The character and glyph of code `code` in font `f`, carrying font program `data`: by the +/// glyph name its `Encoding` gives it (a name such as `A`, `uni20AC` or `Euro` says the +/// character; else the glyph `CharStrings` gives it stands for one in the font's character map +/// or `post` names). The standard encodings (`standard`: whether ISO Latin-1's) have no names +/// here: the code's name in them is used (PLRM 3rd ed., Appendix E.5 and E.6). A code the +/// encoding leaves `.notdef` is read as Latin-1, drawn by that character's glyph. +fn type42_code(f: &Dict, data: &Embedded, code: u8, standard: Option) -> (Option, u32) { + let mut name = glyph_name(f, code); + if &*name == ".notdef" + && let Some(iso) = standard + { + name = Rc::from(standard_name(code, iso)); + } + if &*name == ".notdef" { + let c = char::from(code); + // A font without a character map (an embedded Type 1 font) has that character's glyph + // by its name. A copy of a standard encoding (`StandardEncoding 256 array copy`) comes + // here too: its names are the empty systemdict array's. + let latin = match code { + 0x27 => "quotesingle", + 0x2d => "hyphen", + 0x60 => "grave", + _ => standard_name(code, true), + }; + return (Some(c), data.gid_of(c).or_else(|| char_string(f, latin)).or_else(|| char_string(f, ".notdef")).unwrap_or(0)); + } + let named = named_char(code, &name); + let gid = char_string(f, &name).or_else(|| named.and_then(|c| data.gid_of(c))).or_else(|| char_string(f, ".notdef")).unwrap_or(0); + (named.or_else(|| data.char_of(gid)), gid) +} + +/// The name the standard encoding (or, when `iso`, the ISO Latin-1 encoding) gives code `code`: +/// the same names in the printable ASCII range but for ISO Latin-1's `minus`; ISO Latin-1's +/// upper half named as Windows-1252 names it, with its soft `hyphen`. +fn standard_name(code: u8, iso: bool) -> &'static str { + use skrifa::raw::ps::encoding::PredefinedEncoding; + match (iso, code) { + (false, _) => PredefinedEncoding::Standard.name(code), + (true, 0x2d) => "minus", + (true, 0x20..=0x7e) => PredefinedEncoding::Standard.name(code), + (true, 0xad) => "hyphen", + (true, 0xa0) => "space", + (true, 0xa1..=0xff) => crate::latin::high_name(code).unwrap_or(".notdef"), + _ => ".notdef", + } +} + +/// Most Type 1 fonts read from their encrypted parts. +const MAX_TYPE1: usize = 256; + +/// The warning for CID-keyed type in a CIDFont the file doesn't carry. +const MISSING_CID_FONT: &str = "CID-keyed type in a font the file doesn't carry was left out"; + /// Most Type 42 fonts whose TrueType data is kept between glyphs. const MAX_TYPE42: usize = 16; @@ -730,11 +1294,37 @@ fn code_char(f: &Dict, code: u8) -> char { } } +/// The code font `f`'s `Encoding` gives glyph name `name`, if any. +fn encoded(f: &Dict, name: &str) -> Option { + let items = f.get(&Key::name("Encoding"))?.items()?.to_vec(); + items.iter().position(|o| o.text().as_deref() == Some(name)).and_then(|i| u8::try_from(i).ok()) +} + /// The glyph name font `f`'s `Encoding` gives code `code` (`.notdef` without one). fn glyph_name(f: &Dict, code: u8) -> Rc { f.get(&Key::name("Encoding")).and_then(|e| e.items()?.get(usize::from(code))).and_then(|o| o.text()).unwrap_or_else(|| Rc::from(".notdef")) } +/// The character glyph name `name` (at code `code`) says: a single character or `uniXXXX`; a +/// name of the standard encoding's printable ASCII range (`hyphen`, `quotedbl`: PLRM 3rd ed., +/// Appendix E.6); one of the Windows-1252 names; else `None`. +pub(super) fn named_char(code: u8, name: &str) -> Option { + match glyph_char(name) { + '\u{2022}' if name != "bullet" => {} + c => return Some(c), + } + use skrifa::raw::ps::encoding::PredefinedEncoding; + if let Some(c) = (0x20u8..0x7F).find(|c| PredefinedEncoding::Standard.name(*c) == name) { + // The standard encoding has curly quotes where ASCII has the straight quote and the grave. + return Some(match c { + 0x27 => '\u{2019}', + 0x60 => '\u{2018}', + c => char::from(c), + }); + } + crate::latin::glyph(code, name) +} + /// A font scaled or transformed by `m` (`scalefont`, `makefont`). fn transformed(font: &DictRef, m: Affine) -> DictRef { let mut d = font.borrow().clone(); @@ -744,7 +1334,7 @@ fn transformed(font: &DictRef, m: Affine) -> DictRef { } /// The character a glyph name stands for (`A`, `space`, `uni20AC`), else a bullet. -fn glyph_char(name: &str) -> char { +pub(super) fn glyph_char(name: &str) -> char { let mut chars = name.chars(); if let (Some(c), None) = (chars.next(), chars.next()) { return c; diff --git a/crates/eps/src/import/type1.rs b/crates/eps/src/import/type1.rs new file mode 100644 index 0000000000..3000077721 --- /dev/null +++ b/crates/eps/src/import/type1.rs @@ -0,0 +1,432 @@ +//! Embedded fonts whose glyphs are drawn from the font program the file carries: Type 1 fonts, +//! whose encrypted part (`eexec`: Adobe Type 1 Font Format, chapter 7) holds their charstrings, +//! and Type 42 fonts (see `type42`). The interpreter doesn't run the encrypted part; it is read +//! by the Type 1 font parser, and the font dictionary gets the `CharStrings` dictionary the part +//! would have given it, each glyph name standing for its glyph's index, by which the glyph is +//! drawn. Its charstrings are run here, counting the bytes of the charstrings and subroutines +//! they enter, so that the work of drawing glyphs is paid for from the operation budget. + +use std::cell::Cell; +use std::rc::Rc; + +use skrifa::GlyphId; +use skrifa::outline::OutlinePen; +use skrifa::raw::ps::cs::{self, CharstringContext, CharstringKind, CommandSink, NopFilterSink, TransformSink}; +use skrifa::raw::ps::error::Error as CsError; +use skrifa::raw::ps::type1::Type1Font; +use skrifa::raw::types::Fixed; +use vectorcraft_geom::BezPath; + +use super::type42; + +/// Most bytes of an encrypted font program read. +pub(super) const MAX_PROGRAM: usize = 16 << 20; + +/// The font program a plain or descendant font carries. +#[derive(Clone)] +pub(super) enum Embedded { + TrueType(Rc), + Type1(Rc), +} + +impl Embedded { + /// Glyph `gid`: its outline and advance width, in ems (y up), or `None` when it can't be read. + pub fn glyph(&self, gid: u32) -> Option<(BezPath, f64)> { + match self { + Self::TrueType(f) => type42::glyph(&f.data, gid), + Self::Type1(f) => { + let mut pen = type42::Pen(BezPath::new(), 1.0 / UNITS); + // A glyph that can't be drawn draws nothing, and has no width. + let w = f.draw(gid, &mut pen).map_or(0.0, |w| w / UNITS); + Some((pen.0, if w.is_finite() { w } else { 0.0 })) + } + } + } + + /// Glyph `gid`'s advance width, in ems. + pub fn advance(&self, gid: u32) -> f64 { + match self { + Self::TrueType(f) => type42::advance(&f.data, gid), + Self::Type1(_) => self.glyph(gid).map_or(0.0, |g| g.1), + } + } + + /// The character glyph `gid` stands for, when the font says (a TrueType font's character + /// map or `post` names; a Type 1 glyph's name). + pub fn char_of(&self, gid: u32) -> Option { + match self { + Self::TrueType(f) => f.char_of(gid), + Self::Type1(f) => f.font.glyph_name(GlyphId::new(gid)).and_then(|n| super::text::named_char(0, n)), + } + } + + /// The work done since last asked, for the operation budget: a TrueType font's reading its + /// character map (see [`type42::Font::take_char_map_work`]), a Type 1 font's running its + /// charstrings (see [`Font::draw`]). + pub fn take_work(&self) -> u64 { + match self { + Self::TrueType(f) => f.take_char_map_work(), + Self::Type1(f) => f.work.take(), + } + } + + /// The glyph a TrueType font's character map gives `c` (Type 1 fonts have none). + pub fn gid_of(&self, c: char) -> Option { + match self { + Self::TrueType(f) => f.gid_of(c), + Self::Type1(_) => None, + } + } +} + +/// Type 1 glyph space: 1000 units an em, as the font matrix of the program made for parsing says. +const UNITS: f64 = 1000.0; + +/// A Type 1 font read from its encrypted part: the font, and its charstrings as the font parser +/// reads them, run here so their work is counted. +pub(super) struct Font { + pub font: Type1Font, + /// Each glyph's name and decrypted charstring, by glyph index. + charstrings: Vec<(Vec, Vec)>, + /// The bytes of charstrings and subroutines run since last asked (see [`Embedded::take_work`]). + work: Cell, +} + +impl Font { + /// The bytes the font keeps. + pub fn size(&self) -> usize { + self.charstrings.iter().fold(0usize, |n, (a, b)| n.saturating_add(a.len()).saturating_add(b.len())) + } + + /// Draw glyph `gid` with `pen` (in 1000-unit glyph space, as the font parser draws it): its + /// advance width, or `None` when it can't be run. The bytes of each charstring it enters + /// (its own, its subroutines', `seac` accents') are added to the work done. + fn draw(&self, gid: u32, pen: &mut impl OutlinePen) -> Option { + let (name, charstring) = self.charstrings.get(gid as usize)?; + if self.font.glyph_name(GlyphId::new(gid)).map(str::as_bytes) != Some(name.as_slice()) { + return None; + } + let transform = self.font.transform(None); + let mut filter = NopFilterSink::new(pen); + let mut sink = TransformSink::new(&mut filter, transform); + let (w, work) = evaluate(&self.font, charstring, &mut sink); + self.work.set(self.work.get().saturating_add(work)); + let w = w.ok()??; + Some(f64::from(transform.transform_h_metric(w).to_f32().max(0.0))) + } +} + +/// Type 1 charstring `data` run in context `ctx` into `sink`: its width (when it gives one) and +/// the bytes of the charstrings it entered, at least one for each, which bound the operations it +/// ran. The evaluator stops a charstring after a million operations but starts again for every +/// glyph, so drawing many glyphs is paid for with these. +pub(super) fn evaluate(ctx: &impl CharstringContext, data: &[u8], sink: &mut impl CommandSink) -> (Result, CsError>, u64) { + let counted = Counted { ctx, work: Cell::new(data.len() as u64 + 1) }; + let w = cs::evaluate(&counted, None, data, sink); + (w, counted.work.get()) +} + +/// A charstring context counting the bytes of the charstrings it gives the evaluator. +struct Counted<'a, C> { + ctx: &'a C, + work: Cell, +} + +impl Counted<'_, C> { + fn add<'b>(&self, s: &'b [u8]) -> &'b [u8] { + self.work.set(self.work.get().saturating_add(s.len() as u64 + 1)); + s + } +} + +impl CharstringContext for Counted<'_, C> { + fn kind(&self) -> CharstringKind { + self.ctx.kind() + } + fn seac_components(&self, base: i32, accent: i32) -> Result<[&[u8]; 2], CsError> { + let [b, a] = self.ctx.seac_components(base, accent)?; + Ok([self.add(b), self.add(a)]) + } + fn global_subr(&self, index: i32) -> Result<&[u8], CsError> { + self.ctx.global_subr(index).map(|s| self.add(s)) + } + fn subr(&self, index: i32) -> Result<&[u8], CsError> { + self.ctx.subr(index).map(|s| self.add(s)) + } + fn weight_vector(&self) -> &[Fixed] { + self.ctx.weight_vector() + } +} + +/// The Type 1 font whose encrypted part is `encrypted` (from just after `eexec`, binary or +/// hexadecimal), or `None` when it can't be read. The part is read on its own, after a clear +/// part that gives only the font matrix of 1000-unit glyph space: the font's own clear part, run +/// by the interpreter, gives its matrix and encoding. +pub(super) fn parse(encrypted: &[u8]) -> Option { + if encrypted.len() > MAX_PROGRAM { + return None; + } + let mut program = b"%!FontType1-1.0: Embedded\n/FontMatrix [0.001 0 0 0.001 0 0] readonly def\ncurrentfile eexec\n".to_vec(); + program.extend_from_slice(encrypted); + let font = Type1Font::new(&program).ok()?; + Some(Font { font, charstrings: charstrings(encrypted), work: Cell::new(0) }) +} + +/// The `.notdef` glyph of a font that has none: `0 333 hsbw endchar` (Adobe Type 1 Font Format, +/// §6), as the font parser gives it. +const NOTDEF: &[u8] = &[139, 247, 225, 13, 14]; + +/// The charstrings of encrypted part `encrypted`, with their names, in the order the font parser +/// numbers them: the first `CharStrings` dictionary's entries (`/name len RD bytes ND`) in the +/// order written, decrypted with the charstring key unless `lenIV` is negative (Adobe Type 1 Font +/// Format, §2.4 and §7), `.notdef` (made when missing) swapped to the front. Empty when the part +/// can't be read. +fn charstrings(encrypted: &[u8]) -> Vec<(Vec, Vec)> { + let skip = encrypted.iter().take_while(|c| matches!(c, b' ' | b'\t' | b'\r' | b'\n')).count(); + let encrypted = encrypted.get(skip..).unwrap_or_default(); + let hex = encrypted.len() > 3 && encrypted.iter().take(4).all(u8::is_ascii_hexdigit); + let bytes = if hex { unhex(encrypted) } else { encrypted.to_vec() }; + let plain: Vec = decrypt(&bytes, 55665).into_iter().skip(4).collect(); + let mut lex = Lexer { d: &plain, pos: 0 }; + let mut len_iv = 4; + let mut out = Vec::new(); + while let Some(t) = lex.next() { + match t { + Tok::Name(b"lenIV") => match lex.next() { + Some(Tok::Int(n)) => len_iv = n, + _ => return vec![], + }, + Tok::Name(b"CharStrings") => { + let Some(Tok::Int(_)) = lex.next() else { return vec![] }; + while let Some(t) = lex.next() { + let ends = lex.peek().is_some_and(special_or_space); + match t { + Tok::Other(b"end") if ends => break, + Tok::Other(b"def") if ends && !out.is_empty() => break, + Tok::Name(name) => { + let Some(Tok::Blob(data)) = lex.next() else { return vec![] }; + let data = if len_iv >= 0 { decrypt(data, 4330).into_iter().skip(len_iv as usize).collect() } else { data.to_vec() }; + out.push((name.to_vec(), data)); + } + _ => {} + } + } + break; + } + _ => {} + } + } + if out.is_empty() { + return out; + } + let notdef = match out.iter().position(|(n, _)| n == b".notdef") { + Some(i) => i, + None => { + out.push((b".notdef".to_vec(), NOTDEF.to_vec())); + out.len() - 1 + } + }; + out.swap(0, notdef); + out +} + +/// `data` decrypted with key `r` (Adobe Type 1 Font Format, §7.1). +fn decrypt(data: &[u8], mut r: u16) -> Vec { + data.iter() + .map(|&c| { + let p = c ^ (r >> 8) as u8; + r = (u16::from(c).wrapping_add(r)).wrapping_mul(52845).wrapping_add(22719); + p + }) + .collect() +} + +/// Hexadecimal `data` as bytes, white space skipped, up to the first other character (an odd +/// last digit is its byte's high half). +fn unhex(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() / 2); + let mut high: Option = None; + for &c in data { + if space(c) { + continue; + } + let Some(v) = char::from(c).to_digit(16) else { break }; + let v = v as u8; + match high.take() { + Some(h) => out.push(h << 4 | v), + None => high = Some(v), + } + } + out.extend(high.map(|h| h << 4)); + out +} + +fn space(c: u8) -> bool { + matches!(c, b' ' | b'\n' | b'\r' | b'\t' | b'\0' | 0x0C) +} + +fn special_or_space(c: u8) -> bool { + space(c) || matches!(c, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +/// A token of a font's decrypted encrypted part, as the font parser splits them. +enum Tok<'a> { + Int(i64), + Name(&'a [u8]), + /// The bytes after `len RD ` (or `-|`). + Blob(&'a [u8]), + Other(&'a [u8]), +} + +struct Lexer<'a> { + d: &'a [u8], + pos: usize, +} + +impl<'a> Lexer<'a> { + fn peek(&self) -> Option { + self.d.get(self.pos).copied() + } + + fn byte(&mut self) -> Option { + let c = self.peek()?; + self.pos += 1; + Some(c) + } + + fn skip_while(&mut self, f: impl Fn(u8) -> bool) { + while self.peek().is_some_and(&f) { + self.pos += 1; + } + } + + fn skip_line(&mut self) { + while let Some(c) = self.byte() { + if c == b'\n' || c == b'\r' { + break; + } + } + } + + /// The rest of a string after its `(`, nested parentheses and escapes included. + fn string(&mut self) -> Option<()> { + let mut depth = 1u32; + loop { + match self.byte()? { + b'(' => depth = depth.saturating_add(1), + b')' => { + depth -= 1; + if depth == 0 { + return Some(()); + } + } + b'\\' => { + self.byte()?; + } + _ => {} + } + } + } + + /// The rest of a procedure after its `{`, nested procedures, comments and strings included. + fn procedure(&mut self) -> Option<()> { + let mut depth = 1u32; + loop { + match self.byte()? { + b'{' => depth = depth.saturating_add(1), + b'}' => { + depth -= 1; + if depth == 0 { + return Some(()); + } + } + b'%' => self.skip_line(), + b'(' => self.string()?, + _ => {} + } + } + } + + fn next(&mut self) -> Option> { + loop { + self.skip_while(space); + let start = self.pos; + match self.byte()? { + b'%' => self.skip_line(), + b'{' => return self.procedure().map(|()| Tok::Other(b"{")), + b'(' => return self.string().map(|()| Tok::Other(b"(")), + b'<' if self.peek() == Some(b'<') => self.pos += 1, + b'<' => { + // Hexadecimal digits and white space, then `>`. + let end = loop { + let c = self.byte()?; + if !space(c) && !c.is_ascii_hexdigit() { + break c; + } + }; + return (end == b'>').then_some(Tok::Other(b"<")); + } + b'>' => { + if self.byte()? != b'>' { + return None; + } + } + b'/' => { + let c = self.peek()?; + if special_or_space(c) { + if space(c) { + self.pos += 1; + } + return Some(Tok::Name(&[])); + } + self.skip_while(|c| !special_or_space(c)); + return self.d.get(start + 1..self.pos).map(Tok::Name); + } + b'[' | b']' => return self.d.get(start..self.pos).map(Tok::Other), + c => { + self.skip_while(|c| !special_or_space(c)); + let text = self.d.get(start..self.pos)?; + if (c.is_ascii_digit() || c == b'-') + && !text.contains(&b'.') + && let Some(n) = int(text) + { + return Some(self.blob(n).unwrap_or(Tok::Int(n))); + } + return Some(Tok::Other(text)); + } + } + } + } + + /// The `n` bytes after `RD ` or `-| `, when those come next. + fn blob(&mut self, n: i64) -> Option> { + let mut at = self.pos; + while self.d.get(at).copied().is_some_and(space) { + at += 1; + } + let start = at; + while self.d.get(at).copied().is_some_and(|c| !special_or_space(c)) { + at += 1; + } + if !matches!(self.d.get(start..at), Some(b"RD" | b"-|")) { + return None; + } + // One space, then the bytes; a count past the end ends the part. + let from = at + 1; + let to = usize::try_from(n).ok().and_then(|n| from.checked_add(n)); + self.pos = to.filter(|to| *to <= self.d.len()).unwrap_or(self.d.len()); + Some(Tok::Blob(to.and_then(|to| self.d.get(from..to)).unwrap_or_default())) + } +} + +/// A PostScript integer (`12`, `-3`, `8#17`), or `None`. +fn int(text: &[u8]) -> Option { + let s = std::str::from_utf8(text).ok()?; + match s.find('#') { + Some(i @ (1 | 2)) => { + let radix = s.get(..i)?.parse::().ok().filter(|r| (2..=36).contains(r))?; + i64::from_str_radix(s.get(i + 1..)?, radix).ok() + } + _ => s.parse().ok(), + } +} diff --git a/crates/eps/src/import/type42.rs b/crates/eps/src/import/type42.rs index 1aac00b005..343f869fba 100644 --- a/crates/eps/src/import/type42.rs +++ b/crates/eps/src/import/type42.rs @@ -7,6 +7,9 @@ use skrifa::instance::{LocationRef, Size}; use skrifa::outline::{DrawSettings, OutlinePen}; +use std::cell::{Cell, OnceCell, RefCell}; +use std::collections::HashMap; + use skrifa::{FontRef, GlyphId, MetadataProvider}; use vectorcraft_geom::BezPath; @@ -45,6 +48,86 @@ pub(super) fn font_size(sfnts: &[Obj]) -> (usize, usize) { (sfnts.len(), bytes) } +/// The TrueType font a Type 42 font carries, with the character each glyph stands for (read +/// when first asked). +pub(super) struct Font { + pub data: Vec, + chars: OnceCell>, + /// The characters glyph names give glyphs the character map doesn't reach, misses too: + /// a custom `post` name is found by scanning the names before it, so each glyph is looked + /// up once. + names: RefCell>>, + /// The character-map mappings visited reading `chars`, not yet counted against the + /// operation budget (see [`Self::take_char_map_work`]). + work: Cell, +} + +impl Font { + pub fn new(data: Vec) -> Self { + Self { data, chars: OnceCell::new(), names: RefCell::new(HashMap::new()), work: Cell::new(0) } + } + + /// The work reading the character map did since last asked (mappings visited). + pub fn take_char_map_work(&self) -> u64 { + self.work.take() + } + + /// The character glyph `gid` stands for: the one the font's character map maps to it + /// (the lowest, when it maps several), else the one its `post` table's glyph name says + /// (`uni20AC`, a single character). `None` for a glyph neither names, and for one a symbol + /// font maps only from, or names only as, its private-use codes (U+F000–U+F0FF), which + /// aren't characters. + pub fn char_of(&self, gid: u32) -> Option { + let chars = self.chars.get_or_init(|| { + let mut m = HashMap::new(); + if let Ok(font) = FontRef::new(&self.data) { + for (c, g) in font.charmap().mappings() { + self.work.set(self.work.get().saturating_add(1)); + let Some(c) = char::from_u32(c).filter(|c| is_char(*c)) else { + continue; + }; + m.entry(g.to_u32()).and_modify(|e: &mut char| *e = (*e).min(c)).or_insert(c); + } + } + m + }); + if let Some(c) = chars.get(&gid) { + return Some(*c); + } + if let Some(c) = self.names.borrow().get(&gid) { + return *c; + } + // Finding a custom name reads the names before it: about one operation for every 16. + self.work.set(self.work.get().saturating_add(u64::from(gid / 16) + 1)); + let c = FontRef::new(&self.data).ok().and_then(|font| { + let name = font.glyph_names().get(GlyphId::new(gid))?; + post_name_char(name.as_str()) + }); + self.names.borrow_mut().insert(gid, c); + c + } + + /// The glyph the font's character map gives `c`. + pub fn gid_of(&self, c: char) -> Option { + let font = FontRef::new(&self.data).ok()?; + font.charmap().map(c).map(|g| g.to_u32()).filter(|g| *g != 0) + } +} + +/// Whether character `c`, read from a font's character map or glyph names, is one the glyph +/// stands for: not a symbol font's private-use codes, controls or the soft hyphen, which doesn't +/// show (a hyphen glyph mapped from it is the hyphen's). +fn is_char(c: char) -> bool { + !('\u{F000}'..='\u{F0FF}').contains(&c) && !c.is_control() && c != '\u{AD}' +} + +/// The character `post` table glyph name `name` says (`uni20AC`, a single character), when it +/// says one [`is_char`] accepts. +pub(super) fn post_name_char(name: &str) -> Option { + let c = super::text::glyph_char(name); + (c != '\u{2022}' || name == "bullet").then_some(c).filter(|c| is_char(*c)) +} + /// Glyph `gid` of TrueType font `data`: its outline and advance width, in ems (y up), or `None` /// when the font can't be read. pub(super) fn glyph(data: &[u8], gid: u32) -> Option<(BezPath, f64)> { @@ -65,8 +148,16 @@ pub(super) fn glyph(data: &[u8], gid: u32) -> Option<(BezPath, f64)> { Some((pen.0, if advance.is_finite() { advance } else { 0.0 })) } +/// The advance width of glyph `gid` of TrueType font `data`, in ems (0 when it can't be read). +pub(super) fn advance(data: &[u8], gid: u32) -> f64 { + let Ok(font) = FontRef::new(data) else { return 0.0 }; + let upem = f64::from(font.metrics(Size::unscaled(), LocationRef::default()).units_per_em); + let w = font.glyph_metrics(Size::unscaled(), LocationRef::default()).advance_width(GlyphId::new(gid)).map_or(0.0, f64::from) / upem; + if w.is_finite() { w } else { 0.0 } +} + /// A pen drawing an outline scaled from font units to ems. -struct Pen(BezPath, f64); +pub(super) struct Pen(pub BezPath, pub f64); impl OutlinePen for Pen { fn move_to(&mut self, x: f32, y: f32) { diff --git a/crates/eps/src/latin.rs b/crates/eps/src/latin.rs index be8c5e98be..e3330dd90f 100644 --- a/crates/eps/src/latin.rs +++ b/crates/eps/src/latin.rs @@ -172,6 +172,11 @@ const OTHER_NAMES: &[(&str, char)] = &[ ("grave", '`'), ]; +/// The Windows-1252 glyph name of code `code` (128–255), if it has one. +pub(crate) fn high_name(code: u8) -> Option<&'static str> { + code.checked_sub(0x80).and_then(|i| HIGH.get(usize::from(i))).copied().filter(|n| *n != ".notdef") +} + /// Character `b` of Windows-1252. pub(crate) fn decode(b: u8) -> char { match b { 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..b1cfd30878 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -439,12 +439,12 @@ impl Server { } "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 f52d0aebae..c07aa9efce 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()); @@ -718,6 +718,11 @@ fn errors_are_tool_results_not_crashes() { /// A fake control server: answers `document.inspect`, echoes `engine.execute`, errors otherwise. fn fake_app() -> (String, std::thread::JoinHandle>) { + fake_app_refusing_confirm(None) +} + +/// [`fake_app`], answering `ui.dialog.confirm` with the error `refusal` when one is given. +fn fake_app_refusing_confirm(refusal: Option<&'static str>) -> (String, std::thread::JoinHandle>) { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap().to_string(); let h = std::thread::spawn(move || { @@ -733,6 +738,7 @@ fn fake_app() -> (String, std::thread::JoinHandle>) { "engine.execute" => json!({"ok": true, "result": {"echo": msg["params"]}}), "ui.inspect" => json!({"ok": true, "result": {"tool": "selection"}}), "ui.dialog.set" if !dialog_open => json!({"ok": false, "error": "no dialog open"}), + "ui.dialog.confirm" if refusal.is_some() => json!({"ok": false, "error": refusal}), m if m.starts_with("ui.dialog.") => { dialog_open &= m != "ui.dialog.cancel"; json!({"ok": true, "result": {"echo": msg["params"]}}) @@ -823,6 +829,23 @@ fn answer_dialog_does_not_confirm_when_the_app_refuses_the_set() { assert_eq!(seen[1]["params"], json!({"fields": set})); } +/// The app refuses to confirm a plug-in's install approval for automation: the call is an error +/// with the app's reason, and nothing else is sent that could install the module. +#[test] +fn answer_dialog_reports_that_the_app_refuses_to_approve_a_plugin_install() { + let refusal = "Only the person at the keyboard can approve installing a plug-in"; + let (addr, h) = fake_app_refusing_confirm(Some(refusal)); + let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap())); + let set = json!([{"field": "__params", "value": {"dataBase64": "AAAA"}}]); + let r = call(&mut s, 1, "answer_dialog", json!({"set": set, "action": "confirm"})); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains(refusal), "{r}"); + drop(s); + let seen = h.join().unwrap(); + let methods: Vec<&str> = seen.iter().map(|m| m["method"].as_str().unwrap()).collect(); + assert_eq!(methods, ["ui.dialog.set", "ui.dialog.confirm"]); +} + #[test] fn answer_dialog_needs_the_desktop_app() { let mut s = server(); 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/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/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index eb312021e3..2fea9a5686 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -1,3 +1,5 @@ +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, @@ -64,16 +66,18 @@ impl<'a> Exporter<'a> { } } -/// Glyphs written together as real text: the same font at the same size along one baseline. +/// Glyphs written together as real text: the same font, size and orientation on one layout line. pub(super) struct GlyphLine { pub(super) face: u32, pub(super) font: krilla::text::Font, pub(super) size: f64, /// The glyph space (krilla's, y down, at `size`) → text space, at the line's start. pub(super) frame: Affine, - /// Glyph id, pen position and advance along the line (in glyph space), and the characters it + /// The layout line (or vertical column); offsets alone do not identify a line. + pub(super) layout_line: usize, + /// Glyph id, position and horizontal advance (in glyph space), and the characters it /// stands for (bytes of the plain text, or of the list marker's text). - pub(super) glyphs: Vec<(u32, f64, f64, std::ops::Range)>, + pub(super) glyphs: Vec<(u32, Point, f64, std::ops::Range)>, /// The list marker the glyphs belong to, by its first glyph's index in the layout /// ([`TextLayout::marker_of`]); `None` for glyphs of the plain text. pub(super) marker: Option, diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 17a3a10bfe..4750bef85c 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -435,20 +435,27 @@ impl Exporter<'_> { /// Warn when gradient `g`, drawn as an image, has stops linked to a spot swatch: the image is /// in process colors, so the spot inks have no plate of their own. fn warn_spot_image(&mut self, g: &vectorcraft_color::GradientPaint) { - let doc = self.doc; let from_stops = g.gradient.kind != GradientKind::Freeform || !g.has_freeform_points(); - if from_stops && g.gradient.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { + if from_stops && self.has_spot_stop(&g.gradient) { self.warn( "spot colors in gradients exported as images (freeform or dithered gradients, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", ); } } + /// Is a stop of `g` linked to a spot swatch? + fn has_spot_stop(&self, g: &vectorcraft_color::Gradient) -> bool { + let doc = self.doc; + g.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) + } + /// Draw gradient `g`, placed on `bounds`, as an image over `area`, sampled at the document's /// raster effects resolution where it is drawn (`area` as the current transform sizes it, so /// scaled type gets its pixels too): a freeform gradient's colour field (at most /// [`MAX_FIELD_PX`] a side), or a linear or radial gradient (at most [`MAX_GRADIENT_PX`] a side), - /// with dither's noise when it paints a fill (`fill`). + /// with dither's noise when it paints a fill (`fill`). A linear or radial gradient whose stops + /// are all CMYK and not linked to a spot swatch is a CMYK image, unless its Perceptual curve + /// has too many stops; any other is an RGB image. pub(super) fn field_image(&mut self, s: &mut Surface, g: &vectorcraft_color::GradientPaint, bounds: Rect, area: Rect, fill: bool) { use vectorcraft_color::cms::Model; use vectorcraft_color::freeform::{painted_box, spread_scale}; @@ -469,24 +476,36 @@ impl Exporter<'_> { let (cols, rows) = (along(w), along(h)); let field = freeform.then(|| g.freeform_on(b).model_field(spread_scale(b))); let cmyk_doc = self.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk; - let img = match &field { - Some(field) if field.model() == Some(Model::Cmyk) || (cmyk_doc && field.model() == Some(Model::Gray)) => { + if !freeform { + self.warn("linear and radial gradients drawn as pixels are exported as images"); + } + let ramp_inks = if freeform || self.has_spot_stop(&g.gradient) { None } else { g.ink_pixels(b, area, cols, rows, fill) }; + let ink_image = |inks, alpha| { + let convert = if self.convert { self.out.cmyk_pixels() } else { None }; + crate::images::from_inks(inks, alpha, cols.into(), rows.into(), self.interpolate, convert) + }; + let img = match (&field, ramp_inks) { + (Some(field), _) if field.model() == Some(Model::Cmyk) || (cmyk_doc && field.model() == Some(Model::Gray)) => { let (mut inks, mut alpha) = (Vec::new(), Vec::new()); for (color, a) in field.grid(area, cols, rows) { let [c, m, y, k] = color.to_cmyk(); inks.extend([q(c), q(m), q(y), q(k)]); alpha.push(q(a)); } - let convert = if self.convert { self.out.cmyk_pixels() } else { None }; - crate::images::from_inks(inks, alpha, cols.into(), rows.into(), self.interpolate, convert) + ink_image(inks, alpha) + } + (_, Some(pixels)) => { + let (mut inks, mut alpha) = (Vec::new(), Vec::new()); + for [c, m, y, k, a] in pixels { + inks.extend([c, m, y, k]); + alpha.push(a); + } + ink_image(inks, alpha) } _ => { let rgba: Vec = match &field { Some(field) => field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect(), - None => { - self.warn("linear and radial gradients drawn as pixels are exported as images"); - g.pixels(b, area, cols, rows, fill, &|c| c.to_rgb()).flatten().collect() - } + None => g.pixels(b, area, cols, rows, fill, &|c| c.to_rgb()).flatten().collect(), }; let pixels = if self.convert { self.out.pixels() } else { None }; crate::images::from_rgba_in(rgba, cols.into(), rows.into(), self.interpolate, pixels) diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index d7670a389d..ea38fc3a1d 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -1,3 +1,5 @@ +use vectorcraft_geom::Point; + use super::exporter::{GlyphLine, MAX_INLINE_DEPTH, in_range, norm, to_path, writable, xf}; use super::images::embed; use super::{ @@ -173,7 +175,7 @@ impl Exporter<'_> { /// text space; `text` is the plain text, whose characters the glyphs stand for, which makes /// the text selectable and searchable) → the outlines of the glyphs left to draw as paths: /// those of fonts that can't be embedded, and missing glyphs. Glyphs sharing a font, a frame - /// (size, scale, rotation) and a baseline are written together. Colour glyphs (bitmap emoji, + /// (size, scale, rotation) and a layout line are written together. Colour glyphs (bitmap emoji, /// COLR, SVG), with `images`, are written as text too, which draws their images or layers; the /// indices of those it can't write or draw (SVG glyphs) are returned with the outlines. The /// hyphen the layout adds where it breaks a line inside a word ([`break_hyphen`]) is written @@ -270,31 +272,33 @@ impl Exporter<'_> { } let size = upem * sy; let frame = g.xf * Affine::scale(1.0 / sy); - // Its pen position along the frame's baseline, when it continues the line (a - // line-break hyphen never does). - let x = line + // Keep offset marks with their cluster so the writer maps its characters once. + // Layout-line identity preserves line/column boundaries despite these offsets. + let position = line .as_ref() - .filter(|l| hyphen.is_none() && l.face == g.font_id && (l.size - size).abs() < 1e-6 && l.marker == marker_at) + .filter(|l| { + hyphen.is_none() && l.layout_line == g.line && l.face == g.font_id && (l.size - size).abs() < 1e-6 && l.marker == marker_at + }) .and_then(|l| { let [a, b, c, d, e, f] = (l.frame.inverse() * frame).as_coeffs(); - let same = (a - 1.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6 && f.abs() < 1e-4; - same.then_some(e) + let same = (a - 1.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6; + same.then_some(Point::new(e, f)) }); - let x = match x { - Some(x) => x, + let position = match position { + Some(position) => position, None => { if let Some(l) = line.take() { let text = text_of(&l); self.draw_glyph_line(s, l, text, fill, layout.bounds); } - line = Some(GlyphLine { face: g.font_id, font, size, frame, glyphs: vec![], marker: marker_at }); - 0.0 + line = Some(GlyphLine { face: g.font_id, font, size, frame, layout_line: g.line, glyphs: vec![], marker: marker_at }); + Point::ORIGIN } }; // The glyph's advance in frame units (the last one's ends the line). let advance = g.advance * sy / sx; if let Some(l) = line.as_mut() { - l.glyphs.push((g.gid, x, advance, range)); + l.glyphs.push((g.gid, position, advance, range)); } // A line-break hyphen is written on its own. if hyphen.is_some() @@ -340,14 +344,17 @@ impl Exporter<'_> { .glyphs .iter() .enumerate() - .map(|(i, (gid, x, advance, range))| { - let next = line.glyphs.get(i + 1).map_or(x + advance, |n| n.1); - KrillaGlyph::new(GlyphId::new(*gid), ((next - x) / size) as f32, 0.0, 0.0, 0.0, range.clone(), None) + .map(|(i, (gid, position, advance, range))| { + let next = line.glyphs.get(i + 1).map_or(position.x + advance, |n| n.1.x); + // Horizontal placement is already in the advances; krilla offsets use y up. + KrillaGlyph::new(GlyphId::new(*gid), ((next - position.x) / size) as f32, 0.0, (-position.y / size) as f32, 0.0, range.clone(), None) }) .collect(); - let pens = - line.glyphs.iter().fold(Rect::new(0.0, -size, 0.0, size), |r, (_, x, advance, _)| r.union_pt((*x, 0.0)).union_pt((x + advance, 0.0))); - let spacing: Vec = glyphs.iter().map(|g| f64::from(g.x_advance(1.0)) * 1000.0).collect(); + let pens = line + .glyphs + .iter() + .fold(Rect::new(0.0, -size, 0.0, size), |r, (_, p, advance, _)| r.union_pt((p.x, p.y - size)).union_pt((p.x + advance, p.y + size))); + let spacing: Vec = glyphs.iter().flat_map(|g| [f64::from(g.x_advance(1.0)) * 1000.0, f64::from(g.y_offset(1.0)) * 1000.0]).collect(); if !(writable(s, line.frame, pens) && in_range(&spacing)) { return; } 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 86a4a89a37..b052ff7c32 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -23,9 +23,11 @@ impl<'p> Builder<'p> { glyphs: None, text: None, text_as, + actual: Default::default(), images: HashMap::new(), image_keys: HashMap::new(), cmyk_keys: HashSet::new(), + separation_paints: HashMap::new(), opaque: HashSet::new(), warnings: vec![], fonts: HashMap::new(), @@ -101,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); @@ -582,8 +585,19 @@ impl<'p> Builder<'p> { Some(Paint::Pattern { pattern: name, xf }) } + /// 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::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)) + } + pub(super) fn add_image(&mut self, key: u128, make: impl FnOnce() -> Option<(ImageBlob, u32, u32)>, xf: Affine) { - self.add_image_masked(key, make, xf, None); + self.add_image_masked(key, make, xf, None, None); } /// An image's alpha (its soft mask, stencil mask or colour key, at its own resolution) as a @@ -626,12 +640,15 @@ impl<'p> Builder<'p> { Some(OpacityMask::new(art, true)) } + /// An image of key `key` (its blob made by `make` the first time), placed by `xf`, with opacity + /// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image). pub(super) fn add_image_masked( &mut self, key: u128, make: impl FnOnce() -> Option<(ImageBlob, u32, u32)>, xf: Affine, mask: Option, + colorize: Option, ) { let (k, w, h) = if let Some(v) = self.image_keys.get(&key).cloned() { v @@ -652,6 +669,7 @@ impl<'p> Builder<'p> { NodeKind::Image(Box::new(ImageObject { key: k, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None })), ); n.extras_mut().mask = mask.map(Box::new); + n.extras_mut().colorize = colorize.map(Box::new); self.push_node(n); } @@ -733,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)) { @@ -757,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)) { @@ -769,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()); @@ -833,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 diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 84d8885a0b..2fb6bb9c80 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,7 +1,7 @@ use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ - Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, line_width, mean_scale, resize_alpha, rgba_png, same_outline, stroke_layer, - stroke_outline, + Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline, + stroke_layer, stroke_outline, }; use super::{ Affine, Appearance, AppearanceItem, Arc, BezPath, BlendMode, ClipPath, Device, FillLayer, FillRule, Glyph, GlyphDrawMode, Image, ImageBlob, @@ -248,7 +248,26 @@ impl<'a> Device<'a> for Builder<'_> { // Its mask (read by the interpreter, whatever its kind) becomes an opacity // mask, so the inks stay as they are. 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); + return self.add_image_masked(key, || cmyk.map(|blob| (blob, w, h)), transform, mask, None); + } + // 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. + if !white { + let found = match self.separation_paints.get(&key) { + Some(paint) => paint.clone().map(|p| (p, None)), + None => { + let read = self.separation_image(st, w, h); + self.separation_paints.insert(key, read.as_ref().map(|(p, _)| p.clone())); + read.map(|(p, gray)| (p, Some(gray))) + } + }; + if let Some((paint, gray)) = found { + let mask = if crate::import_image::has_mask(st) { self.alpha_mask(key, &r, w, h, transform) } else { None }; + let make = || gray.and_then(|g| gray_png(g, w, h)).map(|png| (ImageBlob::new("image/png", png), w, h)); + return self.add_image_masked(key ^ 0x5e9_a7e5, make, transform, mask, Some(paint)); + } } // JPEG passthrough for plain DeviceRGB/DeviceGray DCT images. let dict = st.dict(); @@ -290,22 +309,43 @@ impl<'a> Device<'a> for Builder<'_> { Image::Stencil(s) => { let white = self.white_images; let key = craft_pdf::interpret::CacheKey::cache_key(&s) ^ if white { WHITE_KEY } else { 0 }; + // A mask painted in a solid color comes in as a grayscale image of what it paints + // (black, the rest white) colorized by that color, as the `.ai` reader opens an + // image mask: Fill and Recolor Artwork reach the color, a spot color keeps its ink, + // and the mask drawn again in another color keeps that color. Inside an alpha soft + // mask, or painted with a pattern (which isn't drawn), its pixels are white or black. let mut decoded: Option = None; + let mut colorize = None; s.with_stencil( |luma, paint| { - let rgb = match paint { - _ if white => [255, 255, 255, 255], - craft_pdf::interpret::Paint::Color(c) => c.to_rgba().to_rgba8(), - _ => [0, 0, 0, 255], + let px = match paint { + craft_pdf::interpret::Paint::Color(_) if !white => { + // The walk doesn't count images: the ink is found by its color space. + colorize = Some(self.paint(paint, false, None).0); + luma.data.iter().map(|a| u8::MAX - a).collect() + } + _ => { + let v = if white { u8::MAX } else { 0 }; + luma.data.iter().flat_map(|a| [v, v, v, *a]).collect() + } }; - let rgba = luma.data.iter().flat_map(|a| [rgb[0], rgb[1], rgb[2], *a]).collect(); - decoded = Some((rgba, luma.width, luma.height, luma.scale_factors)); + decoded = Some((px, luma.width, luma.height, luma.scale_factors)); }, None, ); - let Some((rgba, w, h, sf)) = decoded else { return }; + let Some((px, w, h, sf)) = decoded else { return }; let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); - self.add_image(key ^ 0x5_7e9c, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf); + match colorize { + // Its own key: its pixels are the gray ones, whatever color paints it. + Some(paint) => self.add_image_masked( + key ^ 0x6a7_57e9c, + || gray_png(px, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), + xf, + None, + Some(paint), + ), + None => self.add_image(key ^ 0x5_7e9c, || rgba_png(px, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf), + } } } } @@ -338,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) { @@ -376,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 abf7499d05..93a84ae688 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -82,10 +82,14 @@ 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`]). pub(super) cmyk_keys: HashSet, + /// Images in a Separation space, by key: the paint of their ink, or `None` when they open in + /// RGB (an ink that can't be told, tints that can't be read). + pub(super) separation_paints: HashMap>, /// Mask keys of CMYK images whose mask turned out to hide nothing. pub(super) opaque: HashSet, pub(super) warnings: Vec, @@ -273,11 +277,15 @@ pub(crate) fn round3(v: f32) -> f32 { (v * 1000.0).round() / 1000.0 } -/// The paints of `nodes`' leaves, in order: what tells two readings of a pattern cell apart. +/// The paints of `nodes`' leaves, in order, colorized images' colors included: what tells two +/// readings of a pattern cell apart. pub(super) fn paints(nodes: &[Arc]) -> Vec { let mut out = vec![]; for n in nodes { - n.walk(&mut |c| out.extend(c.appearance.items.iter().map(|i| i.paint().clone()))); + n.walk(&mut |c| { + out.extend(c.appearance.items.iter().map(|i| i.paint().clone())); + out.extend(c.extras().colorize.as_deref().cloned()); + }); } out } @@ -294,6 +302,13 @@ pub(super) fn rgba_png(rgba: Vec, w: u32, h: u32) -> Option> { Some(out) } +pub(super) fn gray_png(gray: Vec, w: u32, h: u32) -> Option> { + let img = image::GrayImage::from_raw(w, h, gray)?; + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; + Some(out) +} + pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec { if a.width == w && a.height == h { return a.data.clone(); diff --git a/crates/pdf/src/import_color.rs b/crates/pdf/src/import_color.rs index b7e033b6ce..2dfac228d4 100644 --- a/crates/pdf/src/import_color.rs +++ b/crates/pdf/src/import_color.rs @@ -239,6 +239,18 @@ impl<'p> Colors<'p> { } } + /// The space of colour space array `a` (`[/Separation name alt tint]` or `[/DeviceN …]`, such + /// as an image's) among the file's: matched by its kind, its colorant names and its tint + /// transform, not by the page's walk. `None` for another array. + pub fn array_space(&mut self, a: &Array<'_>) -> Option { + self.scan(); + let mut it = a.flex_iter(); + let (device_n, names) = ink_names(&mut it)?; + it.next::>()?; + let key = debug_text(&Function::new(&it.next::>()?)?)?; + self.spaces.iter().position(|s| s.device_n == device_n && s.names == names && s.key == key).map(Space::Inks) + } + /// Whether a space of inks `names` has the kind, colorant count and tint transform of a space /// of other inks. [`Colors::space_of`] tells such spaces apart only by the names from the /// page's walk. diff --git a/crates/pdf/src/import_image.rs b/crates/pdf/src/import_image.rs index cfda8a4944..d376c2b31e 100644 --- a/crates/pdf/src/import_image.rs +++ b/crates/pdf/src/import_image.rs @@ -3,15 +3,19 @@ //! 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`]). 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::ImageDecodeParams; +use craft_pdf::syntax::object::stream::{ImageColorSpace, ImageDecodeParams}; 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"; @@ -56,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(); @@ -90,6 +94,142 @@ pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result(st: &Stream<'a>) -> Option> { + let d = st.dict(); + let a = d.get::>(key(d, b"ColorSpace", b"CS"))?; + 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 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> { + let d = st.dict(); + let bpc = d.get::(key(d, b"BitsPerComponent", b"BPC")).unwrap_or(8); + if !matches!(bpc, 1 | 2 | 4 | 8 | 16) { + return Err(UNREAD_TINTS); + } + // The same cap as CMYK images'. + let n = u64::from(width) * u64::from(height); + if n == 0 || n > MAX_CMYK_PIXELS { + return Err(UNREAD_TINTS); + } + let (lo, hi) = match d.get::>(key(d, b"Decode", b"D")).map(|a| a.iter::().collect::>()).as_deref() { + Some(&[lo, hi]) if lo.is_finite() && hi.is_finite() => (lo, hi), + _ => (0.0, 1.0), + }; + let params = ImageDecodeParams { is_indexed: false, bpc: Some(bpc), num_components: Some(1), target_dimension: None, width, height }; + let decoded = st.decoded_image(¶ms).map_err(|_| UNREAD_TINTS)?; + // An image codec (JPEG, CCITT, JBIG2, JPEG 2000) says what it decoded to: one gray channel of + // the image's size, at its own bit depth. + let bpc = match &decoded.image_data { + None => bpc, + Some(i) + if i.alpha.is_none() + && matches!(i.color_space, Some(ImageColorSpace::Gray)) + && (i.width, i.height) == (width, height) + && matches!(i.bits_per_component, 1 | 2 | 4 | 8 | 16) => + { + i.bits_per_component + } + Some(_) => return Err(UNREAD_TINTS), + }; + let bits = usize::from(bpc); + let row = (width as usize * bits).div_ceil(8); + let data = decoded.data.get(..row * height as usize).ok_or(UNREAD_TINTS)?; + let max = ((1u32 << bits) - 1) as f32; + let mut out = Vec::with_capacity(n as usize); + for line in data.chunks_exact(row) { + for x in 0..width as usize { + let v = match bits { + 16 => line.get(x * 2..x * 2 + 2).map_or(0, |s| s.iter().fold(0u32, |v, b| (v << 8) | u32::from(*b))), + 8 => line.get(x).map_or(0, |b| u32::from(*b)), + // 1, 2 or 4 bits a sample, packed from the high bits of each byte. + _ => line.get(x * bits / 8).map_or(0, |b| (u32::from(*b) >> (8 - bits - (x * bits) % 8)) & ((1 << bits) - 1)), + }; + let tint = (lo + v as f32 / max * (hi - lo)).clamp(0.0, 1.0); + out.push(((1.0 - tint) * 255.0).round() as u8); + } + } + Ok(out) +} + /// Does the image carry its own transparency (a soft mask, a stencil mask or a colour key)? pub(crate) fn has_mask(st: &Stream<'_>) -> bool { let d = st.dict(); 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/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/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 5a38a8201d..6abe2f3885 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -8,7 +8,7 @@ use craft_pdf::syntax::Pdf; use craft_pdf::syntax::object::{Array, Name, Object, Stream}; use serde_json::json; use vectorcraft_color::cms::{self, DEVICE_CMYK, GENERIC_CMYK, SRGB}; -use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, Paint}; +use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint, Swatch}; use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{Appearance, ColorMode, Document, ImageBlob, ImageObject, Node, NodeKind}; use vectorcraft_geom::{Affine, Point, Rect, shapes}; @@ -514,6 +514,103 @@ fn freeform_gradients_of_cmyk_points_are_written_as_cmyk_images() { assert_ne!(w[0].space, "DeviceCMYK", "converted to RGB"); } +/// A 100 × 100 pt document of `mode` whose square is filled with `g`, at one pixel a point. +fn gradient_doc(mode: ColorMode, g: Gradient) -> Document { + let mut d = Document::new_with_mode(100.0, 100.0, mode); + d.raster_effects_ppi = 72.0; + let square = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), + Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0), + ); + let l = d.layers[0].id; + d.insert(Some(l), 0, square).unwrap(); + d +} + +/// A gradient of `stops`, dithered or Perceptual. +fn drawn_as_pixels(kind: GradientKind, stops: Vec, dither: bool) -> Gradient { + let method = if dither { GradientMethod::Classic } else { GradientMethod::Perceptual }; + Gradient { dither, method, ..Gradient::new(kind, stops) } +} + +fn cyan_to_black() -> Vec { + vec![GradientStop::new(0.0, Color::cmyk(1.0, 0.0, 0.0, 0.0)), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 1.0))] +} + +#[test] +fn dithered_and_perceptual_gradients_of_cmyk_stops_are_written_as_cmyk_images() { + for mode in [ColorMode::Cmyk, ColorMode::Rgb] { + for kind in [GradientKind::Linear, GradientKind::Radial] { + for dither in [true, false] { + let d = gradient_doc(mode, drawn_as_pixels(kind, cyan_to_black(), dither)); + let out = export_with_report(&d, &opts(json!({}))).unwrap(); + let w = written(&out.bytes); + assert_eq!(w.len(), 1, "{mode:?} {kind:?} dither {dither}: opaque, no soft mask: {w:?}"); + assert_eq!(w[0].space, "DeviceCMYK", "{mode:?} {kind:?} dither {dither}"); + let back = import(&out.bytes).unwrap(); + let inks = all_images(&back)[0].cmyk().unwrap(); + assert_eq!((inks.width, inks.height), (100, 100)); + assert!(inks.data.chunks(4).all(|p| p[1] == 0 && p[2] == 0), "{mode:?} {kind:?} dither {dither}: only cyan and black"); + if kind == GradientKind::Linear { + let row = &inks.data[50 * 400..51 * 400]; + assert!(close(&row[..4], &[254, 0, 0, 1], 3), "{mode:?} dither {dither}: {:?}", &row[..4]); + assert!(close(&row[396..], &[1, 0, 0, 254], 3), "{mode:?} dither {dither}: {:?}", &row[396..]); + if dither { + assert!(close(&row[50 * 4..50 * 4 + 4], &[127, 0, 0, 128], 3), "{mode:?}: {:?}", &row[50 * 4..50 * 4 + 4]); + } + } + } + } + } + // Opacity goes in a soft mask, and the inks stay. + let mut stops = cyan_to_black(); + stops[1].opacity = 0.5; + let w = written( + &export_with_report(&gradient_doc(ColorMode::Cmyk, drawn_as_pixels(GradientKind::Linear, stops, true)), &opts(json!({}))).unwrap().bytes, + ); + assert_eq!(w.len(), 2, "the image and its soft mask: {w:?}"); + assert!(w.iter().any(|i| i.space == "DeviceCMYK") && w.iter().any(|i| i.space == "DeviceGray"), "{w:?}"); + // The Output settings convert the inks like any CMYK image's. + let d = gradient_doc(ColorMode::Cmyk, drawn_as_pixels(GradientKind::Linear, cyan_to_black(), true)); + let w = written(&export_with_report(&d, &opts(json!({"output": {"conversion": "destination", "destination": SRGB}}))).unwrap().bytes); + assert_eq!(w.len(), 1, "{w:?}"); + assert_ne!(w[0].space, "DeviceCMYK", "converted to RGB"); +} + +/// A stop in another model, or linked to a spot swatch, keeps the RGB image. +#[test] +fn gradients_with_a_stop_that_is_not_process_cmyk_stay_rgb_images() { + let cyan = || GradientStop::new(0.0, Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let others = [Color::rgb(1.0, 0.0, 0.0), Color::gray(0.5), Color::lab(50.0, 10.0, 10.0)]; + for mode in [ColorMode::Cmyk, ColorMode::Rgb] { + for other in others { + for dither in [true, false] { + let d = gradient_doc(mode, drawn_as_pixels(GradientKind::Linear, vec![cyan(), GradientStop::new(1.0, other)], dither)); + let w = written(&export_with_report(&d, &opts(json!({}))).unwrap().bytes); + assert_eq!(w.len(), 1, "{mode:?} {other:?}: {w:?}"); + assert_eq!(w[0].space, "DeviceRGB", "{mode:?} {other:?} dither {dither}"); + } + } + } + // A stop of a spot swatch whose color is CMYK: a dithered fill is an RGB image with a warning. + let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1); + let mut stop = GradientStop::new(1.0, gold); + stop.swatch = Some("Gold".into()); + let mut d = gradient_doc(ColorMode::Cmyk, drawn_as_pixels(GradientKind::Linear, vec![cyan(), stop.clone()], true)); + d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: true }); + let out = export_with_report(&d, &opts(json!({}))).unwrap(); + let w = written(&out.bytes); + assert_eq!(w.len(), 1, "{w:?}"); + assert_eq!(w[0].space, "DeviceRGB"); + assert!(out.warnings.iter().any(|m| m.contains("written in process colors")), "{:?}", out.warnings); + // A stop of a global process swatch is written as its CMYK color. + let mut d = gradient_doc(ColorMode::Cmyk, drawn_as_pixels(GradientKind::Linear, vec![cyan(), stop], true)); + d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: false }); + let w = written(&export_with_report(&d, &opts(json!({}))).unwrap().bytes); + assert_eq!(w[0].space, "DeviceCMYK", "{w:?}"); +} + #[test] fn freeform_gradients_of_lab_points_are_written_as_their_lab_mix() { let d = freeform_doc(ColorMode::Rgb, Color::lab(90.0, -60.0, 40.0), Color::lab(30.0, 60.0, -40.0), 1.0); diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 5ec2e813ab..97388ea313 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -1,5 +1,6 @@ //! Grayscale and 1-bit images colorized by a fill color are written in that color, a spot color //! as its ink, with the image's coverage as the soft mask. +//! An image mask in a PDF opens as a grayscale image colorized by the color it is painted with. use std::sync::Arc; @@ -8,6 +9,7 @@ use craft_pdf::syntax::object::{Array, Name, Object, Stream}; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{ColorMode, Document, ImageBlob, ImageObject, Node, NodeKind}; use vectorcraft_geom::Affine; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; use crate::*; @@ -219,3 +221,275 @@ fn ink_options_naming_no_ink_give_one_short_warning() { assert_eq!(warnings.len(), 1); assert!(warnings[0].contains("`Missing 0`") && warnings[0].contains("and 9990 more") && warnings[0].len() < 500, "{}", warnings[0]); } + +/// An 8 × 1 image mask whose 0 bits (columns 2 to 5) are painted. +const MASK: &str = "<< /Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode /Length 3 >>\nstream\nC3>\nendstream"; + +/// A page drawing [`MASK`] (`/Im1`) with `content`, with a spot ink `SpotRed` as `/CS0`. +fn mask_page(content: &str) -> Vec { + let spot = "[/Separation /SpotRed /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 1 0] /N 1 >>]"; + let resources = format!("/ColorSpace << /CS0 {spot} >> /XObject << /Im1 {} 0 R >>", first_extra(1)); + pdf_with(&[PdfPage { resources, ..PdfPage::new(200.0, 100.0, content) }], &[MASK], None) +} + +/// The imported images, in paint order: their colorize paint and gray pixels. +fn imported_images(d: &Document) -> Vec<(Option, Vec)> { + let mut out = vec![]; + for l in &d.layers { + l.walk(&mut |n| { + if let NodeKind::Image(im) = &n.kind { + let blob = d.images.get(&im.key).unwrap(); + let gray = image::load_from_memory(&blob.bytes).unwrap(); + assert_eq!(gray.color(), image::ColorType::L8, "a grayscale image"); + out.push((n.extras().colorize.as_deref().cloned(), gray.into_luma8().into_raw())); + } + }); + } + out +} + +/// What the mask paints is black, the rest white; a spot color keeps its swatch and tint. +#[test] +fn an_image_mask_opens_colorized_by_its_spot_color() { + let d = crate::import(&mask_page("/CS0 cs 0.5 scn q 80 0 0 10 10 50 cm /Im1 Do Q")).unwrap(); + let images = imported_images(&d); + assert_eq!(images.len(), 1); + let (paint, gray) = &images[0]; + assert_eq!(gray, &[255, 255, 0, 0, 0, 0, 255, 255]); + let Some(Paint::Solid { swatch, tint, .. }) = paint else { panic!("colorized: {paint:?}") }; + assert_eq!((swatch.as_deref(), *tint), (Some("SpotRed"), 0.5)); + assert!(d.swatch("SpotRed").is_some_and(|s| s.spot), "a spot swatch"); +} + +/// A mask drawn twice keeps each color it is painted with, over the same pixels. +#[test] +fn an_image_mask_drawn_in_two_colors_keeps_both() { + let d = crate::import(&mask_page("1 0 0 rg q 80 0 0 10 10 20 cm /Im1 Do Q 0 0 1 rg q 80 0 0 10 10 60 cm /Im1 Do Q")).unwrap(); + let images = imported_images(&d); + let hex: Vec<_> = images.iter().map(|(p, _)| p.as_ref().and_then(Paint::color).map(|c| c.to_hex())).collect(); + assert_eq!(hex, [Some("#ff0000".to_string()), Some("#0000ff".to_string())]); + assert_eq!(images[0].1, images[1].1); +} + +/// An uncolored tiling pattern whose cell draws a mask, filled in red and then in blue, gives a +/// pattern for each color: the readings of its cell differ by the mask's color. +#[test] +fn an_uncolored_pattern_drawing_an_image_mask_keeps_each_color() { + let (mask, pattern) = (first_extra(1), first_extra(1) + 1); + let resources = format!("/ColorSpace << /CS1 [/Pattern /DeviceRGB] >> /Pattern << /P0 {pattern} 0 R >>"); + let cell = format!( + "<< /PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << /XObject << /Im1 {mask} 0 R >> >> /Length 28 >>\nstream\nq 10 0 0 10 0 0 cm /Im1 Do Q\nendstream" + ); + let content = "/CS1 cs 1 0 0 /P0 scn 0 0 100 40 re f 0 0 1 /P0 scn 0 50 100 40 re f"; + let d = crate::import(&pdf_with(&[PdfPage { resources, ..PdfPage::new(100.0, 100.0, content) }], &[MASK, &cell], None)).unwrap(); + let mut colors = vec![]; + for l in &d.layers { + l.walk(&mut |n| { + for item in &n.appearance.items { + let Paint::Pattern { pattern, .. } = item.paint() else { continue }; + let mut hex = vec![]; + for a in &d.pattern(pattern).unwrap().art { + a.walk(&mut |c| hex.extend(c.extras().colorize.as_deref().and_then(Paint::color).map(|c| c.to_hex()))); + } + colors.push(hex); + } + }); + } + assert_eq!(colors, [["#ff0000"], ["#0000ff"]]); +} + +const SPOT_RED: &str = "[/Separation /SpotRed /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 1 0] /N 1 >>]"; + +/// A page drawing a `w` × 1 image in color space `space` (`bpc` bits a sample, more dictionary +/// entries `more`, samples `hex`), then the `extra` objects after it. +fn separation_page(space: &str, w: u32, bpc: u8, more: &str, hex: &str, extra: &[&str]) -> Document { + separation_report(space, w, bpc, more, hex, extra, "q 80 0 0 10 10 50 cm /Im1 Do Q").document +} + +/// [`separation_page`] drawn with `content`, with the import's report. `more` may name filters +/// after ASCIIHex (`/Filter [/ASCIIHexDecode …]`). +fn separation_report(space: &str, w: u32, bpc: u8, more: &str, hex: &str, extra: &[&str], content: &str) -> ImportReport { + let filter = if more.contains("/Filter") { "" } else { "/Filter /ASCIIHexDecode" }; + let image = format!( + "<< /Type /XObject /Subtype /Image /Width {w} /Height 1 /ColorSpace {space} /BitsPerComponent {bpc} {more} {filter} /Length {} >>\nstream\n{hex}>\nendstream", + hex.len() + 1 + ); + let resources = format!("/XObject << /Im1 {} 0 R >>", first_extra(1)); + let mut objects = vec![image.as_str()]; + objects.extend_from_slice(extra); + let pdf = pdf_with(&[PdfPage { resources, ..PdfPage::new(100.0, 100.0, content) }], &objects, None); + import_with_report(&pdf, &ImportOptions::default()).unwrap() +} + +/// An image in a spot ink's Separation space opens as a grayscale image of its tints, colorized by +/// the ink's spot swatch at 100 %. +#[test] +fn a_separation_image_opens_colorized_by_its_ink() { + let d = separation_page(SPOT_RED, 4, 8, "", "0055AAFF", &[]); + let images = imported_images(&d); + assert_eq!(images.len(), 1); + let (paint, gray) = &images[0]; + assert_eq!(gray, &[255, 170, 85, 0], "the tints 0, 1/3, 2/3 and 1"); + let Some(Paint::Solid { swatch, tint, .. }) = paint else { panic!("colorized: {paint:?}") }; + assert_eq!((swatch.as_deref(), *tint), (Some("SpotRed"), 1.0)); + assert!(d.swatch("SpotRed").is_some_and(|s| s.spot), "a spot swatch"); +} + +/// Samples of 1, 4 and 16 bits are unpacked, and the Decode array applied. +#[test] +fn a_separation_image_reads_its_samples_and_decode_array() { + for (bpc, w, more, hex, want) in [ + (1, 8, "/Decode [1 0]", "C3", vec![255, 255, 0, 0, 0, 0, 255, 255]), + (4, 3, "", "0F80", vec![255, 0, 119]), + (16, 2, "", "0000FFFF", vec![255, 0]), + ] { + let d = separation_page(SPOT_RED, w, bpc, more, hex, &[]); + let images = imported_images(&d); + assert_eq!(images.len(), 1, "{bpc} bits"); + assert_eq!(images[0].1, want, "{bpc} bits"); + assert!(images[0].0.is_some(), "{bpc} bits: colorized"); + } +} + +/// A Separation of a process plate colorizes in that plate's CMYK color; the ink `None`, which +/// paints nothing, is left to the interpreter. +#[test] +fn a_separation_image_of_a_process_plate_or_of_no_ink() { + let black = "[/Separation /Black /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 0 1] /N 1 >>]"; + let d = separation_page(black, 2, 8, "", "00FF", &[]); + let images = imported_images(&d); + assert_eq!(images.len(), 1); + assert_eq!(images[0].0, Some(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)))); + assert!(d.swatches.iter().all(|s| !s.spot), "no spot swatch for a process plate"); + let none = "[/Separation /None /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 1 0] /N 1 >>]"; + let d = separation_page(none, 2, 8, "", "00FF", &[]); + let mut colorized = vec![]; + for l in &d.layers { + l.walk(&mut |n| { + if matches!(n.kind, NodeKind::Image(_)) { + colorized.push(n.extras().colorize.is_some()); + } + }); + } + assert!(colorized.iter().all(|c| !c), "{colorized:?}"); +} + +/// A Separation image's soft mask becomes its opacity mask. +#[test] +fn a_separation_image_keeps_its_soft_mask() { + let smask = "<< /Type /XObject /Subtype /Image /Width 4 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode /Length 9 >>\nstream\nFF00FF00>\nendstream"; + let d = separation_page(SPOT_RED, 4, 8, &format!("/SMask {} 0 R", first_extra(1) + 1), "0055AAFF", &[smask]); + let mut found = vec![]; + for l in &d.layers { + l.walk(&mut |n| { + if matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.is_some() { + found.push(n.extras().mask.is_some()); + } + }); + } + assert_eq!(found, [true]); +} + +/// The same Separation image drawn twice is colorized twice, over the same pixels. +#[test] +fn a_separation_image_drawn_twice_is_colorized_twice() { + let d = separation_report(SPOT_RED, 4, 8, "", "0055AAFF", &[], "q 80 0 0 10 10 20 cm /Im1 Do Q q 80 0 0 10 10 60 cm /Im1 Do Q").document; + let images = imported_images(&d); + assert_eq!(images.len(), 2); + assert_eq!(images[0], images[1]); + assert!(images[0].0.is_some(), "colorized"); +} + +/// A one-component JPEG in a Separation space is read through its decoder. +#[test] +fn a_separation_jpeg_opens_colorized_by_its_ink() { + let mut jpeg = vec![]; + jpeg_encoder::Encoder::new(&mut jpeg, 100).encode(&[0, 0, 255, 255, 0, 0, 255, 255], 8, 1, jpeg_encoder::ColorType::Luma).unwrap(); + let hex: String = jpeg.iter().map(|b| format!("{b:02X}")).collect(); + let d = separation_page(SPOT_RED, 8, 8, "/Filter [/ASCIIHexDecode /DCTDecode]", &hex, &[]); + let images = imported_images(&d); + assert_eq!(images.len(), 1); + assert!(images[0].0.is_some(), "colorized"); + // Sample 0 lays no ink (white), 255 lays it all (black); JPEG blurs the edges a little. + let gray = &images[0].1; + assert!(gray[0] > 200 && gray[2] < 55 && gray[4] > 200 && gray[6] < 55, "{gray:?}"); +} + +/// A Separation image whose tints can't be read (its data cut short) opens in RGB each time it is +/// drawn, with one warning and no swatch for its ink. +#[test] +fn a_separation_image_that_cant_be_read_stays_rgb() { + let r = separation_report(SPOT_RED, 4, 8, "", "0055", &[], "q 80 0 0 10 10 20 cm /Im1 Do Q q 80 0 0 10 10 60 cm /Im1 Do Q"); + let mut colorized = vec![]; + for l in &r.document.layers { + l.walk(&mut |n| { + if matches!(n.kind, NodeKind::Image(_)) { + colorized.push(n.extras().colorize.is_some()); + } + }); + } + assert_eq!(colorized, [false, false]); + 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/realtext.rs b/crates/pdf/src/tests/realtext.rs index 375b319b37..b3e105e4f6 100644 --- a/crates/pdf/src/tests/realtext.rs +++ b/crates/pdf/src/tests/realtext.rs @@ -973,3 +973,241 @@ fn dithered_type_keeps_its_resolution_when_scaled_and_stays_searchable() { assert!(ops.contains("3 Tr"), "the characters as invisible text"); assert_eq!(texts(&import_as(&scaled, TextAs::Text)), ["Dither"]); } + +/// Exact craft-fonts face: a substituted Arabic font would miss Noto's dot decomposition. +fn mark_text(text: &str) -> Option { + let face = FontDb::global().face("Noto Sans Arabic", "Regular").filter(|f| f.family == "Noto Sans Arabic"); + let Some(face) = face else { + assert!(std::env::var("CRAFT_FONTS_REQUIRED").as_deref() != Ok("1"), "Noto Sans Arabic is required"); + eprintln!("SKIPPED: PDF mark-text regression needs craft-fonts Noto Sans Arabic"); + return None; + }; + Some(TextObject::point(Point::new(30.0, 100.0), text, CharStyle { font_family: face.family.clone(), ..style(32.0) })) +} + +/// Decode semantic cluster mappings directly: ActualText replaces its enclosed glyphs, whose +/// CIDs otherwise resolve through the active font's ToUnicode. A shared mark glyph can only +/// carry one ToUnicode value; its other clusters must still occur exactly once via ActualText. +fn mark_stream(bytes: &[u8]) -> (usize, Vec, Vec) { + use craft_pdf::syntax::{ + Pdf, + content::UntypedIter, + object::{Dict, Object, Stream}, + }; + let file = Pdf::new(Arc::new(bytes.to_vec())).unwrap(); + let page = &file.pages()[0]; + let resources = page.raw().get::>(b"Resources").unwrap(); + let fonts = resources.get::>(b"Font").unwrap(); + let mut font_maps = std::collections::BTreeMap::new(); + for name in fonts.keys() { + let font = fonts.get::>(name.as_ref()).unwrap(); + let cmap = font.get::>(b"ToUnicode").unwrap().decoded().unwrap(); + let cmap = std::str::from_utf8(&cmap).unwrap(); + let mut mappings = std::collections::BTreeMap::new(); + // The writer emits bfchar entries with a hexadecimal UTF-16BE destination. + for block in cmap.split("beginbfchar").skip(1) { + for entry in block.split("endbfchar").next().unwrap().lines().filter(|l| l.trim_start().starts_with('<')) { + let mut pair = entry.split_whitespace(); + let cid = u16::from_str_radix(pair.next().unwrap().trim_matches(['<', '>']), 16).unwrap(); + let value = pair.next().unwrap().trim_matches(['<', '>']); + let units = (0..value.len()).step_by(4).map(|i| u16::from_str_radix(&value[i..i + 4], 16).unwrap()).collect::>(); + assert!(mappings.insert(cid, String::from_utf16(&units).unwrap()).is_none()); + } + } + let unique: std::collections::BTreeSet<_> = mappings.values().collect(); + assert_eq!(unique.len(), mappings.len(), "a cluster must not be assigned to multiple glyphs: {mappings:?}"); + font_maps.insert(name.as_ref().to_vec(), mappings); + } + let mut ops = UntypedIter::new(page.page_stream().unwrap()); + let (mut batches, mut actual, mut mapped) = (0, vec![], vec![]); + let (mut marked, mut font) = (vec![], vec![]); + while let Some(op) = ops.next() { + match &**op.operator { + b"BT" => batches += 1, + b"Tf" => { + let Some(Object::Name(name)) = op.operands().next() else { panic!("font name") }; + font = name.as_ref().to_vec(); + } + b"BMC" | b"BDC" => { + let replacement = op.operands().find_map(|operand| { + if let Object::Dict(d) = operand { + d.get::>(b"ActualText").map(|s| crate::import_scan::text_string(s.as_bytes())) + } else { + None + } + }); + if let Some(text) = &replacement { + assert!(!marked.contains(&true), "no nested replacement in these fixtures"); + actual.push(text.clone()); + mapped.push(text.clone()); + } + marked.push(replacement.is_some()); + } + b"EMC" => { + marked.pop().unwrap(); + } + b"Tj" | b"TJ" if !marked.contains(&true) => { + let strings: Vec<_> = op + .operands() + .flat_map(|o| match o { + Object::String(s) => vec![s.clone()], + Object::Array(a) => a.iter::>().collect(), + _ => vec![], + }) + .collect(); + for string in strings { + let (cids, trailing) = string.as_bytes().as_chunks::<2>(); + assert!(trailing.is_empty()); + for cid in cids { + let cid = u16::from_be_bytes(*cid); + mapped.push(font_maps[&font].get(&cid).expect("unspanned glyph needs a Unicode mapping").clone()); + } + } + } + _ => {} + } + } + assert!(marked.is_empty()); + (batches, actual, mapped) +} + +/// Every contour, including each dot and harakat, must stay at the outline export's position. +fn mark_placement(real: &[u8], outlined: &[u8]) { + use vectorcraft_geom::{PathEl, Shape}; + let contours = |bytes: &[u8]| { + let mut boxes = vec![]; + import_as(bytes, TextAs::Outlines).walk(|n| { + let paths = match &n.kind { + NodeKind::Path { path, .. } => vec![path.to_bezpath()], + _ => vec![], + }; + for path in paths { + let mut contour = BezPath::new(); + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) && contour.elements().len() > 1 { + boxes.push(std::mem::take(&mut contour).bounding_box()); + } + contour.push(*el); + } + if contour.elements().len() > 1 { + boxes.push(contour.bounding_box()); + } + } + }); + boxes + }; + let (got, mut want) = (contours(real), contours(outlined)); + assert!(!got.is_empty()); + assert_eq!(got.len(), want.len(), "every outline contour is retained"); + for a in got { + let (i, distance) = want + .iter() + .enumerate() + .map(|(i, b)| (i, [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].into_iter().map(f64::abs).fold(0.0, f64::max))) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .unwrap(); + assert!(distance < 0.05, "contour {a:?} moved by {distance} pt; nearest {:?}", want[i]); + want.remove(i); + } +} + +fn check_mark_clusters(text: &str) { + let Some(t) = mark_text(text) else { return }; + let layout = vectorcraft_text::layout(FontDb::global(), &t); + let face = FontDb::global().face("Noto Sans Arabic", "Regular").unwrap(); + assert!(layout.glyphs.iter().all(|g| g.font_id == face.id() && g.gid != 0), "no fallback or missing glyphs"); + assert_eq!(layout.lines.len(), 1); + let mut clusters = std::collections::BTreeMap::<_, Vec<_>>::new(); + for g in &layout.glyphs { + clusters.entry((g.byte, g.len)).or_default().push(g); + } + let repeated: Vec<_> = clusters.iter().filter(|(_, glyphs)| glyphs.len() > 1).collect(); + assert!(!repeated.is_empty(), "fixture must shape into multi-glyph clusters"); + assert!( + repeated.iter().any(|(_, gs)| gs.windows(2).any(|w| (w[0].xf.as_coeffs()[5] - w[1].xf.as_coeffs()[5]).abs() > 0.01)), + "marks have vertical offsets" + ); + assert!(repeated.iter().any(|(_, gs)| gs.iter().any(|g| g.advance.abs() < 1e-6)), "zero-advance marks, including dots in unvocalized شنطة"); + let d = doc(vec![t]); + let r = pdf(&d, false); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let (batches, actual, mappings) = mark_stream(&r.bytes); + assert_eq!(batches, 1, "one batch per compatible layout line: {text}"); + let mut expected_actual: Vec<_> = repeated.iter().map(|((byte, len), _)| text[*byte..byte + len].to_string()).collect(); + let mut actual = actual; + actual.sort(); + expected_actual.sort(); + assert_eq!(actual, expected_actual, "each multi-glyph cluster has exactly one semantic replacement"); + let mut expected: Vec<_> = clusters.keys().map(|(byte, len)| text[*byte..byte + len].to_string()).collect(); + let mut mappings = mappings; + expected.sort(); + mappings.sort(); + assert_eq!(mappings, expected, "each source cluster maps exactly once through ActualText or ToUnicode"); + mark_placement(&r.bytes, &pdf(&d, true).bytes); +} + +#[test] +fn mark_text_harakat_clusters_are_mapped_once() { + check_mark_clusters("مُحَمَّد"); +} + +#[test] +fn mark_text_zero_advance_dot_clusters_are_mapped_once() { + check_mark_clusters("شنطة"); +} + +#[test] +fn mark_text_mixed_arabic_latin_and_digits_are_mapped_once() { + check_mark_clusters("ABC 12 مُحَمَّد شنطة"); +} + +#[test] +fn mark_text_columns_and_rotations_keep_their_boundaries() { + let mut vertical = TextObject::point(Point::new(200.0, 30.0), "§§\n§§", style(24.0)); + vertical.vertical = true; + let layout = vectorcraft_text::layout(FontDb::global(), &vertical); + assert_eq!(layout.lines.len(), 2); + let d = doc(vec![vertical]); + let r = pdf(&d, false); + assert_eq!(mark_stream(&r.bytes).0, 2, "one text batch per vertical column"); + mark_placement(&r.bytes, &pdf(&d, true).bytes); + + let mut arc = BezPath::new(); + arc.move_to((40.0, 200.0)); + arc.curve_to((100.0, 80.0), (260.0, 80.0), (320.0, 200.0)); + let mut t = TextObject::point(Point::ZERO, "CURVE", style(24.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&arc), start: 0.0, end: None }; + let layout = vectorcraft_text::layout(FontDb::global(), &t); + assert!(layout.glyphs.windows(2).all(|w| (w[0].angle - w[1].angle).abs() > 1e-4)); + let d = doc(vec![t]); + let r = pdf(&d, false); + assert_eq!(mark_stream(&r.bytes).0, layout.glyphs.len(), "different rotations still split"); + mark_placement(&r.bytes, &pdf(&d, true).bytes); +} + +#[test] +fn mark_text_pdf_x_variants_export() { + let Some(t) = mark_text("مُحَمَّد شنطة") else { return }; + let d = doc(vec![t]); + for (standard, compatibility) in [("pdfX1a", "1.3"), ("pdfX3", "1.3"), ("pdfX4", "1.6")] { + let settings: PdfSettings = + serde_json::from_value(json!({"standard": standard, "compatibility": compatibility, "advanced": {"outlineText": false}})).unwrap(); + let r = export_with_report(&d, &PdfOptions { settings, ..Default::default() }).unwrap(); + assert_eq!(mark_stream(&r.bytes).0, 1, "{standard}"); + mark_placement(&r.bytes, &pdf(&d, true).bytes); + } +} + +#[test] +#[ignore = "#6165: editable-text importer does not consume ActualText; run explicitly to track the exact round trip"] +fn mark_text_reader_round_trip_harakat() { + let Some(t) = mark_text("مُحَمَّد") else { return }; + assert_eq!(texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text)), ["مُحَمَّد"]); +} + +#[test] +#[ignore = "#6165: editable-text importer does not consume ActualText; run explicitly to track the exact round trip"] +fn mark_text_reader_round_trip_dots() { + let Some(t) = mark_text("شنطة") else { return }; + assert_eq!(texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text)), ["شنطة"]); +} diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index c8dfcb2f08..d0a4619622 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -6,6 +6,7 @@ //! in-range coordinates, capped counts, clamped colours) before it reaches the document. use std::collections::{HashMap, HashSet}; +use std::ops::Range; use std::sync::{Arc, Mutex}; use serde_json::{Value, json}; @@ -46,7 +47,8 @@ pub const MAX_INPUT_RUNS: usize = 4_096; /// image comes with `pixelsOmitted`. pub const MAX_INPUT_PIXELS: usize = 1 << 20; /// Most pixels a filter is given over all the images of one input, in characters of base64: an -/// image whose pixels don't fit what the images before it left comes with `pixelsOmitted`. +/// image whose pixels don't fit what the images before it left comes with `pixelsOmitted`, and an +/// image the host starts to decode takes its size from the total even when decoding fails. pub const MAX_INPUT_PIXELS_TOTAL: usize = 16 << 20; /// Most text a filter is given over all the type of one input, in bytes of the JSON of their runs /// and paragraphs: type that doesn't fit what the type before it left comes with `truncated`. @@ -191,12 +193,15 @@ pub fn encode_input(doc: &Document, ids: &[NodeId]) -> Vec { /// `truncated`), a read-only object whose other fields alone don't fit is an [`Error::Limit`] /// naming it and its size, a path or compound path that doesn't fit is the limit the runtime gives /// an input past its share, and more than [`MAX_OBJECTS`] read-only objects, more than an output -/// may list, is an [`Error::Limit`] too. Also returns those objects by id, which the filter -/// must return as they were ([`decode_output_with`]). -pub fn encode_input_with(doc: &Document, ids: &[NodeId], kinds: &[InputKind], capacity: usize) -> Result<(Vec, HashMap)> { +/// may list, is an [`Error::Limit`] too. Also returns where those objects are in the input, which +/// the filter must return as they were ([`decode_output_with`]). +pub fn encode_input_with(doc: &Document, ids: &[NodeId], kinds: &[InputKind], capacity: usize) -> Result<(Vec, ReadOnlySpans)> { encode_input_within(doc, ids, kinds, Allowance { input: capacity.saturating_sub(EMPTY_INPUT.len()), ..Allowance::FULL }) } +/// Where each read-only object of an input is in the input's bytes. +pub type ReadOnlySpans = HashMap>; + /// The input with no objects; each object adds its JSON and a comma. const EMPTY_INPUT: &[u8] = b"{\"objects\":[]}"; @@ -214,27 +219,23 @@ impl Allowance { const FULL: Allowance = Allowance { pixels: MAX_INPUT_PIXELS_TOTAL, text: MAX_INPUT_TEXT_TOTAL, input: usize::MAX }; } -/// [`encode_input_with`] within `left` of the totals. Each read-only object is kept once, in the map -/// it returns, and written into the input from there. -fn encode_input_within(doc: &Document, ids: &[NodeId], kinds: &[InputKind], mut left: Allowance) -> Result<(Vec, HashMap)> { +/// [`encode_input_with`] within `left` of the totals. Each object is held only while it is written +/// into the input. +fn encode_input_within(doc: &Document, ids: &[NodeId], kinds: &[InputKind], mut left: Allowance) -> Result<(Vec, ReadOnlySpans)> { let mut read_only = HashMap::new(); let symbols = doc.symbol_boxes(); let mut out = b"{\"objects\":[".to_vec(); let mut first = true; for n in ids.iter().filter_map(|id| doc.node(*id)) { - let path; - let (o, checked): (&Value, bool) = match input_kind(n).filter(|k| kinds.contains(k)) { + let (o, checked) = match input_kind(n).filter(|k| kinds.contains(k)) { // The output must return every read-only object, and lists at most `MAX_OBJECTS`. Some(_) if read_only.len() >= MAX_OBJECTS => return Err(too_many_read_only()), Some(_) => match encode_read_only_within(doc, n, &symbols, &mut left)? { - Some(o) => (read_only.entry(n.id).insert_entry(o).into_mut(), true), + Some(o) => (o, true), None => continue, }, None => match encode(n) { - Some(o) => { - path = o; - (&path, false) - } + Some(o) => (o, false), None => continue, }, }; @@ -242,9 +243,13 @@ fn encode_input_within(doc: &Document, ids: &[NodeId], kinds: &[InputKind], mut if !std::mem::take(&mut first) { out.push(b','); } - if serde_json::to_writer(&mut out, o).is_err() { + let object = out.len(); + if serde_json::to_writer(&mut out, &o).is_err() { return Ok((Vec::new(), HashMap::new())); } + if checked { + read_only.insert(n.id, object..out.len()); + } let size = out.len() - start; // A path or compound path past what is left fails the run as the runtime would fail it, // before the rest of the selection is written. @@ -291,7 +296,8 @@ fn affine_json(xf: Affine) -> Value { /// - an image (`"image"`): `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`, /// `linked`, `pixelsOmitted`, and for an embedded image of at most [`MAX_INPUT_PIXELS`] /// `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top (a CMYK image's inks -/// through the working CMYK profile). A linked image's file and path are never read or given; +/// through the working CMYK profile, as sRGB). A linked image's file and path are never read or +/// given; /// - a symbol instance (`"symbolInstance"`): `symbolId` (the symbol's name), `missing: true` when /// the document has no such symbol, and `overrides: {}`. pub fn encode_read_only(doc: &Document, n: &Node) -> Option { @@ -354,13 +360,13 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left NodeKind::Image(im) => { let blob = doc.image_blob(im); let max = MAX_INPUT_PIXELS.min(left.pixels).min(room.saturating_sub(PIXELS_KEY)); + let mut charged = 0; // A linked image's pixels are its file's: never given (nor its path). - let pixels = blob.filter(|_| im.link.is_none()).and_then(|b| rgba_pixels(b, im.width, im.height, max)); + let pixels = blob.filter(|_| im.link.is_none()).and_then(|b| rgba_pixels(b, im.width, im.height, max, &mut charged)); + left.pixels = left.pixels.saturating_sub(charged); o["pixelsOmitted"] = json!(pixels.is_none()); if let Some(p) = pixels { - let b64 = craft_vectorcraft_format::base64::encode(&p); - left.pixels = left.pixels.saturating_sub(b64.len()); - o["pixelsBase64"] = json!(b64); + o["pixelsBase64"] = json!(craft_vectorcraft_format::base64::encode(&p)); } } _ => {} @@ -458,20 +464,34 @@ fn color_mode(b: &ImageBlob) -> &'static str { if readable.is_some() { "rgb" } else { "unknown" } } +#[cfg(test)] +thread_local! { + /// How many images [`rgba_pixels`] has started to decode on this thread. + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The pixels of image `b` as straight RGBA, when it is `w` × `h` pixels and they fit `max` /// characters of base64; the size is checked, and read from the header, before anything is decoded. -fn rgba_pixels(b: &ImageBlob, w: u32, h: u32, max: usize) -> Option> { +/// `charged` gets the characters of base64 an image that reaches the decoder takes from the total, +/// which it takes even when decoding fails. +fn rgba_pixels(b: &ImageBlob, w: u32, h: u32, max: usize, charged: &mut usize) -> Option> { let bytes = u64::from(w).checked_mul(u64::from(h))?.checked_mul(4)?; - if bytes == 0 || bytes.div_ceil(3).saturating_mul(4) > max as u64 || oversized_tiff(&b.bytes).is_some() { + let cost = bytes.div_ceil(3).saturating_mul(4); + if bytes == 0 || cost > max as u64 || oversized_tiff(&b.bytes).is_some() { return None; } - if b.is_cmyk() { - return cmyk_rgba(b, w, h); - } + let cmyk = b.is_cmyk(); let reader = || image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok(); - if reader()?.into_dimensions().ok()? != (w, h) { + let size = if cmyk { b.header_size()? } else { reader()?.into_dimensions().ok()? }; + if size != (w, h) { return None; } + *charged = cost as usize; + #[cfg(test)] + DECODES.with(|n| n.set(n.get() + 1)); + if cmyk { + return cmyk_rgba(b, w, h); + } let mut r = reader()?; let mut limits = image::Limits::default(); // The decoder's own buffers besides the RGBA it gives. @@ -484,13 +504,10 @@ fn rgba_pixels(b: &ImageBlob, w: u32, h: u32, max: usize) -> Option> { /// The inks → XYZ table of [`cmyk_rgba`] and the color settings it was built with. static CMYK_DISPLAY: Mutex, Arc)>> = Mutex::new(None); -/// The pixels of CMYK image `b` as straight RGBA, when it is `w` × `h` pixels (checked from its -/// header first): its inks shown through the working CMYK profile, by a table built as -/// `vectorcraft-render`'s `InkLut` builds its own and kept for the active color settings. +/// The pixels of CMYK image `b` as straight RGBA, when it is `w` × `h` pixels: its inks shown +/// through the working CMYK profile, by a table built as `vectorcraft-render`'s `InkLut` builds its +/// own and kept for the active color settings. fn cmyk_rgba(b: &ImageBlob, w: u32, h: u32) -> Option> { - if b.header_size()? != (w, h) { - return None; - } let inks = b.cmyk().filter(|i| (i.width, i.height) == (w, h))?; let lut = { let cms = cms::active(); @@ -761,16 +778,18 @@ pub struct Output { /// Parses a filter's output: `{"objects": [...], "documentData"?: …}`, or `{"error": "message"}` /// when the plug-in declined (the message reaches the user). pub fn decode_output(bytes: &[u8]) -> Result { - decode_output_with(bytes, &HashMap::new()) + decode_output_with(bytes, &[], &HashMap::new()) } -/// [`decode_output`] for a filter given `read_only` objects ([`encode_input_with`]): it must list -/// each of them exactly once, as `{"id": …}` alone or exactly as it was given (numbers compared by -/// value), and such an entry is [`OutObject::kept`]. Any other entry for one of them, and one left -/// out, is refused naming the object and the first field that differs, before anything changes. -pub fn decode_output_with(bytes: &[u8], read_only: &HashMap) -> Result { +/// [`decode_output`] for a filter given `read_only` objects, at those places in `input` +/// ([`encode_input_with`]): it must list each of them exactly once, as `{"id": …}` alone or exactly +/// as it was given (numbers compared by value), and such an entry is [`OutObject::kept`]. Any other +/// entry for one of them, and one left out, is refused naming the object and the first field that +/// differs, before anything changes. Each object is parsed from `input` only to compare it, one at +/// a time, and an object that can't be read from there is an error. +pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) -> Result { let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; - let objects = decode_objects(&v, read_only)?; + let objects = decode_objects(&v, input, read_only)?; let document_data = match v.get_mut("documentData").map(Value::take) { None => None, Some(Value::Null) => Some(None), @@ -789,12 +808,12 @@ pub fn decode_output_with(bytes: &[u8], read_only: &HashMap) -> R /// declined (the message reaches the user). A live effect's other keys don't matter. pub fn decode(bytes: &[u8]) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; - decode_objects(&v, &HashMap::new()) + decode_objects(&v, &[], &HashMap::new()) } /// The objects of output `v`, or its decline; entries for `read_only` objects as /// [`decode_output_with`] reads them. -fn decode_objects(v: &Value, read_only: &HashMap) -> Result> { +fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result> { if let Some(e) = declined(v) { return Err(e); } @@ -808,12 +827,16 @@ fn decode_objects(v: &Value, read_only: &HashMap) -> Result { + Some((id, span)) => { let at = format!("objects[{i}] (id {})", id.0); if !returned.insert(id) { return Err(out_err(&at, "is listed twice")); } - check_unchanged(o, given, &at)?; + // `{"id": …}` alone keeps the object, so there is nothing to compare it with. + if o.as_object().is_none_or(|m| m.len() != 1) { + let given = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?; + check_unchanged(o, &given, &at)?; + } Ok(OutObject { id: Some(id), kept: true, ..OutObject::default() }) } None => decode_object(o, &format!("objects[{i}]"), &mut anchors), @@ -836,15 +859,12 @@ fn output_id(o: &Value) -> Option { id.as_u64().or_else(|| id.as_f64().filter(|f| f.fract() == 0.0 && (0.0..=9_007_199_254_740_992.0).contains(f)).map(|f| f as u64)).map(NodeId) } -/// Checks entry `o` of a filter's output for a read-only object it was `given`: `{"id": …}` alone, -/// or `given` itself, numbers compared by value. Otherwise the error names the first field that -/// differs (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as +/// Checks entry `o` of a filter's output for a read-only object it was `given`: `given` itself, +/// numbers compared by value. Otherwise the error names the first field that differs +/// (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as /// [`crate::permissions::display_text`] shows a manifest string, since the entry's keys are the /// plug-in's. fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> { - if o.as_object().is_some_and(|m| m.len() == 1) { - return Ok(()); - } let changed = match (o, given) { (Value::Object(x), Value::Object(y)) => { let mut keys: Vec<&String> = x.keys().collect(); diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 0a7b1d0d12..ba4cccae21 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -481,6 +481,212 @@ fn cmyk_image_pixels_go_through_the_working_cmyk_profile() { assert_ne!(&pixels[..3], &[0, 0, 0], "not converted without the profile"); } +/// The image object for `key` in `d`'s layer, `size` pixels. +fn placed(d: &mut Document, layer: NodeId, key: &str, size: (u32, u32)) -> NodeId { + let n = image_node(d, key, size, None); + d.insert(Some(layer), usize::MAX, n).unwrap() +} + +/// The largest pixels one image may have fill exactly [`MAX_INPUT_PIXELS`] characters of base64 +/// (512 × 384); one pixel more doesn't fit. +#[test] +fn an_image_at_the_limit_is_given_and_one_pixel_more_is_omitted() { + let (mut d, _, layer, _) = mixed(); + for ((w, h), omitted) in [((512, 384), false), ((1, 196_609), true)] { + d.images.insert("limit".into(), ImageBlob::png(png(w, h))); + let id = placed(&mut d, layer, "limit", (w, h)); + let o = encode_read_only(&d, d.node(id).unwrap()).unwrap(); + assert_eq!(o["pixelsOmitted"], json!(omitted), "{w} × {h}"); + assert_eq!(o.get("pixelsBase64").and_then(Value::as_str).map(str::len), (!omitted).then_some(MAX_INPUT_PIXELS), "{w} × {h}"); + } +} + +/// Sixteen images at the per-image limit fill [`MAX_INPUT_PIXELS_TOTAL`] exactly and are all given; +/// the next one in paint order, even a small one, comes with `pixelsOmitted`. +#[test] +fn images_fill_the_pixel_total_and_the_next_is_omitted() { + let (mut d, _, layer, [_, embedded, ..]) = mixed(); + d.images.insert("limit".into(), ImageBlob::png(png(512, 384))); + let mut ids: Vec = (0..16).map(|_| placed(&mut d, layer, "limit", (512, 384))).collect(); + ids.push(embedded); + let (bytes, _) = encode_input_with(&d, &ids, &[InputKind::Image], usize::MAX).unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + let objects = v["objects"].as_array().unwrap(); + assert_eq!(objects.len(), 17); + let given: usize = objects.iter().filter_map(|o| o.get("pixelsBase64")?.as_str()).map(str::len).sum(); + assert_eq!(given, MAX_INPUT_PIXELS_TOTAL); + let omitted: Vec = objects.iter().map(|o| o["pixelsOmitted"] == json!(true)).collect(); + assert_eq!(omitted, [vec![false; 16], vec![true]].concat()); +} + +/// Type whose runs and paragraphs together fill [`MAX_INPUT_TEXT_TOTAL`] exactly is all given, and +/// type after it in paint order comes with `truncated`. With one byte more, the last type that +/// doesn't fit comes with `truncated` and what it leaves still goes to the type after it. +#[test] +fn type_fills_the_text_total_and_what_follows_is_truncated() { + use vectorcraft_doc::{CharStyle, TextObject}; + let (mut d, _, layer, _) = mixed(); + let place = |d: &mut Document, len: usize| { + let t = TextObject::point(Point::new(0.0, 0.0), &"x".repeat(len), CharStyle::default()); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + d.insert(Some(layer), usize::MAX, n).unwrap() + }; + let one = place(&mut d, 1); + let o = encode_read_only(&d, d.node(one).unwrap()).unwrap(); + // Everything but the text itself, with the commas between runs and paragraphs and without + // their brackets. + let overhead: usize = ["runs", "paragraphs"].iter().map(|k| o["text"][k].to_string().len() - 2).sum::() - 1; + let full = overhead + MAX_INPUT_TEXT; + let count = MAX_INPUT_TEXT_TOTAL / full; + let rest = MAX_INPUT_TEXT_TOTAL - count * full - overhead; + assert!((1..=MAX_INPUT_TEXT).contains(&rest)); + for (filler, truncated) in [(rest, [false, true]), (rest + 1, [true, false])] { + let mut ids: Vec = (0..count).map(|_| place(&mut d, MAX_INPUT_TEXT)).collect(); + ids.push(place(&mut d, filler)); + ids.push(one); + let (bytes, _) = encode_input_with(&d, &ids, &[InputKind::Type], usize::MAX).unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + let objects = v["objects"].as_array().unwrap(); + assert_eq!(objects.len(), count + 2); + assert!(objects[..count].iter().all(|o| o["truncated"] == json!(false)), "filler {filler}"); + assert_eq!([&objects[count]["truncated"], &objects[count + 1]["truncated"]], truncated.map(|t| json!(t)).each_ref(), "filler {filler}"); + } +} + +/// A CMYK TIFF `w` × `h` pixels of no ink. +fn cmyk_blob(w: u32, h: u32) -> ImageBlob { + let inks = vectorcraft_doc::cmyk::Inks::new(w, h, vec![0; (w * h * 4) as usize]).unwrap(); + ImageBlob::cmyk_tiff(&inks).unwrap() +} + +/// `blob`, a little-endian TIFF, with its strip offset past the end of the file: its header still +/// reads and its pixels don't. +fn without_strips(blob: &ImageBlob) -> ImageBlob { + let mut bytes = blob.bytes.to_vec(); + assert_eq!(&bytes[..2], b"II"); + let word = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) as usize; + let ifd = word(&bytes, 4); + let count = usize::from(u16::from_le_bytes([bytes[ifd], bytes[ifd + 1]])); + let entry = (0..count).map(|i| ifd + 2 + i * 12).find(|&e| bytes[e..e + 2] == 273u16.to_le_bytes()).unwrap(); + let past = (bytes.len() as u32 + 4096).to_le_bytes(); + bytes[entry + 8..entry + 12].copy_from_slice(&past); + ImageBlob::png(bytes) +} + +/// An image that can't be given isn't decoded: past the per-image limit, past what is left of the +/// total, once the total is used up, when its header disagrees with its object, and when it is +/// linked, a CMYK image as much as any other. One that fits is decoded once. +#[test] +fn an_image_that_cannot_be_given_is_not_decoded() { + let (mut d, _, layer, [_, embedded, linked, ..]) = mixed(); + d.images.insert("big".into(), ImageBlob::png(png(1, 196_609))); + d.images.insert("k".into(), cmyk_blob(2, 1)); + let big = placed(&mut d, layer, "big", (1, 196_609)); + let wrong = placed(&mut d, layer, "e", (3, 1)); + let cmyk = placed(&mut d, layer, "k", (2, 1)); + let cmyk_wrong = placed(&mut d, layer, "k", (3, 1)); + let within = |pixels: usize| Allowance { pixels, ..Allowance::FULL }; + for (id, left, omitted, decodes, what) in [ + (big, Allowance::FULL, true, 0, "past the per-image limit"), + (embedded, within(11), true, 0, "past what is left of the total"), + (embedded, within(0), true, 0, "the total used up"), + (wrong, Allowance::FULL, true, 0, "another size than its object"), + (linked, Allowance::FULL, true, 0, "linked"), + (embedded, within(12), false, 1, "fits"), + (cmyk, within(11), true, 0, "CMYK past what is left of the total"), + (cmyk_wrong, Allowance::FULL, true, 0, "CMYK of another size than its object"), + (cmyk, within(12), false, 1, "CMYK that fits"), + ] { + DECODES.with(|n| n.set(0)); + let (bytes, _) = encode_input_within(&d, &[id], &[InputKind::Image], left).unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(v["objects"][0]["pixelsOmitted"], json!(omitted), "{what}"); + assert_eq!(DECODES.with(|n| n.get()), decodes, "{what}"); + } +} + +/// An image that reaches the decoder and fails takes its size from the total, a broken CMYK image +/// as much as a broken PNG: the next image doesn't fit what the broken one left. +#[test] +fn an_image_that_fails_to_decode_takes_from_the_total() { + let (mut d, _, layer, [_, embedded, ..]) = mixed(); + let mut png_data = png(2, 1); + let idat = png_data.windows(4).position(|w| w == b"IDAT").unwrap(); + png_data[idat + 6] ^= 0xFF; + for (what, blob, expect_cmyk) in [("PNG", ImageBlob::png(png_data), false), ("CMYK", without_strips(&cmyk_blob(2, 1)), true)] { + assert_eq!(blob.is_cmyk(), expect_cmyk, "{what}"); + d.images.insert("broken".into(), blob); + let bad = placed(&mut d, layer, "broken", (2, 1)); + let omitted = |pixels: usize| { + DECODES.with(|n| n.set(0)); + let left = Allowance { pixels, ..Allowance::FULL }; + let (bytes, _) = encode_input_within(&d, &[bad, embedded], &[InputKind::Image], left).unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + (v["objects"][0]["pixelsOmitted"].clone(), v["objects"][1]["pixelsOmitted"].clone(), DECODES.with(|n| n.get())) + }; + assert_eq!(omitted(12), (json!(true), json!(true), 1), "{what}: one decode fits 12 characters"); + assert_eq!(omitted(24), (json!(true), json!(false), 2), "{what}: the next image fits what is left"); + } +} + +/// Runs in one paragraph keep their own leading: each run comes with its character attributes, and +/// the paragraph is one paragraph style. +#[test] +fn runs_in_one_paragraph_keep_their_own_leading() { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + let (mut d, _, layer, _) = mixed(); + let mut t = TextObject::point(Point::new(0.0, 0.0), "", CharStyle::default()); + let leading = CharStyle { leading: Some(14.0), ..CharStyle::default() }; + t.runs = vec![TextRun::new("a".to_string(), leading), TextRun::new("b".to_string(), CharStyle::default())]; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let o = encode_read_only(&d, d.node(id).unwrap()).unwrap(); + assert_eq!(o["text"]["runs"][0]["style"]["leading"], json!(14.0)); + assert_eq!((&o["text"]["runs"][1]["text"], &o["text"]["runs"][1]["style"]["leading"]), (&json!("b"), &Value::Null)); + assert_eq!(o["text"]["paragraphs"].as_array().unwrap().len(), 1); +} + +/// Each read-only object's place in the input holds that object, pixels included, and the input's +/// paths have no place. An output that echoes an object is compared with what that place holds; an +/// input that doesn't hold it refuses the output, as the host's own error rather than the +/// plug-in's. +#[test] +fn read_only_objects_are_read_from_their_place_in_the_input_and_fail_closed() { + let (d, ids, _, [text, embedded, ..]) = mixed(); + let order = [ids[0], text, embedded]; + let (bytes, read_only) = encode_input_with(&d, &order, &InputKind::ALL, usize::MAX).unwrap(); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(read_only.len(), 2); + let at = |id: NodeId| serde_json::from_slice::(&bytes[read_only[&id].clone()]).unwrap(); + assert_eq!(at(text), v["objects"][1]); + assert_eq!(at(embedded), v["objects"][2]); + assert!(at(embedded)["pixelsBase64"].is_string()); + let echo = json!({"objects": [v["objects"][1], v["objects"][2]]}).to_string(); + assert!(decode_output_with(echo.as_bytes(), &bytes, &read_only).is_ok()); + let garbage = vec![b'x'; bytes.len()]; + for input in [garbage.as_slice(), b"not json", br#"{"objects":[]}"#, b"{}", b""] { + let e = decode_output_with(echo.as_bytes(), input, &read_only).unwrap_err().to_string(); + assert!(!e.starts_with("plug-in"), "{e}"); + } + // `{"id": …}` alone needs nothing from the input. + let kept = json!({"objects": [{"id": text.0}, {"id": embedded.0}]}).to_string(); + assert!(decode_output_with(kept.as_bytes(), b"", &read_only).is_ok()); +} + +/// A path's effect parameters can nest deeper than the JSON reader goes. Checking the output reads +/// only the read-only objects from the input, so such a path beside one doesn't fail the run. +#[test] +fn a_path_nested_past_the_json_reader_beside_a_read_only_object_passes_the_check() { + let (mut d, ids, _, [text, ..]) = mixed(); + let params = (0..200).fold(json!(1), |inner, _| json!([inner])); + d.node_mut(ids[0]).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "x".into(), params, visible: true }); + let (bytes, read_only) = encode_input_with(&d, &[ids[0], text], &[InputKind::Type], usize::MAX).unwrap(); + assert!(serde_json::from_slice::(&bytes).is_err(), "the input is deeper than the reader goes"); + let echo = serde_json::from_slice::(&bytes[read_only[&text].clone()]).unwrap(); + let out = decode_output_with(json!({"objects": [echo]}).to_string().as_bytes(), &bytes, &read_only).unwrap(); + assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 1); +} + /// A symbol instance comes with the symbol it shows and its transform, never its art; one whose /// symbol the document lacks says so. #[test] @@ -521,7 +727,7 @@ fn input_totals_cover_images_and_type_in_order() { assert!(objects[1]["text"]["runs"].as_array().unwrap().is_empty() && objects[4].get("pixelsBase64").is_none()); assert_eq!(objects[3]["pixelsBase64"], encode_read_only(&d, d.node(embedded).unwrap()).unwrap()["pixelsBase64"]); for o in objects { - assert_eq!(Some(o), read_only.get(&NodeId(o["id"].as_u64().unwrap()))); + assert!(read_only.contains_key(&NodeId(o["id"].as_u64().unwrap()))); } // Within the full totals every one of them is given. let (bytes, _) = encode_input_with(&d, &ids, &InputKind::ALL, usize::MAX).unwrap(); @@ -689,7 +895,7 @@ fn a_changed_field_is_named_escaped_and_short() { let at = v["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(text.0)).unwrap(); let key = format!("\u{202E}{}", "k".repeat(500)); v["objects"][at][key.as_str()] = json!(1); - let e = decode_output_with(v.to_string().as_bytes(), &read_only).unwrap_err().to_string(); + let e = decode_output_with(v.to_string().as_bytes(), &bytes, &read_only).unwrap_err().to_string(); let shown = e.split('\'').nth(1).unwrap_or_default(); assert!(!e.contains('\u{202E}') && shown.starts_with("\\u{202E}kkk") && shown.ends_with('…'), "{e}"); assert_eq!(shown.chars().count(), crate::permissions::MAX_SHOWN_FIELD, "{e}"); @@ -707,7 +913,7 @@ fn read_only_kind_field_and_omission_refuse() { assert_eq!(read_only.len(), 5); let input: Value = serde_json::from_slice(&bytes).unwrap(); let before = d.clone(); - let out = decode_output_with(&bytes, &read_only).unwrap(); + let out = decode_output_with(&bytes, &bytes, &read_only).unwrap(); assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5); apply_output(&mut d, &targets, out.objects, None, &keep).unwrap(); assert_eq!(d, before, "an exact echo changes nothing"); @@ -716,19 +922,20 @@ fn read_only_kind_field_and_omission_refuse() { // Numbers written another way are the same numbers. let mut echo = input.clone(); echo["objects"][3]["transform"] = json!([1, 0, 0, 1, 5, 50]); - assert!(decode_output_with(echo.to_string().as_bytes(), &read_only).is_ok()); + assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_ok()); // So is an id written as a float; a fractional one names no object. let id = input["objects"][3]["id"].as_u64().unwrap(); let mut echo = input.clone(); echo["objects"][3]["id"] = json!(id as f64); - let out = decode_output_with(echo.to_string().as_bytes(), &read_only).unwrap(); + let out = decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).unwrap(); assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5); echo["objects"][3]["id"] = json!(id as f64 + 0.5); - assert!(decode_output_with(echo.to_string().as_bytes(), &read_only).is_err()); + assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_err()); // `{"id"}` alone keeps it; the paths left out are deleted and a new path goes above the type. let ro = |id: NodeId| json!({"id": id.0}); let out = json!({"objects": [ro(text), {"name": "new", "path": square(0.0)}, ro(embedded), ro(linked), ro(star), ro(ghost)]}); - let made = apply_output(&mut d, &targets, decode_output_with(out.to_string().as_bytes(), &read_only).unwrap().objects, None, &keep).unwrap(); + let made = + apply_output(&mut d, &targets, decode_output_with(out.to_string().as_bytes(), &bytes, &read_only).unwrap().objects, None, &keep).unwrap(); assert_eq!(names(&d, layer), ["?", "?", "T", "new", "E", "L", "S", "G"]); assert_eq!(made.len(), 6); assert!(ids.iter().all(|id| d.node(*id).is_none())); @@ -767,7 +974,7 @@ fn read_only_kind_field_and_omission_refuse() { "`type` must be \"path\" or \"compound\"".to_string(), ), ] { - let e = decode_output_with(out.to_string().as_bytes(), &read_only).unwrap_err().to_string(); + let e = decode_output_with(out.to_string().as_bytes(), &bytes, &read_only).unwrap_err().to_string(); assert!(e.contains(&says), "{says}: {e}"); } // Writing one or leaving one out is refused when applying too, whatever decoded the output. diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index b2f830778e..be7f12180f 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -165,7 +165,9 @@ pub fn load_folder(dir: &std::path::Path) -> Result { /// permissions only those `approve` accepts; the others are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and /// skipped, by its file before it loads or by its id after (its file is then disabled too, so the /// next load skips it before it runs); the launch marker names each file while it loads -/// ([`crate::safe_mode::loading`]). In Safe Mode nothing loads ([`Error::SafeMode`]). +/// ([`crate::safe_mode::loading`]). In Safe Mode nothing loads ([`Error::SafeMode`]). When the +/// module a load leaves under an id lists no permissions, the process's grant for that id is +/// forgotten. #[cfg(not(target_arch = "wasm32"))] pub fn load_folder_where( dir: &std::path::Path, @@ -213,6 +215,11 @@ pub fn load_folder_where( Err(e) => report.failed.push((f.display().to_string(), e.to_string())), } } + for id in &report.loaded { + if get(id).is_some_and(|p| !p.manifest().asks_permissions()) { + revoke(id); + } + } Ok(report) } 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..9bc9ba7565 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,61 @@ 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 art = effects::revolve_art(n).or_else(|| effects::solid_art(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..75143f9a06 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(a).or_else(|| effects::solid_art(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..5c4474b229 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,608 @@ 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:?}"); +} + +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 +1762,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/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..5ccb3f0b9c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -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/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(" bool { + matches!( + c as u32, + 0x0610..=0x061A + | 0x064B..=0x065F + | 0x0670 + | 0x06D6..=0x06DC + | 0x06DF..=0x06E4 + | 0x06E7..=0x06E8 + | 0x06EA..=0x06ED + | 0x08D3..=0x08FF + ) +} + +/// Do character styles `a` and `b` differ, if at all, only in paint: fill, stroke and how the +/// stroke is drawn, overprint, and the character style name? Those are not read by the shaper +/// and change no glyph, advance or position. Stricter than [`crate::shape`]'s `shapes_alike` +/// (which also ignores baseline shift, tracking, underline, …). +pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { + // Exhaustive: a new attribute must explicitly keep or relax this boundary rule. + let CharStyle { + font_family, + font_style, + font_version, + font_axes, + size, + leading, + tracking, + kerning, + optical_kerning, + baseline_shift, + h_scale, + v_scale, + rotation, + underline, + strikethrough, + all_caps, + features, + position, + small_caps, + char_align, + char_direction, + kashidas, + proportional_metrics, + tate_chu_yoko, + tcy_up_down, + tcy_left_right, + standard_vertical_roman, + digits, + font_height_reference, + no_break, + language, + glyph_alternate, + fill, + stroke, + stroke_width, + stroke_miter_limit, + stroke_dash, + overprint_fill: _, + overprint_stroke: _, + stroke_cap: _, + stroke_join: _, + stroke_align: _, + style_name: _, + } = a; + // Previously b's paint was replaced with a's before comparing the whole styles. Keep + // that PartialEq behavior for non-reflexive paint values (NaN), without cloning paint. + let original_paint = (&a.fill, &a.stroke, &a.stroke_width, &a.stroke_miter_limit, &a.stroke_dash); + let normalized_paint = (fill, stroke, stroke_width, stroke_miter_limit, stroke_dash); + original_paint == normalized_paint + && font_family == &b.font_family + && font_style == &b.font_style + && font_version == &b.font_version + && font_axes == &b.font_axes + && size == &b.size + && leading == &b.leading + && tracking == &b.tracking + && kerning == &b.kerning + && optical_kerning == &b.optical_kerning + && baseline_shift == &b.baseline_shift + && h_scale == &b.h_scale + && v_scale == &b.v_scale + && rotation == &b.rotation + && underline == &b.underline + && strikethrough == &b.strikethrough + && all_caps == &b.all_caps + && features == &b.features + && position == &b.position + && small_caps == &b.small_caps + && char_align == &b.char_align + && char_direction == &b.char_direction + && kashidas == &b.kashidas + && proportional_metrics == &b.proportional_metrics + && tate_chu_yoko == &b.tate_chu_yoko + && tcy_up_down == &b.tcy_up_down + && tcy_left_right == &b.tcy_left_right + && standard_vertical_roman == &b.standard_vertical_roman + && digits == &b.digits + && font_height_reference == &b.font_height_reference + && no_break == &b.no_break + && language == &b.language + && glyph_alternate == &b.glyph_alternate +} + +/// Is the run boundary at byte `at` of `text`, between styles `before` and `after`, one that +/// stays inside a shaping cluster: they differ only in paint and a harakat is on either side? +pub(crate) fn paint_only_mark_boundary(text: &str, at: usize, before: &CharStyle, after: &CharStyle) -> bool { + let next = text.get(at..).and_then(|s| s.chars().next()); + let previous = text.get(..at).and_then(|s| s.chars().next_back()); + (next.is_some_and(is_harakat) || previous.is_some_and(is_harakat)) && paint_only(before, after) +} + +/// The byte ranges of the harakat in `text[range]`, each run of consecutive harakat as one range. +/// The range is normalised as [`crate::edit::style_range`] takes one: its ends clamped to the +/// text, each moved back to the start of the character it falls in, and put in order. +#[cfg(test)] +pub(crate) fn harakat_ranges(text: &str, range: std::ops::Range) -> Vec> { + let (mut start, mut end) = (crate::edit::floor_char(text, range.start), crate::edit::floor_char(text, range.end)); + if start > end { + std::mem::swap(&mut start, &mut end); + } + let Some(part) = text.get(start..end) else { + return vec![]; + }; + let mut out: Vec> = vec![]; + for (i, c) in part.char_indices().filter(|(_, c)| is_harakat(*c)) { + let (a, b) = (start + i, start + i + c.len_utf8()); + match out.last_mut() { + Some(last) if last.end == a => last.end = b, + _ => out.push(a..b), + } + } + out +} + +/// Does `face`'s GDEF GlyphClassDef name glyph `gid` as class 3 (mark)? False when the face has +/// no GDEF, no class def, or the class is unavailable (typical of AAT/`morx` paths). +#[cfg(test)] +pub(crate) fn is_gdef_mark(face: &FontFace, gid: u32) -> bool { + mark_classes(face).as_ref().is_some_and(|classes| classes.get(skrifa::GlyphId::new(gid)) == 3) +} + +/// Borrow the face's mark classification once for a shaping pass. No GDEF, missing classes +/// or malformed tables keep the conservative cluster-start ownership. +pub(crate) fn mark_classes(face: &FontFace) -> Option> { + face.skrifa()?.gdef().ok()?.glyph_class_def()?.ok() +} + +/// Each glyph's own character, from the shaping `by_char` at character cluster level of the +/// glyphs `raw` (glyph id, cluster, x advance, x and y offset; `by_char` with the y advance after +/// the x advance), the segment ending at byte `end`, and `text` for character identity. +/// `is_gdef_mark(gid)` is true only when the face's GDEF GlyphClassDef names that glyph class 3. +/// Empty unless `by_char` sets the same glyphs the same way (glyph id, advance and offsets, glyph +/// by glyph): repeated glyph ids alone could hide a changed correspondence. A glyph whose character +/// lies outside its own shaping cluster of `raw` (from its cluster value up to the next larger one, +/// else `end`) gets its cluster's first character instead. A later in-cluster character is kept +/// only when the glyph is a GDEF mark and that character is a harakat; otherwise the cluster start +/// is kept (conservative: a mark may miss its colour; a base must never take a mark's). `raw`'s +/// clusters are never changed. These are HarfBuzz shaping clusters, which can span more than one +/// grapheme (a ligature). +pub(crate) fn own_chars( + raw: &[(u32, u32, i32, i32, i32)], + by_char: &[(u32, u32, i32, i32, i32, i32)], + end: usize, + text: &str, + is_gdef_mark: impl Fn(u32) -> bool, +) -> Vec { + let same = by_char.len() == raw.len() && by_char.iter().zip(raw).all(|(c, r)| c.0 == r.0 && c.2 == r.2 && c.4 == r.3 && c.5 == r.4); + if !same { + return vec![]; + } + let mut starts: Vec = raw.iter().map(|g| g.1).collect(); + starts.sort_unstable(); + starts.dedup(); + let cluster_end = |cl: u32| starts.get(starts.partition_point(|&c| c <= cl)).map_or(end, |&c| c as usize); + by_char + .iter() + .zip(raw) + .map(|(c, r)| { + let in_cluster = r.1 <= c.1 && (c.1 as usize) < cluster_end(r.1); + if !in_cluster { + return r.1; + } + if c.1 == r.1 { + return c.1; + } + // Later in-cluster character: only a positively identified mark glyph on a harakat. + let mark_char = text.get(c.1 as usize..).and_then(|s| s.chars().next()).is_some_and(is_harakat); + if is_gdef_mark(r.0) && mark_char { c.1 } else { r.1 } + }) + .collect() +} diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 9d96dca049..8e594c0369 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -503,11 +503,22 @@ impl Ctx<'_> { }); } + /// Source-run index covering byte `b` (the cluster start for a letter with its marks). + fn run_index_at(&self, b: usize) -> Option { + let find = |b: usize| { + let i = self.runs.partition_point(|(r, _)| r.end <= b); + self.runs.get(i).filter(|(r, _)| r.start <= b).map(|_| i) + }; + find(b).or_else(|| b.checked_sub(1).and_then(find)) + } + /// Draw a kashida `len` points long from `at` (the pen on the baseline) on line `line`, as /// tatweels in the face, size and style of glyph `g`. Short, Medium and Long kashidas are one /// tatweel stretched along the baseline; a Stylistic one is tatweels side by side. Each tatweel /// is a glyph at `g`'s byte offset that stands for no character (length 0) and does not - /// advance: `g`'s advance takes the kashida in. + /// advance: `g`'s advance takes the kashida in. Paint comes from the base letter's run at the + /// cluster start (`g.byte`), not from a trailing mark that may be the last glyph of the + /// cluster when harakat are coloured or hidden apart from their letters. fn emit_kashida(&mut self, g: &SGlyph, kind: Kashida, len: f64, at: Point, line: usize) { let Some((gid, t)) = kashida::tatweel(g) else { return }; let mut k = g.clone(); @@ -521,6 +532,10 @@ impl Ctx<'_> { k.ch = kashida::TATWEEL; k.inline = None; k.tcy = None; + // Base letter's run: `g` may be a mark (last in the shaping cluster) with mark paint. + if let Some(run) = self.run_index_at(g.byte) { + k.run = run; + } if kind == Kashida::Stylistic { let n = (len / t).round().clamp(1.0, kashida::MAX_TATWEELS) as usize; for m in 0..n { @@ -535,3 +550,167 @@ impl Ctx<'_> { #[cfg(test)] mod wrapping_tests; + +/// Forced mark-last kashida emitter: the absorbing glyph carries a mark run while the cluster +/// start is a letter run; the tatweel must take the letter run. Reverting the base-run assignment +/// in [`Ctx::emit_kashida`] fails these. +#[cfg(test)] +mod emit_kashida_mark_last { + use super::*; + use std::sync::Arc; + use vectorcraft_doc::color::{Color, Paint}; + + fn arabic_face() -> Option> { + let db = FontDb::global(); + ["Noto Sans Arabic", "Arial", "Tahoma", "Times New Roman"] + .into_iter() + .filter_map(|name| db.face(name, "Regular")) + .find(|face| face.covers('ب') && face.covers('\u{064E}') && face.covers('\u{0640}')) + } + + fn force_mark_last(mark_fill: Paint) { + let Some(face) = arabic_face() else { + eprintln!("SKIPPED: emit_kashida_mark_last; no Arabic face with tatweel"); + return; + }; + let Some((tat_gid, _)) = kashida::tatweel(&SGlyph { + face: Arc::clone(&face), + gid: 0, + byte: 0, + len: 2, + run: 0, + adv: 10.0, + dx: 0.0, + dy: 0.0, + kern_shift: 0.0, + sx: face.upem.recip() * 48.0, + sy: face.upem.recip() * 48.0, + bshift: 0.0, + rotation: 0.0, + ascent: 40.0, + descent: 10.0, + leading: 0.0, + cap: 30.0, + xh: 20.0, + ch: 'ب', + tcy: None, + inline: None, + word_end: false, + lead: 0.0, + proportional: false, + vpal: None, + level: Level::rtl(), + no_break: false, + vertical_roman: false, + cursive: true, + hyphen_language: crate::hyphen::Language::English, + }) else { + eprintln!("SKIPPED: emit_kashida_mark_last; face has no tatweel"); + return; + }; + let letter = CharStyle { font_family: face.family.clone(), size: 48.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let mut mark = letter.clone(); + mark.fill = mark_fill.clone(); + // "بَ": letter run 0 covers 0..2, mark run 1 covers 2..4. Cluster starts at byte 0. + let text = "بَ"; + let opts = LayoutOptions::default(); + let db = FontDb::global(); + let mut cx = Ctx { + on_path: false, + db, + text, + runs: vec![(0..2, &letter), (2..4, &mark)], + set_runs: Vec::new(), + inlines: vec![None, None], + faces: vec![std::cell::OnceCell::new(), std::cell::OnceCell::new()], + default: letter.clone(), + opts: &opts, + vertical: false, + system_layout: false, + fractional_widths: true, + upright_cluster: None, + out: TextLayout::default(), + }; + // Last visual glyph of the cluster: a mark that wrongly keeps the mark run (run 1). + let mut g = SGlyph { + face: Arc::clone(&face), + gid: face.glyph_for('\u{064E}'), + byte: 0, + len: 4, + run: 1, + adv: 0.0, + dx: 0.0, + dy: 0.0, + kern_shift: 0.0, + sx: face.upem.recip() * 48.0, + sy: face.upem.recip() * 48.0, + bshift: 0.0, + rotation: 0.0, + ascent: 40.0, + descent: 10.0, + leading: 0.0, + cap: 30.0, + xh: 20.0, + ch: '\u{064E}', + tcy: None, + inline: None, + word_end: false, + lead: 0.0, + proportional: false, + vpal: None, + level: Level::rtl(), + no_break: false, + vertical_roman: false, + cursive: true, + hyphen_language: crate::hyphen::Language::English, + }; + assert_ne!(g.run, 0, "precondition: absorbing glyph has mark run ≠ cluster-start run"); + assert_eq!(cx.style_at(g.byte).fill, letter.fill, "precondition: cluster start is letter paint"); + assert_eq!(mark.fill, mark_fill, "precondition: mark paint differs"); + cx.emit_kashida(&g, Kashida::Long, 20.0, Point::ZERO, 0); + let tatweels: Vec<_> = cx.out.glyphs.iter().filter(|pg| pg.gid == tat_gid && pg.len == 0).collect(); + assert!(!tatweels.is_empty(), "tatweel emitted"); + for t in tatweels { + assert_eq!(t.run, 0, "tatweel must use base letter run, not mark run {}", g.run); + let fill = cx.runs.get(t.run).map(|(_, s)| &s.fill).expect("run"); + assert_eq!(fill, &letter.fill, "tatweel paint is the letter's"); + assert_ne!(fill, &mark_fill, "tatweel must not inherit mark paint"); + } + // Without the base-run assignment, emit_kashida would keep g.run == 1. + g.run = 1; + let mut broken = Ctx { + on_path: false, + db, + text, + runs: vec![(0..2, &letter), (2..4, &mark)], + set_runs: Vec::new(), + inlines: vec![None, None], + faces: vec![std::cell::OnceCell::new(), std::cell::OnceCell::new()], + default: letter.clone(), + opts: &opts, + vertical: false, + system_layout: false, + fractional_widths: true, + upright_cluster: None, + out: TextLayout::default(), + }; + // Simulate the pre-fix path: clone run from the mark glyph only. + let mut k = g.clone(); + k.gid = tat_gid; + k.len = 0; + k.ch = kashida::TATWEEL; + // k.run stays 1 — what emit_kashida did before the fix. + broken.emit(&k, Affine::IDENTITY, Point::ZERO, 0.0, 0.0, 0); + assert_eq!(broken.out.glyphs[0].run, 1, "sanity: unrepaired path keeps mark run"); + } + + #[test] + fn coloured_mark_last_tatweel_uses_letter_run() { + force_mark_last(Paint::solid(Color::rgb8(200, 30, 30))); + } + + #[test] + fn hidden_mark_last_tatweel_uses_letter_run() { + force_mark_last(Paint::None); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 27d35c1703..cbc5157edd 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -19,6 +19,7 @@ pub mod embed; mod features; mod fontconfig; mod fontdb; +mod harakat; pub mod hyphen; mod justify; mod kashida; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 88f9a1f39c..b913c7cc28 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -8,7 +8,7 @@ use unicode_bidi::Level; use unicode_script::{Script, UnicodeScript}; use unicode_segmentation::UnicodeSegmentation; -use harfrust::{Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; +use harfrust::{BufferClusterLevel, Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; use kurbo::Shape; use skrifa::MetadataProvider; use skrifa::charmap::Charmap; @@ -1007,6 +1007,10 @@ struct Shaped { raw: Vec<(u32, u32, i32, i32, i32)>, proportional: Vec, vpal: Vec>, + /// Each glyph's own character (cluster at character level), when harakat are styled apart + /// from their letters and the character-level pass matches ([`crate::harakat`]); empty + /// otherwise (glyphs keep their shaping-cluster start). + chars: Vec, } fn is_mark(c: char) -> bool { @@ -1073,6 +1077,14 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe if !manual_ends.is_empty() { return shape_apart(manual_ends, out); } + // Harakat styled apart from their letters (paint only): shaped with them, each glyph then + // takes its own character's run ([`crate::harakat`]). + let mark_boundaries: Vec = boundaries() + .filter(|&b| run_at(b - 1).1 != run_at(b).1 && crate::harakat::paint_only_mark_boundary(text, b, run_at(b - 1).1, run_at(b).1)) + .collect(); + // Source run starts are sorted. Reuse their classification when checking cluster splits. + let styled_marks = !mark_boundaries.is_empty(); + let char_level = std::cell::Cell::new(false); // Shape the segment as if all of it were in `st`, with the features `more` on top. let shape_in = |st: &CharStyle, more: &[Feature]| { @@ -1083,12 +1095,15 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe .filter(|l| l.len() <= 35 && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')) .and_then(|l| l.parse::().ok()); let mut shaped = Shaped::default(); - let Shaped { raw, proportional, vpal } = &mut shaped; + let Shaped { raw, proportional, vpal, chars } = &mut shaped; let hb_shaped = face.hb().map(|hb| { let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build(); + // The baseline and character-level pass use exactly the same resolved features. + // Alternate positioning passes still resolve their own features, with `more` last. + let with_more = |resolved: Vec| resolved.into_iter().chain(more.iter().cloned()).collect::>(); + let along_features = with_more(feats.resolve(st)); // gid, cluster, x and y advance, x and y offset. let shape = |feats: &[Feature], direction: Direction| { - let feats: Vec = feats.iter().chain(more).cloned().collect(); let mut buf = UnicodeBuffer::new(); for (i, c) in text_seg.char_indices() { let cl = (range.start + i) as u32; @@ -1103,6 +1118,9 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe } buf.set_direction(direction); buf.guess_segment_properties(); + if char_level.get() { + buf.set_cluster_level(BufferClusterLevel::Characters); + } // The characters' language picks the font's forms for it (`locl`: Turkish keeps fi // apart and the dot on its i). if let Some(l) = &language { @@ -1119,8 +1137,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe } // A buffer whose characters name no script reads as `UNKNOWN`: its plan has none. let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN); - let plan = face.shape_plan(&shaper, buf.direction(), script, language.as_ref(), &feats); - let gb = shaper.shape(buf, ShapeOptions::new().features(&feats).plan(Some(&plan))); + let plan = face.shape_plan(&shaper, buf.direction(), script, language.as_ref(), feats); + let gb = shaper.shape(buf, ShapeOptions::new().features(feats).plan(Some(&plan))); gb.glyph_infos() .iter() .zip(gb.glyph_positions()) @@ -1128,13 +1146,25 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe .collect::>() }; let along = if level.is_rtl() { Direction::RightToLeft } else { Direction::LeftToRight }; - *raw = shape(&feats.resolve(st), along).into_iter().map(|(g, c, xa, _, xo, yo)| (g, c, xa, xo, yo)).collect(); + *raw = shape(&along_features, along).into_iter().map(|(g, c, xa, _, xo, yo)| (g, c, xa, xo, yo)).collect(); let raw = &*raw; let same_glyphs = |v: &[(u32, u32, i32, i32, i32, i32)]| v.len() == raw.len() && v.iter().zip(raw).all(|(a, b)| a.0 == b.0); + // The same shaping at character level names each glyph's own character (kept only when + // it sets the same glyphs alike, each character in its glyph's cluster). + if let Some(classes) = styled_marks.then(|| crate::harakat::mark_classes(face)).flatten() + // Without a mark glyph, no glyph can take a later character's paint. Avoid + // reshaping; the original clusters already give the conservative ownership. + && raw.iter().any(|g| classes.get(skrifa::GlyphId::new(g.0)) == 3) + { + char_level.set(true); + let by_char = shape(&along_features, along); + char_level.set(false); + *chars = crate::harakat::own_chars(raw, &by_char, range.end, text, |gid| classes.get(skrifa::GlyphId::new(gid)) == 3); + } if feats.proportional(st) { // `palt` is positioning only: the same glyphs set on their full widths tell which // advances it changed (kerning and the rest change both alike). - let full = shape(&feats.resolve_fixed_width(st), along); + let full = shape(&with_more(feats.resolve_fixed_width(st)), along); if same_glyphs(&full) { *proportional = full.iter().zip(raw).map(|(a, b)| a.2 != b.2).collect(); } @@ -1145,7 +1175,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe // and without either tell how it moves each and changes its advance down the column // (y up, advances negative). Which advances `vpal` itself changed comes from setting // them with it alone. - let ttb = |proportional, kerning| shape(&feats.resolve_vertical(st, proportional, kerning), Direction::TopToBottom); + let ttb = |proportional, kerning| shape(&with_more(feats.resolve_vertical(st, proportional, kerning)), Direction::TopToBottom); let (with, without, alone) = (ttb(true, true), ttb(false, false), ttb(true, false)); if same_glyphs(&with) && same_glyphs(&without) && same_glyphs(&alone) { *vpal = with @@ -1185,7 +1215,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe shaped }; let first_optical = if optical(range.start) { Some(range.start) } else { boundaries().find(|&b| optical(b)) }; - let Shaped { raw, proportional, vpal } = if let Some(first) = first_optical.filter(|_| !feats.vertical) { + let Shaped { raw, proportional, vpal, chars } = if let Some(first) = first_optical.filter(|_| !feats.vertical) { // The pair entering Optical keeps the left character's font kerning. Subsequent // Optical pairs use outline spacing, so font pair features stop at its second character. let optical_off = if first == range.start { @@ -1245,7 +1275,11 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe cluster_starts.dedup(); // A glyph is drawn in one style: where a cluster would take in characters of runs in different // styles, the runs are shaped apart, as runs that do not shape alike are. - let inside_clusters: Vec = boundaries().filter(|&b| cluster_starts.binary_search(&b).is_err() && run_at(b - 1).1 != run_at(b).1).collect(); + // Except at harakat styled apart only in paint ([`crate::harakat`]). + let inside_clusters: Vec = boundaries() + .filter(|&b| cluster_starts.binary_search(&b).is_err() && run_at(b - 1).1 != run_at(b).1) + .filter(|b| mark_boundaries.binary_search(b).is_err()) + .collect(); if !inside_clusters.is_empty() { return shape_apart(inside_clusters, out); } @@ -1305,6 +1339,11 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe for (gi, &(gid, cl, xa, xo, yo)) in raw.iter().enumerate() { let cl = cl as usize; let (run, gst) = run_at(cl); + // A glyph of a harakat styled apart takes its own character's run (paint only). + let run = match chars.get(gi).map(|&c| run_at(c as usize)) { + Some((own, own_st)) if crate::harakat::paint_only(gst, own_st) => own, + _ => run, + }; let end = cluster_end(cl); let last_in_cluster = gi + 1 == n || raw[gi + 1].1 as usize != cl; let ch = first_char(cl); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 68fe655280..2dd3c424c6 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -14,6 +14,7 @@ mod devanagari; mod embed; mod fit; mod hang; +mod harakat; mod inline; mod joiners; mod justify; diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs new file mode 100644 index 0000000000..c097fc48b9 --- /dev/null +++ b/crates/text/src/tests/harakat.rs @@ -0,0 +1,651 @@ +//! Arabic marks (harakat) styled apart from their letters ([`crate::harakat`]). +//! Layout cases need an Arabic face: craft-fonts' Noto Sans Arabic when the build has +//! `CRAFT_FONTS_DIR`, else an installed OpenType Arabic face. Without either they skip. + +use std::sync::Arc; + +use kurbo::{Affine, Point, Rect, Shape}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::text::Kashida; +use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; +use vectorcraft_geom::PathData; + +use crate::harakat::{harakat_ranges, is_gdef_mark, is_harakat, own_chars, paint_only, paint_only_mark_boundary}; +use crate::{FontDb, FontFace, PositionedGlyph, TextLayout, layout}; + +const FAMILY: &str = "Noto Sans Arabic"; +const VOCALIZED: &str = "بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ"; +/// Short vocalized word used to probe whether a face's shaped mark glyphs are GDEF class 3. +const GDEF_PROBE: &str = "بَبَب"; + +/// An OpenType Arabic face covering harakat whose shaped fixture glyphs include GDEF mark +/// (class 3) glyphs. Strict colour/ownership layout tests need that: without GDEF, production +/// correctly keeps the letter's paint and those assertions would fail. Fonts with coverage and +/// GSUB but no mark classes are skipped here; synthetic `own_chars` cases and +/// `installed_fonts_keep_their_glyphs_with_coloured_harakat` still cover the no-GDEF fallback. +fn arabic_face(test: &str) -> Option> { + let opentype = |face: &FontFace| { + use skrifa::raw::TableProvider; + face.skrifa().is_some_and(|f| f.gsub().is_ok()) + }; + let db = FontDb::global(); + let face = ["Noto Sans Arabic", "Arial", "Geeza Pro", "SF Arabic", "Tahoma", "Times New Roman"] + .into_iter() + .filter_map(|name| db.face(name, "Regular")) + .find(|face| { + if !(face.covers('ب') && face.covers('\u{064E}') && face.covers('\u{0640}') && opentype(face)) { + return false; + } + // Shape the probe: every zero-advance authored glyph must be a GDEF mark, and at least + // one must appear, so strict colour assertions match production ownership. + let shaped = layout(db, &text_with_harakat(GDEF_PROBE, &face.family, None)); + let marks: Vec<_> = shaped.glyphs.iter().filter(|g| g.len > 0 && g.advance.abs() < 1e-6).collect(); + !marks.is_empty() && marks.iter().all(|g| is_gdef_mark(face, g.gid)) + }); + match &face { + Some(face) => eprintln!("ASSERTIONS RUN: {test}; Arabic font {} {} (GDEF marks)", face.family, face.style), + None => { + eprintln!("SKIPPED: {test}; no OpenType Arabic font with harakat and GDEF mark classes (set CRAFT_FONTS_DIR or install one)") + } + } + face +} + +fn red() -> Paint { + Paint::solid(Color::rgb8(200, 30, 30)) +} + +fn style(family: &str) -> CharStyle { + CharStyle { font_family: family.into(), size: 48.0, ..CharStyle::default() } +} + +/// `text` in `family`, its harakat filled with `fill` (`None`: as the letters). +fn text_with_harakat(text: &str, family: &str, fill: Option) -> TextObject { + let mut t = TextObject::point(Point::ZERO, text, style(family)); + if let Some(fill) = fill { + for r in harakat_ranges(text, 0..text.len()) { + crate::edit::style_range(&mut t.runs, r.start, r.end, |st| st.fill = fill.clone()); + } + } + t +} + +/// One glyph's geometry, bit for bit: face, glyph id, cluster, pen position, transform, advance. +type Geometry = (u32, u32, usize, usize, [u64; 2], [u64; 6], u64); + +fn geometry(l: &TextLayout) -> Vec { + l.glyphs + .iter() + .map(|g| { + (g.font_id, g.gid, g.byte, g.len, [g.origin.x.to_bits(), g.origin.y.to_bits()], g.xf.as_coeffs().map(f64::to_bits), g.advance.to_bits()) + }) + .collect() +} + +fn painted(t: &TextObject, l: &TextLayout, fill: &Paint) -> usize { + l.glyphs.iter().filter(|g| run_of(t, g).style.fill == *fill).count() +} + +fn run_of<'a>(t: &'a TextObject, g: &PositionedGlyph) -> &'a vectorcraft_doc::TextRun { + t.runs.get(g.run).unwrap_or_else(|| panic!("glyph {} at byte {} names missing run {}", g.gid, g.byte, g.run)) +} + +type LetterGlyphs = std::collections::HashSet<(u32, u32)>; + +/// Glyphs drawn by the fixture's bare letters, including separately shaped letter dots. +/// Include the face id: glyph ids are only meaningful within their own font. +fn letter_glyphs(text: &str, family: &str) -> LetterGlyphs { + let bare: String = text.chars().filter(|&c| !is_harakat(c)).collect(); + layout(FontDb::global(), &text_with_harakat(&bare, family, None)).glyphs.iter().map(|g| (g.font_id, g.gid)).collect() +} + +fn fixture_mark(g: &PositionedGlyph, letters: &LetterGlyphs) -> bool { + // Some fonts draw a letter's dots as zero-advance GDEF marks. They keep the letter's paint. + g.advance.abs() < 1e-6 && !letters.contains(&(g.font_id, g.gid)) +} + +/// Expected fill from the fixture's source runs, independent of the glyph's assigned `run`: +/// zero-advance glyphs absent from the bare letters take the first harakat's fill in their +/// cluster; letter glyphs (including their dots) take the cluster-start fill. +fn expected_fill(t: &TextObject, text: &str, g: &PositionedGlyph, letters: &LetterGlyphs) -> Paint { + let end = (g.byte + g.len).min(text.len()); + let span = text.get(g.byte..end).unwrap_or(""); + let letter_fill = style_fill_at(t, g.byte); + if fixture_mark(g, letters) && span.chars().any(is_harakat) { + // Mark glyph: first harakat in the cluster span. + let off = span.char_indices().find(|(_, c)| is_harakat(*c)).map(|(i, _)| g.byte + i).unwrap_or(g.byte); + return style_fill_at(t, off); + } + letter_fill +} + +fn style_fill_at(t: &TextObject, byte: usize) -> Paint { + let mut off = 0; + for r in &t.runs { + let end = off + r.text.len(); + if byte < end || (byte == end && byte == off) { + return r.style.fill.clone(); + } + off = end; + } + t.runs.last().map(|r| r.style.fill.clone()).unwrap_or_else(|| Paint::solid(Color::BLACK)) +} + +#[test] +fn paint_only_differences_are_told_apart() { + let a = style(FAMILY); + let mut b = a.clone(); + b.fill = red(); + b.stroke = red(); + b.stroke_width = 2.0; + assert!(paint_only(&a, &b) && paint_only(&a, &a)); + let mut c = a.clone(); + c.size = 12.0; + assert!(!paint_only(&a, &c)); + let mut d = b.clone(); + d.baseline_shift = 3.0; + assert!(!paint_only(&a, &d), "a raised harakat is not paint only"); + assert!(paint_only_mark_boundary("بِ", "ب".len(), &a, &b)); + assert!(!paint_only_mark_boundary("بب", "ب".len(), &a, &b), "between two letters"); + assert!(!paint_only_mark_boundary("e\u{301}", 1, &a, &b), "a Latin accent keeps the existing rule"); + assert_eq!(harakat_ranges("بِسْمِ", 0.."بِسْمِ".len()), [2..4, 6..8, 10..12]); + assert_eq!(harakat_ranges("اللَّهِ", 0.."اللَّهِ".len()), [6..10, 12..14], "shadda and fatha together"); +} + +/// The allocation-free comparison must keep the previous comparison's complete contract, +/// including attributes that affect layout rather than shaping and non-reflexive file values. +#[test] +fn paint_only_keeps_every_nonpaint_attribute_and_partial_equality() { + use vectorcraft_doc::{CharAlign, CharPosition, Dash, Digits, FontHeightReference, GlyphChoice, LineCap, LineJoin, ParaDirection, StrokeAlign}; + + fn previous(a: &CharStyle, b: &CharStyle) -> bool { + let mut b = b.clone(); + b.fill = a.fill.clone(); + b.stroke = a.stroke.clone(); + b.stroke_width = a.stroke_width; + b.overprint_fill = a.overprint_fill; + b.overprint_stroke = a.overprint_stroke; + b.stroke_cap = a.stroke_cap; + b.stroke_join = a.stroke_join; + b.stroke_miter_limit = a.stroke_miter_limit; + b.stroke_dash = a.stroke_dash.clone(); + b.stroke_align = a.stroke_align; + b.style_name = a.style_name.clone(); + *a == b + } + + fn check(a: &CharStyle, b: &CharStyle, want: bool, name: &str) { + for (left, right) in [(a, b), (b, a)] { + assert_eq!(paint_only(left, right), previous(left, right), "{name}: old contract"); + } + assert_eq!(paint_only(a, b), want, "{name}"); + } + + let a = CharStyle { + fill: Paint::Pattern { pattern: "named pattern".repeat(8), xf: Affine::IDENTITY }, + stroke: Paint::Solid { color: Color::BLACK, swatch: Some("global swatch".repeat(8)), tint: 0.5 }, + stroke_dash: Some(Dash { pattern: vec![2.0, 3.0, 4.0, 5.0], offset: 0.5, align_corners: true }), + style_name: Some("named character style".repeat(8)), + ..style(FAMILY) + }; + macro_rules! field { + ($field:ident, $value:expr, $want:expr) => {{ + let mut b = a.clone(); + b.$field = $value; + check(&a, &b, $want, stringify!($field)); + }}; + } + field!(font_family, "other family".into(), false); + field!(font_style, "Bold".into(), false); + field!(font_version, Some("other version".into()), false); + field!(font_axes, [("wght".into(), 700.0)].into(), false); + field!(size, 13.0, false); + field!(leading, Some(60.0), false); + field!(tracking, 20.0, false); + field!(kerning, Some(0.0), false); + field!(optical_kerning, true, false); + field!(baseline_shift, 1.0, false); + field!(h_scale, 90.0, false); + field!(v_scale, 90.0, false); + field!(rotation, 3.0, false); + field!(underline, true, false); + field!(strikethrough, true, false); + field!(all_caps, true, false); + field!(features, vec!["-liga".into()], false); + field!(position, CharPosition::Superscript(Default::default()), false); + field!(small_caps, Some(80.0), false); + field!(char_align, CharAlign::EmBoxTop, false); + field!(char_direction, Some(ParaDirection::RightToLeft), false); + field!(kashidas, false, false); + field!(proportional_metrics, true, false); + field!(tate_chu_yoko, true, false); + field!(tcy_up_down, 1.0, false); + field!(tcy_left_right, 1.0, false); + field!(standard_vertical_roman, true, false); + field!(digits, Digits::Hindi, false); + field!(font_height_reference, FontHeightReference::CapHeight, false); + field!(no_break, true, false); + field!(language, Some("ar".into()), false); + field!(glyph_alternate, Some(GlyphChoice { ch: 'a', gid: 1, font: "other".into(), version: String::new() }), false); + field!(fill, Paint::None, true); + field!(stroke, Paint::None, true); + field!(stroke_width, 2.0, true); + field!(overprint_fill, true, true); + field!(overprint_stroke, true, true); + field!(stroke_cap, LineCap::Round, true); + field!(stroke_join, LineJoin::Round, true); + field!(stroke_miter_limit, 2.0, true); + field!(stroke_dash, None, true); + field!(stroke_align, StrokeAlign::Outside, true); + field!(style_name, None, true); + // Only the first style's ignored fields survive the old normalization. A NaN in the + // second style's paint is ignored, but reversing the arguments must still return false. + field!(fill, Paint::solid(Color::Gray { k: f32::NAN }), true); + field!(stroke, Paint::solid(Color::Gray { k: f32::NAN }), true); + field!(stroke_width, f64::NAN, true); + field!(stroke_miter_limit, f64::NAN, true); + field!(stroke_dash, Some(Dash { pattern: vec![f64::NAN], offset: 0.0, align_corners: false }), true); + field!(tracking, f64::NAN, false); +} + +/// A face without usable mark classification keeps cluster-start paint, without changing +/// its glyphs or positioning when a harakat's paint is edited. All variants are in-memory. +#[test] +fn synthetic_harakat_keep_geometry_with_and_without_gdef_marks() { + use skrifa::raw::TableProvider; + use write_fonts::FontBuilder; + use write_fonts::tables::gdef::Gdef; + use write_fonts::tables::layout::ClassDefFormat1; + use write_fonts::types::{GlyphId16, Tag}; + + let bytes = crate::test_fonts::lam_alef_font(b"rlig").unwrap(); + let font = skrifa::FontRef::new(&bytes).unwrap(); + for variant in ["marks", "no GDEF", "no class definition", "base classes"] { + let mut builder = FontBuilder::new(); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if variant == "marks" || tag != Tag::new(b"GDEF") { + builder.add_raw(tag, font.table_data(r.tag()).unwrap().as_bytes()); + } + } + if variant == "no class definition" { + builder.add_table(&Gdef::new(None, None, None, None)).unwrap(); + } else if variant == "base classes" { + let classes = ClassDefFormat1::new(GlyphId16::new(0), vec![1; usize::from(font.maxp().unwrap().num_glyphs())]); + builder.add_table(&Gdef::new(Some(classes.into()), None, None, None)).unwrap(); + } + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(builder.build()), 1, "{variant}"); + let family = crate::test_fonts::lam_alef_family(b"rlig"); + let plain = text_with_harakat("بَبَبَ", family, None); + let coloured = text_with_harakat("بَبَبَ", family, Some(red())); + let before = layout(&db, &plain); + let after = layout(&db, &coloured); + assert!(!before.glyphs.is_empty(), "{variant}"); + assert_eq!(geometry(&before), geometry(&after), "{variant}"); + assert_eq!(coloured.plain_text(), plain.plain_text(), "{variant}"); + if variant == "marks" { + assert!(painted(&coloured, &after, &red()) > 0, "{variant}: harakat own their paint"); + } else { + assert!(after.glyphs.iter().all(|g| run_of(&coloured, g).style.fill != red()), "{variant}: cluster-start paint"); + } + } +} + +/// A range is normalised as `edit::style_range` takes one: clamped, each end moved back to the +/// start of its character, put in order. Never a silent empty result for a usable range. +#[test] +fn harakat_ranges_normalise_their_range() { + let word = "بِسْمِ"; // ب 0..2, kasra 2..4, س 4..6, sukun 6..8, م 8..10, kasra 10..12 + let all = harakat_ranges(word, 0..word.len()); + assert_eq!(harakat_ranges(word, word.len()..0), all, "reversed"); + assert_eq!(harakat_ranges(word, 0..usize::MAX), all, "past the end"); + assert!(harakat_ranges(word, usize::MAX..usize::MAX).is_empty(), "wholly past the end"); + assert_eq!(harakat_ranges(word, 1..word.len()), all, "a start inside ب moves back to it"); + assert_eq!(harakat_ranges(word, 0..7), [std::ops::Range { start: 2, end: 4 }], "an end inside the sukun moves back before it"); + assert_eq!(harakat_ranges(word, 3..9), [2..4, 6..8], "both ends inside characters"); + assert_eq!(harakat_ranges(word, std::ops::Range { start: 9, end: 3 }), [2..4, 6..8], "reversed, inside characters"); + assert!(harakat_ranges(word, 4..4).is_empty(), "empty"); +} + +/// The character-level pass names each glyph's own character only when it sets the same glyphs +/// the same way, and only a character in that glyph's shaping cluster: repeated glyph ids alone +/// don't do. A later in-cluster owner is kept only for a GDEF mark glyph on a harakat character; +/// everything else stays at the cluster start (conservative). +#[test] +fn own_chars_need_the_same_setting_and_each_character_in_its_cluster() { + // بَبَب right to left: final beh (cluster 8), fatha and medial beh (cluster 4), fatha and + // initial beh (cluster 0). Bytes: ب0 ف2 ب4 ف6 ب8. Glyph id 20 is the fatha (GDEF mark). + const TEXT: &str = "بَبَب"; + let marks = |gid: u32| gid == 20; + let raw = [(10, 8, 500, 0, 0), (20, 4, 0, -30, 400), (11, 4, 300, 0, 0), (20, 0, 0, -40, 420), (12, 0, 450, 0, 0)]; + let by_char = |own: [u32; 5]| raw.iter().zip(own).map(|(g, c)| (g.0, c, g.2, 0, g.3, g.4)).collect::>(); + let ok = by_char([8, 6, 4, 2, 0]); + assert_eq!(own_chars(&raw, &ok, 10, TEXT, marks), [8, 6, 4, 2, 0]); + // The fathas' characters swapped (the same glyph ids): each is outside its glyph's cluster, + // so both keep their cluster's (their letter's) character, never the other fatha's. + assert_eq!(own_chars(&raw, &by_char([8, 2, 4, 6, 0]), 10, TEXT, marks), [8, 4, 4, 0, 0]); + // A character before its glyph's cluster, or past the segment's end: the cluster's own. + assert_eq!(own_chars(&raw, &by_char([8, 3, 4, 2, 0]), 10, TEXT, marks), [8, 4, 4, 2, 0]); + assert_eq!(own_chars(&raw, &by_char([9, 6, 4, 2, 0]), 9, TEXT, marks), [8, 6, 4, 2, 0]); + // A base letter named as its mark keeps the letter (not a GDEF mark). + assert_eq!(own_chars(&raw, &by_char([8, 6, 6, 2, 0]), 10, TEXT, marks), [8, 6, 4, 2, 0]); + // Without GDEF mark classification every later owner falls back to the cluster start. + assert_eq!(own_chars(&raw, &ok, 10, TEXT, |_| false), [8, 4, 4, 0, 0]); + // Wide mark (advance 500) beside a narrower base (300): mark keeps 2; base keeps 0. + // Review counterexample: advance must not decide ownership. + let wide = [(20, 0, 500, 0, 0), (11, 0, 300, 0, 0)]; + let wide_by = [(20, 2, 500, 0, 0, 0), (11, 2, 300, 0, 0, 0)]; + assert_eq!(own_chars(&wide, &wide_by, 4, "بَ", marks), [2, 0], "wide GDEF mark keeps harakat owner"); + // Equal advances: same rule. + let equal = [(20, 0, 300, 0, 0), (11, 0, 300, 0, 0)]; + let equal_by = [(20, 2, 300, 0, 0, 0), (11, 2, 300, 0, 0, 0)]; + assert_eq!(own_chars(&equal, &equal_by, 4, "بَ", marks), [2, 0], "equal advances"); + // Multi-component glyph (GDEF class 4, not mark) named as a later harakat stays at cluster start. + let multi = [(40, 0, 100, 0, 0), (11, 0, 300, 0, 0)]; + let multi_by = [(40, 2, 100, 0, 0, 0), (11, 0, 300, 0, 0, 0)]; + assert_eq!(own_chars(&multi, &multi_by, 4, "بَ", marks), [0, 0], "component is not a mark"); + // Single-glyph ligature (one output for letter+mark) named as the mark stays at cluster start: + // one glyph can represent a ligature containing a base, not a lone mark. + let liga = [(50, 0, 400, 0, 0)]; + let liga_by = [(50, 2, 400, 0, 0, 0)]; + assert_eq!(own_chars(&liga, &liga_by, 4, "بَ", |_| false), [0], "ligature without GDEF mark class"); + assert_eq!(own_chars(&liga, &liga_by, 4, "بَ", |gid| gid == 50), [2], "only if GDEF names it mark"); + // Sole advancing glyph without GDEF mark proof stays at the cluster start. + let advancing = [(20, 0, 100, 0, 0)]; + let advancing_by = [(20, 2, 100, 0, 0, 0)]; + assert_eq!(own_chars(&advancing, &advancing_by, 4, "بَ", |_| false), [0]); + assert_eq!(own_chars(&advancing, &advancing_by, 4, "بَ", marks), [2]); + // The same ids set otherwise (an advance or an offset changed, another glyph, one short): + // nothing is borrowed. + let mut moved = ok.clone(); + moved[1].5 += 1; + assert!(own_chars(&raw, &moved, 10, TEXT, marks).is_empty(), "a mark moved"); + let mut wider = ok.clone(); + wider[2].2 += 1; + assert!(own_chars(&raw, &wider, 10, TEXT, marks).is_empty(), "an advance changed"); + let mut other = ok.clone(); + other[0].0 = 13; + assert!(own_chars(&raw, &other, 10, TEXT, marks).is_empty(), "another glyph"); + assert!(own_chars(&raw, &ok[1..], 10, TEXT, marks).is_empty(), "a glyph short"); +} + +/// A word whose letters and marks repeat the same glyph ids (بَبَب): each fatha takes its own +/// colour, on its own letter, and every glyph is set as without colour. +#[test] +fn repeated_glyphs_take_their_own_harakat_colour() { + let Some(face) = arabic_face("repeated_glyphs_take_their_own_harakat_colour") else { + return; + }; + const WORD: &str = "بَبَب"; // ب 0, fatha 2, ب 4, fatha 6, ب 8 + let db = FontDb::global(); + let green = Paint::solid(Color::rgb8(30, 140, 70)); + let plain = text_with_harakat(WORD, &face.family, None); + let mut coloured = plain.clone(); + crate::edit::style_range(&mut coloured.runs, 2, 4, |st| st.fill = green.clone()); + crate::edit::style_range(&mut coloured.runs, 6, 8, |st| st.fill = red()); + let (a, b) = (layout(db, &plain), layout(db, &coloured)); + assert_eq!(geometry(&a), geometry(&b), "joining and mark positions unchanged"); + assert_authored_ownership(&coloured, WORD, &b, "repeated"); + let fill = |g: &PositionedGlyph| run_of(&coloured, g).style.fill.clone(); + let letters = letter_glyphs(WORD, &face.family); + let marks: Vec<&PositionedGlyph> = b.glyphs.iter().filter(|g| fixture_mark(g, &letters) && !g.outline.is_empty()).collect(); + assert_eq!(marks.len(), 2, "two fathas"); + assert_eq!(marks[0].gid, marks[1].gid, "the same glyph id twice"); + for m in &marks { + let want = if m.byte == 0 { green.clone() } else { red() }; + assert!(m.byte == 0 || m.byte == 4, "a fatha in its letter's cluster: {}", m.byte); + assert_eq!(fill(m), want, "the fatha of the letter at {} keeps its own colour", m.byte); + } + let letter_fill = plain.runs[0].style.fill.clone(); + assert!(b.glyphs.iter().filter(|g| letters.contains(&(g.font_id, g.gid))).all(|g| fill(g) == letter_fill), "letters keep theirs"); +} + +/// Coloured harakat: the letters keep their joining and the marks their attachment, glyph for +/// glyph and bit for bit; every mark glyph (and only the marks) is drawn in the harakat's run. +#[test] +fn harakat_coloured_apart_keep_every_glyph_and_take_their_own_colour() { + let Some(face) = arabic_face("harakat_coloured_apart_keep_every_glyph_and_take_their_own_colour") else { + return; + }; + let db = FontDb::global(); + let family = face.family.as_str(); + let plain = text_with_harakat(VOCALIZED, family, None); + let coloured = text_with_harakat(VOCALIZED, family, Some(red())); + assert!(coloured.runs.len() > 1); + let (a, b) = (layout(db, &plain), layout(db, &coloured)); + assert_eq!(geometry(&a), geometry(&b), "joining and mark positions unchanged"); + let letters = letter_glyphs(VOCALIZED, family); + let marks = b.glyphs.iter().filter(|g| fixture_mark(g, &letters) && !g.outline.is_empty()).count(); + assert!(marks > 0, "vocalized text has mark glyphs"); + assert_eq!(painted(&coloured, &b, &red()), marks); + assert_authored_ownership(&coloured, VOCALIZED, &b, "coloured"); + let hidden = text_with_harakat(VOCALIZED, family, Some(Paint::None)); + let h = layout(db, &hidden); + assert_eq!(geometry(&a), geometry(&h)); + assert_eq!(painted(&hidden, &h, &Paint::None), marks); + assert_authored_ownership(&hidden, VOCALIZED, &h, "hidden"); + let mut sized = text_with_harakat(VOCALIZED, family, None); + let first = harakat_ranges(VOCALIZED, 0..VOCALIZED.len())[0].clone(); + crate::edit::style_range(&mut sized.runs, first.start, first.end, |st| st.size = 30.0); + assert_ne!(geometry(&layout(db, &sized)), geometry(&a)); +} + +/// Justified kashida lines with coloured or hidden harakat keep authored glyph ownership, and +/// inserted tatweels take the base letter's paint—not a trailing mark's. +#[test] +fn coloured_harakat_keep_kashida() { + let Some(face) = arabic_face("coloured_harakat_keep_kashida") else { + return; + }; + let db = FontDb::global(); + let family = face.family.as_str(); + let justified = |t: &mut TextObject, width: f64| { + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, width, 2000.0).to_path(0.1)) }; + t.xf = Affine::IDENTITY; + t.para.justify = Justify::JustifyAll; + t.para.kashida = Kashida::Long; + }; + const PARTLY: &str = "بِسْمِ اللَّهِ الرحمن الرحيم الحمد لله رب العالمين"; + let tat = face.glyph_for('\u{0640}'); + let mut tatweels = 0; + for width in [200.0, 260.0, 300.0, 420.0, 600.0] { + let mut plain = text_with_harakat(PARTLY, family, None); + let mut coloured = text_with_harakat(PARTLY, family, Some(red())); + let before = layout(db, &coloured); + assert_authored_ownership(&coloured, PARTLY, &before, &format!("before kashida {width}")); + justified(&mut plain, width); + justified(&mut coloured, width); + let (a, b) = (layout(db, &plain), layout(db, &coloured)); + tatweels += a.glyphs.iter().filter(|g| g.gid == tat && g.len == 0).count(); + assert_eq!(geometry(&a), geometry(&b), "{width}"); + assert_kashida_ownership(&coloured, &before, &b, &red(), &format!("coloured {width}"), false); + } + assert!(tatweels > 0, "the text takes kashida"); + let mut stretched = 0; + for width in [200.0, 260.0, 300.0, 420.0, 600.0] { + let mut plain = text_with_harakat(FULLY, family, None); + let mut coloured = text_with_harakat(FULLY, family, Some(red())); + let mut hidden = text_with_harakat(FULLY, family, Some(Paint::None)); + let before_c = layout(db, &coloured); + let before_h = layout(db, &hidden); + assert_authored_ownership(&coloured, FULLY, &before_c, &format!("full before {width}")); + justified(&mut plain, width); + justified(&mut coloured, width); + justified(&mut hidden, width); + let (a, b, h) = (layout(db, &plain), layout(db, &coloured), layout(db, &hidden)); + assert_eq!(geometry(&a), geometry(&b), "{width}"); + assert_eq!(geometry(&a), geometry(&h), "hidden {width}"); + stretched += stretched_words_with_harakat(FULLY, &b, tat); + assert_kashida_ownership(&coloured, &before_c, &b, &red(), &format!("full coloured {width}"), false); + assert_kashida_ownership(&hidden, &before_h, &h, &Paint::None, &format!("full hidden {width}"), false); + } + assert!(stretched > 0, "words with coloured harakat take kashida"); +} + +/// Harakat on every word. +const FULLY: &str = "بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ الرَّحْمَنِ الرَّحِيمِ مَالِكِ يَوْمِ الدِّينِ"; + +/// The words of `text` with harakat that `l` stretched with a tatweel (glyph `tat`). +fn stretched_words_with_harakat(text: &str, l: &TextLayout, tat: u32) -> usize { + let mut words: Vec = l + .glyphs + .iter() + .filter(|g| g.gid == tat && g.len == 0) + .map(|g| text[..g.byte].rfind(' ').map_or(0, |i| i + 1)) + .filter(|&start| text[start..].split(' ').next().is_some_and(|w| w.chars().any(is_harakat))) + .collect(); + words.dedup(); + words.len() +} + +/// Authored glyphs paint as the independent expected fill from source runs; run indices must exist. +fn assert_authored_ownership(t: &TextObject, text: &str, l: &TextLayout, what: &str) { + let letters = letter_glyphs(text, &t.runs[0].style.font_family); + for g in &l.glyphs { + if g.len == 0 { + continue; + } + let actual = &run_of(t, g).style.fill; + let want = expected_fill(t, text, g, &letters); + assert_eq!(actual, &want, "{what}: glyph {} at {} len {} adv {}", g.gid, g.byte, g.len, g.advance); + } +} + +/// 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`, +/// at least one tatweel must follow a same-cluster glyph whose run is the mark paint (so the +/// emitter fix is exercised: reverting `emit_kashida`'s base-run assignment fails). +fn assert_kashida_ownership( + coloured: &TextObject, + before: &TextLayout, + with_kashida: &TextLayout, + mark_fill: &Paint, + what: &str, + require_mark_last: bool, +) -> usize { + let mut before_runs: std::collections::HashMap<(usize, u32), Vec> = 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); + } + 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)); + 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); + } + assert_eq!(after_n, before.glyphs.iter().filter(|g| g.len > 0).count(), "{what}: authored glyph count"); + assert!(before_runs.values().all(|v| v.is_empty()), "{what}: unjustified authored glyphs left unmatched"); + let mut mark_last = 0; + for (i, g) in with_kashida.glyphs.iter().enumerate().filter(|(_, g)| g.len == 0) { + let letter_fill = style_fill_at(coloured, g.byte); + let fill = &run_of(coloured, g).style.fill; + assert_eq!(fill, &letter_fill, "{what}: tatweel at {} must use base-letter paint", g.byte); + assert_ne!(fill, mark_fill, "{what}: tatweel must not inherit mark paint at {}", g.byte); + // The glyph that absorbed the kashida (last of the cluster in visual order) is emitted + // immediately before the tatweel and shares its cluster byte. + if let Some(prev) = i.checked_sub(1).and_then(|j| with_kashida.glyphs.get(j)) + && prev.byte == g.byte + && prev.len > 0 + && &run_of(coloured, prev).style.fill == mark_fill + && letter_fill != *mark_fill + { + mark_last += 1; + } + } + if require_mark_last { + assert!(mark_last > 0, "{what}: need a mark-last insertion (last visual glyph has mark paint ≠ letter) to exercise emit_kashida"); + } + mark_last +} + +/// Installed OpenType Arabic faces (when present): coloured harakat change no glyph, position or +/// advance; letter gids from the bare text must not take harakat paint. Glyphs absent from that +/// bare set may take either the harakat colour or the letter colour (AAT/`morx` ligature fallback +/// keeps the letter)—this test does not prove every mark owns its character. Selected AAT faces +/// below record an explicit letter-fill allowance for non-letter gids; they may also paint no +/// glyph in the harakat colour when GDEF is unavailable. +#[test] +fn installed_fonts_keep_their_glyphs_with_coloured_harakat() { + const FONTS: &[&str] = &[ + "Geeza Pro", + "SF Arabic", + "Al Nile", + "Baghdad", + "Damascus", + "KufiStandardGK", + "DecoType Naskh", + "Diwan Thuluth", + "Farah", + "Noto Nastaliq Urdu", + "Arial", + "Times New Roman", + "Tahoma", + "Noto Naskh Arabic", + "Noto Kufi Arabic", + "Noto Sans Arabic", + "Amiri", + "Aref Ruqaa", + "IBM Plex Sans Arabic", + ]; + let db = FontDb::with_font_dirs(crate::system_font_dirs()); + let harakat = VOCALIZED.chars().filter(|c| is_harakat(*c)).count(); + let mut rows = vec![]; + for &family in FONTS { + if !db.has_family(family) { + continue; + } + let Some(face) = db.face(family, "Regular") else { + continue; + }; + let plain = text_with_harakat(VOCALIZED, &face.family, None); + let coloured = text_with_harakat(VOCALIZED, &face.family, Some(red())); + let bare: String = VOCALIZED.chars().filter(|c| !is_harakat(*c)).collect(); + let (a, b) = (layout(&db, &plain), layout(&db, &coloured)); + assert_eq!(geometry(&a), geometry(&b), "{family}: coloured harakat changed the glyphs"); + let letter_fill = style_fill_at(&coloured, 0); + let letter_gids: std::collections::HashSet = + layout(&db, &text_with_harakat(&bare, &face.family, None)).glyphs.iter().map(|g| g.gid).collect(); + // AAT faces where a ligature mark may keep the letter's colour (explicit allowance, not a + // per-glyph ownership proof). + let aat_letter_ok = matches!(family, "Geeza Pro" | "Al Nile" | "Baghdad" | "Damascus" | "KufiStandardGK" | "DecoType Naskh"); + for g in b.glyphs.iter().filter(|g| g.len > 0) { + let actual = &run_of(&coloured, g).style.fill; + if letter_gids.contains(&g.gid) { + // A glyph the bare letters also draw: must not take harakat paint. + assert_ne!(actual, &red(), "{family}: letter gid {} at {} took harakat paint", g.gid, g.byte); + } else if aat_letter_ok { + assert!( + actual == &red() || actual == &letter_fill, + "{family}: non-letter gid {} at {} may be harakat or letter paint (AAT), got {actual:?}", + g.gid, + g.byte + ); + } else { + // OpenType with GDEF: prefer harakat paint; letter paint still allowed when the + // character-level pass falls back (does not prove every mark owns its character). + assert!( + actual == &red() || actual == &letter_fill, + "{family}: non-letter at {} should be harakat or letter paint, got {actual:?}", + g.byte + ); + } + } + let red_glyphs = painted(&coloured, &b, &red()); + // Without GDEF (or when the character-level pass falls back), every glyph may keep the + // letter's paint—conservative and allowed. This is not every-mark ownership. + let all_letter = b.glyphs.iter().filter(|g| g.len > 0).all(|g| run_of(&coloured, g).style.fill == letter_fill); + assert!(red_glyphs > 0 || all_letter, "{family}: expected some harakat paint or a full letter-paint fallback (aat={aat_letter_ok})"); + rows.push(format!("{family}: {} glyphs identical; {red_glyphs} glyphs in the harakat colour ({harakat} harakat)", b.glyphs.len())); + } + if rows.is_empty() { + eprintln!("SKIPPED: installed_fonts_keep_their_glyphs_with_coloured_harakat; none of the candidate families are installed"); + } else { + eprintln!("{rows:#?}"); + } +} diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 6ce5f3501e..fa22c10fb3 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -18,11 +18,16 @@ 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; +/// 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 +91,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 +122,7 @@ impl Default for Revolve { shade: true, smooth_shading: true, cap_ends: true, + curve_samples: None, } } } @@ -307,6 +316,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 +463,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 +702,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 +721,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 +769,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 +806,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/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/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/direct.rs b/crates/tools/src/direct.rs index a2ffbbf870..833f482255 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1437,7 +1437,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 +1474,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/guides/snap.rs b/crates/tools/src/guides/snap.rs index 0b117b95b5..9d530f4db5 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 { 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..b4a7d69971 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -536,6 +536,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/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 9bbc26d4fb..49775e2419 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -81,6 +81,7 @@ impl VectorcraftApp { print_tiling: None, live_paint_gaps: None, hidden_chars: Default::default(), + spelling: Default::default(), selection_marks: Default::default(), selection_box: None, selection_bounds: None, @@ -168,6 +169,7 @@ impl VectorcraftApp { scrub_scope: None, automation_roots: None, synthetic_frame: false, + pending_plugin_install: None, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 7d91162908..8f4ce246f5 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -24,12 +24,18 @@ impl VectorcraftApp { /// control or MCP request, or a frame of synthetic input): the automation roots don't confine /// what that app does. pub(crate) fn refuse_automation(&self, id: &str) -> Result<(), String> { - if self.ui.answering_control || self.synthetic_frame { + if self.automation_is_acting() { return Err(format!("{id} opens another app: only the person at the keyboard can run it")); } Ok(()) } + /// Did automation send what is being handled now: a control or MCP request, or a frame of + /// synthetic input? + pub(crate) fn automation_is_acting(&self) -> bool { + self.ui.answering_control || self.synthetic_frame + } + /// Run a Help link command and open the URL it returns. pub fn open_link(&mut self, id: &str) { if let Ok(v) = self.run(id, serde_json::json!({})) 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 a9211eccff..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 @@ -45,11 +45,15 @@ pub struct CanvasCache { /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::HiddenChars, + /// The words Edit › Spelling › Auto Spell Check underlined on each text object in the last + /// frame; dropped while it is off. + pub spelling: canvas::SpellingMarks, /// 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 19244247dc..ed9c62d0b7 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -69,12 +69,12 @@ pub(crate) use raster::{color_image, color_image_owned, render_job}; pub use selection_marks::SelectionMarks; use task_bar::task_bar; pub(crate) use task_bar::{has_colors, task_bar_rect}; -pub use tool_overlays::HiddenChars; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; +pub use tool_overlays::{HiddenChars, SpellingMarks}; use tool_overlays::{ grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, - print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, thread_overlays, + print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, }; pub(crate) use view::animated_zoom; pub use view::fit; @@ -511,6 +511,11 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin // (#444). The system cursor stands in for cursors without a glyph. Over a window // without the focus, macOS shows its own pointer whichever cursor the window sets, // and the glyph is not painted there. + // Interim #2292: remove when pinned winit correctly handles macOS cursor image and hotspot sizing. + #[cfg(target_os = "macos")] + Some(_) if !app.services.wayland => { + crate::cursors::native_request::request(ui.ctx(), c, cursor_icon(c), custom, ui.ctx().zoom_factor() / ui_scale) + } Some(_) if custom && crate::cursors::os_cursors(crate::cursors::OS_CURSORS, app.services.wayland) => { let ppp = ui.ctx().pixels_per_point() / ui_scale; ui.ctx().set_cursor_image(app.canvas.cursors.get(c, ppp)); @@ -734,6 +739,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); @@ -746,6 +755,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(), @@ -1103,6 +1115,13 @@ fn selection_visuals( hidden_chars_overlay(app, painter, xf); } } + // Edit › Spelling › Auto Spell Check: shown with the edges hidden too, as it marks the type + // rather than the selection. + if app.ui.view.auto_spell_check && !revolve_edit { + spelling_overlay(app, painter, xf); + } else { + app.canvas.spelling = SpellingMarks::default(); + } overlays } 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/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 5a94afb3f4..42778c729f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4645,7 +4645,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 +4747,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 +4772,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 +4820,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. @@ -10656,3 +10834,238 @@ fn direct_selection_shows_the_bounding_box_while_cmd_is_held() { assert!(!handle_drawn(&mut app, egui::Modifiers::NONE), "gone once Cmd is released"); 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] +fn mac_cursor_canvas_without_host_keeps_visible_fallback() { + use crate::cursors::native_request; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let view = vectorcraft_engine::ViewInfo::default(); + for (tool, expected) in [("selection", egui::CursorIcon::Default), ("type", egui::CursorIcon::Text), ("pen", egui::CursorIcon::Crosshair)] { + app.session.select_tool(tool, view).unwrap(); + app.hover_doc = Some(Point::new(200.0, 150.0)); + let output = + mac_cursor_headless(&ctx, egui::RawInput { events: vec![egui::Event::PointerMoved(pos2(200.0, 150.0))], ..Default::default() }, |ui| { + native_request::clear(ui.ctx()); + canvas_cursor(&mut app, ui, view, true); + }); + assert_eq!(output.platform_output.cursor_icon, expected, "{tool}: the fallback stays visible without a host"); + assert!(output.platform_output.cursor_image.is_none()); + assert!(output.shapes.iter().all(|s| matches!(s.shape, egui::Shape::Noop)), "no tool glyph is painted"); + assert!(native_request::take(&ctx).is_some(), "{tool}: publish a native request"); + } +} + +#[cfg(target_os = "macos")] +#[test] +fn mac_cursor_canvas_respects_precise_scaling_focus_and_presentation() { + use crate::cursors::native_request; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let view = vectorcraft_engine::ViewInfo::default(); + app.session.select_tool("pen", view).unwrap(); + app.hover_doc = Some(Point::new(200.0, 150.0)); + let ctx = egui::Context::default(); + ctx.set_zoom_factor(1.5); + let frame = |app: &mut VectorcraftApp, focused| { + let _ = mac_cursor_headless( + &ctx, + egui::RawInput { focused, events: vec![egui::Event::PointerMoved(pos2(200.0, 150.0))], ..Default::default() }, + |ui| { + native_request::clear(ui.ctx()); + canvas_cursor(app, ui, view, true); + }, + ); + native_request::take(&ctx) + }; + let normal = frame(&mut app, true).unwrap(); + app.run("prefs.set", json!({"key": "usePreciseCursors", "value": true})).unwrap(); + let precise = frame(&mut app, true).unwrap(); + assert_ne!(normal.key, precise.key); + let _ = mac_cursor_headless(&ctx, egui::RawInput { events: vec![egui::Event::PointerMoved(pos2(200.0, 150.0))], ..Default::default() }, |ui| { + native_request::request(ui.ctx(), Cursor::Crosshair, egui::CursorIcon::Crosshair, true, 1.0); + }); + assert_eq!(native_request::take(&ctx).unwrap().key, precise.key); + app.run("prefs.set", json!({"key": "scaleCursorWithUi", "value": true})).unwrap(); + let scaled = frame(&mut app, true).unwrap(); + assert_ne!(scaled.key, precise.key); + assert!(scaled.bitmap.representations[0].size[0] > precise.bitmap.representations[0].size[0]); + assert!(frame(&mut app, false).is_none()); + assert_eq!(frame(&mut app, true).unwrap().key, scaled.key); + app.ui.screen_mode = 3; + assert!(frame(&mut app, true).is_none()); +} + +#[cfg(target_os = "macos")] +fn mac_cursor_headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput { + let mut output = ctx.run_ui(input, draw); + output.textures_delta.clear(); + output +} + +/// The shapes Edit › Spelling › Auto Spell Check draws in one frame, seen through `xf`. +fn spelling_lines(app: &mut VectorcraftApp, ctx: &egui::Context, xf: &Xf) -> Vec { + let raw = egui::RawInput { screen_rect: Some(xf.rect), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| spelling_overlay(app, ui.painter(), xf)); + out.textures_delta.clear(); + out.shapes.into_iter().map(|c| c.shape).collect() +} + +/// A document with one point type object of `text` at the top left, and a view of it. +fn spelling_doc(text: &str) -> (VectorcraftApp, u64, Xf) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 20, "y": 60, "text": text})).unwrap()["id"].as_u64().unwrap(); + let xf = Xf { rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 1.0, center: Point::new(200.0, 150.0), rot: 0.0 }; + (app, id, xf) +} + +/// Auto Spell Check draws one wavy line under each unknown word, under its glyphs, and none under +/// the words the dictionaries know. +#[test] +fn auto_spell_check_underlines_the_unknown_words() { + let ctx = egui::Context::default(); + let (mut app, _, xf) = spelling_doc("the cat sat"); + assert!(spelling_lines(&mut app, &ctx, &xf).is_empty(), "every word is known"); + let (mut app, id, xf) = spelling_doc("the Qzvbtrw sat\nZvqtrbx"); + let lines = spelling_lines(&mut app, &ctx, &xf); + assert_eq!(lines.len(), 2, "one line under each unknown word: {lines:?}"); + // The first line runs under the second word: below the type's top and within its width. + let bounds = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap(); + let on_screen = xf.rect_to_screen(bounds); + let Shape::Path(first) = &lines[0] else { panic!("{:?}", lines[0]) }; + let xs = || first.points.iter().map(|p| p.x); + let (left, right) = (xs().fold(f32::MAX, f32::min), xs().fold(f32::MIN, f32::max)); + assert!(left > on_screen.left() + 5.0 && right < on_screen.right() - 5.0, "under the middle word: {left}..{right} in {on_screen:?}"); + assert!(first.points.iter().all(|p| p.y > on_screen.top() && p.y < on_screen.center().y + on_screen.height()), "{first:?}"); + assert!(first.points.windows(2).any(|w| w[0].y != w[1].y), "wavy"); +} + +/// The lines follow the type and the dictionaries: an edit, Ignore All and Add to Dictionary each +/// change what is underlined in the next frame, and a frame with no change checks no type again. +#[test] +fn auto_spell_check_follows_edits_ignore_all_and_the_dictionary() { + let ctx = egui::Context::default(); + let (mut app, id, xf) = spelling_doc("Wqzxvtr and Pzxqvrt"); + let kept = |app: &VectorcraftApp| app.canvas.spelling.lines[&vectorcraft_doc::NodeId(id)].1.clone(); + assert_eq!(spelling_lines(&mut app, &ctx, &xf).len(), 2); + // Tests running alongside add fonts and words, which checks all type again: frames are drawn + // until neither changed between two of them. + let again = (0..100).any(|_| { + let (inputs, before) = (app.canvas.spelling.inputs.clone(), kept(&app)); + spelling_lines(&mut app, &ctx, &xf); + app.canvas.spelling.inputs == inputs && std::sync::Arc::ptr_eq(&kept(&app), &before) + }); + assert!(again, "a frame keeps the lines of the frame before"); + app.session.execute("text.setText", &json!({"id": id, "text": "Wqzxvtr and Pzxqvrt or Qxzvwtr"})).unwrap(); + assert_eq!(spelling_lines(&mut app, &ctx, &xf).len(), 3, "the edit is checked"); + app.session.execute("text.spelling.ignoreAll", &json!({"word": "wqzxvtr"})).unwrap(); + assert_eq!(spelling_lines(&mut app, &ctx, &xf).len(), 2, "Ignore All"); + app.session.execute("text.spelling.addWord", &json!({"word": "Pzxqvrt"})).unwrap(); + let after_add = spelling_lines(&mut app, &ctx, &xf).len(); + app.session.execute("text.spelling.removeWord", &json!({"word": "pzxqvrt"})).unwrap(); + assert_eq!(after_add, 1, "Add to Dictionary"); + assert_eq!(spelling_lines(&mut app, &ctx, &xf).len(), 2, "deleted from the dictionary again"); +} + +/// Type with an effect shown, and hidden type, has no lines: the helpx page leaves type with +/// effects out of Auto Spell Check. +#[test] +fn auto_spell_check_leaves_out_type_with_effects_and_hidden_type() { + let ctx = egui::Context::default(); + let (mut app, id, xf) = spelling_doc("Xqzvtrw"); + assert_eq!(spelling_lines(&mut app, &ctx, &xf).len(), 1); + app.session.execute("effect.apply", &json!({"ids": [id], "effect": "distort.roughen", "params": {"size": 1}})).unwrap(); + assert!(spelling_lines(&mut app, &ctx, &xf).is_empty(), "an effect"); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spelling_lines(&mut app, &ctx, &xf).len(), 1, "undone"); + app.session.execute("object.hide", &json!({"ids": [id]})).unwrap(); + assert!(spelling_lines(&mut app, &ctx, &xf).is_empty(), "hidden"); +} + +/// Edit › Spelling › Auto Spell Check is a toggle, off at first: on, the canvas draws the lines; +/// off again, it draws none and keeps no text node. +#[test] +fn auto_spell_check_is_a_toggle_of_the_canvas_lines() { + let ctx = egui::Context::default(); + let (mut app, _, _) = spelling_doc("Yqzvtrx"); + let red = |s: &Shape| matches!(s, Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(Color32::from_rgb(0xe0, 0x20, 0x20))); + let count = |app: &mut VectorcraftApp| shapes(app, &ctx).iter().filter(|s| red(s)).count(); + assert!(!app.ui.view.auto_spell_check, "off at first"); + assert_eq!(count(&mut app), 0); + assert_eq!(app.run("edit.autoSpellCheck", json!({})).unwrap(), json!(true)); + assert_eq!(count(&mut app), 1, "on"); + assert_eq!(app.run("edit.autoSpellCheck", json!({})).unwrap(), json!(false)); + assert_eq!(count(&mut app), 0, "off"); + assert!(app.canvas.spelling.lines.is_empty(), "no node is kept"); +} diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 7b88244f68..67f6ac861a 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -105,6 +105,207 @@ impl HiddenMarks { } } +/// Edit › Spelling › Auto Spell Check: a red wavy line under each word of the visible type its +/// dictionaries don't know ([`vectorcraft_engine::cmd::spelling::misspellings`], what +/// `text.spelling.check` lists), in the run's language, without the active document's Ignore All +/// words. Type with effects isn't underlined +/// ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)). +/// Each text object's lines are kept from one frame to the next ([`SpellingMarks`]). +pub(super) fn spelling_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { + let kept = &mut app.canvas.spelling; + let Some(st) = app.session.active() else { + *kept = SpellingMarks::default(); + return; + }; + let clip = p.clip_rect(); + // `last` holds the lines of the last frame; the objects this frame doesn't draw are dropped. + let mut last = std::mem::take(&mut kept.lines); + let inputs = SpellingInputs { + fonts: vectorcraft_text::FontDb::global().generation(), + hyphenation: vectorcraft_text::hyphenation_exceptions(), + dictionary: vectorcraft_engine::cmd::spelling::dictionary_generation(), + doc: st.uid, + // Ignore All only adds words while the document is open. + ignored: st.spelling_ignored.len(), + }; + if kept.inputs.as_ref() != Some(&inputs) { + last.clear(); + kept.inputs = Some(inputs); + } + let stroke = Stroke::new(1.0, Color32::from_rgb(0xe0, 0x20, 0x20)); + // Depth first in paint order, leaving out hidden objects and what is inside them. + fn walk(nodes: &[std::sync::Arc], f: &mut impl FnMut(&std::sync::Arc)) { + for n in nodes.iter().filter(|n| n.visible) { + f(n); + if let Some(children) = n.children() { + walk(children, f); + } + } + } + walk(&st.doc.layers, &mut |n| { + let NodeKind::Text(tx) = &n.kind else { return }; + 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) { + Some((was, lines)) if std::sync::Arc::ptr_eq(&was, n) => lines, + _ => std::sync::Arc::new(underlines(tx, &st.spelling_ignored)), + }; + for &(a, b) in lines.iter() { + wavy_line(p, xf.to_screen(a), xf.to_screen(b), stroke); + } + kept.lines.insert(n.id, (n.clone(), lines)); + }); +} + +/// 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; + +/// The document-space segments under the unknown words of `tx`: for each word, the bottom edge of +/// each piece of it on a line, from the start of the line to its end. +fn underlines(tx: &vectorcraft_doc::TextObject, ignored: &std::collections::BTreeSet) -> Vec<(Point, Point)> { + let (words, _) = vectorcraft_engine::cmd::spelling::misspellings(tx, ignored, MAX_UNDERLINED); + if words.is_empty() { + return vec![]; + } + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx); + words + .iter() + .flat_map(|w| vectorcraft_text::selection_quads(&lay, w.range.start, w.range.end)) + // Clockwise from the top left: q[3] and q[2] are the bottom left and right. + .map(|q| (tx.xf * q[3], tx.xf * q[2])) + .collect() +} + +/// A wavy line from `a` to `b` on screen, waves 4 pixels long and 1.5 high. +fn wavy_line(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) { + const STEP: f32 = 2.0; + const HIGH: f32 = 1.5; + let d = b - a; + let len = d.length(); + if !len.is_finite() || len < 1.0 { + return; + } + let along = d / len; + // Down the page from the line, whichever way the type runs. + let across = vec2(-along.y, along.x); + // At most 2000 waves on one line, however far the view is zoomed in. + let n = ((len / STEP) as usize).clamp(1, 4_000); + let step = len / n as f32; + let points: Vec = (0..=n).map(|i| a + along * (step * i as f32) + across * if i % 2 == 0 { 0.0 } else { HIGH }).collect(); + p.add(Shape::line(points, stroke)); +} + +/// What Auto Spell Check's kept lines depend on beyond the text object itself: when any of it +/// changes, all type is checked again. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct SpellingInputs { + /// The fonts' generation ([`vectorcraft_text::FontDb::generation`]). + fonts: u64, + /// The hyphenation exceptions, which move line breaks. + hyphenation: String, + /// The custom dictionary's generation + /// ([`vectorcraft_engine::cmd::spelling::dictionary_generation`]). + dictionary: u64, + /// The document the lines are of. + doc: u64, + /// How many Ignore All words the document has. + ignored: usize, +} + +/// The lines Auto Spell Check drew under each text object in the last frame +/// ([`crate::CanvasCache::spelling`]). Each is kept with the object it was found in: an edited +/// object is a new `Arc` and is checked again. +#[derive(Default)] +pub struct SpellingMarks { + pub(super) inputs: Option, + /// Each text object drawn, by id: the node it was checked in and its lines in document space. + pub(super) lines: std::collections::HashMap, Underlines)>, +} + +/// One text object's Auto Spell Check lines: the document-space ends of each. +pub(super) type Underlines = std::sync::Arc>; + /// View › Show Text Threads: for each thread with a selected frame, a line in its first frame's /// layer colour from each frame's out port to the next frame's in port, both showing the arrow of a /// threaded port, where the tools draw the ports of selected type ([`vectorcraft_tools::text`]). diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 39bc805453..558bf011d9 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -65,6 +65,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 +354,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 +403,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 +411,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 +433,7 @@ pub(super) fn wheel( egui::TouchPhase::End | egui::TouchPhase::Cancel => { turn.gesture = false; turn.held = egui::Modifiers::NONE; + turn.fine = false; } } } @@ -420,6 +441,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 +449,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 +483,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 +502,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/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 5374305e0a..1c326609ee 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -86,6 +86,7 @@ fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { (tl!("Snap to Point"), "view.snapToPoint", app.ui.view.snap_to_point), (tl!("Snap to Grid"), "view.snapToGrid", app.ui.view.snap_to_grid), (tl!("Snap to Pixel"), "view.snapToPixel", app.ui.view.snap_to_pixel), + (tl!("Snap to Glyph"), "view.snapToGlyph", app.ui.view.snap_to_glyph), ] { if widgets::check(ui, label, on, true) { crate::menus::invoke(app, cmd, json!({})); @@ -93,6 +94,7 @@ fn snapping_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); for (key, label, on) in [ + ("alignmentGuides", tl!("Alignment Guides"), app.session.prefs.alignment_guides), ("snapTangent", tl!("Snap to Tangent"), app.session.prefs.snap_tangent), ("snapPerpendicular", tl!("Snap to Perpendicular"), app.session.prefs.snap_perpendicular), ] { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 93888a4d6f..15c856cd85 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1898,6 +1898,118 @@ fn full_screen_modes_fill_the_screen_and_normal_mode_restores_the_window() { assert!(sent(&mut app, true).is_empty(), "still full screen, as the user had it"); } +/// Snapping quick access includes the existing glyph and alignment settings. Pointer clicks use +/// their commands, and reopening reads the same state as View and Preferences (#6164). +#[test] +fn the_control_bar_snapping_menu_shares_glyph_and_alignment_settings() { + struct RestoreLanguage(crate::i18n::Lang); + impl Drop for RestoreLanguage { + fn drop(&mut self) { + crate::i18n::set_current(self.0); + } + } + let _language = RestoreLanguage(crate::i18n::current()); + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.snap_to_glyph = false; + app.run("prefs.set", json!({"key": "alignmentGuides", "value": true})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 400.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>; + let find = |nodes: &Nodes, name: &str| { + nodes.iter().find(|(_, n)| n.label() == Some(name)).map(|(_, n)| n.clone()).unwrap_or_else(|| panic!("missing {name}")) + }; + let center = |n: &egui::accesskit::Node| { + let b = n.bounds().expect("a visible menu control"); + assert!(b.x0 >= 0.0 && b.y0 >= 0.0 && b.x1 <= 1200.0 && b.y1 <= 400.0, "menu control stays inside the window: {b:?}"); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + let click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]); + frame(app, vec![]); + frame(app, vec![]) + }; + let check = |nodes: &Nodes, name: &str, on: bool| { + let node = find(nodes, name); + assert_eq!(node.role(), egui::accesskit::Role::CheckBox, "{name}"); + assert_eq!(node.toggled(), Some(if on { egui::accesskit::Toggled::True } else { egui::accesskit::Toggled::False }), "{name}"); + center(&node) + }; + let dismiss = |app: &mut crate::VectorcraftApp| { + let before = (app.ui.view.snap_to_glyph, app.session.prefs.to_json(), app.run_count); + frame( + app, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + frame( + app, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() }], + ); + let nodes = frame(app, vec![]); + assert!(!nodes.iter().any(|(_, n)| n.label() == Some("Snap to Glyph")), "Escape closes Snapping"); + assert_eq!( + (app.ui.view.snap_to_glyph, app.session.prefs.to_json(), app.run_count), + before, + "dismissal changes no settings and runs no command" + ); + }; + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + let menu = center(&find(&nodes, "Snapping")); + let nodes = click(&mut app, menu); + let glyph = check(&nodes, "Snap to Glyph", false); + check(&nodes, "Alignment Guides", true); + // The two extra rows still leave the original menu entries visible. + for name in ["Smart Guides", "Snap to Point", "Snap to Grid", "Snap to Pixel", "Snap to Tangent", "Snap to Perpendicular"] { + center(&find(&nodes, name)); + } + click(&mut app, glyph); + assert!(app.ui.view.snap_to_glyph); + assert_eq!(crate::menus::checked(&app, "view.snapToGlyph", &json!({})), Some(true)); + assert!(app.session.prefs.alignment_guides, "glyph snapping leaves Alignment Guides alone"); + dismiss(&mut app); + let nodes = click(&mut app, menu); + check(&nodes, "Snap to Glyph", true); + let alignment = check(&nodes, "Alignment Guides", true); + let commands = app.run_count; + click(&mut app, alignment); + assert_eq!(app.run_count, commands + 1, "Alignment Guides uses the app command entry point"); + assert_eq!(app.run("prefs.get", json!({"key": "alignmentGuides"})).unwrap(), json!(false)); + assert!(!app.session.prefs.alignment_guides); + crate::prefs_dialog::snapshot(&mut app); + let saved = serde_json::to_string(&app.ui.engine_prefs).unwrap(); + let mut restored = crate::VectorcraftApp::new(Session::new(), Default::default()); + restored.ui.engine_prefs = serde_json::from_str(&saved).unwrap(); + crate::prefs_dialog::restore(&mut restored); + assert_eq!( + restored.run("prefs.get", json!({"key": "alignmentGuides"})).unwrap(), + json!(false), + "Alignment Guides survives host preference persistence" + ); + assert!(app.ui.view.snap_to_glyph, "Alignment Guides leaves glyph snapping alone"); + dismiss(&mut app); + let nodes = click(&mut app, menu); + check(&nodes, "Snap to Glyph", true); + check(&nodes, "Alignment Guides", false); + // Changes made through the existing command surfaces are reflected on the next opening too. + crate::menus::invoke(&mut app, "view.snapToGlyph", json!({})); + app.run("prefs.set", json!({"key": "alignmentGuides", "value": true})).unwrap(); + dismiss(&mut app); + let nodes = click(&mut app, menu); + check(&nodes, "Snap to Glyph", false); + check(&nodes, "Alignment Guides", true); +} + /// The window the Control bar docking tests draw the bar in. const DOCK_SCREEN: egui::Rect = egui::Rect { min: egui::Pos2::ZERO, max: egui::pos2(1200.0, 300.0) }; diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index eda747fc8f..c26cae36ac 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -5,6 +5,10 @@ //! The desktop app shows them as OS cursors ([`Images`]): the system moves those itself, at once, //! while a cursor painted into the window follows the pointer a few frames late (#444). +/// Platform-neutral bitmap requests for the interim macOS host adapter. +#[cfg(any(target_os = "macos", test))] +pub mod native_request; + use egui::epaint::{Mesh, TessellationOptions, Tessellator, Vertex}; use egui::{Color32, CustomCursorImage, Painter, Pos2, Shape, Stroke, Vec2, pos2, vec2}; use vectorcraft_tools::Cursor; @@ -691,7 +695,8 @@ pub fn paint(painter: &Painter, c: Cursor, p: Pos2, scale: f32) -> bool { /// Does the window show the glyphs as OS cursors ([`Images`])? Not on macOS, which sizes a cursor /// bitmap in points (a Retina one would show twice as big, or blurred), nor on the web (eframe has no -/// bitmap cursors there): those paint them into the window ([`paint`]). +/// bitmap cursors there): the web paints them into the window ([`paint`]); the macOS desktop host +/// uses its native request adapter instead. pub const OS_CURSORS: bool = !cfg!(any(target_os = "macos", target_arch = "wasm32")); /// Does this window show the glyphs as OS cursors, on a build that can ([`OS_CURSORS`])? Not on diff --git a/crates/ui-egui/src/cursors/native_request.rs b/crates/ui-egui/src/cursors/native_request.rs new file mode 100644 index 0000000000..61f81d5708 --- /dev/null +++ b/crates/ui-egui/src/cursors/native_request.rs @@ -0,0 +1,136 @@ +//! Prepared, platform-neutral requests. The desktop host alone owns native cursor state. + +use super::{Cursor, rasterize}; +use egui::{Context, CursorIcon, CustomCursorImage, Id, ViewportId}; +use std::sync::Arc; + +const CAPACITY: usize = 128; +const MAX_PADDED_SIDE: u16 = 258; + +/// Opaque identity: the resolved tool cursor and logical scale, independent of display scale. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Key(Cursor, u32); + +/// The same artwork at one and two pixels per logical point, aligned without resampling. +#[derive(Clone, Debug)] +pub struct Bitmap { + /// Straight-alpha RGBA representations; the second size/hotspot is exactly twice the first. + pub representations: [CustomCursorImage; 2], +} + +/// One canvas request, valid only for its viewport and pass. +#[derive(Clone, Debug)] +pub struct Request { + /// Identity owned by the UI; the host need not depend on the tools crate. + pub key: Key, + /// Shared prepared pixels, retained independently of cache eviction. + pub bitmap: Arc, + /// Visible fallback, also used to detect a later UI override. + pub fallback: CursorIcon, + /// Viewport that selected this cursor. + pub viewport: ViewportId, + /// Cumulative pass number when the request was made. + pub pass: u64, +} + +#[derive(Clone, Default)] +struct Cache(Vec<(Key, Option>)>); + +impl Cache { + fn get(&mut self, cursor: Cursor, scale: f32) -> Option<(Key, Arc)> { + // Bound before tessellation, including malicious/non-finite preference values. + if !scale.is_finite() || !(0.125..=4.0).contains(&scale) { + return None; + } + let key = Key(cursor, scale.to_bits()); + if let Some((_, bitmap)) = self.0.iter().find(|(k, _)| *k == key) { + return bitmap.clone().map(|bitmap| (key, bitmap)); + } + let bitmap = prepare(cursor, scale).map(Arc::new); + if self.0.len() >= CAPACITY { + self.0.clear(); + } + self.0.push((key, bitmap.clone())); + bitmap.map(|bitmap| (key, bitmap)) + } +} + +fn prepare(cursor: Cursor, scale: f32) -> Option { + align([rasterize(cursor, scale)?, rasterize(cursor, scale * 2.0)?]) +} + +fn valid(image: &CustomCursorImage) -> bool { + let [w, h] = image.size; + w > 0 && h > 0 && w <= 256 && h <= 256 && image.hotspot[0] < w && image.hotspot[1] < h && image.rgba.len() == usize::from(w) * usize::from(h) * 4 +} + +fn align(source: [CustomCursorImage; 2]) -> Option { + if !source.iter().all(valid) { + return None; + } + let [one, two] = &source; + let mut size = [0; 2]; + let mut hotspot = [0; 2]; + for axis in 0..2 { + hotspot[axis] = one.hotspot[axis].max(two.hotspot[axis].div_ceil(2)); + let after = (one.size[axis] - one.hotspot[axis]).max((two.size[axis] - two.hotspot[axis]).div_ceil(2)); + size[axis] = hotspot[axis].checked_add(after)?; + if size[axis].checked_mul(2)? > MAX_PADDED_SIDE { + return None; + } + } + Some(Bitmap { representations: [pad(one, size, hotspot, 1)?, pad(two, size, hotspot, 2)?] }) +} + +fn pad(source: &CustomCursorImage, size: [u16; 2], hotspot: [u16; 2], factor: u16) -> Option { + let size = [size[0].checked_mul(factor)?, size[1].checked_mul(factor)?]; + let hotspot = [hotspot[0].checked_mul(factor)?, hotspot[1].checked_mul(factor)?]; + let x = usize::from(hotspot[0].checked_sub(source.hotspot[0])?); + let y = usize::from(hotspot[1].checked_sub(source.hotspot[1])?); + let stride = usize::from(size[0]) * 4; + let row = usize::from(source.size[0]) * 4; + let mut rgba = vec![0; stride.checked_mul(usize::from(size[1]))?]; + for (i, pixels) in source.rgba.chunks_exact(row).enumerate() { + let start = (y + i) * stride + x * 4; + rgba.get_mut(start..start + row)?.copy_from_slice(pixels); + } + Some(CustomCursorImage { rgba: rgba.into(), size, hotspot }) +} + +fn pending_id(ctx: &Context) -> Id { + Id::unique(("native-canvas-cursor", ctx.viewport_id())) +} + +/// Expire the current viewport's request at the start of every host pass. +pub fn clear(ctx: &Context) { + let id = pending_id(ctx); + ctx.data_mut(|data| data.remove::(id)); +} + +/// Consume only this viewport's request. The host validates its pass at finalization. +pub fn take(ctx: &Context) -> Option { + let id = pending_id(ctx); + ctx.data_mut(|data| { + let request = data.get_temp::(id); + data.remove::(id); + request + }) +} + +/// Publish eligible pixels and always return a visible system fallback, even without a host. +pub fn request(ctx: &Context, cursor: Cursor, fallback: CursorIcon, custom: bool, scale: f32) -> CursorIcon { + clear(ctx); + let fallback = if fallback == CursorIcon::None { CursorIcon::Default } else { fallback }; + if custom && ctx.input(|i| i.focused && i.pointer.hover_pos().is_some()) { + let prepared = ctx.data_mut(|data| data.get_temp_mut_or_default::(Id::unique("native-cursor-bitmaps")).get(cursor, scale)); + if let Some((key, bitmap)) = prepared { + let request = Request { key, bitmap, fallback, viewport: ctx.viewport_id(), pass: ctx.cumulative_pass_nr() }; + let id = pending_id(ctx); + ctx.data_mut(|data| data.insert_temp(id, request)); + } + } + fallback +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/cursors/native_request/tests.rs b/crates/ui-egui/src/cursors/native_request/tests.rs new file mode 100644 index 0000000000..719fc5bcc9 --- /dev/null +++ b/crates/ui-egui/src/cursors/native_request/tests.rs @@ -0,0 +1,98 @@ +use super::*; + +#[test] +fn every_glyph_and_rotation_preserves_pixels_and_logical_hotspots() { + let cursors = super::super::GLYPHS.into_iter().chain((0..8).map(Cursor::RotateToward)); + for cursor in cursors { + for scale in [0.75, 1.0, 1.25, 1.5, 2.0] { + let bitmap = prepare(cursor, scale).unwrap(); + let [one, two] = &bitmap.representations; + assert_eq!(two.size, one.size.map(|x| x * 2)); + assert_eq!(two.hotspot, one.hotspot.map(|x| x * 2)); + for (i, dest) in bitmap.representations.iter().enumerate() { + let source = rasterize(cursor, scale * (i + 1) as f32).unwrap(); + let dx = dest.hotspot[0] - source.hotspot[0]; + let dy = dest.hotspot[1] - source.hotspot[1]; + for y in 0..dest.size[1] { + for x in 0..dest.size[0] { + let offset = (usize::from(y) * usize::from(dest.size[0]) + usize::from(x)) * 4; + let actual = &dest.rgba[offset..offset + 4]; + if x >= dx && x < dx + source.size[0] && y >= dy && y < dy + source.size[1] { + let at = (usize::from(y - dy) * usize::from(source.size[0]) + usize::from(x - dx)) * 4; + assert_eq!(actual, &source.rgba[at..at + 4], "{cursor:?}, {scale}"); + } else { + assert_eq!(actual, [0; 4]); + } + } + } + } + } + } +} + +#[test] +fn invalid_inputs_and_system_states_are_bounded_and_cached() { + let mut cache = Cache::default(); + for scale in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::MAX, 100.0] { + assert!(cache.get(Cursor::Arrow, scale).is_none()); + } + for cursor in [Cursor::Busy, Cursor::NotAllowed, Cursor::ScissorsNotAllowed] { + assert!(cache.get(cursor, 1.0).is_none()); + assert!(cache.get(cursor, 1.0).is_none()); + } + assert_eq!(cache.0.len(), 3); + let good = rasterize(Cursor::Pen, 1.0).unwrap(); + for bad in [ + CustomCursorImage { rgba: Arc::from([]), ..good.clone() }, + CustomCursorImage { size: [u16::MAX, 1], ..good.clone() }, + CustomCursorImage { hotspot: good.size, ..good.clone() }, + ] { + assert!(align([bad, good.clone()]).is_none()); + } + let (_, retained) = cache.get(Cursor::Pen, 1.0).unwrap(); + assert!(Arc::ptr_eq(&retained, &cache.get(Cursor::Pen, 1.0).unwrap().1)); + for i in 0..140 { + cache.get(Cursor::Pen, 1.0 + i as f32 / 1000.0); + } + assert!(cache.0.len() <= CAPACITY); + assert!(valid(&retained.representations[0])); +} + +#[test] +fn requests_are_consumed_per_viewport_and_expire_on_empty_passes() { + let ctx = Context::default(); + let raw = |id| { + let mut input = egui::RawInput { viewport_id: id, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() }; + input.viewports.entry(id).or_default(); + input + }; + let root = ViewportId::ROOT; + let panel = ViewportId::from_hash_of("panel"); + let _ = headless(&ctx, raw(root), |ui| { + request(ui.ctx(), Cursor::Pen, CursorIcon::Crosshair, true, 1.0); + }); + let _ = headless(&ctx, raw(panel), |ui| { + clear(ui.ctx()); + assert!(take(ui.ctx()).is_none()); + }); + assert!(ctx.data(|d| d.get_temp::(Id::unique(("native-canvas-cursor", root)))).is_some()); + let _ = headless(&ctx, raw(root), |ui| { + clear(ui.ctx()); + assert!(take(ui.ctx()).is_none()); + }); + let _ = headless(&ctx, raw(root), |ui| { + request(ui.ctx(), Cursor::Pen, CursorIcon::Crosshair, true, 1.25); + let req = take(ui.ctx()).unwrap(); + assert_eq!(req.viewport, root); + assert_eq!(req.pass, ui.ctx().cumulative_pass_nr()); + assert!(take(ui.ctx()).is_none()); + request(ui.ctx(), Cursor::Pen, CursorIcon::Crosshair, false, 1.0); + assert!(take(ui.ctx()).is_none()); + }); +} + +fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput { + let mut output = ctx.run_ui(input, draw); + output.textures_delta.clear(); + output +} diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index e70f7d488a..63ab6c23a1 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -349,6 +349,9 @@ fn the_canvas_hands_the_tool_cursor_to_the_os_and_idles_while_the_pointer_rests( assert_eq!(img, &app.canvas.cursors.get(Cursor::Arrow, 1.0).unwrap()); // Where the OS can't show the bitmap, its system cursor. assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::Default); + } else if cfg!(target_os = "macos") { + assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::Default); + assert!(out.platform_output.cursor_image.is_none()); } else { assert_eq!(out.platform_output.cursor_icon, egui::CursorIcon::None); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d69241812c..9137442f04 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -152,8 +152,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; @@ -402,6 +402,7 @@ registry! { Plugin: [plugin::KIND] => plugin::SPEC, PluginExport: [plugin::EXPORT_KIND] => plugin::EXPORT_SPEC, PluginImport: [plugin::IMPORT_KIND] => plugin::IMPORT_SPEC, + PluginInstall: [plugin::INSTALL_KIND] => plugin::INSTALL_SPEC, ScriptCheck: [script_check::KIND] => script_check::SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, @@ -559,10 +560,17 @@ 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); } + if d.kind == plugin::INSTALL_KIND { + app.pending_plugin_install = None; + } if d.kind == safe_mode::STOPPED { safe_mode::cancel_stopped(app); } 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 8d4a68ed08..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); } @@ -1109,10 +1128,11 @@ pub(super) fn bleed(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Un } } -/// A small grey caption above a field (New Document's details column). -pub(super) fn caption(ui: &mut egui::Ui, text: &str) { +/// A small grey caption above a field (New Document's details column) → its response, so the field +/// can be named by it. +pub(super) fn caption(ui: &mut egui::Ui, text: &str) -> egui::Response { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(tl!(text)).size(11.0).color(t.text_dim)); + ui.label(egui::RichText::new(tl!(text)).size(11.0).color(t.text_dim)) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 4c977ed6a5..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,28 +406,35 @@ 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); - form::caption(ui, tl!("Document Name")); - ui.horizontal(|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); - form::caption(ui, tl!("Width")); + let caption = form::caption(ui, tl!("Width")); ui.horizontal(|ui| { - form::length(ui, d, "width", unit, DETAILS - 124.0); - units_dropdown(ui, d, 112.0); + ui.label_inputs_by(caption.id, |ui| form::length(ui, d, "width", unit, DETAILS - 124.0)); + ui.name_inputs(tl!("Units"), |ui| units_dropdown(ui, d, 112.0)); }); ui.add_space(4.0); ui.horizontal_top(|ui| { ui.vertical(|ui| { - form::caption(ui, tl!("Height")); - form::length(ui, d, "height", unit, 104.0); + let caption = form::caption(ui, tl!("Height")); + ui.label_inputs_by(caption.id, |ui| form::length(ui, d, "height", unit, 104.0)); }); ui.add_space(6.0); ui.vertical(|ui| { @@ -386,21 +443,22 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut }); ui.add_space(6.0); ui.vertical(|ui| { - form::caption(ui, tl!("Artboards")); - artboards(ui, d, 76.0); + let caption = form::caption(ui, tl!("Artboards")); + ui.label_inputs_by(caption.id, |ui| artboards(ui, d, "newdoc-artboards", 76.0)); }); }); ui.add_space(8.0); form::caption(ui, tl!("Bleed")); form::bleed(ui, d, unit, 52.0); ui.add_space(8.0); - form::caption(ui, tl!("Background Contents")); - background(ui, d, DETAILS - 34.0); + let caption = form::caption(ui, tl!("Background Contents")); + ui.label_inputs_by(caption.id, |ui| background(ui, d, DETAILS - 34.0)); 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,43 +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); - form::caption(ui, tl!("Preset Name")); - ui.horizontal(|ui| { - let enter = form::text_edit(ui, d, "presetName", DETAILS - 140.0).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) { @@ -480,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)); } }); @@ -542,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; @@ -791,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 @@ -877,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; @@ -896,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())), @@ -905,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}"); } @@ -956,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); @@ -976,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/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index ba00752060..76f71f3b4e 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -13,16 +13,22 @@ //! Export button writes the file. Importers open the files File › Open finds no built-in format //! for, and File › Open With lists them, to open a file with one of them by name; one with //! parameters opens dialog `pluginImport` once the file is picked, and its Open button opens it. +//! +//! Dialog `pluginInstall` asks a person to approve a plug-in's permissions or heavy budget. What it +//! shows and installs is held by the app, not in its fields; a control request or synthetic input +//! can't confirm it. Enter confirms it only when OK has the keyboard focus. use std::sync::Arc; use serde_json::{Map, Value, json}; +use vectorcraft_engine::cmd::plugin::InstallApproval; use vectorcraft_plugins::{Budget, Kind, Manifest, Plugin, permissions, registry}; -use super::{DialogSpec, form}; +use super::{DialogAction, DialogSpec, form}; use crate::VectorcraftApp; use crate::menus::Item; use crate::state::Dialog; +use crate::widgets; /// The dialog kind of plug-in filters. pub const KIND: &str = "plugin"; @@ -310,3 +316,71 @@ fn import_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result let picked = p["picked"] == true; crate::io::open_with_on(app, &p, picked && crate::opening::available()) } + +/// The dialog kind of the approval of a plug-in install. +pub const INSTALL_KIND: &str = "pluginInstall"; + +/// A plug-in install waiting for a person's answer. +pub(crate) struct PendingInstall { + /// The question and the lines under it, in the UI language. + pub message: String, + pub detail: String, + /// `plugin.install`'s params for OK. + pub params: Value, + /// What OK approves: the module the question is about. + pub approval: InstallApproval, +} + +/// No OK in the shared footer: the OK in its body is a `Sense::click` button, which Enter clicks +/// only when it has the keyboard focus. +pub(super) const INSTALL_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Install Plug-in…").trim_end_matches('…').to_string(), + body_with_actions: Some(install_body), + confirm: install_confirm, + ok: None, + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Asks a person whether to install what `pending` describes. → `{pending}`. +pub(crate) fn ask_install(app: &mut VectorcraftApp, pending: PendingInstall) -> Value { + app.pending_plugin_install = Some(pending); + app.ui.dialog = Some(Dialog::new(INSTALL_KIND, json!({}))); + json!({ "pending": INSTALL_KIND }) +} + +fn install_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> DialogAction { + let Some(pending) = app.pending_plugin_install.as_ref() else { return DialogAction::Cancel }; + ui.label(egui::RichText::new(&pending.message).strong()); + ui.add_space(8.0); + ui.label(egui::RichText::new(&pending.detail).color(crate::theme::Tokens::get(ui.ctx()).text_dim)); + ui.add_space(16.0); + let mut action = DialogAction::None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::primary_button_enabled(ui, "OK", true).clicked() { + action = DialogAction::Confirm; + } + ui.add_space(8.0); + if widgets::secondary_button(ui, "Cancel").clicked() { + action = DialogAction::Cancel; + } + }); + action +} + +/// OK: installs the module the dialog showed, if a person pressed it; automation is refused and the +/// dialog stays open. +fn install_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { + if app.automation_is_acting() { + return Err("Only the person at the keyboard can approve installing a plug-in".into()); + } + app.ui.dialog = None; + let Some(pending) = app.pending_plugin_install.take() else { return Ok(Value::Null) }; + app.session.approve_plugin_install(pending.approval); + let r = app.run("plugin.install", pending.params); + app.session.clear_plugin_install_approval(); + let r = r?; + crate::io::report_installed(app, &r); + Ok(r) +} diff --git a/crates/ui-egui/src/dialogs/tests_accessibility.rs b/crates/ui-egui/src/dialogs/tests_accessibility.rs index ac469f6b72..d3ef1ce8ce 100644 --- a/crates/ui-egui/src/dialogs/tests_accessibility.rs +++ b/crates/ui-egui/src/dialogs/tests_accessibility.rs @@ -81,6 +81,35 @@ fn document_setup_names_each_bleed_side() { } } +/// New Document's Preset Details column names each field by the caption above it. +#[test] +fn new_document_names_its_fields_by_their_captions() { + let mut app = app(); + app.run("file.newDialog", json!({})).unwrap(); + let h = strict(app); + for name in ["Document Name", "Width", "Height", "Artboards"] { + let _ = h.get_by_role_and_label(Role::TextInput, name); + } + for name in ["Units", "Background Contents"] { + let _ = h.get_by_role_and_label(Role::ComboBox, name); + } +} + +/// 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(); + app.run("file.newDialog", json!({})).unwrap(); + 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); + 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 /// inputs by axis and context. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs index 8a66bc8a94..f5f4e719a0 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -13,6 +13,13 @@ use vectorcraft_plugins::wat as tpl; use super::*; +/// The install approval has no OK in the shared footer, so Enter presses OK only when OK has the +/// keyboard focus. +#[test] +fn enter_does_not_answer_the_install_approval() { + assert!(plugin::INSTALL_SPEC.ok.is_none() && plugin::INSTALL_SPEC.body_with_actions.is_some()); +} + /// A filter whose parameters use every presentation key. fn manifest(id: &str) -> String { format!( diff --git a/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs b/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs index 0249bb1999..75aecde466 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,94 @@ 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 clipping_group() -> Vec<(&'static str, Value)> { + vec![ + ("shape.ellipse", json!({"x":20,"y":20,"width":100,"height":100})), + ("shape.rectangle", json!({"x":60,"y":60,"width":100,"height":100})), + ("select.all", json!({})), + ("object.clippingMask.make", json!({})), + ] +} + +/// #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(&clipping_group(), true); + assert!(!h.ok_is_on()); + assert!(h.shows("requires a path")); + 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(&clipping_group(), false); + assert!(!h.ok_is_on()); + assert!(h.shows("requires a path")); + 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(&clipping_group(), 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("requires a path")); + 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/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 2f620a7dfa..619c563e44 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -340,6 +340,14 @@ fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool { true } +/// Gives the main window the keyboard when a floating document's OS window has it. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn focus_main_window(app: &VectorcraftApp, ctx: &egui::Context) { + if native(app, ctx) && app.ui.floating.iter().any(|w| w.focused) { + ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); + } +} + /// The OS window of document window `w`. fn viewport_id(w: &DocWindow) -> egui::ViewportId { egui::ViewportId::from_hash_of(("vectorcraft-document-window", w.uid, w.number)) diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 4311d8bbe8..64a693a09b 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -451,6 +451,41 @@ fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() { ); } +/// The update prompt, opening on its own, takes the keyboard once from a document's OS window that +/// has it, and leaves the keyboard alone when none of those windows has it. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_update_prompt_takes_the_keyboard_from_a_document_window() { + let _host = native_host(); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let mut app = app_with(2); + if !native(&app, &ctx) { + // Wayland: the windows are inside the main window. + return; + } + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let focus_commands = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::updates_ui::show(app, ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(0, |v| v.commands.iter().filter(|c| **c == egui::ViewportCommand::Focus).count()) + }; + + app.ui.floating[0].focused = true; + assert_eq!(focus_commands(&mut app), 0, "no prompt is open"); + crate::updates_ui::open_prompt_for_test(&mut app); + assert_eq!(focus_commands(&mut app), 1, "the main window gets the keyboard"); + assert_eq!(focus_commands(&mut app), 0, "once"); + + crate::updates_ui::close_dialogs_for_test(&mut app); + assert_eq!(focus_commands(&mut app), 0, "the prompt closed"); + app.ui.floating[0].focused = false; + crate::updates_ui::open_prompt_for_test(&mut app); + assert_eq!(focus_commands(&mut app), 0, "no document window has the keyboard"); +} + /// Where the last frame drew the title of `title`'s tab in the tab strip. fn tab_at(shapes: &[Shape], title: &str) -> Pos2 { shapes 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 3d639e1801..05ba6858f8 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 Запази данни за възстановяване @@ -3422,7 +3422,6 @@ digits Malayalam Малаялам Template Шаблон Templates Шаблони Templates Folder Папка с шаблони - Templates… Шаблони… Text Displayed in Cell: Текст, показван в клетката: Text Export Options Опции за експортиране на текст Text Fill & Stroke Color Цвят на запълване и щрих на текста @@ -5833,6 +5832,9 @@ axis Y Axis Y ос @plural Result: {n}|Results: {n} Резултат: {n}|Резултати: {n} Add to Symbols Добавяне към символи Basic Shapes Основни фигури + Button Бутон + Panel Панел + UI Frames UI рамки Open Symbol Library Отваряне на библиотека със символи Save Symbol Library Запазване на библиотека със символи Save Symbol Library… Запази библиотека със символи… @@ -5893,6 +5895,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 Скриване на опциите за прилепване към глиф @@ -6296,7 +6300,7 @@ breakText Glyphs Глифи Reset Symbol Instance Нулиране на екземпляра на символ @msg type must be static or dynamic, not {v} type трябва да е static или dynamic, а не {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` е статичен символ: първо задайте типа на символа на „Динамичен“ -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change На път, съставен път или текст, избран в екземпляр на символ, могат да се променят само плътните цветове на запълването и контура +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change На път, съставен път или текст, избран в екземпляр на символ, могат да се променят само запълването, контурът, непрозрачността и режим на смесване @msg path must be a list of child indices path трябва да е списък с индекси на дъщерни обекти @msg no object at path {shown} in the symbol's art в графиката на символа няма обект на пътя {shown} @msg give fill, stroke, opacity and/or blend задайте fill, stroke, opacity и/или blend diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 33bf4b5eb0..eb96edd5f8 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 @@ -964,6 +965,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 +2533,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 +2549,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 +3484,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 @@ -5792,7 +5791,7 @@ axis Y Axis Y osa @msg Running “{name}”… Pokretanje „{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` živi efekat radi dok se dokument iscrtava, pa ne može biti `heavy` @msg an exporter always gets an export's budget: leave `budget` out izvoznik uvijek dobija budžet izvoza: izostavite `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees „{_1}” traži veliki budžet (svako pokretanje do {minutes} minuta i {times} puta više uobičajenih instrukcija): instalirajte ga s `allowHeavy: true` kada korisnik pristane +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” traži veliki budžet (svako pokretanje do {minutes} minuta i {times} puta više uobičajenih instrukcija): osoba ga mora odobriti u desktop aplikaciji, ili proslijedite `allowHeavy: true` u sesiji pokrenutoj s --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instalirati „{name}”, koji traži ove dozvole? ID: {id} ID: {id} @@ -5823,7 +5822,9 @@ axis Y Axis Y osa @msg permission `{shown}` is listed twice dozvola `{shown}` navedena je dvaput @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it dozvola `{shown}` rezervisana je za kasniji API dodataka; ovaj domaćin je ne dodjeljuje @msg unknown permission `{shown}` nepoznata dozvola `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees „{name}” traži dozvole {asked}: instalirajte ga s `grant` koji ih navodi kada korisnik pristane +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}” traži dozvole {asked}: osoba ih mora odobriti u desktop aplikaciji, ili proslijedite `grant` u sesiji pokrenutoj s --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` i `allowHeavy` važe samo u sesiji pokrenutoj s --allow-plugin-grants: odobrite dodatak u desktop aplikaciji +@msg Only the person at the keyboard can approve installing a plug-in Instalaciju dodatka može odobriti samo osoba za tastaturom @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” nije dobio `{p}`, što je potrebno njegovom izlazu: ništa nije promijenjeno @msg the module doesn't have the SHA-256 `hash` gives: nothing was installed modul nema SHA-256 naveden u `hash`: ništa nije instalirano New Set… Novi skup… @@ -5875,6 +5876,9 @@ axis Y Axis Y osa @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ili raspon poput 1, 3-5, a ne {v} Add to Symbols Dodaj u simbole Basic Shapes Osnovni oblici + Button Dugme + Panel Panel + UI Frames UI okviri Open Symbol Library Otvori biblioteku simbola Save Symbol Library Sačuvaj biblioteku simbola Save Symbol Library… Sačuvaj biblioteku simbola… @@ -5947,6 +5951,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 @@ -6344,7 +6350,7 @@ shape Open Otvoren Reset Symbol Instance Vrati instancu simbola na početno @msg type must be static or dynamic, not {v} type mora biti static ili dynamic, a ne {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` je statički simbol: prvo postavite vrstu simbola na Dinamički -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Putanji, složenoj putanji ili tekstu odabranom u instanci simbola mogu se mijenjati samo pune boje ispune i poteza +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Putanji, složenoj putanji ili tekstu odabranom u instanci simbola mogu se mijenjati samo ispuna, potez, neprozirnost i mješanje @msg path must be a list of child indices path mora biti lista indeksa podređenih objekata @msg no object at path {shown} in the symbol's art nema objekta na putanji {shown} u grafici simbola @msg give fill, stroke, opacity and/or blend navedite fill, stroke, opacity i/ili blend diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 038950b625..cad8f83d4a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -423,7 +423,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 @@ -441,6 +440,9 @@ antiAlias Sharp Nítid Basic Bàsic Basic Latin Llatí bàsic Basic Shapes Formes bàsiques + Button Botó + Panel Panell + UI Frames Marcs d’IU Batch Lot Batch… Lot… Bearing Orientació @@ -792,6 +794,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 @@ -914,7 +917,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: @@ -2336,6 +2338,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 @@ -2594,7 +2597,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) @@ -3640,6 +3642,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ó @@ -4366,7 +4369,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 @@ -5431,6 +5433,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 @@ -5851,6 +5854,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) @@ -5909,7 +5917,7 @@ 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 or group. Convert images and other objects to paths first. {label} actualment requereix un traçat, un traçat compost, text o un grup. Converteix primer les imatges i altres objectes en traçats. @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 @@ -5927,7 +5935,7 @@ digits Malayalam Malaiàlam @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools {tool} no forma part d’un grup de diverses eines a la barra d’eines -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees «{_1}» demana un pressupost elevat (cada execució fins a {minutes} minuts i {times} vegades les instruccions habituals): instal·la’l amb `allowHeavy: true` quan l’usuari hi estigui d’acord +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» demana un pressupost elevat (cada execució fins a {minutes} minuts i {times} vegades les instruccions habituals): una persona l’ha d’aprovar a l’aplicació d’escriptori, o passa `allowHeavy: true` en una sessió iniciada amb --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instal·la «{name}», que demana aquests permisos? ID: {id} ID: {id} @@ -5967,7 +5975,9 @@ digits Malayalam Malaiàlam @msg object budget (more than {MAX_OBJECTS} read-only objects) pressupost d’objectes (més de {MAX_OBJECTS} objectes de només lectura) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permís `{shown}` està reservat per a una API de complements posterior; aquest amfitrió no el concedeix @msg unknown permission `{shown}` permís desconegut `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees «{name}» demana els permisos {asked}: instal·la’l amb un `grant` que els enumeri quan l’usuari hi estigui d’acord +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants «{name}» demana els permisos {asked}: una persona els ha d’aprovar a l’aplicació d’escriptori, o passa `grant` en una sessió iniciada amb --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` i `allowHeavy` només tenen efecte en una sessió iniciada amb --allow-plugin-grants: aprova el complement a l’aplicació d’escriptori +@msg Only the person at the keyboard can approve installing a plug-in Només la persona al teclat pot aprovar la instal·lació d’un complement @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a «{name}» no se li ha concedit `{p}`, que la seva sortida necessita: no s’ha canviat res @msg a heavy filter runs in the background, so it can't declare `commands` un filtre pesat s’executa en segon pla, de manera que no pot declarar `commands` @msg at most {MAX_COMMANDS} `commands` com a màxim {MAX_COMMANDS} `commands` @@ -6057,6 +6067,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 @@ -6493,7 +6505,7 @@ breakText Glyphs Glifs Reset Symbol Instance Restableix la instància de símbol @msg type must be static or dynamic, not {v} type ha de ser static o dynamic, no {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` és un símbol estàtic: primer establiu el tipus de símbol a Dinàmic -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change D'un traçat, un traçat compost o un text seleccionat en una instància de símbol només es pot canviar el color sòlid de l'emplenament i el traç +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change En un traçat, traçat compost o text seleccionat en una instància de símbol només es poden canviar l'emplenament, el traç, l'opacitat i la fusió @msg path must be a list of child indices path ha de ser una llista d’índexs de fills @msg no object at path {shown} in the symbol's art no hi ha cap objecte al camí {shown} de l’art del símbol @msg give fill, stroke, opacity and/or blend indiqueu fill, stroke, opacity i/o blend @@ -6643,3 +6655,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 85adaff0c4..e494c36668 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 @@ -984,6 +985,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 +2564,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 +2580,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 +3534,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 @@ -4724,6 +4723,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 +5587,7 @@ 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 or group. Convert images and other objects to paths first. {label} zatím vyžaduje cestu, složenou cestu, text nebo skupinu. Obrazy a další objekty nejprve převeďte na cesty. @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 +5595,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 @@ -5919,7 +5924,7 @@ axis Y Axis osa Y @msg Running “{name}”… Spouští se „{name}“… @msg a live effect runs while the document is drawn, so it can't be `heavy` živý efekt běží během vykreslování dokumentu, takže nemůže být `heavy` @msg an exporter always gets an export's budget: leave `budget` out exportní zásuvný modul dostává vždy rozpočet exportu: klíč `budget` vynechte -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees „{_1}“ žádá o velký výpočetní rozpočet (každé spuštění až {minutes} minut a {times}krát víc instrukcí než obvykle): nainstalujte ho s `allowHeavy: true`, jakmile uživatel souhlasí +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ žádá o velký výpočetní rozpočet (každé spuštění až {minutes} minut a {times}krát víc instrukcí než obvykle): musí ho schválit člověk v desktopové aplikaci, nebo předejte `allowHeavy: true` v relaci spuštěné s --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Nainstalovat „{name}“, který žádá o tato oprávnění? ID: {id} ID: {id} @@ -5959,7 +5964,9 @@ axis Y Axis osa Y @msg object budget (more than {MAX_OBJECTS} read-only objects) rozpočet objektů (více než {MAX_OBJECTS} objektů jen pro čtení) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it oprávnění `{shown}` je vyhrazeno pro pozdější API zásuvných modulů; tento hostitel ho neuděluje @msg unknown permission `{shown}` neznámé oprávnění `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees „{name}“ žádá o oprávnění {asked}: nainstalujte ho s `grant`, který je uvádí, jakmile uživatel souhlasí +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}“ žádá o oprávnění {asked}: musí je schválit člověk v desktopové aplikaci, nebo předejte `grant` v relaci spuštěné s --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` a `allowHeavy` platí jen v relaci spuštěné s --allow-plugin-grants: schvalte zásuvný modul v desktopové aplikaci +@msg Only the person at the keyboard can approve installing a plug-in Instalaci zásuvného modulu může schválit jen člověk u klávesnice @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ nedostal `{p}`, které jeho výstup potřebuje: nic se nezměnilo @msg a heavy filter runs in the background, so it can't declare `commands` těžký filtr běží na pozadí, takže nemůže deklarovat `commands` @msg at most {MAX_COMMANDS} `commands` nejvýše {MAX_COMMANDS} `commands` @@ -6020,6 +6027,9 @@ axis Y Axis osa Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all nebo rozsah, například 1, 3-5, ne {v} Add to Symbols Přidat do symbolů Basic Shapes Základní tvary + Button Tlačítko + Panel Panel + UI Frames Rámce UI Open Symbol Library Otevřít knihovnu symbolů Save Symbol Library Uložit knihovnu symbolů Save Symbol Library… Uložit knihovnu symbolů… @@ -6094,6 +6104,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 @@ -6512,7 +6524,7 @@ breakText Glyphs Glyfy Reset Symbol Instance Obnovit instanci symbolu @msg type must be static or dynamic, not {v} type musí být static nebo dynamic, ne {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` je statický symbol: nejprve nastavte jeho typ symbolu na Dynamický -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change U cesty, složené cesty nebo textu vybraného v instanci symbolu lze měnit jen plnou barvu výplně a tahu +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change U cesty, složené cesty nebo textu vybraného v instanci symbolu lze měnit jen výplň, tah, krytí a režim prolnutí @msg path must be a list of child indices path musí být seznam indexů potomků @msg no object at path {shown} in the symbol's art v kresbě symbolu není na cestě {shown} žádný objekt @msg give fill, stroke, opacity and/or blend zadejte fill, stroke, opacity a/nebo blend @@ -6662,3 +6674,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 453b5c9c29..9cf36f69f5 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 @@ -905,6 +906,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 +2352,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 +2368,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 +3271,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 @@ -5848,6 +5847,9 @@ axis Y Axis Y-akse @plural Result: {n}|Results: {n} Resultat: {n}|Resultater: {n} Add to Symbols Føj til symboler Basic Shapes Grundlæggende former + Button Knap + Panel Panel + UI Frames UI-rammer Open Symbol Library Åbn symbolbibliotek Save Symbol Library Gem symbolbibliotek Save Symbol Library… Gem symbolbibliotek… @@ -5908,6 +5910,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 @@ -6310,7 +6314,7 @@ breakText Glyphs Glyffer Reset Symbol Instance Nulstil symbolforekomst @msg type must be static or dynamic, not {v} type skal være static eller dynamic, ikke {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` er et statisk symbol: indstil først symboltypen til Dynamisk -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change For en kurve, sammensat kurve eller tekst, der er markeret i en symbolforekomst, kan kun ensfarvet fyld og streg ændres +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change For en kurve, sammensat kurve eller tekst markeret i en symbolforekomst kan kun fyld, streg, opacitet og blanding ændres @msg path must be a list of child indices path skal være en liste over underordnede indekser @msg no object at path {shown} in the symbol's art intet objekt ved stien {shown} i symbolets grafik @msg give fill, stroke, opacity and/or blend angiv fill, stroke, opacity og/eller blend diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d1564645f4..740231edd7 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 @@ -3454,7 +3454,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 @@ -4331,6 +4330,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 +5154,7 @@ 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 or group. Convert images and other objects to paths first. {label} erfordert derzeit einen Pfad, zusammengesetzten Pfad, Text oder eine Gruppe. Wandeln Sie Bilder und andere Objekte zuerst in Pfade um. @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 +5162,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 @@ -5502,7 +5507,7 @@ axis Y Axis Y-Achse @msg Running “{name}”… „{name}“ wird ausgeführt… @msg a live effect runs while the document is drawn, so it can't be `heavy` ein Live-Effekt läuft, während das Dokument gezeichnet wird, daher kann er nicht `heavy` sein @msg an exporter always gets an export's budget: leave `budget` out ein Export-Plug-in erhält immer das Budget eines Exports: Lassen Sie `budget` weg -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees „{_1}“ verlangt ein großes Rechenbudget (jede Ausführung bis zu {minutes} Minuten und {times}-mal so viele Anweisungen wie üblich): Installieren Sie es mit `allowHeavy: true`, sobald der Benutzer zustimmt +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ verlangt ein großes Rechenbudget (jede Ausführung bis zu {minutes} Minuten und {times}-mal so viele Anweisungen wie üblich): Eine Person muss es in der Desktop-App genehmigen, oder übergeben Sie `allowHeavy: true` in einer mit --allow-plugin-grants gestarteten Sitzung # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? „{name}“ installieren, das diese Berechtigungen verlangt? ID: {id} ID: {id} @@ -5542,7 +5547,9 @@ axis Y Axis Y-Achse @msg object budget (more than {MAX_OBJECTS} read-only objects) Objektbudget (mehr als {MAX_OBJECTS} schreibgeschützte Objekte) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it die Berechtigung `{shown}` ist für eine spätere Plug-in-API reserviert; dieser Host gewährt sie nicht @msg unknown permission `{shown}` unbekannte Berechtigung `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees „{name}“ verlangt die Berechtigungen {asked}: Installieren Sie es mit `grant`, das sie aufführt, sobald der Benutzer zustimmt +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}“ verlangt die Berechtigungen {asked}: Eine Person muss sie in der Desktop-App genehmigen, oder übergeben Sie `grant` in einer mit --allow-plugin-grants gestarteten Sitzung +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` und `allowHeavy` wirken nur in einer mit --allow-plugin-grants gestarteten Sitzung: Genehmigen Sie das Plug-in in der Desktop-App +@msg Only the person at the keyboard can approve installing a plug-in Nur die Person an der Tastatur kann die Installation eines Plug-ins genehmigen @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ wurde `{p}` nicht gewährt, das seine Ausgabe braucht: Es wurde nichts geändert @msg a heavy filter runs in the background, so it can't declare `commands` ein schwerer Filter läuft im Hintergrund und kann daher keine `commands` deklarieren @msg at most {MAX_COMMANDS} `commands` höchstens {MAX_COMMANDS} `commands` @@ -5603,6 +5610,9 @@ axis Y Axis Y-Achse @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all oder ein Bereich wie 1, 3-5, nicht {v} Add to Symbols Zu Symbolen hinzufügen Basic Shapes Grundformen + Button Schaltfläche + Panel Bedienfeld + UI Frames UI-Rahmen Open Symbol Library Symbol-Bibliothek öffnen Save Symbol Library Symbol-Bibliothek speichern Save Symbol Library… Symbol-Bibliothek speichern… @@ -5677,6 +5687,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 @@ -6099,7 +6111,7 @@ breakText Glyphs Glyphen Reset Symbol Instance Symbolinstanz zurücksetzen @msg type must be static or dynamic, not {v} type muss static oder dynamic sein, nicht {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` ist ein statisches Symbol: Stellen Sie zuerst den Symboltyp auf „Dynamisch“ ein -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Bei einem in einer Symbolinstanz ausgewählten Pfad, zusammengesetzten Pfad oder Text lässt sich nur die Vollfarbe von Fläche und Kontur ändern +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Bei einem Pfad, zusammengesetzten Pfad oder Text, der in einer Symbolinstanz ausgewählt ist, können nur Fläche, Kontur, Decigkeit und Füllmethode geändert werden @msg path must be a list of child indices path muss eine Liste von Kindindizes sein @msg no object at path {shown} in the symbol's art kein Objekt am Pfad {shown} in der Grafik des Symbols @msg give fill, stroke, opacity and/or blend geben Sie fill, stroke, opacity und/oder blend an @@ -6249,3 +6261,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d7bb1c96f8..7e1fb15850 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 Χρωματική απόχρωση @@ -2902,7 +2901,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 +3464,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 Αποθήκευση προεπιλογής για ιστό @@ -4369,6 +4368,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 +4948,7 @@ 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 or group. Convert images and other objects to paths first. Το {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 +4956,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 χρώματα @@ -5870,7 +5875,7 @@ axis Y Axis Άξονας Y @msg Running “{name}”… Εκτέλεση του «{name}»… @msg a live effect runs while the document is drawn, so it can't be `heavy` ένα δυναμικό εφέ εκτελείται κατά τη σχεδίαση του εγγράφου, οπότε δεν μπορεί να είναι `heavy` @msg an exporter always gets an export's budget: leave `budget` out ένα πρόσθετο εξαγωγής παίρνει πάντα τον προϋπολογισμό μιας εξαγωγής: παραλείψτε το `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees το «{_1}» ζητά μεγάλο υπολογιστικό προϋπολογισμό (κάθε εκτέλεση έως {minutes} λεπτά και {times} φορές τις συνήθεις εντολές): εγκαταστήστε το με `allowHeavy: true` μόλις συμφωνήσει ο χρήστης +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants το «{_1}» ζητά μεγάλο υπολογιστικό προϋπολογισμό (κάθε εκτέλεση έως {minutes} λεπτά και {times} φορές τις συνήθεις εντολές): πρέπει να το εγκρίνει ένα άτομο στην εφαρμογή επιφάνειας εργασίας ή περάστε `allowHeavy: true` σε μια συνεδρία που ξεκίνησε με --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Να εγκατασταθεί το «{name}», που ζητά αυτά τα δικαιώματα; ID: {id} Αναγνωριστικό: {id} @@ -5910,7 +5915,9 @@ axis Y Axis Άξονας Y @msg object budget (more than {MAX_OBJECTS} read-only objects) προϋπολογισμός αντικειμένων (περισσότερα από {MAX_OBJECTS} αντικείμενα μόνο για ανάγνωση) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it το δικαίωμα `{shown}` είναι δεσμευμένο για μεταγενέστερο API προσθέτων· αυτός ο κεντρικός υπολογιστής δεν το παραχωρεί @msg unknown permission `{shown}` άγνωστο δικαίωμα `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees το «{name}» ζητά τα δικαιώματα {asked}: εγκαταστήστε το με ένα `grant` που τα απαριθμεί μόλις συμφωνήσει ο χρήστης +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants το «{name}» ζητά τα δικαιώματα {asked}: πρέπει να τα εγκρίνει ένα άτομο στην εφαρμογή επιφάνειας εργασίας ή περάστε `grant` σε μια συνεδρία που ξεκίνησε με --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app τα `grant` και `allowHeavy` ισχύουν μόνο σε συνεδρία που ξεκίνησε με --allow-plugin-grants: εγκρίνετε το πρόσθετο στην εφαρμογή επιφάνειας εργασίας +@msg Only the person at the keyboard can approve installing a plug-in Μόνο το άτομο στο πληκτρολόγιο μπορεί να εγκρίνει την εγκατάσταση ενός πρόσθετου @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed στο «{name}» δεν παραχωρήθηκε το `{p}`, που χρειάζεται η έξοδός του: δεν άλλαξε τίποτα @msg a heavy filter runs in the background, so it can't declare `commands` ένα βαρύ φίλτρο εκτελείται στο παρασκήνιο, οπότε δεν μπορεί να δηλώνει `commands` @msg at most {MAX_COMMANDS} `commands` το πολύ {MAX_COMMANDS} `commands` @@ -5971,6 +5978,9 @@ axis Y Axis Άξονας Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ή ένα εύρος όπως 1, 3-5, όχι {v} Add to Symbols Προσθήκη στα σύμβολα Basic Shapes Βασικά σχήματα + Button Κουμπί + Panel Πίνακας + UI Frames Πλαίσια UI Open Symbol Library Άνοιγμα βιβλιοθήκης συμβόλων Save Symbol Library Αποθήκευση βιβλιοθήκης συμβόλων Save Symbol Library… Αποθήκευση βιβλιοθήκης συμβόλων… @@ -6045,6 +6055,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 Απόκρυψη επιλογών προσκόλλησης σε γλυφή @@ -6464,7 +6476,7 @@ breakText Glyphs Γλύφοι Reset Symbol Instance Επαναφορά στιγμιότυπου συμβόλου @msg type must be static or dynamic, not {v} το type πρέπει να είναι static ή dynamic, όχι {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first το `{name}` είναι στατικό σύμβολο: ορίστε πρώτα τον τύπο συμβόλου σε Δυναμικό -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Σε διαδρομή, σύνθετη διαδρομή ή κείμενο που έχει επιλεγεί σε στιγμιότυπο συμβόλου αλλάζει μόνο το συμπαγές χρώμα του γεμίσματος και της πινελιάς +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Σε μια διαδρομή, σύνθετη διαδρομή ή κείμενο που έχει επιλεγεί σε στιγμιότυπο συμβόλου μπορούν να αλλάξουν μόνο το γέμισμα, η διαδρομή, η αδιαφάνεια και η ανάμειξη @msg path must be a list of child indices το path πρέπει να είναι λίστα δεικτών θυγατρικών αντικειμένων @msg no object at path {shown} in the symbol's art δεν υπάρχει αντικείμενο στη διαδρομή {shown} στο γραφικό του συμβόλου @msg give fill, stroke, opacity and/or blend δώστε fill, stroke, opacity ή/και blend @@ -6614,3 +6626,6 @@ 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 Καμία πρόταση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 592db60c27..ebd4165638 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 @@ -3510,7 +3510,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 @@ -4415,6 +4414,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 +5528,7 @@ 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 or group. Convert images and other objects to paths first. {label} requiere por ahora un trazado, un trazado compuesto, texto o un grupo. Convierta primero las imágenes y otros objetos en trazados. @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 +5536,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 @@ -5861,7 +5866,7 @@ axis Y Axis Eje Y @msg Running “{name}”… Ejecutando “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` un efecto interactivo se ejecuta mientras se dibuja el documento, así que no puede ser `heavy` @msg an exporter always gets an export's budget: leave `budget` out un plugin de exportación siempre recibe el presupuesto de una exportación: omite `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}” pide un presupuesto de cálculo grande (cada ejecución hasta {minutes} minutos y {times} veces las instrucciones habituales): instálalo con `allowHeavy: true` cuando el usuario lo acepte +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” pide un presupuesto de cálculo grande (cada ejecución hasta {minutes} minutos y {times} veces las instrucciones habituales): una persona debe aprobarlo en la aplicación de escritorio, o pasa `allowHeavy: true` en una sesión iniciada con --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? ¿Instalar “{name}”, que pide estos permisos? ID: {id} ID: {id} @@ -5901,7 +5906,9 @@ axis Y Axis Eje Y @msg object budget (more than {MAX_OBJECTS} read-only objects) presupuesto de objetos (más de {MAX_OBJECTS} objetos de solo lectura) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it el permiso `{shown}` está reservado para una API de plugins posterior; este host no lo concede @msg unknown permission `{shown}` permiso desconocido `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}” pide los permisos {asked}: instálalo con un `grant` que los incluya cuando el usuario lo acepte +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” pide los permisos {asked}: una persona debe aprobarlos en la aplicación de escritorio, o pasa `grant` en una sesión iniciada con --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` y `allowHeavy` solo tienen efecto en una sesión iniciada con --allow-plugin-grants: aprueba el complemento en la aplicación de escritorio +@msg Only the person at the keyboard can approve installing a plug-in Solo la persona que está en el teclado puede aprobar la instalación de un complemento @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” no se le concedió `{p}`, que su resultado necesita: no se cambió nada @msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesado se ejecuta en segundo plano, así que no puede declarar `commands` @msg at most {MAX_COMMANDS} `commands` como máximo {MAX_COMMANDS} `commands` @@ -5962,6 +5969,9 @@ axis Y Axis Eje Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervalo como 1, 3-5, no {v} Add to Symbols Agregar a símbolos Basic Shapes Formas básicas + Button Botón + Panel Panel + UI Frames Marcos de IU Open Symbol Library Abrir biblioteca de símbolos Save Symbol Library Guardar biblioteca de símbolos Save Symbol Library… Guardar biblioteca de símbolos… @@ -6036,6 +6046,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 @@ -6455,7 +6467,7 @@ breakText Glyphs Glifos Reset Symbol Instance Restablecer instancia de símbolo @msg type must be static or dynamic, not {v} type debe ser static o dynamic, no {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` es un símbolo estático: primero establezca su tipo de símbolo en Dinámico -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change De un trazado, trazado compuesto o texto seleccionado en una instancia de símbolo solo se puede cambiar el color sólido del relleno y del trazo +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change En un trazado, trazado compuesto o texto seleccionado en una instancia de símbolo solo se pueden cambiar el relleno, el trazo, la opacidad y la fusión @msg path must be a list of child indices path debe ser una lista de índices de hijos @msg no object at path {shown} in the symbol's art no hay ningún objeto en la ruta {shown} del arte del símbolo @msg give fill, stroke, opacity and/or blend indique fill, stroke, opacity y/o blend @@ -6605,3 +6617,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a50a11ad66..2923bee24d 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 @@ -963,6 +964,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 +2508,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 +2524,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 +3472,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 @@ -4632,6 +4631,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 +5471,7 @@ 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 or group. Convert images and other objects to paths first. {label} vaatii tällä hetkellä polun, yhdistelmäpolun, tekstin tai ryhmän. Muunna kuvat ja muut objektit ensin poluiksi. @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 +5479,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 @@ -5949,7 +5954,7 @@ axis Y Axis Y-akseli @msg Running “{name}”… Suoritetaan ”{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` live-tehoste suoritetaan asiakirjaa piirrettäessä, joten se ei voi olla `heavy` @msg an exporter always gets an export's budget: leave `budget` out vientilaajennus saa aina viennin budjetin: jätä `budget` pois -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees ”{_1}” pyytää suurta laskentabudjettia (jokainen ajo enintään {minutes} minuuttia ja {times} kertaa tavallinen määrä käskyjä): asenna se asetuksella `allowHeavy: true`, kun käyttäjä hyväksyy +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants ”{_1}” pyytää suurta laskentabudjettia (jokainen ajo enintään {minutes} minuuttia ja {times} kertaa tavallinen määrä käskyjä): ihmisen on hyväksyttävä se työpöytäsovelluksessa, tai anna `allowHeavy: true` istunnossa, joka on käynnistetty valitsimella --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Asennetaanko ”{name}”, joka pyytää näitä käyttöoikeuksia? ID: {id} Tunnus: {id} @@ -5989,7 +5994,9 @@ axis Y Axis Y-akseli @msg object budget (more than {MAX_OBJECTS} read-only objects) objektibudjetti (yli {MAX_OBJECTS} vain luku -objektia) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it käyttöoikeus `{shown}` on varattu myöhemmälle laajennus-API:lle; tämä isäntä ei myönnä sitä @msg unknown permission `{shown}` tuntematon käyttöoikeus `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees ”{name}” pyytää käyttöoikeuksia {asked}: asenna se `grant`-luettelolla, jossa ne ovat, kun käyttäjä suostuu +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants ”{name}” pyytää käyttöoikeuksia {asked}: ihmisen on hyväksyttävä ne työpöytäsovelluksessa, tai anna `grant` istunnossa, joka on käynnistetty valitsimella --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` ja `allowHeavy` toimivat vain istunnossa, joka on käynnistetty valitsimella --allow-plugin-grants: hyväksy laajennus työpöytäsovelluksessa +@msg Only the person at the keyboard can approve installing a plug-in Vain näppäimistön ääressä oleva ihminen voi hyväksyä laajennuksen asennuksen @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” ei saanut käyttöoikeutta `{p}`, jota sen tulos tarvitsee: mitään ei muutettu @msg a heavy filter runs in the background, so it can't declare `commands` raskas suodin suoritetaan taustalla, joten se ei voi määritellä `commands`-kohtaa @msg at most {MAX_COMMANDS} `commands` enintään {MAX_COMMANDS} `commands` @@ -6050,6 +6057,9 @@ axis Y Axis Y-akseli @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all tai alue, kuten 1, 3-5, ei {v} Add to Symbols Lisää symboleihin Basic Shapes Perusmuodot + Button Painike + Panel Paneeli + UI Frames UI-kehykset Open Symbol Library Avaa symbolikirjasto Save Symbol Library Tallenna symbolikirjasto Save Symbol Library… Tallenna symbolikirjasto… @@ -6124,6 +6134,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 @@ -6542,7 +6554,7 @@ breakText Glyphs Merkit Reset Symbol Instance Palauta symboli-ilmentymä @msg type must be static or dynamic, not {v} type-arvon on oltava static tai dynamic, ei {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` on staattinen symboli: aseta ensin sen symbolin tyypiksi Dynaaminen -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Symboli-ilmentymästä valitusta polusta, yhdistelmäpolusta tai tekstistä voi muuttaa vain täytön ja viivan yhtenäistä väriä +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Symbolin esiintymässä valitun polun, yhdistelmäpolun tai tekstin täyttöä, viivaa, peittävyyttä ja sekoitusta voi vain muuttaa @msg path must be a list of child indices path-arvon on oltava luettelo alikohteiden indeksejä @msg no object at path {shown} in the symbol's art symbolin kuvituksessa ei ole objektia polussa {shown} @msg give fill, stroke, opacity and/or blend anna fill, stroke, opacity ja/tai blend @@ -6697,3 +6709,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 67b0aad76e..43e44f3410 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 @@ -3502,7 +3502,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 @@ -4404,6 +4403,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 +5158,7 @@ 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 or group. Convert images and other objects to paths first. {label} nécessite pour l'instant un tracé, un tracé transparent, du texte ou un groupe. Convertissez d'abord les images et les autres objets en tracés. @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 +5166,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 @@ -5914,7 +5919,7 @@ axis Y Axis Axe Y @msg Running “{name}”… Exécution de « {name} »… @msg a live effect runs while the document is drawn, so it can't be `heavy` un effet dynamique s’exécute pendant le tracé du document, il ne peut donc pas être `heavy` @msg an exporter always gets an export's budget: leave `budget` out un module externe d’exportation reçoit toujours le budget d’une exportation : omettez `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees « {_1} » demande un budget de calcul important (chaque exécution jusqu’à {minutes} minutes et {times} fois les instructions habituelles) : installez-le avec `allowHeavy: true` une fois que l’utilisateur l’accepte +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants « {_1} » demande un budget de calcul important (chaque exécution jusqu’à {minutes} minutes et {times} fois les instructions habituelles) : une personne doit l’approuver dans l’application de bureau, ou passez `allowHeavy: true` dans une session démarrée avec --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installer « {name} », qui demande ces autorisations ? ID: {id} ID : {id} @@ -5954,7 +5959,9 @@ axis Y Axis Axe Y @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget mémoire (l’objet {_1} nécessite {size} octets d’entrée, il en reste {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budget d’objets (plus de {MAX_OBJECTS} objets en lecture seule) @msg unknown permission `{shown}` autorisation inconnue `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees « {name} » demande les autorisations {asked} : installez-le avec `grant` qui les liste une fois que l’utilisateur l’accepte +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants « {name} » demande les autorisations {asked} : une personne doit les approuver dans l’application de bureau, ou passez `grant` dans une session démarrée avec --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` et `allowHeavy` ne prennent effet que dans une session démarrée avec --allow-plugin-grants : approuvez le module externe dans l’application de bureau +@msg Only the person at the keyboard can approve installing a plug-in Seule la personne au clavier peut approuver l’installation d’un module externe @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed « {name} » n’a pas reçu `{p}`, dont sa sortie a besoin : rien n’a été modifié @msg a heavy filter runs in the background, so it can't declare `commands` un filtre lourd s’exécute en arrière-plan, il ne peut donc pas déclarer `commands` @msg at most {MAX_COMMANDS} `commands` au plus {MAX_COMMANDS} `commands` @@ -6015,6 +6022,9 @@ axis Y Axis Axe Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards` : all ou une plage telle que 1, 3-5, et non {v} Add to Symbols Ajouter aux symboles Basic Shapes Formes de base + Button Bouton + Panel Panneau + UI Frames Cadres d’IU 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… @@ -6089,6 +6099,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 @@ -6507,7 +6519,7 @@ breakText Glyphs Glyphes Reset Symbol Instance Réinitialiser l'instance de symbole @msg type must be static or dynamic, not {v} type doit être static ou dynamic, et non {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` est un symbole statique : définissez d'abord son type de symbole sur Dynamique -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Seules les couleurs unies du fond et du contour d'un tracé, d'un tracé transparent ou d'un texte sélectionné dans une instance de symbole peuvent changer +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Seul le fond, le contour, l’opacité et le mode de fusion d’un tracé, tracé composé ou texte sélectionné dans une occurrence de symbole peuvent être modifiés @msg path must be a list of child indices path doit être une liste d'indices d'enfants @msg no object at path {shown} in the symbol's art aucun objet au chemin {shown} dans l'illustration du symbole @msg give fill, stroke, opacity and/or blend indiquez fill, stroke, opacity et/ou blend @@ -6657,3 +6669,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 4a598c488c..db5ac56829 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 एरिया टाइप ऑप्शन्स @@ -491,7 +492,6 @@ antiAlias Sharp शार्प Back वापस Background Color: बैकग्राउंड रंग: Background Contents बैकग्राउंड सामग्री - Background Contents: बैकग्राउंड सामग्री: Background Level बैकग्राउंड स्तर Background: बैकग्राउंड: Backspace Backspace @@ -511,6 +511,9 @@ antiAlias Sharp शार्प Basic Character Formats बुनियादी कैरेक्टर फ़ॉर्मैट Basic Latin बेसिक लैटिन Basic Shapes बुनियादी शेप्स + Button बटन + Panel पैनल + UI Frames UI फ़्रेम Batch बैच Batch Trace Folder फ़ोल्डर बैच ट्रेस करें Batch… बैच… @@ -894,6 +897,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 कमिट्स @@ -1026,7 +1030,6 @@ antiAlias Sharp शार्प Create Clipping Mask क्लिपिंग मास्क बनाएँ Create Compound Path From Ellipses एलिप्स से कंपाउंड पाथ बनाएँ Create Dimension आयाम बनाएँ - Create Document डॉक्यूमेंट बनाएं Create from Guides गाइड से बनाएँ Create from Selection सिलेक्शन से बनाएँ Create From: से बनाएँ: @@ -2552,6 +2555,7 @@ antiAlias Sharp शार्प Lock Artboards लॉक आर्टबोर्ड Lock Grid लॉक ग्रिड Lock Guides गाइड्स लॉक करें + Lock Guides by Default गाइड्स डिफ़ॉल्ट रूप से लॉक करें Lock Others लॉक अन्य Lock Selected लॉक सिलेक्टेड Lock Slices स्लाइस लॉक करें @@ -2833,7 +2837,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-क्लिक करें) @@ -3954,6 +3957,7 @@ antiAlias Sharp शार्प Save PDF Preset PDF प्रीसेट सेव करें Save Perspective Grid Preset सेव पर्सपेक्टिव ग्रिड प्रीसेट Save Preset प्रीसेट सेव करें + Save Document Preset डॉक्यूमेंट प्रीसेट सेव करें Save Preset… प्रीसेट सेव करें… Save Print Preset सेव करें प्रिंट प्रीसेट Save Recovery Data रिकवरी डेटा सेव करें @@ -4733,7 +4737,6 @@ antiAlias Sharp शार्प Template literal not closed टेम्पलेट साक्षर नहीं बंद Templates टेम्पलेट्स Templates Folder टेम्पलेट्स फ़ोल्डर - Templates… टेम्पलेट्स… Tetrad टेट्राड Tetrad 2 टेट्राड 2 Tetrad 3 टेट्राड 3 @@ -5259,7 +5262,7 @@ antiAlias Sharp शार्प Zoom with Mouse Wheel माउस व्हील के साथ ज़ूम @id file.close बंद करें @id pathfinder.add मिलाएँ -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}” अधिक संसाधन माँगता है (हर रन में {minutes} मिनट और सामान्य से {times} गुना निर्देश): उपयोगकर्ता की सहमति मिलने पर इसे `allowHeavy: true` से इंस्टॉल करें +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” अधिक संसाधन माँगता है (हर रन में {minutes} मिनट और सामान्य से {times} गुना निर्देश): इसे डेस्कटॉप ऐप में किसी व्यक्ति को स्वीकृत करना होगा, या --allow-plugin-grants से शुरू किए गए सत्र में `allowHeavy: true` दें @msg "{0}" is not a colour: write it as #rrggbb "{0}" एक रंग नहीं है: इसे #rrggbb के रूप में लिखें # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? "{name}" स्थापित करें, जो ये अनुमतियां मांगता है? @@ -5300,7 +5303,9 @@ antiAlias Sharp शार्प @msg object budget (more than {MAX_OBJECTS} read-only objects) ऑब्जेक्ट बजट ({MAX_OBJECTS} से अधिक केवल-पठन ऑब्जेक्ट) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it अनुमति `{shown}` बाद के प्लग-इन API के लिए आरक्षित है; यह होस्ट इसे नहीं देता @msg unknown permission `{shown}` अज्ञात अनुमति `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}” अनुमतियां {asked} मांगता है: उपयोगकर्ता की सहमति मिलने पर इसे उन्हें सूचीबद्ध करने वाले `grant` के साथ इंस्टॉल करें +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” अनुमतियां {asked} मांगता है: इन्हें डेस्कटॉप ऐप में किसी व्यक्ति को स्वीकृत करना होगा, या --allow-plugin-grants से शुरू किए गए सत्र में `grant` दें +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` और `allowHeavy` केवल --allow-plugin-grants से शुरू किए गए सत्र में प्रभावी होते हैं: डेस्कटॉप ऐप में प्लग-इन स्वीकृत करें +@msg Only the person at the keyboard can approve installing a plug-in प्लग-इन इंस्टॉल करने की स्वीकृति केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” को `{p}` नहीं दी गई, जो उसके आउटपुट को चाहिए: कुछ नहीं बदला @msg a heavy filter runs in the background, so it can't declare `commands` भारी फ़िल्टर पृष्ठभूमि में चलता है, इसलिए वह `commands` घोषित नहीं कर सकता @msg at most {MAX_COMMANDS} `commands` अधिकतम {MAX_COMMANDS} `commands` @@ -5400,7 +5405,7 @@ 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 or group. Convert images and other objects to paths first. {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} पर होना चाहिए @@ -5543,7 +5548,7 @@ antiAlias Sharp शार्प @msg `{name}` is a built-in workspace; choose another name `{name}` एक अंतर्निहित वर्कस्पेस है; एक और नाम चुनें @msg `{name}` is a process colour: tints apply to global and spot colours `{name}` एक प्रक्रिया रंग है: टिंट वैश्विक और स्पॉट रंगों पर लागू होते हैं @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` एक स्थिर सिंबल है: अपने सिंबल प्रकार को पहले गतिशील करने के लिए सेट करें -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change सिंबल इंस्टेंस में चुने गए पाथ, कंपाउंड पाथ या टाइप का केवल ठोस रंग वाला फ़िल और स्ट्रोक बदला जा सकता है +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change प्रतीक इंस्टेंस में चयनित पथ, संयोजित पथ या पाठ का केवल भराव, स्ट्रोक, अपारदर्शिता और ब्लेंड बदला जा सकता है @msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}` `{base}` का एक टिंट है: `{base}` संपादित करें (केवल एक टिंट swatch केवल एक नया नाम लेता है) @msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` वर्किंग स्पेस है: पहले edit.colorSettings से दूसरा चुनें @msg `{name}` is built in and stays `{name}` बनाया गया है और रहता है @@ -7387,6 +7392,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 +7800,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 +8115,6 @@ 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 कोई सुझाव नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 974f17d662..54d303f688 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 @@ -4164,7 +4164,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 @@ -5097,6 +5096,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 +5570,7 @@ 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 or group. Convert images and other objects to paths first. {label} egyelőre görbét, összetett görbét, szöveget vagy csoportot igényel. Előbb alakítsa görbévé a képeket és az egyéb objektumokat. @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 +5578,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 @@ -5902,7 +5907,7 @@ axis Y Axis Y tengely @msg Running “{name}”… Futtatás: „{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` az élő effektus a dokumentum rajzolása közben fut, ezért nem lehet `heavy` @msg an exporter always gets an export's budget: leave `budget` out az exportáló bővítmény mindig az exportálás keretét kapja: hagyd ki a `budget` kulcsot -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees a(z) „{_1}” nagy számítási keretet kér (futásonként legfeljebb {minutes} perc és a szokásos utasításszám {times}-szorosa): telepítsd az `allowHeavy: true` megadásával, miután a felhasználó beleegyezett +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants a(z) „{_1}” nagy számítási keretet kér (futásonként legfeljebb {minutes} perc és a szokásos utasításszám {times}-szorosa): egy személynek jóvá kell hagynia az asztali alkalmazásban, vagy add meg az `allowHeavy: true` értéket egy --allow-plugin-grants kapcsolóval indított munkamenetben # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Telepíted a(z) „{name}” bővítményt, amely ezeket az engedélyeket kéri? ID: {id} Azonosító: {id} @@ -5942,7 +5947,9 @@ axis Y Axis Y tengely @msg object budget (more than {MAX_OBJECTS} read-only objects) objektumkeret (több mint {MAX_OBJECTS} csak olvasható objektum) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a(z) `{shown}` engedély egy későbbi bővítmény-API számára van fenntartva; ez a gazdaprogram nem adja meg @msg unknown permission `{shown}` ismeretlen engedély: `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees a(z) „{name}” a következő engedélyeket kéri: {asked}; telepítsd egy őket felsoroló `grant` értékkel, ha a felhasználó beleegyezik +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants a(z) „{name}” a következő engedélyeket kéri: {asked}; egy személynek jóvá kell hagynia őket az asztali alkalmazásban, vagy add meg a `grant` értéket egy --allow-plugin-grants kapcsolóval indított munkamenetben +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app a `grant` és az `allowHeavy` csak --allow-plugin-grants kapcsolóval indított munkamenetben érvényes: hagyd jóvá a bővítményt az asztali alkalmazásban +@msg Only the person at the keyboard can approve installing a plug-in Bővítmény telepítését csak a billentyűzetnél ülő személy hagyhatja jóvá @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a(z) „{name}” nem kapta meg a(z) `{p}` engedélyt, amelyre a kimenetének szüksége van: semmi sem változott @msg a heavy filter runs in the background, so it can't declare `commands` a nehéz szűrő a háttérben fut, ezért nem deklarálhat `commands` értéket @msg at most {MAX_COMMANDS} `commands` legfeljebb {MAX_COMMANDS} `commands` @@ -6003,6 +6010,9 @@ axis Y Axis Y tengely @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all vagy egy tartomány, például 1, 3-5, nem {v} Add to Symbols Hozzáadás a szimbólumokhoz Basic Shapes Alapalakzatok + Button Gomb + Panel Panel + UI Frames UI keretek 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… @@ -6077,6 +6087,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 @@ -6496,7 +6508,7 @@ breakText Glyphs Glifák Reset Symbol Instance Szimbólumpéldány visszaállítása @msg type must be static or dynamic, not {v} a type értéke static vagy dynamic lehet, nem {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` statikus szimbólum: előbb állítsa a szimbólum típusát Dinamikusra -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Egy szimbólumpéldányban kijelölt útvonalnak, összetett útvonalnak vagy szövegnek csak a kitöltés és a körvonal egyszínű színe módosítható +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Egy szimbólumpéldányban kijelölt görbe, összetett görbe vagy szöveg esetén csak a kitöltés, a körvonal, az átlátszatlanság és a keverési mód módosítható @msg path must be a list of child indices a path gyermekindexek listája kell legyen @msg no object at path {shown} in the symbol's art a szimbólum grafikájában nincs objektum a(z) {shown} útvonalon @msg give fill, stroke, opacity and/or blend adja meg a fill, stroke, opacity és/vagy blend értékét @@ -6646,3 +6658,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 3f2bf60fd2..5188002c0b 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 @@ -905,6 +906,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 +2352,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 +2368,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 +3271,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 @@ -5848,6 +5847,9 @@ axis Y Axis Sumbu Y @plural Result: {n}|Results: {n} Hasil: {n} Add to Symbols Tambahkan ke simbol Basic Shapes Bentuk dasar + Button Tombol + Panel Panel + UI Frames Bingkai UI Open Symbol Library Buka pustaka simbol Save Symbol Library Simpan pustaka simbol Save Symbol Library… Simpan pustaka simbol… @@ -5908,6 +5910,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 @@ -6310,7 +6314,7 @@ breakText Glyphs Glif Reset Symbol Instance Atur ulang instans simbol @msg type must be static or dynamic, not {v} type harus static atau dynamic, bukan {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` adalah simbol statis: setel dulu jenis simbolnya ke Dinamis -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Hanya warna solid isian dan goresan jalur, jalur majemuk, atau teks yang dipilih dalam instans simbol yang dapat diubah +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Hanya isian, goresan, opacity, dan blend jalur, jalur majemuk, atau teks yang dipilih dalam instans simbol yang dapat diubah @msg path must be a list of child indices path harus berupa daftar indeks anak @msg no object at path {shown} in the symbol's art tidak ada objek di jalur {shown} dalam karya seni simbol @msg give fill, stroke, opacity and/or blend berikan fill, stroke, opacity dan/atau blend diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e7c6d32fd7..726026fe42 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 @@ -3546,7 +3546,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 @@ -4457,6 +4456,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 +5196,7 @@ 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 or group. Convert images and other objects to paths first. {label} richiede per ora un tracciato, un tracciato composto, testo o un gruppo. Convertite prima immagini e altri oggetti in tracciati. @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 +5204,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 @@ -5536,7 +5541,7 @@ axis Y Axis Asse Y @msg Running “{name}”… Esecuzione di “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` un effetto dinamico viene eseguito mentre il documento viene disegnato, quindi non può essere `heavy` @msg an exporter always gets an export's budget: leave `budget` out un plug-in di esportazione riceve sempre il budget di un’esportazione: ometti `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}” chiede un budget di calcolo elevato (ogni esecuzione fino a {minutes} minuti e {times} volte le istruzioni consuete): installalo con `allowHeavy: true` quando l’utente acconsente +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” chiede un budget di calcolo elevato (ogni esecuzione fino a {minutes} minuti e {times} volte le istruzioni consuete): una persona deve approvarlo nell’app desktop, oppure passa `allowHeavy: true` in una sessione avviata con --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installare “{name}”, che chiede queste autorizzazioni? ID: {id} ID: {id} @@ -5576,7 +5581,9 @@ axis Y Axis Asse Y @msg object budget (more than {MAX_OBJECTS} read-only objects) budget di oggetti (più di {MAX_OBJECTS} oggetti di sola lettura) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it l’autorizzazione `{shown}` è riservata a un’API dei plug-in successiva; questo host non la concede @msg unknown permission `{shown}` autorizzazione sconosciuta `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}” chiede le autorizzazioni {asked}: installalo con un `grant` che le elenca quando l’utente acconsente +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” chiede le autorizzazioni {asked}: una persona deve approvarle nell’app desktop, oppure passa `grant` in una sessione avviata con --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` e `allowHeavy` hanno effetto solo in una sessione avviata con --allow-plugin-grants: approva il plug-in nell’app desktop +@msg Only the person at the keyboard can approve installing a plug-in Solo la persona alla tastiera può approvare l’installazione di un plug-in @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” non è stata concessa `{p}`, che serve al suo risultato: non è stato modificato nulla @msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesante viene eseguito in background, quindi non può dichiarare `commands` @msg at most {MAX_COMMANDS} `commands` al massimo {MAX_COMMANDS} `commands` @@ -5637,6 +5644,9 @@ axis Y Axis Asse Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervallo come 1, 3-5, non {v} Add to Symbols Aggiungi ai simboli Basic Shapes Forme di base + Button Pulsante + Panel Pannello + UI Frames Cornici UI Open Symbol Library Apri libreria simboli Save Symbol Library Salva libreria simboli Save Symbol Library… Salva libreria simboli… @@ -5711,6 +5721,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 @@ -6133,7 +6145,7 @@ breakText Glyphs Glifi Reset Symbol Instance Reimposta istanza di simbolo @msg type must be static or dynamic, not {v} type deve essere static o dynamic, non {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` è un simbolo statico: imposta prima il tipo di simbolo su Dinamico -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Di un tracciato, un tracciato composto o un testo selezionato in un'istanza di simbolo si può modificare solo il colore pieno di riempimento e traccia +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Di un tracciato, un tracciato composto o un testo selezionato in un'istanza di simbolo si possono modificare solo riempimento, traccia, opacità e fusione @msg path must be a list of child indices path deve essere un elenco di indici figlio @msg no object at path {shown} in the symbol's art nessun oggetto al percorso {shown} nella grafica del simbolo @msg give fill, stroke, opacity and/or blend specifica fill, stroke, opacity e/o blend @@ -6283,3 +6295,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0ec6cb1a43..4f8c7408be 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 ガイドを消去 @@ -1076,7 +1077,6 @@ antiAlias Sharp シャープ Update While Dragging ドラッグ中に更新 Hide Video Rulers ビデオ定規を隠す Background Contents 背景のカラー - Background Contents: 背景のカラー: Background: 背景: Bar Graph Tool 棒グラフツール Baseline Shift ベースラインシフト @@ -1253,6 +1253,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 +1303,6 @@ antiAlias Sharp シャープ Corners… コーナー… Chamfer 面取り Create Clipping Mask クリッピングマスクを作成 - Create Document ドキュメントを作成 Create From: 作成元: Create Graph グラフを作成 Create New Layer 新規レイヤーを作成 @@ -2362,7 +2362,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 +2904,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 +3253,6 @@ mark-style Japanese 日本式 Target Contents 内容をターゲット Target: ターゲット: Templates Folder テンプレートフォルダー - Templates… テンプレート… Text Displayed in Cell: セルに表示するテキスト: Text Export Options テキスト書き出しオプション Text Import Options テキスト読み込みオプション @@ -4803,6 +4802,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 ステップを超えるアクションがあります @@ -5238,7 +5238,7 @@ 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 or group. Convert images and other objects to paths first. {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 +5246,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 のいずれの画像でもありません @@ -5601,7 +5606,7 @@ axis Y Axis Y 軸 @msg Running “{name}”… 「{name}」を実行中… @msg a live effect runs while the document is drawn, so it can't be `heavy` ライブ効果はドキュメントの描画中に実行されるため、`heavy` にはできません @msg an exporter always gets an export's budget: leave `budget` out 書き出しプラグインには常に書き出しの予算が割り当てられます。`budget` は省略してください -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees 「{_1}」は大きな計算予算を求めています (1 回の実行につき最大 {minutes} 分、通常の {times} 倍の命令)。ユーザーが同意したら `allowHeavy: true` を指定してインストールしてください +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants 「{_1}」は大きな計算予算を求めています (1 回の実行につき最大 {minutes} 分、通常の {times} 倍の命令)。デスクトップ アプリで人が承認するか、--allow-plugin-grants を付けて開始したセッションで `allowHeavy: true` を指定してください # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? これらの権限を求める「{name}」をインストールしますか? ID: {id} ID: {id} @@ -5641,7 +5646,9 @@ axis Y Axis Y 軸 @msg object budget (more than {MAX_OBJECTS} read-only objects) オブジェクト予算 ({MAX_OBJECTS} 個を超える読み取り専用オブジェクト) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 権限 `{shown}` は今後のプラグイン API 用に予約されています。このホストはこの権限を付与しません @msg unknown permission `{shown}` 不明な権限 `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees 「{name}」は権限 {asked} を求めています。ユーザーが同意したら、それらを列挙した `grant` を指定してインストールしてください +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants 「{name}」は権限 {asked} を求めています。デスクトップ アプリで人が承認するか、--allow-plugin-grants を付けて開始したセッションで `grant` を指定してください +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` と `allowHeavy` は --allow-plugin-grants を付けて開始したセッションでのみ有効です。デスクトップ アプリでプラグインを承認してください +@msg Only the person at the keyboard can approve installing a plug-in プラグインのインストールを承認できるのはキーボードの前にいる人だけです @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」には出力に必要な `{p}` が付与されていません。何も変更されませんでした @msg a heavy filter runs in the background, so it can't declare `commands` 重いフィルターはバックグラウンドで実行されるため、`commands` を宣言できません @msg at most {MAX_COMMANDS} `commands` `commands` は最大 {MAX_COMMANDS} 個です @@ -5702,6 +5709,9 @@ axis Y Axis Y 軸 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all または 1, 3-5 のような範囲を指定してください ({v} ではなく) Add to Symbols シンボルに追加 Basic Shapes 基本シェイプ + Button ボタン + Panel パネル + UI Frames UIフレーム Open Symbol Library シンボルライブラリを開く Save Symbol Library シンボルライブラリを保存 Save Symbol Library… シンボルライブラリを保存… @@ -5776,6 +5786,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 グリフにスナップのオプションを隠す @@ -6198,7 +6210,7 @@ breakText Glyphs 字形 Reset Symbol Instance シンボルインスタンスをリセット @msg type must be static or dynamic, not {v} type は static または dynamic にしてください({v} は無効です) @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` はスタティックシンボルです。先にシンボルの種類をダイナミックに設定してください -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change シンボルインスタンス内で選択したパス、複合パス、テキストは、塗りと線の単色のみ変更できます +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change シンボルインスタンス内で選択したパス、複合パス、または文字について変更できるのは塗り、線、不透明度、描画モードだけです @msg path must be a list of child indices path は子のインデックスのリストにしてください @msg no object at path {shown} in the symbol's art シンボルのアートのパス {shown} にオブジェクトがありません @msg give fill, stroke, opacity and/or blend fill、stroke、opacity、blend のいずれかを指定してください @@ -6348,3 +6360,6 @@ 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 候補なし diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 69f43e4f01..c21c3002b8 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 დამხმარე ხაზების მოხსნა @@ -857,6 +858,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 +2254,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 +2269,6 @@ digits Malayalam მალაიალამური Preview Mode გადახედვის რეჟიმი RECENT ბოლოდროინდელი SAVED შენახული - Templates… შაბლონები… Transparent (Default) გამჭვირვალე (ნაგულისხმევი) Save for Office Documents შენახვა Office-ის დოკუმენტებისთვის Transparent Background გამჭვირვალე ფონი @@ -3095,6 +3093,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 განაწილება @@ -4182,6 +4181,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 +4959,7 @@ 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 or group. Convert images and other objects to paths first. {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 +4967,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 ფერის ნიმუშების ბიბლიოთეკები @@ -5842,7 +5847,7 @@ axis Y Axis Y ღერძი @msg Running “{name}”… მიმდინარეობს „{name}“-ის გაშვება… @msg a live effect runs while the document is drawn, so it can't be `heavy` ცოცხალი ეფექტი დოკუმენტის დახატვისას ეშვება, ამიტომ ის ვერ იქნება `heavy` @msg an exporter always gets an export's budget: leave `budget` out ექსპორტის პლაგინი ყოველთვის ექსპორტის ბიუჯეტს იღებს: გამოტოვეთ `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees „{_1}“ დიდ გამოთვლით ბიუჯეტს ითხოვს (თითო გაშვება {minutes} წუთამდე და ჩვეულებრივზე {times}-ჯერ მეტი ინსტრუქცია): მომხმარებლის თანხმობის შემდეგ დააყენეთ ის `allowHeavy: true` პარამეტრით +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ დიდ გამოთვლით ბიუჯეტს ითხოვს (თითო გაშვება {minutes} წუთამდე და ჩვეულებრივზე {times}-ჯერ მეტი ინსტრუქცია): ის დესკტოპის აპში ადამიანმა უნდა დაამტკიცოს, ან გადაეცით `allowHeavy: true` --allow-plugin-grants-ით გაშვებულ სესიაში # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? დავაყენოთ „{name}“, რომელიც ამ ნებართვებს ითხოვს? ID: {id} ID: {id} @@ -5882,7 +5887,9 @@ axis Y Axis Y ღერძი @msg object budget (more than {MAX_OBJECTS} read-only objects) ობიექტების ბიუჯეტი ({MAX_OBJECTS}-ზე მეტი მხოლოდ წასაკითხი ობიექტი) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it ნებართვა `{shown}` დაჯავშნილია პლაგინების მომავალი API-სთვის; ეს ჰოსტი მას არ გასცემს @msg unknown permission `{shown}` უცნობი ნებართვა `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees „{name}“ ითხოვს ნებართვებს {asked}: მომხმარებლის თანხმობის შემდეგ დააყენეთ ის `grant` პარამეტრით, რომელშიც ისინი ჩამოთვლილია +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}“ ითხოვს ნებართვებს {asked}: ისინი დესკტოპის აპში ადამიანმა უნდა დაამტკიცოს, ან გადაეცით `grant` --allow-plugin-grants-ით გაშვებულ სესიაში +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` და `allowHeavy` მოქმედებს მხოლოდ --allow-plugin-grants-ით გაშვებულ სესიაში: დაამტკიცეთ დამატება დესკტოპის აპში +@msg Only the person at the keyboard can approve installing a plug-in დამატების დაყენებას მხოლოდ კლავიატურასთან მყოფი ადამიანი ამტკიცებს @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“-ს არ მიეცა `{p}`, რომელიც მის შედეგს სჭირდება: არაფერი შეცვლილა @msg a heavy filter runs in the background, so it can't declare `commands` მძიმე ფილტრი ფონურ რეჟიმში მუშაობს, ამიტომ მას არ შეუძლია `commands`-ის გამოცხადება @msg at most {MAX_COMMANDS} `commands` მაქსიმუმ {MAX_COMMANDS} `commands` @@ -5943,6 +5950,9 @@ axis Y Axis Y ღერძი @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ან დიაპაზონი, მაგალითად 1, 3-5, და არა {v} Add to Symbols სიმბოლოებში დამატება Basic Shapes ძირითადი ფიგურები + Button ღილაკი + Panel პანელი + UI Frames UI ჩარჩოები Open Symbol Library სიმბოლოების ბიბლიოთეკის გახსნა Save Symbol Library სიმბოლოების ბიბლიოთეკის შენახვა Save Symbol Library… სიმბოლოების ბიბლიოთეკის შენახვა… @@ -6090,6 +6100,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 გლიფზე მიბმის პარამეტრების დამალვა @@ -6509,7 +6521,7 @@ breakText Glyphs გლიფები Reset Symbol Instance სიმბოლოს ეგზემპლარის ჩამოყრა @msg type must be static or dynamic, not {v} type უნდა იყოს static ან dynamic და არა {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` სტატიკური სიმბოლოა: ჯერ სიმბოლოს ტიპად დააყენეთ „დინამიკური“ -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change სიმბოლოს ეგზემპლარში მონიშნულ ტრაექტორიას, შედგენილ ტრაექტორიას ან ტექსტს მხოლოდ შევსებისა და კონტურის მთლიანი ფერი შეეცვლება +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change სიმბოლოს ეგზემპლარში მონიშნული მრუდის, შედგენილი მრუდის ან ტექსტის მხოლოდ შევსება, კონტური, გამჭვირვალობა და შერევა შეიძლება შეიცვალოს @msg path must be a list of child indices path უნდა იყოს შვილობილი ინდექსების სია @msg no object at path {shown} in the symbol's art სიმბოლოს გრაფიკაში გზაზე {shown} ობიექტი არ არის @msg give fill, stroke, opacity and/or blend მიუთითეთ fill, stroke, opacity და/ან blend @@ -6723,3 +6735,6 @@ 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 შემოთავაზებები არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 648f249e31..c262be5b77 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 안내선 지우기 @@ -1066,7 +1067,6 @@ antiAlias Sharp 날카롭게 Update While Dragging 드래그하는 동안 업데이트 Hide Video Rulers 비디오 눈금자 숨기기 Background Contents 배경 내용 - Background Contents: 배경 내용: Background: 배경: Bar Graph Tool 막대 그래프 도구 Baseline Shift 기준선 이동 @@ -1243,6 +1243,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 +1293,6 @@ antiAlias Sharp 날카롭게 Corners… 모퉁이… Chamfer 모따기 Create Clipping Mask 클리핑 마스크 만들기 - Create Document 문서 만들기 Create From: 만들기 기준: Create Graph 그래프 만들기 Create New Layer 새 레이어 만들기 @@ -2352,7 +2352,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 +2893,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 +3242,6 @@ mark-style Japanese 일본식 Target Contents 대상 내용 Target: 대상: Templates Folder 템플릿 폴더 - Templates… 템플릿… Text Displayed in Cell: 셀에 표시할 텍스트: Text Export Options 텍스트 내보내기 옵션 Text Import Options 텍스트 가져오기 옵션 @@ -4730,6 +4729,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개를 넘는 액션이 있습니다 @@ -5157,7 +5157,7 @@ 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 or group. Convert images and other objects to paths first. {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 +5165,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 이미지가 아닙니다 @@ -5497,7 +5502,7 @@ axis Y Axis Y축 @msg Running “{name}”… “{name}” 실행 중… @msg a live effect runs while the document is drawn, so it can't be `heavy` 라이브 효과는 문서를 그리는 동안 실행되므로 `heavy`일 수 없습니다 @msg an exporter always gets an export's budget: leave `budget` out 내보내기 플러그인은 항상 내보내기 예산을 받습니다. `budget`은 생략하세요 -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}”은(는) 큰 계산 예산을 요청합니다(실행당 최대 {minutes}분, 평소의 {times}배 명령어). 사용자가 동의하면 `allowHeavy: true`로 설치하세요 +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}”은(는) 큰 계산 예산을 요청합니다(실행당 최대 {minutes}분, 평소의 {times}배 명령어). 데스크톱 앱에서 사람이 승인하거나 --allow-plugin-grants로 시작한 세션에서 `allowHeavy: true`를 전달하세요 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 이 권한을 요청하는 “{name}”을(를) 설치하시겠습니까? ID: {id} ID: {id} @@ -5537,7 +5542,9 @@ axis Y Axis Y축 @msg object budget (more than {MAX_OBJECTS} read-only objects) 개체 예산(읽기 전용 개체 {MAX_OBJECTS}개 초과) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` 권한은 이후 플러그인 API용으로 예약되어 있습니다. 이 호스트는 이 권한을 부여하지 않습니다 @msg unknown permission `{shown}` 알 수 없는 권한 `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}”은(는) {asked} 권한을 요청합니다. 사용자가 동의하면 이를 나열한 `grant`로 설치하세요 +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}”은(는) {asked} 권한을 요청합니다. 데스크톱 앱에서 사람이 승인하거나 --allow-plugin-grants로 시작한 세션에서 `grant`를 전달하세요 +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant`와 `allowHeavy`는 --allow-plugin-grants로 시작한 세션에서만 적용됩니다. 데스크톱 앱에서 플러그인을 승인하세요 +@msg Only the person at the keyboard can approve installing a plug-in 플러그인 설치는 키보드 앞에 있는 사람만 승인할 수 있습니다 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”에 출력에 필요한 `{p}` 권한이 부여되지 않았습니다. 아무것도 변경되지 않았습니다 @msg a heavy filter runs in the background, so it can't declare `commands` 무거운 필터는 백그라운드에서 실행되므로 `commands`를 선언할 수 없습니다 @msg at most {MAX_COMMANDS} `commands` `commands`는 최대 {MAX_COMMANDS}개입니다 @@ -5598,6 +5605,9 @@ axis Y Axis Y축 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all 또는 1, 3-5 같은 범위여야 합니다({v}이(가) 아님) Add to Symbols 심볼에 추가 Basic Shapes 기본 모양 + Button 버튼 + Panel 패널 + UI Frames UI 프레임 Open Symbol Library 심볼 라이브러리 열기 Save Symbol Library 심볼 라이브러리 저장 Save Symbol Library… 심볼 라이브러리 저장… @@ -5672,6 +5682,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 글리프에 스냅 옵션 숨기기 @@ -6094,7 +6106,7 @@ breakText Glyphs 글리프 Reset Symbol Instance 심볼 인스턴스 재설정 @msg type must be static or dynamic, not {v} type은 static 또는 dynamic이어야 합니다({v}는 안 됨) @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}`은(는) 정적 심볼입니다. 먼저 심볼 유형을 동적으로 설정하세요 -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change 심볼 인스턴스에서 선택한 패스, 컴파운드 패스 또는 문자는 칠과 선의 단색만 변경할 수 있습니다 +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change 심볼 인스턴스에서 선택한 패스, 복합 패스 또는 텍스트는 칠, 선, 불투명도, 혼합만 변경할 수 있습니다 @msg path must be a list of child indices path는 자식 인덱스 목록이어야 합니다 @msg no object at path {shown} in the symbol's art 심볼 아트의 경로 {shown}에 개체가 없습니다 @msg give fill, stroke, opacity and/or blend fill, stroke, opacity 및/또는 blend를 지정하세요 @@ -6244,3 +6256,6 @@ 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 제안 없음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 41f494c761..36ab0e6642 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 @@ -919,6 +920,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 +2366,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 +2382,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 +3285,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 @@ -5899,6 +5898,9 @@ axis Y Axis Y-as @plural Result: {n}|Results: {n} Resultaat: {n}|Resultaten: {n} Add to Symbols Aan symbolen toevoegen Basic Shapes Basisvormen + Button Knop + Panel Paneel + UI Frames UI-kaders Open Symbol Library Symboolbibliotheek openen Save Symbol Library Symboolbibliotheek opslaan Save Symbol Library… Symboolbibliotheek opslaan… @@ -5959,6 +5961,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 @@ -6361,7 +6365,7 @@ breakText Glyphs Glyphs Reset Symbol Instance Symboolinstantie opnieuw instellen @msg type must be static or dynamic, not {v} type moet static of dynamic zijn, niet {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` is een statisch symbool: stel eerst het symbooltype in op Dynamisch -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Van een pad, samengesteld pad of tekst die in een symboolinstantie is geselecteerd, kan alleen de effen kleur van vulling en lijn veranderen +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Van een pad, samengesteld pad of tekst geselecteerd in een symboolinstantie kunnen alleen de vulling, lijn, dekking en overvloeimodus worden gewijzigd @msg path must be a list of child indices path moet een lijst met onderliggende indexen zijn @msg no object at path {shown} in the symbol's art geen object op pad {shown} in de illustratie van het symbool @msg give fill, stroke, opacity and/or blend geef fill, stroke, opacity en/of blend op diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e3f4d7824d..47099ed184 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 @@ -920,6 +921,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 +2478,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 +2493,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 +3413,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ść @@ -4547,6 +4546,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 +5417,7 @@ 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 or group. Convert images and other objects to paths first. {label} wymaga obecnie ścieżki, ścieżki złożonej, tekstu lub grupy. Najpierw przekonwertuj obrazy i inne obiekty na ścieżki. @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 +5434,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 @@ -5773,7 +5778,7 @@ axis Y Axis Oś Y @msg Running “{name}”… Uruchamianie „{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` efekt na żywo działa podczas rysowania dokumentu, więc nie może być `heavy` @msg an exporter always gets an export's budget: leave `budget` out wtyczka eksportu zawsze dostaje budżet eksportu: pomiń `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees „{_1}” prosi o duży budżet obliczeń (każde uruchomienie do {minutes} minut i {times} razy więcej instrukcji niż zwykle): zainstaluj wtyczkę z `allowHeavy: true`, gdy użytkownik się zgodzi +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” prosi o duży budżet obliczeń (każde uruchomienie do {minutes} minut i {times} razy więcej instrukcji niż zwykle): musi ją zatwierdzić osoba w aplikacji desktopowej albo przekaż `allowHeavy: true` w sesji uruchomionej z --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Zainstalować „{name}”, wtyczkę, która prosi o te uprawnienia? ID: {id} ID: {id} @@ -5813,7 +5818,9 @@ axis Y Axis Oś Y @msg object budget (more than {MAX_OBJECTS} read-only objects) budżet obiektów (ponad {MAX_OBJECTS} obiektów tylko do odczytu) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it uprawnienie `{shown}` jest zarezerwowane dla późniejszego API wtyczek; ten host go nie przyznaje @msg unknown permission `{shown}` nieznane uprawnienie `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees „{name}” prosi o uprawnienia {asked}: zainstaluj ją z `grant`, który je wymienia, gdy użytkownik się zgodzi +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants „{name}” prosi o uprawnienia {asked}: musi je zatwierdzić osoba w aplikacji desktopowej albo przekaż `grant` w sesji uruchomionej z --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` i `allowHeavy` działają tylko w sesji uruchomionej z --allow-plugin-grants: zatwierdź wtyczkę w aplikacji desktopowej +@msg Only the person at the keyboard can approve installing a plug-in Instalację wtyczki może zatwierdzić tylko osoba przy klawiaturze @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” nie otrzymała `{p}`, którego potrzebuje jej wynik: nic nie zmieniono @msg a heavy filter runs in the background, so it can't declare `commands` ciężki filtr działa w tle, więc nie może deklarować `commands` @msg at most {MAX_COMMANDS} `commands` najwyżej {MAX_COMMANDS} `commands` @@ -5874,6 +5881,9 @@ axis Y Axis Oś Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all lub zakres, np. 1, 3-5, a nie {v} Add to Symbols Dodaj do symboli Basic Shapes Kształty podstawowe + Button Przycisk + Panel Panel + UI Frames Ramki UI Open Symbol Library Otwórz bibliotekę symboli Save Symbol Library Zapisz bibliotekę symboli Save Symbol Library… Zapisz bibliotekę symboli… @@ -5948,6 +5958,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 @@ -6368,7 +6380,7 @@ breakText Glyphs Glify Reset Symbol Instance Resetuj wystąpienie symbolu @msg type must be static or dynamic, not {v} type musi mieć wartość static lub dynamic, a nie {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` jest symbolem statycznym: najpierw ustaw jego typ symbolu na Dynamiczny -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change W ścieżce, ścieżce złożonej lub tekście zaznaczonym w wystąpieniu symbolu można zmienić tylko jednolity kolor wypełnienia i obrysu +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change W ścieżce, ścieżce złożonej lub tekście zaznaczonym w wystąpieniu symbolu można zmienić tylko wypełnienie, obrys, krycie i tryb mieszania @msg path must be a list of child indices path musi być listą indeksów elementów podrzędnych @msg no object at path {shown} in the symbol's art brak obiektu w ścieżce {shown} w grafice symbolu @msg give fill, stroke, opacity and/or blend podaj fill, stroke, opacity i/lub blend @@ -6518,3 +6530,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b1d0e92b58..218ea24cd1 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 @@ -2880,7 +2880,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 @@ -3987,6 +3986,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 +4505,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 @@ -5527,7 +5532,7 @@ 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 or group. Convert images and other objects to paths first. {label} exige, por enquanto, um caminho, caminho composto, texto ou grupo. Converta antes imagens e outros objetos em caminhos. @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 @@ -5834,7 +5839,7 @@ axis Y Axis Eixo Y @msg Running “{name}”… Executando “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` um efeito dinâmico é executado enquanto o documento é desenhado, então não pode ser `heavy` @msg an exporter always gets an export's budget: leave `budget` out um plug-in de exportação sempre recebe o orçamento de uma exportação: omita `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}” pede um orçamento de processamento grande (cada execução até {minutes} minutos e {times} vezes as instruções habituais): instale-o com `allowHeavy: true` depois que o usuário concordar +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” pede um orçamento de processamento grande (cada execução até {minutes} minutos e {times} vezes as instruções habituais): uma pessoa precisa aprová-lo no aplicativo de desktop, ou passe `allowHeavy: true` em uma sessão iniciada com --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instalar “{name}”, que pede estas permissões? ID: {id} ID: {id} @@ -5874,7 +5879,9 @@ axis Y Axis Eixo Y @msg object budget (more than {MAX_OBJECTS} read-only objects) orçamento de objetos (mais de {MAX_OBJECTS} objetos somente leitura) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it a permissão `{shown}` está reservada para uma API de plug-in futura; este host não a concede @msg unknown permission `{shown}` permissão desconhecida `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}” pede as permissões {asked}: instale-o com `grant` listando-as depois que o usuário concordar +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” pede as permissões {asked}: uma pessoa precisa aprová-las no aplicativo de desktop, ou passe `grant` em uma sessão iniciada com --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` e `allowHeavy` só têm efeito em uma sessão iniciada com --allow-plugin-grants: aprove o plug-in no aplicativo de desktop +@msg Only the person at the keyboard can approve installing a plug-in Somente a pessoa ao teclado pode aprovar a instalação de um plug-in @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” não recebeu `{p}`, de que sua saída precisa: nada foi alterado @msg a heavy filter runs in the background, so it can't declare `commands` um filtro pesado é executado em segundo plano, então não pode declarar `commands` @msg at most {MAX_COMMANDS} `commands` no máximo {MAX_COMMANDS} `commands` @@ -5935,6 +5942,9 @@ axis Y Axis Eixo Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ou um intervalo como 1, 3-5, não {v} Add to Symbols Adicionar aos Símbolos Basic Shapes Formas Básicas + Button Botão + Panel Painel + UI Frames Molduras de IU Open Symbol Library Abrir Biblioteca de Símbolos Save Symbol Library Salvar Biblioteca de Símbolos Save Symbol Library… Salvar Biblioteca de Símbolos… @@ -6009,6 +6019,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 @@ -6430,7 +6442,7 @@ breakText Glyphs Glifos Reset Symbol Instance Redefinir instância de símbolo @msg type must be static or dynamic, not {v} type deve ser static ou dynamic, não {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` é um símbolo estático: defina primeiro o tipo de símbolo como Dinâmico -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change De um caminho, caminho composto ou texto selecionado em uma instância de símbolo só é possível alterar a cor sólida do preenchimento e do traçado +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change De um caminho, caminho composto ou texto selecionado em uma instância de símbolo só é possível alterar o preenchimento, o traçado, a opacidade e a mesclagem @msg path must be a list of child indices path deve ser uma lista de índices de filhos @msg no object at path {shown} in the symbol's art nenhum objeto no caminho {shown} na arte do símbolo @msg give fill, stroke, opacity and/or blend informe fill, stroke, opacity e/ou blend @@ -6735,3 +6747,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 08f5dafb3c..e76f24ae6f 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 Сохранить набор печати @@ -3541,7 +3541,6 @@ digits Malayalam Малаялам Template Шаблон Templates Шаблоны Templates Folder Папка шаблонов - Templates… Шаблоны… Text Displayed in Cell: Текст, отображаемый в ячейке: Text Export Options Параметры экспорта текста Text Fill & Stroke Color Цвет заливки и обводки текста @@ -4451,6 +4450,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 +5190,7 @@ 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 or group. Convert images and other objects to paths first. {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 +5198,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 @@ -5530,7 +5535,7 @@ axis Y Axis Ось Y @msg Running “{name}”… Выполняется «{name}»… @msg a live effect runs while the document is drawn, so it can't be `heavy` динамический эффект выполняется во время отрисовки документа, поэтому он не может быть `heavy` @msg an exporter always gets an export's budget: leave `budget` out модуль экспорта всегда получает бюджет экспорта: не указывайте `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees «{_1}» запрашивает большой вычислительный бюджет (каждый запуск до {minutes} минут и в {times} раз больше инструкций, чем обычно): установите его с `allowHeavy: true`, когда пользователь согласится +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» запрашивает большой вычислительный бюджет (каждый запуск до {minutes} минут и в {times} раз больше инструкций, чем обычно): его должен одобрить человек в настольном приложении, либо передайте `allowHeavy: true` в сеансе, запущенном с --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Установить «{name}», которому нужны эти разрешения? ID: {id} ID: {id} @@ -5570,7 +5575,9 @@ axis Y Axis Ось Y @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет объектов (более {MAX_OBJECTS} объектов только для чтения) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it разрешение `{shown}` зарезервировано для будущего API модулей; этот хост его не выдаёт @msg unknown permission `{shown}` неизвестное разрешение `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees «{name}» запрашивает разрешения {asked}: установите его с `grant`, где они перечислены, когда пользователь согласится +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants «{name}» запрашивает разрешения {asked}: их должен одобрить человек в настольном приложении, либо передайте `grant` в сеансе, запущенном с --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` и `allowHeavy` действуют только в сеансе, запущенном с --allow-plugin-grants: одобрите плагин в настольном приложении +@msg Only the person at the keyboard can approve installing a plug-in Одобрить установку плагина может только человек за клавиатурой @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не получил разрешение `{p}`, нужное для его результата: ничего не изменено @msg a heavy filter runs in the background, so it can't declare `commands` тяжёлый фильтр выполняется в фоне, поэтому не может объявлять `commands` @msg at most {MAX_COMMANDS} `commands` не более {MAX_COMMANDS} `commands` @@ -5631,6 +5638,9 @@ axis Y Axis Ось Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all или диапазон, например 1, 3-5, а не {v} Add to Symbols Добавить в символы Basic Shapes Базовые фигуры + Button Кнопка + Panel Панель + UI Frames UI-рамки Open Symbol Library Открыть библиотеку символов Save Symbol Library Сохранить библиотеку символов Save Symbol Library… Сохранить библиотеку символов… @@ -6071,6 +6081,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 Скрыть параметры привязки к глифу @@ -6489,7 +6501,7 @@ breakText Glyphs Глифы Reset Symbol Instance Сбросить экземпляр символа @msg type must be static or dynamic, not {v} type должен быть static или dynamic, а не {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` — статический символ: сначала задайте для него тип символа «Динамический» -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change У контура, составного контура или текста, выделенного в экземпляре символа, можно изменить только сплошной цвет заливки и обводки +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change У контура, составного контура или текста, выделенного в экземпляре символа, можно изменить только заливку, обводку, непрозрачность и режим наложения @msg path must be a list of child indices path должен быть списком индексов дочерних объектов @msg no object at path {shown} in the symbol's art в графике символа нет объекта по пути {shown} @msg give fill, stroke, opacity and/or blend укажите fill, stroke, opacity и/или blend @@ -6751,3 +6763,6 @@ 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 Нет вариантов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f1b705258a..3fa6df127f 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 @@ -3432,7 +3432,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 @@ -4319,6 +4318,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 +5062,7 @@ 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 or group. Convert images and other objects to paths first. {label} kräver för närvarande en bana, sammansatt bana, text eller grupp. Konvertera bilder och andra objekt till banor först. @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 +5070,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 @@ -5942,7 +5947,7 @@ axis Y Axis Y-axel @msg Running “{name}”… Kör ”{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` en live-effekt körs medan dokumentet ritas, så den kan inte vara `heavy` @msg an exporter always gets an export's budget: leave `budget` out ett exportinsticksprogram får alltid en exports budget: utelämna `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees ”{_1}” begär en stor beräkningsbudget (varje körning upp till {minutes} minuter och {times} gånger de vanliga instruktionerna): installera det med `allowHeavy: true` när användaren har godkänt +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants ”{_1}” begär en stor beräkningsbudget (varje körning upp till {minutes} minuter och {times} gånger de vanliga instruktionerna): en person måste godkänna det i skrivbordsappen, eller skicka `allowHeavy: true` i en session som startats med --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installera ”{name}”, som begär dessa behörigheter? ID: {id} ID: {id} @@ -5982,7 +5987,9 @@ axis Y Axis Y-axel @msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (fler än {MAX_OBJECTS} skrivskyddade objekt) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it behörigheten `{shown}` är reserverad för ett senare plugin-API; den här värden beviljar den inte @msg unknown permission `{shown}` okänd behörighet `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees ”{name}” begär behörigheterna {asked}: installera det med en `grant` som listar dem när användaren har godkänt +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants ”{name}” begär behörigheterna {asked}: en person måste godkänna dem i skrivbordsappen, eller skicka `grant` i en session som startats med --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` och `allowHeavy` gäller bara i en session som startats med --allow-plugin-grants: godkänn insticksprogrammet i skrivbordsappen +@msg Only the person at the keyboard can approve installing a plug-in Bara personen vid tangentbordet kan godkänna installationen av ett insticksprogram @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” beviljades inte `{p}`, som dess utdata behöver: ingenting ändrades @msg a heavy filter runs in the background, so it can't declare `commands` ett tungt filter körs i bakgrunden, så det kan inte deklarera `commands` @msg at most {MAX_COMMANDS} `commands` högst {MAX_COMMANDS} `commands` @@ -6043,6 +6050,9 @@ axis Y Axis Y-axel @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all eller ett intervall som 1, 3-5, inte {v} Add to Symbols Lägg till i symboler Basic Shapes Grundformer + Button Knapp + Panel Panel + UI Frames UI-ramar Open Symbol Library Öppna symbolbibliotek Save Symbol Library Spara symbolbibliotek Save Symbol Library… Spara symbolbibliotek… @@ -6117,6 +6127,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 @@ -6564,7 +6576,7 @@ breakText Glyphs Glyfer Reset Symbol Instance Återställ symbolinstans @msg type must be static or dynamic, not {v} type måste vara static eller dynamic, inte {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` är en statisk symbol: ställ först in symboltypen på Dynamisk -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change För en bana, sammansatt bana eller text som är markerad i en symbolinstans kan bara enfärgad fyllning och linje ändras +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change För en bana, sammansatt bana eller text som är markerad i en symbolinstans kan bara fyllning, linje, opacitet och blandning ändras @msg path must be a list of child indices path måste vara en lista med underordnade index @msg no object at path {shown} in the symbol's art inget objekt vid sökvägen {shown} i symbolens bild @msg give fill, stroke, opacity and/or blend ange fill, stroke, opacity och/eller blend @@ -8147,3 +8159,6 @@ 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 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 5f15d25e40..2201aec721 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 @@ -3323,7 +3323,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 @@ -4179,6 +4178,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 +4858,7 @@ 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 or group. Convert images and other objects to paths first. {label} şu anda bir yol, bileşik yol, yazı veya grup gerektiriyor. Önce görüntüleri ve diğer nesneleri yollara dönüştürün. @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 +4866,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 @@ -5875,7 +5880,7 @@ axis Y Axis Y ekseni @msg Running “{name}”… “{name}” çalıştırılıyor… @msg a live effect runs while the document is drawn, so it can't be `heavy` canlı efekt belge çizilirken çalışır, bu yüzden `heavy` olamaz @msg an exporter always gets an export's budget: leave `budget` out dışa aktarma eklentisi her zaman bir dışa aktarmanın bütçesini alır: `budget` anahtarını çıkarın -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}” büyük bir hesaplama bütçesi istiyor (her çalıştırma en fazla {minutes} dakika ve olağan komutların {times} katı): kullanıcı onayladıktan sonra `allowHeavy: true` ile yükleyin +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” büyük bir hesaplama bütçesi istiyor (her çalıştırma en fazla {minutes} dakika ve olağan komutların {times} katı): masaüstü uygulamasında bir kişinin onaylaması gerekir veya --allow-plugin-grants ile başlatılan bir oturumda `allowHeavy: true` geçirin # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Bu izinleri isteyen “{name}” yüklensin mi? ID: {id} Kimlik: {id} @@ -5915,7 +5920,9 @@ axis Y Axis Y ekseni @msg object budget (more than {MAX_OBJECTS} read-only objects) nesne bütçesi ({MAX_OBJECTS} adetten fazla salt okunur nesne) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it `{shown}` izni sonraki bir eklenti API’si için ayrılmıştır; bu ana bilgisayar bu izni vermez @msg unknown permission `{shown}` bilinmeyen izin `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}” {asked} izinlerini istiyor: kullanıcı onayladıktan sonra bunları listeleyen bir `grant` ile yükleyin +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” {asked} izinlerini istiyor: masaüstü uygulamasında bir kişinin onaylaması gerekir veya --allow-plugin-grants ile başlatılan bir oturumda `grant` geçirin +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` ve `allowHeavy` yalnızca --allow-plugin-grants ile başlatılan bir oturumda etkili olur: eklentiyi masaüstü uygulamasında onaylayın +@msg Only the person at the keyboard can approve installing a plug-in Bir eklentinin yüklenmesini yalnızca klavye başındaki kişi onaylayabilir @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” öğesine çıktısının ihtiyaç duyduğu `{p}` izni verilmedi: hiçbir şey değiştirilmedi @msg a heavy filter runs in the background, so it can't declare `commands` ağır bir filtre arka planda çalışır, bu yüzden `commands` bildiremez @msg at most {MAX_COMMANDS} `commands` en fazla {MAX_COMMANDS} `commands` @@ -5976,6 +5983,9 @@ axis Y Axis Y ekseni @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ya da 1, 3-5 gibi bir aralık olmalı, {v} değil Add to Symbols Sembollere Ekle Basic Shapes Temel Şekiller + Button Düğme + Panel Panel + UI Frames UI çerçeveleri Open Symbol Library Sembol Kitaplığını Aç Save Symbol Library Sembol Kitaplığını Kaydet Save Symbol Library… Sembol Kitaplığını Kaydet… @@ -6050,6 +6060,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 @@ -6468,7 +6480,7 @@ breakText Glyphs Glifler Reset Symbol Instance Sembol Örneğini Sıfırla @msg type must be static or dynamic, not {v} type static veya dynamic olmalıdır, {v} değil @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` statik bir semboldür: önce Sembol Türünü Dinamik olarak ayarlayın -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Bir sembol örneğinde seçilen yolun, bileşik yolun veya yazının yalnızca dolgu ve konturunun düz rengi değiştirilebilir +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Bir sembol örneğinde seçili yol, bileşik yol veya metnin yalnızca dolgu, kontur, opaklık ve karışımı değiştirilebilir @msg path must be a list of child indices path alt öğe dizinlerinden oluşan bir liste olmalıdır @msg no object at path {shown} in the symbol's art sembolün çiziminde {shown} yolunda nesne yok @msg give fill, stroke, opacity and/or blend fill, stroke, opacity ve/veya blend verin @@ -6618,3 +6630,6 @@ 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 diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ec60d12ecb..25ee4d80ac 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 Зберегти набір друку @@ -3539,7 +3539,6 @@ effect Points Точки Template Шаблон Templates Шаблони Templates Folder Папка шаблонів - Templates… Шаблони… Text Displayed in Cell: Текст, що відображається в комірці: Text Export Options Параметри експорту тексту Text Fill & Stroke Color Колір заливки та обведення тексту @@ -4441,6 +4440,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 +5176,7 @@ 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 or group. Convert images and other objects to paths first. {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 +5184,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 @@ -5516,7 +5521,7 @@ axis Y Axis Вісь Y @msg Running “{name}”… Виконується «{name}»… @msg a live effect runs while the document is drawn, so it can't be `heavy` динамічний ефект виконується під час відмальовування документа, тому він не може бути `heavy` @msg an exporter always gets an export's budget: leave `budget` out модуль експорту завжди отримує бюджет експорту: не вказуйте `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees «{_1}» запитує великий обчислювальний бюджет (кожен запуск до {minutes} хвилин і в {times} разів більше інструкцій, ніж зазвичай): встановіть його з `allowHeavy: true`, коли користувач погодиться +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» запитує великий обчислювальний бюджет (кожен запуск до {minutes} хвилин і в {times} разів більше інструкцій, ніж зазвичай): його має схвалити людина в настільному застосунку, або передайте `allowHeavy: true` у сеансі, запущеному з --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Встановити «{name}», якому потрібні ці дозволи? ID: {id} ID: {id} @@ -5556,7 +5561,9 @@ axis Y Axis Вісь Y @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет об’єктів (понад {MAX_OBJECTS} об’єктів лише для читання) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it дозвіл `{shown}` зарезервовано для пізнішого API модулів; цей хост його не надає @msg unknown permission `{shown}` невідомий дозвіл `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees «{name}» запитує дозволи {asked}: установіть його з `grant`, де їх перелічено, коли користувач погодиться +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants «{name}» запитує дозволи {asked}: їх має схвалити людина в настільному застосунку, або передайте `grant` у сеансі, запущеному з --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` і `allowHeavy` діють лише в сеансі, запущеному з --allow-plugin-grants: схваліть плагін у настільному застосунку +@msg Only the person at the keyboard can approve installing a plug-in Схвалити встановлення плагіна може лише людина за клавіатурою @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не отримав дозволу `{p}`, потрібного для його результату: нічого не змінено @msg a heavy filter runs in the background, so it can't declare `commands` важкий фільтр виконується у фоні, тому не може оголошувати `commands` @msg at most {MAX_COMMANDS} `commands` щонайбільше {MAX_COMMANDS} `commands` @@ -5617,6 +5624,9 @@ axis Y Axis Вісь Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all або діапазон, наприклад 1, 3-5, а не {v} Add to Symbols Додати до символів Basic Shapes Базові фігури + Button Кнопка + Panel Панель + UI Frames UI-рамки Open Symbol Library Відкрити бібліотеку символів Save Symbol Library Зберегти бібліотеку символів Save Symbol Library… Зберегти бібліотеку символів… @@ -5691,6 +5701,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 Приховати параметри прив’язки до гліфа @@ -6113,7 +6125,7 @@ breakText Glyphs Гліфи Reset Symbol Instance Скинути екземпляр символу @msg type must be static or dynamic, not {v} type має бути static або dynamic, а не {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` — статичний символ: спершу встановіть для нього тип символу «Динамічний» -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change У контуру, складеного контуру або тексту, виділеного в екземплярі символу, можна змінити лише суцільний колір заливки й обведення +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change У контуру, складеного контуру або тексту, виділеного в екземплярі символу, можна змінити лише заливку, обведення, непрозорість і режим накладання @msg path must be a list of child indices path має бути списком індексів дочірніх об’єктів @msg no object at path {shown} in the symbol's art у графіці символу немає об’єкта за шляхом {shown} @msg give fill, stroke, opacity and/or blend вкажіть fill, stroke, opacity та/або blend @@ -6263,3 +6275,6 @@ 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 Немає варіантів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 55d3d3300f..7a6fdc5bd4 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 @@ -3873,7 +3873,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 @@ -4750,6 +4749,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 +5119,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 +5176,7 @@ 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 or group. Convert images and other objects to paths first. {label} hiện yêu cầu một đường dẫn, đường dẫn phức, văn bản hoặc nhóm. Hãy chuyển hình ảnh và các đối tượng khác thành đường dẫn trước. @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 @@ -5517,7 +5522,7 @@ axis Y Axis Trục Y @msg Running “{name}”… Đang chạy “{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` hiệu ứng trực tiếp chạy trong lúc tài liệu được vẽ nên không thể là `heavy` @msg an exporter always gets an export's budget: leave `budget` out plug-in xuất luôn nhận ngân sách của một lần xuất: hãy bỏ `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}” yêu cầu ngân sách tính toán lớn (mỗi lần chạy tới {minutes} phút và gấp {times} lần số lệnh thông thường): hãy cài đặt với `allowHeavy: true` khi người dùng đồng ý +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” yêu cầu ngân sách tính toán lớn (mỗi lần chạy tới {minutes} phút và gấp {times} lần số lệnh thông thường): cần một người phê duyệt trong ứng dụng máy tính, hoặc truyền `allowHeavy: true` trong phiên khởi động bằng --allow-plugin-grants # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Cài đặt “{name}”, plug-in yêu cầu các quyền này? ID: {id} ID: {id} @@ -5557,7 +5562,9 @@ axis Y Axis Trục Y @msg object budget (more than {MAX_OBJECTS} read-only objects) ngân sách đối tượng (hơn {MAX_OBJECTS} đối tượng chỉ đọc) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it quyền `{shown}` được dành cho một API plug-in sau này; máy chủ này không cấp quyền đó @msg unknown permission `{shown}` quyền không xác định `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}” yêu cầu các quyền {asked}: hãy cài đặt với `grant` liệt kê chúng khi người dùng đồng ý +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}” yêu cầu các quyền {asked}: cần một người phê duyệt trong ứng dụng máy tính, hoặc truyền `grant` trong phiên khởi động bằng --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` và `allowHeavy` chỉ có hiệu lực trong phiên khởi động bằng --allow-plugin-grants: hãy phê duyệt trình cắm trong ứng dụng máy tính +@msg Only the person at the keyboard can approve installing a plug-in Chỉ người ngồi tại bàn phím mới có thể phê duyệt việc cài đặt trình cắm @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” chưa được cấp `{p}`, quyền mà đầu ra của nó cần: không có gì thay đổi @msg a heavy filter runs in the background, so it can't declare `commands` bộ lọc nặng chạy ở chế độ nền nên không thể khai báo `commands` @msg at most {MAX_COMMANDS} `commands` tối đa {MAX_COMMANDS} `commands` @@ -5618,6 +5625,9 @@ axis Y Axis Trục Y @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all hoặc một phạm vi như 1, 3-5, không phải {v} Add to Symbols Thêm vào ký hiệu Basic Shapes Hình cơ bản + Button Nút + Panel Bảng + UI Frames Khung UI 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… @@ -5692,6 +5702,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 @@ -6114,7 +6126,7 @@ breakText Glyphs Glyph Reset Symbol Instance Đặt lại đối tượng ký hiệu @msg type must be static or dynamic, not {v} type phải là static hoặc dynamic, không phải {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` là ký hiệu tĩnh: trước tiên hãy đặt Kiểu ký hiệu thành Động -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change Chỉ có thể thay đổi màu đặc của màu tô và nét của đường dẫn, đường dẫn phức hoặc chữ được chọn trong một đối tượng ký hiệu +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change Chỉ có thể đổi tô, nét, độ đục và hòa trộn của đường dẫn, đường dẫn phức hợp hoặc chữ được chọn trong một thực thể ký hiệu @msg path must be a list of child indices path phải là danh sách chỉ số con @msg no object at path {shown} in the symbol's art không có đối tượng tại đường dẫn {shown} trong hình của ký hiệu @msg give fill, stroke, opacity and/or blend hãy cung cấp fill, stroke, opacity và/hoặc blend @@ -6264,3 +6276,6 @@ 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 ý diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 542f595cb0..1f11aa4d6c 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 保存打印预设 @@ -3374,7 +3374,6 @@ digits Malayalam 马拉雅拉姆数字 Template 模板 Templates 模板 Templates Folder 模板文件夹 - Templates… 模板… Text Displayed in Cell: 单元格中显示的文字: Text Export Options 文本导出选项 Text Fill & Stroke Color 文字填色和描边颜色 @@ -4510,6 +4509,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 个步骤 @@ -5457,7 +5457,7 @@ 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 or group. Convert images and other objects to paths first. {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 +5465,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 文件不完整 @@ -5757,7 +5762,7 @@ axis Y Axis Y 轴 @msg Running “{name}”… 正在运行“{name}”… @msg a live effect runs while the document is drawn, so it can't be `heavy` 实时效果在绘制文档时运行,因此不能为 `heavy` @msg an exporter always gets an export's budget: leave `budget` out 导出增效工具始终使用导出的预算:请省略 `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}”需要大量计算预算(每次运行最多 {minutes} 分钟,指令数为通常的 {times} 倍):请在用户同意后使用 `allowHeavy: true` 安装 +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}”需要大量计算预算(每次运行最多 {minutes} 分钟,指令数为通常的 {times} 倍):需要有人在桌面应用中批准,或在以 --allow-plugin-grants 启动的会话中传入 `allowHeavy: true` # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 要安装需要这些权限的“{name}”吗? ID: {id} ID:{id} @@ -5797,7 +5802,9 @@ axis Y Axis Y 轴 @msg object budget (more than {MAX_OBJECTS} read-only objects) 对象预算(超过 {MAX_OBJECTS} 个只读对象) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 权限 `{shown}` 保留给以后的增效工具 API;此主机不授予该权限 @msg unknown permission `{shown}` 未知权限 `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees “{name}”需要权限 {asked}:请在用户同意后使用列出这些权限的 `grant` 安装 +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants “{name}”需要权限 {asked}:需要有人在桌面应用中批准,或在以 --allow-plugin-grants 启动的会话中传入 `grant` +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` 和 `allowHeavy` 仅在以 --allow-plugin-grants 启动的会话中生效:请在桌面应用中批准此插件 +@msg Only the person at the keyboard can approve installing a plug-in 只有键盘前的人才能批准安装插件 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”未获授予其输出所需的 `{p}`:未作任何更改 @msg a heavy filter runs in the background, so it can't declare `commands` 重型滤镜在后台运行,因此不能声明 `commands` @msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 个 `commands` @@ -5858,6 +5865,9 @@ axis Y Axis Y 轴 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:应为 all 或 1, 3-5 这样的范围,而不是 {v} Add to Symbols 添加到符号 Basic Shapes 基本形状 + Button 按钮 + Panel 面板 + UI Frames UI 框架 Open Symbol Library 打开符号库 Save Symbol Library 保存符号库 Save Symbol Library… 保存符号库… @@ -5932,6 +5942,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 隐藏靠齐字符选项 @@ -6353,7 +6365,7 @@ breakText Glyphs 字形 Reset Symbol Instance 重置符号实例 @msg type must be static or dynamic, not {v} type 必须是 static 或 dynamic,而不是 {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` 是静态符号:请先将其符号类型设为动态 -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change 在符号实例中选中的路径、复合路径或文字只能更改填色和描边的纯色 +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change 在符号实例中选中的路径、复合路径或文字只能更改填色、描边、不透明度和混合模式 @msg path must be a list of child indices path 必须是子项索引列表 @msg no object at path {shown} in the symbol's art 符号图稿中路径 {shown} 处没有对象 @msg give fill, stroke, opacity and/or blend 请提供 fill、stroke、opacity 和/或 blend diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ccdc7adcf0..9997599d8c 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: 建立來源: @@ -2354,6 +2353,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 個步驟 @@ -2800,6 +2800,7 @@ file-filter Templates 範本 Lock (⌘2) 鎖定 (⌘2) Lock Grid 鎖定格點 Lock Guides 鎖定參考線 + Lock Guides by Default 預設鎖定參考線 Lock Others 鎖定其他 Lock Slices 鎖定切片 Lock Station Point 鎖定基準點 @@ -3064,7 +3065,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 +3861,7 @@ digits Malayalam 馬來亞拉姆數字 Save PDF Preset 儲存 PDF 預設集 Save Perspective Grid Preset 儲存透視格點預設集 Save Preset 儲存預設集 + Save Document Preset 儲存文件預設集 Preset {number} 預設集 {number} Save Preset… 儲存預設集… Save Print Preset 儲存列印預設集 @@ -4438,7 +4439,6 @@ digits Malayalam 馬來亞拉姆數字 Template 範本 Templates 範本 Templates Folder 範本資料夾 - Templates… 範本… Text Displayed in Cell: 儲存格中顯示的文字: Text Export Options 文字匯出選項 Text Fill & Stroke Color 文字填色與筆畫顏色 @@ -5283,7 +5283,7 @@ 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 or group. Convert images and other objects to paths first. {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 +5291,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 影像 @@ -5554,7 +5559,7 @@ axis Y Axis Y 軸 @msg Running “{name}”… 正在執行「{name}」… @msg a live effect runs while the document is drawn, so it can't be `heavy` 即時效果會在繪製文件時執行,因此不能是 `heavy` @msg an exporter always gets an export's budget: leave `budget` out 匯出增效模組一律使用匯出的預算:請移除 `budget` -@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees 「{_1}」需要大量運算預算(每次執行最多 {minutes} 分鐘,指令數為一般的 {times} 倍):請在使用者同意後以 `allowHeavy: true` 安裝 +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants 「{_1}」需要大量運算預算(每次執行最多 {minutes} 分鐘,指令數為一般的 {times} 倍):需要有人在桌面應用程式中核准,或在以 --allow-plugin-grants 啟動的工作階段中傳入 `allowHeavy: true` # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 要安裝需要這些權限的「{name}」嗎? ID: {id} ID:{id} @@ -5594,7 +5599,9 @@ axis Y Axis Y 軸 @msg object budget (more than {MAX_OBJECTS} read-only objects) 物件預算(超過 {MAX_OBJECTS} 個唯讀物件) @msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it 權限 `{shown}` 保留給日後的增效模組 API;此主機不授予該權限 @msg unknown permission `{shown}` 未知權限 `{shown}` -@msg “{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees 「{name}」需要權限 {asked}:請在使用者同意後以列出這些權限的 `grant` 安裝 +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants 「{name}」需要權限 {asked}:需要有人在桌面應用程式中核准,或在以 --allow-plugin-grants 啟動的工作階段中傳入 `grant` +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` 和 `allowHeavy` 僅在以 --allow-plugin-grants 啟動的工作階段中生效:請在桌面應用程式中核准此外掛 +@msg Only the person at the keyboard can approve installing a plug-in 只有鍵盤前的人才能核准安裝外掛 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」未獲授予其輸出所需的 `{p}`:未做任何變更 @msg a heavy filter runs in the background, so it can't declare `commands` 重型濾鏡在背景執行,因此不能宣告 `commands` @msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 個 `commands` @@ -5655,6 +5662,9 @@ axis Y Axis Y 軸 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:應為 all 或 1, 3-5 這類範圍,而不是 {v} Add to Symbols 新增至符號 Basic Shapes 基本形狀 + Button 按鈕 + Panel 面板 + UI Frames UI 框架 Open Symbol Library 開啟符號資料庫 Save Symbol Library 儲存符號資料庫 Save Symbol Library… 儲存符號資料庫… @@ -5729,6 +5739,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 隱藏靠齊字符選項 @@ -6151,7 +6163,7 @@ breakText Glyphs 字符 Reset Symbol Instance 重設符號實體 @msg type must be static or dynamic, not {v} type 必須是 static 或 dynamic,而不是 {v} @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` 是靜態符號:請先將其符號類型設為動態 -@msg Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change 在符號實體中選取的路徑、複合路徑或文字只能變更填色和筆畫的純色 +@msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change 在符號實體中選取的路徑、複合路徑或文字只能變更填色、筆畫、不透明度和混合模式 @msg path must be a list of child indices path 必須是子項索引清單 @msg no object at path {shown} in the symbol's art 符號圖稿中路徑 {shown} 處沒有物件 @msg give fill, stroke, opacity and/or blend 請提供 fill、stroke、opacity 和/或 blend diff --git a/crates/ui-egui/src/ime.rs b/crates/ui-egui/src/ime.rs index 95c0c03239..7f4893c6f9 100644 --- a/crates/ui-egui/src/ime.rs +++ b/crates/ui-egui/src/ime.rs @@ -109,7 +109,7 @@ pub(crate) fn install_hooks(ctx: &Context) { } /// The base eligibility every custom-descriptor consumer shares: a hidden viewport, the Home -/// screen, a modal dialog, the palette, a file sheet, an unfocused window, another egui keyboard +/// screen, a modal dialog, an update dialog, the palette, a file sheet, an unfocused window, another egui keyboard /// owner or no Type-tool text edit all mean this pass publishes a stock descriptor or none. One /// helper so the pre-UI route test, the post-UI finalizer and the end-of-pass observation cannot /// drift apart; Home in particular is an ineligible route even though the Type tool keeps its @@ -118,6 +118,7 @@ fn pass_eligible(app: &VectorcraftApp, ctx: &Context) -> bool { !app.viewport_hidden(ctx) && !crate::menus::home_showing(app) && app.ui.dialog.is_none() + && !crate::updates_ui::blocks_input(app) && !app.ui.palette_open && !app.file_sheet_open() && ctx.input(|input| input.focused) @@ -801,6 +802,31 @@ pub(crate) fn write_output(ctx: &Context, update: Option, rect #[cfg(test)] mod tests { use super::*; + use serde_json::json; + use vectorcraft_engine::Session; + + /// The update prompt ends the Type tool's IME route, as a dialog does. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn the_update_prompt_ends_the_type_tools_route() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 80, "text": "Text", "size": 12, "color": "#000000"})).unwrap()["id"].as_u64().unwrap(); + let view = app.view_info(); + app.session.select_tool("type", view).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": id, "start": 4, "end": 4})); + assert!(app.session.tool_wants_text()); + let ctx = Context::default(); + let eligible = |app: &VectorcraftApp| { + let mut eligible = false; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| eligible = pass_eligible(app, ui.ctx())); + out.textures_delta.clear(); + eligible + }; + assert!(eligible(&app)); + crate::updates_ui::open_prompt_for_test(&mut app); + assert!(!eligible(&app), "no canvas descriptor behind the prompt"); + } /// A changed context generation or IME purpose for the same owner requires a replacement reset, /// while an unchanged descriptor keeps the existing request. diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 91f08da1ba..cc6f5d2262 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -21,6 +21,7 @@ pub use export::{EXPORT_CANCELLED, cancel_exports, export, export_for_screens, e pub(crate) use export::{ export_files, exported_with_notes, file_url, open_in_app, open_original, reveal_path, run_to_file, save_command_output_named, }; +pub(crate) use open::report_installed; pub(crate) use open::{EXPORT_PRESETS, import_presets, open_with_on, opened}; pub use open::{ MAX_RECENT_FILES, OpensAs, ask_revert, install_module, install_plugin, new_from_template, note_recent, open_bytes, open_dialog, open_document, diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index aa61d42a85..a75171ae36 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -1,3 +1,4 @@ +use vectorcraft_engine::cmd::plugin::InstallApproval; use vectorcraft_plugins::permissions; use super::save::suggested; @@ -190,79 +191,94 @@ fn permission_words(name: &str) -> String { } /// Installs the plug-in module that `module` names (`plugin.install`'s `path`, or `dataBase64` -/// with `name`) → `plugin.install`'s result. A plug-in that lists permissions the user hasn't -/// granted it yet (`grant`) asks them first, showing its name, id, version, file hash and what each -/// permission lets it do, so does a filter that asks for a heavy budget the user hasn't allowed -/// yet (`allowHeavy`), and so does a module that would take the place of another one with its id -/// and get its settings and cache (`replace`); OK installs it if the module still has the hash the -/// prompt showed, Cancel installs nothing → `{pending}` while it asks. Every -/// text from the manifest is shown with its hidden characters escaped and its length capped +/// with `name`) → `plugin.install`'s result. A plug-in that lists permissions no person has granted +/// it yet asks first, showing its name, id, version, file hash and what each permission lets it +/// do, so does a filter that asks for a heavy budget, and so does a module that would take the +/// place of another one with its id and get its settings and cache (`replace`); OK installs it if +/// the module still has the hash the prompt showed, Cancel installs nothing → `{pending}` while it +/// asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves. +/// Every text from the manifest is shown with its hidden characters escaped and its length capped /// ([`permissions::display_text`]). pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result { - let heavy_allowed = module.get("allowHeavy").and_then(Value::as_bool) == Some(true); - let granted = module.get("grant").is_some_and(|g| !g.is_null()); + let given = |k: &str| module.get(k).map(|v| (k.to_string(), v.clone())); + let source = Value::Object(["path", "dataBase64", "name"].into_iter().filter_map(given).collect()); + let mut install = Value::Object(["path", "dataBase64", "name", "replace", "hash"].into_iter().filter_map(given).collect()); + let info = app.run("plugin.inspect", source)?; + let (needs_grant, heavy) = (info["needsApproval"] == true, info["budget"] == "heavy"); // `replace: false` asks for no replacing, so only a module without `replace` asks. - let replace_given = module.get("replace").is_some_and(|r| !r.is_null()); - if !heavy_allowed || !granted || !replace_given { - let given = |k: &str| module.get(k).map(|v| (k.to_string(), v.clone())); - let source = Value::Object(["path", "dataBase64", "name"].into_iter().filter_map(given).collect()); - // What OK installs: the same module, with what the user has agreed to so far, pinned to - // the bytes the prompt shows (`hash`). - let mut answered = - Value::Object(["path", "dataBase64", "name", "replace", "grant", "allowHeavy", "hash"].into_iter().filter_map(given).collect()); - let info = app.run("plugin.inspect", source)?; - if answered.get("hash").is_none() { - answered["hash"] = info["hash"].clone(); - } - let shown = |k: &str, max: usize| permissions::display_text(info[k].as_str().unwrap_or_default(), max); - let name = shown("name", permissions::MAX_SHOWN_NAME); - if !granted && info["needsApproval"] == true { - let message = crate::i18n::fmt(tl!("Install “{name}”, which asks for these permissions?"), &[("name", &name)]); - let mut lines = vec![crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))])]; - let version = shown("version", permissions::MAX_SHOWN_FIELD); - if !version.is_empty() { - lines.push(crate::i18n::fmt(tl!("Version: {version}"), &[("version", &version)])); - } - lines.push(crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))])); - lines.push(String::new()); - let asked = info["permissions"].as_array().cloned().unwrap_or_default(); - lines.extend(asked.iter().filter_map(Value::as_str).map(|p| format!("• {}", permission_words(p)))); - let mut again = answered; - again["grant"] = Value::Array(asked); - dialogs::confirm::ask(app, &message, &lines.join("\n"), "ui.installPlugin", again); - return Ok(json!({ "pending": dialogs::confirm::KIND })); - } - if !heavy_allowed && info["budget"] == "heavy" { - let (minutes, times) = vectorcraft_plugins::heavy_terms(); - let message = crate::i18n::fmt(tl!("Install “{name}”, which asks for a heavy budget?"), &[("name", &name)]); - let detail = crate::i18n::fmt( - tl!( - "Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it." - ), - &[("minutes", &minutes.to_string()), ("times", ×.to_string())], - ); - let mut allowed = answered; - allowed["allowHeavy"] = json!(true); - dialogs::confirm::ask(app, &message, &detail, "ui.installPlugin", allowed); - return Ok(json!({ "pending": dialogs::confirm::KIND })); - } - if !replace_given && info["needsReplace"] == true { - let message = crate::i18n::fmt(tl!("Install “{name}” in place of the plug-in with the same ID?"), &[("name", &name)]); - let lines = [ - crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))]), - crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))]), - String::new(), - tl!("This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID.").to_string(), - ]; - let mut replaced = answered; - replaced["replace"] = json!(true); - dialogs::confirm::ask(app, &message, &lines.join("\n"), "ui.installPlugin", replaced); - return Ok(json!({ "pending": dialogs::confirm::KIND })); - } + let asks_replace = module.get("replace").is_none_or(Value::is_null) && info["needsReplace"] == true; + if !needs_grant && !heavy && !asks_replace { + let r = app.run("plugin.install", install)?; + report_installed(app, &r); + return Ok(r); } - let r = app.run("plugin.install", module)?; + // Pinned to the bytes the prompt shows. + if install.get("hash").is_none() { + install["hash"] = info["hash"].clone(); + } + let shown = |k: &str, max: usize| permissions::display_text(info[k].as_str().unwrap_or_default(), max); + let name = shown("name", permissions::MAX_SHOWN_NAME); + let identity = [ + crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))]), + crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))]), + ] + .join("\n"); + let takes_place = tl!("This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID."); + if asks_replace { + install["replace"] = json!(true); + } + // A client may pass `replace` itself, so taking another module's place alone needs no approval + // that only a person can give. + if !needs_grant && !heavy { + let message = crate::i18n::fmt(tl!("Install “{name}” in place of the plug-in with the same ID?"), &[("name", &name)]); + dialogs::confirm::ask(app, &message, &format!("{identity}\n\n{takes_place}"), "ui.installPlugin", install); + return Ok(json!({ "pending": dialogs::confirm::KIND })); + } + let asked = info["permissions"].as_array().cloned().unwrap_or_default(); + let mut paragraphs = vec![]; + if needs_grant { + let mut lines = vec![crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))])]; + let version = shown("version", permissions::MAX_SHOWN_FIELD); + if !version.is_empty() { + lines.push(crate::i18n::fmt(tl!("Version: {version}"), &[("version", &version)])); + } + lines.push(crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))])); + lines.push(String::new()); + lines.extend(asked.iter().filter_map(Value::as_str).map(|p| format!("• {}", permission_words(p)))); + paragraphs.push(lines.join("\n")); + install["grant"] = Value::Array(asked.clone()); + } + if heavy { + let (minutes, times) = vectorcraft_plugins::heavy_terms(); + paragraphs.push(crate::i18n::fmt( + tl!( + "Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it." + ), + &[("minutes", &minutes.to_string()), ("times", ×.to_string())], + )); + install["allowHeavy"] = json!(true); + } + if asks_replace { + paragraphs.push(if needs_grant { takes_place.to_string() } else { format!("{identity}\n\n{takes_place}") }); + } + let message = if needs_grant { + crate::i18n::fmt(tl!("Install “{name}”, which asks for these permissions?"), &[("name", &name)]) + } else { + crate::i18n::fmt(tl!("Install “{name}”, which asks for a heavy budget?"), &[("name", &name)]) + }; + let approval = InstallApproval { + id: info["id"].as_str().unwrap_or_default().to_string(), + hash: info["hash"].as_str().unwrap_or_default().to_string(), + permissions: asked.iter().filter_map(Value::as_str).map(str::to_string).collect(), + heavy, + }; + let pending = dialogs::plugin::PendingInstall { message, detail: paragraphs.join("\n\n"), params: install, approval }; + Ok(dialogs::plugin::ask_install(app, pending)) +} + +/// Says in the status bar that `plugin.install`'s result `r` was installed. +pub(crate) fn report_installed(app: &mut VectorcraftApp, r: &Value) { app.status(format!("Installed plug-in {}", permissions::display_text(r["name"].as_str().unwrap_or_default(), permissions::MAX_SHOWN_NAME))); - Ok(r) } /// Where File → Open… starts: the folder of the most recently opened file, else the active diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6a71ca862b..03acb7597e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -309,6 +309,9 @@ pub struct VectorcraftApp { /// This frame carries input the control channel injected ([`Self::raw_input_hook`]): it runs /// confined to [`Self::automation_roots`]. synthetic_frame: bool, + /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which + /// `ui.dialog.set` writes. + pub(crate) pending_plugin_install: Option, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index bc191593a8..387cd099cd 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]); } @@ -108,6 +109,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 { 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/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 8821679e8f..9ec98faae7 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -267,6 +267,7 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.view.text_threads), "type.hiddenCharacters" => flag(&mut app.ui.view.hidden_chars), + "edit.autoSpellCheck" => flag(&mut app.ui.view.auto_spell_check), "type.bold" => crate::panels::character::toggle_face(app, Face::Bold), "type.italic" => crate::panels::character::toggle_face(app, Face::Italic), "type.highlightFontName" => crate::panels::character::highlight(app, crate::panels::character::Field::FontName), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index c0a0c04baf..1941504e57 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -51,6 +51,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { selected_text(true).is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())) } "view.smartGuides" => v.smart_guides, + "edit.autoSpellCheck" => v.auto_spell_check, "view.grid" => v.grid, "view.snapToGrid" => v.snap_to_grid, "view.snapToPoint" => v.snap_to_point, diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index fdea9664b7..c51f36e7de 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -97,7 +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![todo("Auto Spell Check"), todos("Check Spelling…", "Cmd+I"), todo("Edit Custom Dictionary…")]), + sub( + "Spelling", + vec![c("Auto Spell Check", "edit.autoSpellCheck"), todos("Check Spelling…", "Cmd+I"), todo("Edit Custom Dictionary…")], + ), 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 c3af44d3d6..3b314f8335 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -162,6 +162,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), + ( + "edit.autoSpellCheck", + "Auto Spell Check", + "", + "{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on", + ), ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), @@ -1488,7 +1494,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.installPlugin", "Install Plug-in…", "", - "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), allowHeavy?: bool (the user agreed to its heavy budget), grant?: [permission] (the permissions the user granted it), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing → plugin.install's result | {pending: \"confirm\"} while it asks", + "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK when it asks about permissions or a heavy budget: ui.dialog.confirm, answer_dialog and synthetic input are refused → plugin.install's result | {pending: \"pluginInstall\"} while it asks about permissions or a heavy budget | {pending: \"confirm\"} while it asks only about replacing", ), ( "plugin.cancelRuns", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 270c46a117..a74f47b6a9 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1204,8 +1204,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } -/// Whether a modal is open: a dialog, About, the command palette, a native file dialog, or a -/// window behind the modal backdrop last frame (export progress, plug-in runs). Floating panels +/// Whether a modal is open: a dialog, About, the command palette, a native file dialog, an update +/// dialog, or a window behind the modal backdrop last frame (export progress, plug-in runs). Floating panels /// in OS windows of their own take no input meanwhile, as the main window behind it takes none. /// The window level and visibility a palette window takes: hidden under a modal dialog (a click /// must not bring it back over the dialog), at the normal level under a menu or another popup drawn @@ -1260,6 +1260,7 @@ pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { || app.ui.about || app.ui.palette_open || app.file_dialog_open() + || crate::updates_ui::blocks_input(app) || ctx.memory(|m| m.areas().is_visible(&crate::dialogs::modal::backdrop())) } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 26614634a5..db1e6be36c 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -642,6 +642,33 @@ fn a_modal_blocks_native_windows_and_takes_the_keyboard_from_them() { assert_eq!(h.app.session.tool_id(), "pen", "the window takes keys again once the modal closes"); } +/// The update prompt and the result window of a check block a floating panel's OS window as any +/// modal does. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_update_dialogs_block_native_windows_and_take_the_keyboard_from_them() { + type Open = fn(&mut Harness); + let opens: [(&str, Open); 2] = [ + ("the prompt", |h| crate::updates_ui::open_prompt_for_test(&mut h.app)), + ("the result window", |h| crate::updates_ui::open_result_window_for_test(&mut h.app, &h.ctx)), + ]; + for (name, open) in opens { + let mut h = Harness::new(); + let viewport = h.float("swatches"); + open(&mut h); + h.frames(6); + let focus_commands = h.host.borrow().commands.iter().filter(|(id, c)| *id == ViewportId::ROOT && *c == ViewportCommand::Focus).count(); + assert_eq!(focus_commands, 1, "{name}: the main window gets the keyboard"); + h.key_in(viewport, Key::P); + assert_eq!(h.app.session.tool_id(), "selection", "{name}: a key typed in the blocked window does nothing"); + + crate::updates_ui::close_dialogs_for_test(&mut h.app); + h.frames(3); + h.key_in(viewport, Key::P); + assert_eq!(h.app.session.tool_id(), "pen", "{name}: the window takes keys again once the dialog closes"); + } +} + /// The level and visibility a palette window takes under a dialog or a menu, and otherwise: a /// palette stays out of the way of anything drawn in the main window. #[test] @@ -1027,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), @@ -1060,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), @@ -1426,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 afae95ca03..1b8b1a168a 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -321,6 +321,13 @@ fn the_tools_panel_docks_on_the_right_left_of_the_panels() { h.app.run("window.panel.float", json!({"panel": "tools"})).unwrap(); assert_eq!(h.app.run("window.panel.dock", json!({"panel": "tools"})).unwrap()["side"], "right", "back on the side it docked at last"); assert!(h.app.run("window.panel.dock", json!({"panel": "tools", "side": "top"})).is_err()); + // A side that isn't text is an error too, not the last side: it leaves Tools where it is. + h.app.run("window.panel.float", json!({"panel": "tools"})).unwrap(); + for side in [json!(5), json!(true), json!(["left"])] { + assert!(h.app.run("window.panel.dock", json!({"panel": "tools", "side": side})).is_err(), "{side}"); + assert!(h.app.ui.toolbar_pos.is_some(), "still floating after side {side}"); + } + assert_eq!(h.app.run("window.panel.dock", json!({"panel": "tools", "side": null})).unwrap()["side"], "right", "null: the last side"); } /// The docked Tools panel as last drawn. diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 9790270a44..d46e5c4ac3 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 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/tests_symbol_libraries.rs b/crates/ui-egui/src/panels/tests_symbol_libraries.rs index 329b2a0cd7..6482bf3123 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")]); + assert_eq!(opened, [json!("basic-shapes"), json!("ui-frames")]); 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/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/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 5987050c04..63e311aeae 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -210,6 +210,11 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::ime::controls_without_editor(app, ctx); return; } + // The update prompt and the modal result window draw over everything and read Escape themselves. + if crate::updates_ui::blocks_input(app) { + crate::ime::controls_without_editor(app, ctx); + return; + } if app.ui.dialog.is_some() || app.ui.palette_open { crate::ime::controls_without_editor(app, ctx); if app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active) && crate::dialogs::revolve_gizmo::dragging(ctx) { @@ -221,7 +226,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); diff --git a/crates/ui-egui/src/shortcuts/held_tool.rs b/crates/ui-egui/src/shortcuts/held_tool.rs index a3a809b966..5d69422a05 100644 --- a/crates/ui-egui/src/shortcuts/held_tool.rs +++ b/crates/ui-egui/src/shortcuts/held_tool.rs @@ -91,9 +91,9 @@ pub(super) fn follow(app: &mut VectorcraftApp, ctx: &egui::Context, focused: boo // Each pass looks at the key held last; one that goes back hands over to the key under it. loop { let gesture = app.session.tool_busy() || app.session.pointer_held(); - // A dialog, or a canvas drag that does not reach the tool (a pan, zoom or turn of the view), - // defers the decision. - let dialog = app.ui.dialog.is_some() || crate::canvas::dragging(ctx); + // A dialog, an update dialog, or a canvas drag that does not reach the tool (a pan, zoom or + // turn of the view), defers the decision. + let dialog = app.ui.dialog.is_some() || crate::updates_ui::blocks_input(app) || crate::canvas::dragging(ctx); let active = app.session.tool_id(); let on = app.session.prefs.hold_tool_keys; let Some(held) = app.held_tool.last_mut() else { return }; diff --git a/crates/ui-egui/src/shortcuts/held_tool/tests.rs b/crates/ui-egui/src/shortcuts/held_tool/tests.rs index e2217b8226..c272024adb 100644 --- a/crates/ui-egui/src/shortcuts/held_tool/tests.rs +++ b/crates/ui-egui/src/shortcuts/held_tool/tests.rs @@ -75,6 +75,21 @@ fn pen_app() -> VectorcraftApp { app } +/// S let go while the update prompt is open leaves Scale chosen until the prompt closes. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_tool_key_let_go_behind_the_update_prompt_returns_after_it() { + let mut app = pen_app(); + let keys = Keyboard::new(); + keys.press_s(&mut app, 0.0); + crate::updates_ui::open_prompt_for_test(&mut app); + keys.release_s(&mut app, 1.0); + assert_eq!(app.session.tool_id(), "scale", "Scale stays behind the prompt"); + crate::updates_ui::close_dialogs_for_test(&mut app); + keys.frame(&mut app, 1.1, vec![], None); + assert_eq!(app.session.tool_id(), "pen", "the Pen is back after the prompt"); +} + /// S held from 0 s, its repeats at `repeats`, let go at `release`. fn hold_s(app: &mut VectorcraftApp, keys: &Keyboard, repeats: &[f64], release: f64) { keys.press_s(app, 0.0); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index d02576fd19..44d438b73b 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -2647,6 +2647,7 @@ fn a_filter_plugin_keeps_its_shortcut_when_replaced_or_reloaded() { fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() { use vectorcraft_plugins::wat as tpl; let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.allow_plugin_grants_from_requests(); app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks"); for (id, params, chord) in [(at_once, "{}", "Cmd+Alt+Shift+F7"), (asks, r#"{"wiggle":{"type":"bool"}}"#, "Cmd+Alt+Shift+F8")] { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 95ffcd9cd6..ce03daca56 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -267,6 +267,10 @@ pub struct ViewFlags { pub live_paint_gaps: bool, /// Type → Show Hidden Characters. pub hidden_chars: bool, + /// Edit › Spelling › Auto Spell Check: a red underline under the words of the type its + /// dictionaries don't know. + #[serde(default)] + pub auto_spell_check: bool, /// View → Hide/Show Template: template layers drawn (dimmed) or left out of the canvas. #[serde(default = "yes")] pub templates: bool, @@ -294,6 +298,7 @@ impl Default for ViewFlags { gradient_annotator: true, live_paint_gaps: false, hidden_chars: false, + auto_spell_check: false, templates: true, } } @@ -343,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 { @@ -410,6 +430,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. @@ -997,6 +1021,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/automation.rs b/crates/ui-egui/src/tests/automation.rs index 49232057b5..c66cc7cd5a 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -372,6 +372,147 @@ fn an_unidentifiable_stale_injected_batch_fails_closed() { let _ = std::fs::remove_dir_all(base); } +/// A plug-in's permissions are approved only by a person. A control request (or MCP, which comes +/// through it) can't pass `grant`, can't answer the approval dialog or rewrite what it installs, +/// and a frame of synthetic input can't press its OK; the person at the keyboard can. +#[test] +fn automation_cannot_approve_a_plugin_install() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = "test.ui.approval.automation"; + let manifest = format!(r#"{{"id":"{id}","name":"Approval","version":"1","kind":"filter","permissions":["doc.read"]}}"#); + let bytes = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let data = vectorcraft_format::base64_encode(&bytes); + let refused = |r: &Value, says: &str| assert!(r["error"].as_str().is_some_and(|e| e.contains(says)), "{r}"); + + let r = request(&mut app, &tx, "engine.execute", json!({"command": "plugin.install", "params": {"dataBase64": data, "grant": ["doc.read"]}})); + refused(&r, "--allow-plugin-grants"); + assert!(app.ui.dialog.is_none()); + + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {"dataBase64": data}})); + assert_eq!(r["result"]["pending"], crate::dialogs::plugin::INSTALL_KIND, "{r}"); + let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); + refused(&r, "Only the person at the keyboard"); + assert!(app.ui.dialog.is_some(), "the refused answer leaves it open"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + + // What the dialog installs isn't in its fields. + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__params", "value": {"dataBase64": "AAAA"}})); + assert!(r.get("error").is_none(), "{r}"); + // What MCP's `answer_dialog` sends: `ui.dialog.set {fields}`, then `ui.dialog.confirm`. + let r = request(&mut app, &tx, "ui.dialog.set", json!({"fields": [{"field": "__params", "value": {"dataBase64": "AAAA"}}]})); + assert!(r.get("error").is_none(), "{r}"); + let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); + refused(&r, "Only the person at the keyboard"); + assert!(app.ui.dialog.is_some() && vectorcraft_plugins::registry::get(id).is_none()); + app.synthetic_frame = true; + assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains("Only the person at the keyboard")); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + app.synthetic_frame = false; + + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&bytes))); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + +type DialogHarness = egui_kittest::Harness<'static, VectorcraftApp>; + +/// Runs one UI pass of `h` for each batch of synthetic input the control path queued, each taken +/// through the host's raw-input hook, until none is left and the last batch is acknowledged. +fn take_injected(h: &mut DialogHarness) { + let ctx = h.ctx.clone(); + loop { + let mut raw = egui::RawInput::default(); + h.state_mut().raw_input_hook(&ctx, &mut raw); + if raw.events.is_empty() && h.state().synthetic.is_empty() { + break; + } + h.input_mut().events.extend(raw.events); + h.step(); + } +} + +/// The open install approval, with nothing installed or granted for `id`. +fn still_waiting(h: &DialogHarness, id: &str) -> bool { + h.state().ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::plugin::INSTALL_KIND) + && vectorcraft_plugins::registry::get(id).is_none() + && vectorcraft_plugins::registry::granted(id).is_none() +} + +/// Keys and pointer input sent through the control path approve nothing at the open install +/// approval: Enter and Space press nothing with no button focused, and with OK focused they and a +/// `ui.click` on it press it and are refused. `ui.pointer` drives the canvas. A person's click on +/// the same button approves. +#[test] +fn injected_keys_and_pointer_input_cannot_approve_a_plugin_install() { + use egui_kittest::kittest::{NodeT, Queryable}; + let refusal = "Only the person at the keyboard"; + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = "test.ui.approval.injected"; + let manifest = format!(r#"{{"id":"{id}","name":"Approval","version":"1","kind":"filter","permissions":["doc.read"]}}"#); + let bytes = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let data = vectorcraft_format::base64_encode(&bytes); + let r = request(&mut app, &tx, "ui.menu.invoke", json!({"command": "ui.installPlugin", "params": {"dataBase64": data}})); + assert_eq!(r["result"]["pending"], crate::dialogs::plugin::INSTALL_KIND, "{r}"); + let mut fonts = false; + let mut h: DialogHarness = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + + for key in ["Enter", "Space"] { + assert!(!h.get_by_label("OK").accesskit_node().is_focused(), "no button has the focus yet"); + h.state_mut().ui.status.clear(); + let r = request(h.state_mut(), &tx, "ui.key", json!({"key": key})); + assert_eq!(r["ok"], true, "{r}"); + take_injected(&mut h); + assert!(still_waiting(&h, id), "{key}"); + assert_eq!(h.state().ui.status, "", "{key} presses nothing"); + } + + for key in ["Enter", "Space"] { + h.get_by_label("OK").focus(); + h.run_steps(2); + assert!(h.get_by_label("OK").accesskit_node().is_focused()); + h.state_mut().ui.status.clear(); + let r = request(h.state_mut(), &tx, "ui.key", json!({"key": key})); + assert_eq!(r["ok"], true, "{r}"); + take_injected(&mut h); + assert!(still_waiting(&h, id), "{key} on a focused OK"); + assert!(h.state().ui.status.contains(refusal), "{key} pressed OK and was refused: {:?}", h.state().ui.status); + } + + let at = h.get_by_label("OK").rect().center(); + h.state_mut().ui.status.clear(); + let r = request(h.state_mut(), &tx, "ui.click", json!({"x": at.x, "y": at.y})); + assert_eq!(r["ok"], true, "{r}"); + take_injected(&mut h); + assert!(still_waiting(&h, id), "ui.click"); + assert!(h.state().ui.status.contains(refusal), "ui.click pressed OK and was refused: {:?}", h.state().ui.status); + + let events = json!([{"kind": "down", "x": at.x, "y": at.y}, {"kind": "up", "x": at.x, "y": at.y}]); + let r = request(h.state_mut(), &tx, "ui.pointer", json!({"events": events})); + assert_eq!(r["ok"], true, "{r}"); + take_injected(&mut h); + assert!(still_waiting(&h, id), "ui.pointer"); + + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.status); + assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&bytes))); + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); +} + /// Edit Original and the Attributes panel's Browser button hand a file or URL to another app: a /// control request (or MCP, which comes through it) can't run them, roots or not. #[test] diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 6dadd856cd..26e04961bb 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![], }) @@ -370,6 +373,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 +399,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/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index 194ec133d9..c3bd9df302 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -13,6 +13,7 @@ use crate::{VectorcraftApp, dialogs, plugin_runs, theme}; /// An app with a new 200 × 200 pt document. fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.allow_plugin_grants_from_requests(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app } @@ -71,10 +72,10 @@ fn installing_a_heavy_filter_asks_first() { let id = "test.ui.heavy.install"; let bytes = heavy(id, 1, "{}"); let r = app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "route.wasm"})).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::KIND); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("message"), format!("Install “Test {id}”, which asks for a heavy budget?")); - assert!(d.str("detail").contains("up to 5 minutes and do 20 times the work"), "{}", d.str("detail")); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND); + let pending = app.pending_plugin_install.as_ref().unwrap(); + assert_eq!(pending.message, format!("Install “Test {id}”, which asks for a heavy budget?")); + assert!(pending.detail.contains("up to 5 minutes and do 20 times the work"), "{}", pending.detail); assert!(registry::get(id).is_none(), "not before the user agrees"); dialogs::confirm(&mut app).unwrap(); assert_eq!(registry::get(id).map(|p| p.manifest().name.clone()), Some(format!("Test {id}"))); @@ -82,7 +83,7 @@ fn installing_a_heavy_filter_asks_first() { // File › Open of the .wasm asks too, and Cancel installs nothing. registry::remove(id); crate::io::open_bytes(&mut app, "route.wasm", &bytes, None).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::confirm::KIND)); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::plugin::INSTALL_KIND)); dialogs::cancel(&mut app); assert!(registry::get(id).is_none()); } diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 4bda0c94e4..22cd5caffb 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -131,8 +131,8 @@ fn asking(id: &str, name: &str, permissions: &str) -> Vec { /// Installing a plug-in that lists permissions asks first, showing its name, id, version, file hash /// and each permission in plain words, with hidden characters from the manifest escaped. Cancel /// installs nothing, OK installs it; installing the same module again doesn't ask, one with other -/// bytes asks again, even when it lists the same permissions, and then whether to take the -/// installed one's place, as does one that asks for another permission. +/// bytes asks again, even when it lists the same permissions, and in the same dialog whether to +/// take the installed one's place, as does one that asks for another permission. #[test] fn installing_a_plugin_that_lists_permissions_asks_first() { let mut app = app(); @@ -143,25 +143,26 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { let bytes = asking(id, name, r#"["doc.read","doc.write"]"#); let data = vectorcraft_format::base64_encode(&bytes); let r = app.run("ui.installPlugin", json!({"dataBase64": data, "name": "tidy.wasm"})).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::KIND); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("message"), "Install “Tidy\\u{202E}fdp.exe\\u{2066}”, which asks for these permissions?"); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND); + let pending = app.pending_plugin_install.as_ref().unwrap(); + assert_eq!(pending.message, "Install “Tidy\\u{202E}fdp.exe\\u{2066}”, which asks for these permissions?"); let hash = vectorcraft_plugins::permissions::sha256_hex(&bytes); - assert_eq!(d.fields.get("__params").map(|p| p["hash"].clone()), Some(json!(hash)), "OK installs the module shown"); - let detail = d.str("detail"); + assert_eq!(pending.params["hash"], json!(hash), "OK installs the module shown"); + let detail = pending.detail.clone(); assert_eq!( detail, format!( "ID: {id}\nVersion: 3.0\\u{{202E}}\\u{{0009}}\\u{{0007}}\nFile SHA-256: {hash}\n\n• Read the objects it is given\n• Change, add and delete objects in the document" ) ); - assert!(!detail.chars().chain(d.str("message").chars()).any(|c| matches!(c, '\u{202E}' | '\u{2066}' | '\t' | '\u{0007}'))); + assert!(!detail.chars().chain(pending.message.chars()).any(|c| matches!(c, '\u{202E}' | '\u{2066}' | '\t' | '\u{0007}'))); assert!(vectorcraft_plugins::registry::get(id).is_none(), "not before the user agrees"); dialogs::cancel(&mut app); assert!(vectorcraft_plugins::registry::get(id).is_none(), "Cancel installs nothing"); + assert!(app.pending_plugin_install.is_none(), "Cancel drops what it asked about"); // File › Open asks too, and OK installs it with what it lists granted. io::open_bytes(&mut app, "tidy.wasm", &bytes, None).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::confirm::KIND)); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::plugin::INSTALL_KIND)); dialogs::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); assert!(vectorcraft_plugins::registry::get(id).is_some()); @@ -173,39 +174,37 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { // installed. let again = asking(id, "Tidy 2", r#"["doc.write","doc.read"]"#); let r = app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&again)})).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::KIND, "other bytes ask again"); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("message"), "Install “Tidy 2”, which asks for these permissions?"); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND, "other bytes ask again"); + assert_eq!(app.pending_plugin_install.as_ref().unwrap().message, "Install “Tidy 2”, which asks for these permissions?"); dialogs::cancel(&mut app); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some(name.into()), "Cancel keeps the one installed"); io::open_bytes(&mut app, "tidy2.wasm", &again, None).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::confirm::KIND), "File › Open asks too"); - dialogs::confirm(&mut app).unwrap(); - // OK on the permissions goes on to ask before it takes the installed one's place, showing its - // id and file hash; Cancel there keeps the one installed and records no grant. - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("message"), "Install “Tidy 2” in place of the plug-in with the same ID?"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::plugin::INSTALL_KIND), "File › Open asks too"); + // The same dialog says it takes the installed one's place, and OK replaces it; Cancel keeps the + // one installed and records no grant. + let pending = app.pending_plugin_install.as_ref().unwrap(); let again_hash = vectorcraft_plugins::permissions::sha256_hex(&again); - assert_eq!( - d.str("detail"), - format!( - "ID: {id}\nFile SHA-256: {again_hash}\n\nThis file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID." - ) + assert!(pending.detail.contains(&format!("File SHA-256: {again_hash}")), "{}", pending.detail); + assert!( + pending.detail.ends_with("\n\nThis file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID."), + "{}", + pending.detail ); + assert_eq!(pending.params["replace"], json!(true), "OK replaces the one installed"); dialogs::cancel(&mut app); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some(name.into()), "Cancel keeps the one installed"); assert_ne!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(again_hash), "Cancel records no grant"); app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&again)})).unwrap(); dialogs::confirm(&mut app).unwrap(); - dialogs::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none(), "both questions are answered"); + assert!(app.ui.dialog.is_none(), "one question"); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some("Tidy 2".into())); let new_hash = vectorcraft_plugins::permissions::sha256_hex(&again); assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(new_hash), "OK records the new module's hash"); // One that asks for another permission asks again. let more = asking(id, "Tidy 3", r#"["doc.read","doc.write","state"]"#); let r = app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&more)})).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::KIND); - assert!(app.ui.dialog.as_ref().unwrap().str("detail").ends_with("• Keep data of its own with the document")); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND); + assert!(app.pending_plugin_install.as_ref().unwrap().detail.contains("• Keep data of its own with the document")); dialogs::cancel(&mut app); assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.manifest().name.clone()), Some("Tidy 2".into()), "Cancel keeps the one installed"); // OK keeps the `replace` it was asked with: `false` leaves the installed one in place. @@ -215,6 +214,43 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// A module with other bytes than the one installed with its id asks before taking its place: in +/// the ordinary confirm when it needs nothing that only a person can approve, and in the approval +/// dialog, with its id and file hash, when it also asks for a heavy budget. +#[test] +fn installing_a_plugin_over_another_module_asks_first() { + let mut app = app(); + let id = "test.ui.replaces"; + let plain = |output: &str| wat::parse_str(tpl::returning(&format!(r#"{{"id":"{id}","name":"Plain","kind":"filter"}}"#), output)).unwrap(); + let module = |wasm: &[u8]| json!({"dataBase64": vectorcraft_format::base64_encode(wasm)}); + let takes_place = "This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID."; + app.run("ui.installPlugin", module(&plain(r#"{"objects":[]}"#))).unwrap(); + assert!(app.ui.dialog.is_none(), "nothing to take the place of"); + + let other = plain(r#"{"objects":[],"error":null}"#); + let other_hash = vectorcraft_plugins::permissions::sha256_hex(&other); + let r = app.run("ui.installPlugin", module(&other)).unwrap(); + assert_eq!(r["pending"], dialogs::confirm::KIND); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("message"), "Install “Plain” in place of the plug-in with the same ID?"); + assert_eq!(d.str("detail"), format!("ID: {id}\nFile SHA-256: {other_hash}\n\n{takes_place}")); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(other_hash)); + + let manifest = format!(r#"{{"id":"{id}","name":"Heavy","kind":"filter","budget":"heavy"}}"#); + let heavy = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap(); + let heavy_hash = vectorcraft_plugins::permissions::sha256_hex(&heavy); + let r = app.run("ui.installPlugin", module(&heavy)).unwrap(); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND); + let pending = app.pending_plugin_install.as_ref().unwrap(); + assert!(pending.detail.ends_with(&format!("\n\nID: {id}\nFile SHA-256: {heavy_hash}\n\n{takes_place}")), "{}", pending.detail); + assert_eq!(pending.params["replace"], json!(true), "OK replaces the one installed"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(heavy_hash)); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + /// A plug-in with two commands: Grow, which adds a triangle (`_context.command` is `grow`), and /// Size, with a parameter, whose `menu` names another menu. fn commands_plugin(id: &str) -> Vec { @@ -300,6 +336,63 @@ fn a_shortcut_runs_a_plugin_command() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// The `grant` and `allowHeavy` that `ui.installPlugin` is given approve nothing: it asks all the +/// same, and what OK would approve comes from the manifest. A module with nothing to approve +/// installs without either. +#[test] +fn ui_install_plugin_takes_no_grant_or_heavy_budget_from_its_params() { + let mut app = app(); + let id = "test.ui.approval.params"; + let manifest = format!(r#"{{"id":"{id}","name":"Asks","kind":"filter","permissions":["doc.read"]}}"#); + let asks = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let given = |wasm: &[u8]| json!({"dataBase64": vectorcraft_format::base64_encode(wasm), "grant": ["doc.read", "doc.write"], "allowHeavy": true}); + let r = app.run("ui.installPlugin", given(&asks)).unwrap(); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND); + assert!(vectorcraft_plugins::registry::get(id).is_none() && vectorcraft_plugins::registry::granted(id).is_none()); + let pending = app.pending_plugin_install.as_ref().unwrap(); + assert_eq!(pending.approval.permissions, ["doc.read"], "the permissions the manifest lists"); + assert_eq!(pending.params["grant"], json!(["doc.read"])); + assert!(!pending.approval.heavy && pending.params.get("allowHeavy").is_none(), "no heavy budget was asked about"); + dialogs::cancel(&mut app); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + + let heavy_id = "test.ui.approval.params.heavy"; + let manifest = format!(r#"{{"id":"{heavy_id}","name":"Heavy","kind":"filter","budget":"heavy"}}"#); + let heavy = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap(); + let r = app.run("ui.installPlugin", given(&heavy)).unwrap(); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND, "allowHeavy skips no question"); + assert!(vectorcraft_plugins::registry::get(heavy_id).is_none()); + dialogs::cancel(&mut app); + + let plain_id = "test.ui.approval.params.plain"; + let manifest = format!(r#"{{"id":"{plain_id}","name":"Plain","kind":"filter"}}"#); + let plain = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let r = app.run("ui.installPlugin", given(&plain)).unwrap(); + assert!(r.get("pending").is_none() && app.ui.dialog.is_none(), "{r}"); + assert!(vectorcraft_plugins::registry::get(plain_id).is_some()); + assert!(vectorcraft_plugins::registry::granted(plain_id).is_none(), "the grant it was given isn't recorded"); + app.run("plugin.remove", json!({"id": plain_id})).unwrap(); +} + +/// An action's step can't grant what only a person approves: a played `plugin.install` with `grant` +/// is refused at Accelerated and at Step by Step, and nothing is installed. +#[test] +fn an_action_step_cannot_grant_a_plugin_its_permissions() { + use crate::panels::actions::{Action, ActionSet, PlaybackSpeed, play}; + let mut app = app(); + let id = "test.ui.approval.action"; + let manifest = format!(r#"{{"id":"{id}","name":"Asks","kind":"filter","permissions":["doc.read"]}}"#); + let wasm = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let step = json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]}); + app.ui.action_sets = vec![ActionSet::new("Test", vec![Action::new("Install", vec![("plugin.install".into(), step)])])]; + for speed in [PlaybackSpeed::Accelerated, PlaybackSpeed::Step] { + app.ui.action_playback.speed = speed; + let e = play(&mut app, 0, 0).unwrap_err(); + assert!(e.contains("take effect only in a session started with --allow-plugin-grants"), "{e}"); + assert!(vectorcraft_plugins::registry::get(id).is_none() && vectorcraft_plugins::registry::granted(id).is_none()); + } +} + /// A plug-in of API level 2 that lists `progress` names it in plain words when it asks. #[test] fn installing_a_plugin_that_reports_progress_says_so() { @@ -308,8 +401,8 @@ fn installing_a_plugin_that_reports_progress_says_so() { let manifest = format!(r#"{{"id":"{id}","name":"Count","kind":"filter","api":2,"permissions":["doc.read","progress"]}}"#); let bytes = wat::parse_str(tpl::reporting(&manifest, "(call $vc_progress (i64.const 1) (i64.const 2))", r#"{"objects":[]}"#)).unwrap(); let r = app.run("ui.installPlugin", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::KIND); - let detail = app.ui.dialog.as_ref().unwrap().str("detail"); + assert_eq!(r["pending"], dialogs::plugin::INSTALL_KIND); + let detail = app.pending_plugin_install.as_ref().unwrap().detail.clone(); assert!(detail.ends_with("• Read the objects it is given\n• Show its progress, see Cancel and write log lines"), "{detail}"); dialogs::confirm(&mut app).unwrap(); assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); diff --git a/crates/ui-egui/src/tools_float.rs b/crates/ui-egui/src/tools_float.rs index 2781e42325..0cc6433429 100644 --- a/crates/ui-egui/src/tools_float.rs +++ b/crates/ui-egui/src/tools_float.rs @@ -219,12 +219,14 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Ok(app.ui.toolbar_right), + let right = match p.get("side") { + None | Some(Value::Null) => Ok(app.ui.toolbar_right), // `Start` and `End`, as panels take them, too. - Some(s) if s.eq_ignore_ascii_case("left") || s.eq_ignore_ascii_case("start") => Ok(false), - Some(s) if s.eq_ignore_ascii_case("right") || s.eq_ignore_ascii_case("end") => Ok(true), - Some(s) => Err(format!("side is left or right, not `{s}`")), + Some(Value::String(s)) if s.eq_ignore_ascii_case("left") || s.eq_ignore_ascii_case("start") => Ok(false), + Some(Value::String(s)) if s.eq_ignore_ascii_case("right") || s.eq_ignore_ascii_case("end") => Ok(true), + Some(Value::String(s)) => Err(format!("side is left or right, not `{s}`")), + // A number, a list…: an error, not the last side. + Some(v) => Err(format!("side is left or right, not `{v}`")), }; Some(position(p).and_then(|at| { let right = right?; diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index c8dade12b1..77a00c33a5 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -20,6 +20,9 @@ pub(crate) struct Runtime { /// The context of the last frame, to wake the UI when a check is queued from a menu callback. #[cfg(not(target_arch = "wasm32"))] repaint: Option, + /// Whether an update dialog held the input in the last frame. + #[cfg(not(target_arch = "wasm32"))] + was_blocking: bool, /// The web build has no updater; its window only says so. #[cfg(target_arch = "wasm32")] pub(crate) manual_window_open: bool, @@ -38,6 +41,8 @@ impl Default for Runtime { check_requested: false, #[cfg(not(target_arch = "wasm32"))] repaint: None, + #[cfg(not(target_arch = "wasm32"))] + was_blocking: false, #[cfg(target_arch = "wasm32")] manual_window_open: false, #[cfg(target_arch = "wasm32")] @@ -103,12 +108,52 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool { !prompt_open && !matches!(status, Status::Idle) } +/// Whether the update prompt or the modal result window is open: keys, tool keys and clipboard +/// events then stay out of the documents behind it, and the app's other windows take no input. +pub(crate) fn blocks_input(app: &VectorcraftApp) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + let updater = &app.updates_rt.updater; + holds_keyboard(updater.status(), updater.prompt_open()) + } + #[cfg(target_arch = "wasm32")] + { + let _ = app; + false + } +} + +/// The prompt is modal, and so is the result window for every status but [`Status::Updated`], a +/// notice that leaves the app usable behind it. +#[cfg(not(target_arch = "wasm32"))] +fn holds_keyboard(status: &Status, prompt_open: bool) -> bool { + prompt_open || !matches!(status, Status::Idle | Status::Updated(_)) +} + +/// Whether an update may install and close the app: no document holds unsaved work, no save, +/// export, file opening, plug-in filter or Image Trace is running, no action is playing, no dialog +/// or file dialog is open, and no tool is in the middle of a drag or an edit it computes on +/// another thread. +#[cfg(not(target_arch = "wasm32"))] +fn safe_to_close(app: &VectorcraftApp) -> bool { + let session = &app.session; + !crate::unsaved::any_dirty(app) + && app.background.jobs.is_empty() + && !crate::opening::long_operation_busy(app) + && app.ui.action_playing.is_none() + && app.ui.dialog.is_none() + && !app.file_dialog_open() + && !session.in_interaction() + && !session.tool_busy() + && !session.tool_editing() +} + pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { - // The close for a ready update waits until no document holds unsaved work. - let clean = !crate::unsaved::any_dirty(app); - match app.updates_rt.updater.show_if(ctx, clean) { + // An installation, and the close for a ready update, wait for unsaved and running work. + let safe = safe_to_close(app); + match app.updates_rt.updater.show_if(ctx, safe) { Action::OpenUrl(url) => app.open_url(&url), Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Action::None => {} @@ -124,6 +169,12 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), } } + // A check at startup can open the prompt while a floating document's window covers it. + let blocking = blocks_input(app); + if blocking && !app.updates_rt.was_blocking { + crate::doc_windows::focus_main_window(app, ctx); + } + app.updates_rt.was_blocking = blocking; } #[cfg(target_arch = "wasm32")] @@ -150,10 +201,109 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } } +/// Opens the update prompt for a test in another module. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn open_prompt_for_test(app: &mut VectorcraftApp) { + tests::offer(app); +} + +/// Opens the result window of a running check for a test in another module. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn open_result_window_for_test(app: &mut VectorcraftApp, ctx: &egui::Context) { + app.updates_rt.updater = tests::isolated_updater(env!("CARGO_PKG_VERSION"), "result"); + app.updates_rt.updater.check_now(ctx); +} + +/// Closes the update prompt and the result window for a test in another module. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn close_dialogs_for_test(app: &mut VectorcraftApp) { + app.updates_rt.updater = tests::isolated_updater(env!("CARGO_PKG_VERSION"), "closed"); +} + #[cfg(test)] mod tests { use super::*; + use serde_json::json; use vectorcraft_engine::Session; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + /// The folder that holds `name`'s update records. + #[cfg(not(target_arch = "wasm32"))] + fn update_root(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("vectorcraft-updates-{}-{name}", std::process::id())) + } + + /// An updater that reads its records and the launcher's pins only under [`update_root`]. + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn isolated_updater(version: &str, name: &str) -> Updater { + let root = update_root(name); + Updater::new(&crate::UPDATE_APP, version) + .with_source(std::sync::Arc::new(|| Ok(None))) + .with_paths(craft_update::Paths::under(&root)) + .with_pins_path(root.join("pins.json")) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn offer(app: &mut VectorcraftApp) { + app.updates_rt.updater = isolated_updater(env!("CARGO_PKG_VERSION"), "prompt"); + app.updates_rt.updater.offer(craft_update::Release { + tag: "v99.0.0".into(), + version: craft_update::parse_version("99.0.0"), + name: "VectorCraft 99.0.0".into(), + html_url: "https://github.com/storytold/vectorcraft/releases/tag/v99.0.0".into(), + ..Default::default() + }); + } + + /// An app with one saved document holding a selected rectangle. + #[cfg(not(target_arch = "wasm32"))] + fn app_with_saved_object() -> VectorcraftApp { + let services = crate::Services { write: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("file.save", json!({"path": "/docs/saved.vectorcraft"})).unwrap(); + assert!(!crate::unsaved::any_dirty(&app)); + app + } + + #[cfg(not(target_arch = "wasm32"))] + fn press(key: egui::Key) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE } + } + + /// One frame in the app's order: the shortcuts read the input, then the update dialogs draw. + #[cfg(not(target_arch = "wasm32"))] + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui.ctx()); + }); + output.textures_delta.clear(); + } + + /// A Copy, the Pen tool's key and Delete, in one frame each: none of them may act. + #[cfg(not(target_arch = "wasm32"))] + fn assert_keys_do_nothing(app: &mut VectorcraftApp, ctx: &egui::Context) { + let tool = app.session.tool_id(); + let mut reached = Vec::new(); + frame(app, ctx, vec![egui::Event::Copy]); + if !app.session.clipboard.is_empty() { + reached.push("Copy"); + } + let tool_key = + egui::Event::Key { key: egui::Key::P, physical_key: Some(egui::Key::P), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(app, ctx, vec![tool_key, egui::Event::Text("p".into())]); + if app.session.tool_id() != tool { + reached.push("the tool key"); + } + frame(app, ctx, vec![press(egui::Key::Delete)]); + if app.session.doc().unwrap().selection.is_empty() { + reached.push("Delete"); + } + assert_eq!(reached, Vec::<&str>::new(), "these reached the document"); + assert!(!crate::unsaved::any_dirty(app), "a key edited the document"); + } #[test] fn default_runtime_is_idle() { @@ -208,4 +358,164 @@ mod tests { output.textures_delta.clear(); assert!(app.updates_rt.updater.prompt_open()); } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn the_prompt_and_the_result_window_hold_the_keyboard_but_the_updated_notice_does_not() { + for status in [ + Status::Checking, + Status::UpToDate, + Status::Failed("offline".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::InstallFailed("locked".into()), + ] { + assert!(holds_keyboard(&status, false), "{status:?}"); + } + assert!(!holds_keyboard(&Status::Idle, false)); + assert!(!holds_keyboard(&Status::Updated("99.0.0".into()), false)); + assert!(holds_keyboard(&Status::Idle, true), "the prompt"); + } + + /// The update prompt, drawn: keys stop at it, Escape closes it, and the next key acts again. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn keys_do_not_reach_the_document_behind_the_update_prompt() { + let mut app = app_with_saved_object(); + let ctx = egui::Context::default(); + offer(&mut app); + frame(&mut app, &ctx, vec![]); + assert_keys_do_nothing(&mut app, &ctx); + assert!(app.updates_rt.updater.prompt_open()); + + frame(&mut app, &ctx, vec![press(egui::Key::Escape)]); + assert!(!app.updates_rt.updater.prompt_open(), "Escape closes the prompt"); + assert!(!app.session.doc().unwrap().selection.is_empty(), "Escape stops at the prompt"); + frame(&mut app, &ctx, vec![press(egui::Key::Delete)]); + assert!(crate::unsaved::any_dirty(&app), "Delete acts once the prompt has closed"); + } + + /// The result window of a check that is still running, drawn: keys stop at it too. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn keys_do_not_reach_the_document_behind_the_check_result_window() { + let mut app = app_with_saved_object(); + let ctx = egui::Context::default(); + app.updates_rt.updater = isolated_updater("0.0.1", "checking"); + app.updates_rt.updater.check_now(&ctx); + assert_eq!(app.updates_rt.updater.status(), &Status::Checking); + frame(&mut app, &ctx, vec![]); + assert_keys_do_nothing(&mut app, &ctx); + } + + /// The notice of a finished update, drawn: the keys act behind it. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn keys_reach_the_document_behind_the_updated_notice() { + let mut app = app_with_saved_object(); + let ctx = egui::Context::default(); + let root = update_root("updated"); + let records = craft_update::Paths::under(&root).data; + std::fs::create_dir_all(&records).unwrap(); + std::fs::write(records.join("self-update-done.txt"), "v99.0.0").unwrap(); + app.updates_rt.updater = isolated_updater("99.0.0", "updated"); + app.updates_rt.updater.check_at_start(&ctx); + assert_eq!(app.updates_rt.updater.status(), &Status::Updated("99.0.0".into())); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![press(egui::Key::Delete)]); + let _ = std::fs::remove_dir_all(&root); + assert!(crate::unsaved::any_dirty(&app), "Delete acts behind the notice"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn unsaved_changes_dialogs_and_running_work_hold_an_update_back() { + let mut app = app_with_saved_object(); + assert!(safe_to_close(&app)); + + app.run("shape.rectangle", json!({"x": 70, "y": 10, "width": 50, "height": 50})).unwrap(); + assert!(!safe_to_close(&app), "unsaved changes"); + app.run("file.save", json!({"path": "/docs/saved.vectorcraft"})).unwrap(); + assert!(safe_to_close(&app)); + + app.ui.dialog = Some(crate::state::Dialog::new("about", json!({}))); + assert!(!safe_to_close(&app), "a dialog"); + app.ui.dialog = None; + + let (shown, _) = crate::tests_picks::off_the_ui_thread(&mut app.services); + // The command asks again with the answer: until then it reports that it has none. + assert!(app.run("file.open", json!({})).is_err()); + assert!(app.file_dialog_open()); + assert!(!safe_to_close(&app), "a file dialog"); + shown.answer(&[]); + crate::picks::poll(&mut app, &egui::Context::default()); + assert!(!app.file_dialog_open()); + assert!(safe_to_close(&app)); + + app.services.write_shared = Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))); + let (release, held) = std::sync::mpsc::channel::<()>(); + let work = move |_: crate::background::Writer| { + let _ = held.recv(); + Ok(Value::Null) + }; + // No label: a job the status bar does not list holds the close back too. + crate::background::run(&mut app, true, String::new(), None, work, |_, r| r).unwrap(); + assert!(!safe_to_close(&app), "a background save"); + let _ = release.send(()); + crate::background::wait_all(&mut app); + assert!(safe_to_close(&app)); + + crate::opening::start(&mut app, "/art/Wait.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(10.0, 10.0), false)) + .unwrap(); + assert!(!safe_to_close(&app), "a file opening"); + app.opening.pending.clear(); + assert!(safe_to_close(&app)); + + use crate::panels::actions::{Action, ActionSet, PlaybackSpeed, play}; + let step = ("object.move".to_owned(), json!({"dx": 1, "dy": 0})); + app.ui.action_sets = vec![ActionSet::new("Test", vec![Action::new("Move", vec![step.clone(), step])])]; + app.ui.action_playback.speed = PlaybackSpeed::Step; + assert_eq!(play(&mut app, 0, 0).unwrap()["pending"], json!(1)); + app.run("file.save", json!({"path": "/docs/saved.vectorcraft"})).unwrap(); + crate::background::wait_all(&mut app); + assert!(!safe_to_close(&app), "an action playing"); + app.ui.action_playing = None; + assert!(safe_to_close(&app)); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_gesture_or_a_tools_edit_holds_an_update_back() { + let mut app = app_with_saved_object(); + let view = app.view_info(); + app.session.begin_interaction("Move").unwrap(); + assert!(!safe_to_close(&app), "an interaction"); + app.session.cancel_interaction().unwrap(); + assert!(safe_to_close(&app)); + + app.select_tool("selection"); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), view).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 180.0), view).unwrap(); + assert!(app.session.tool_busy() && !app.session.in_interaction()); + assert!(!safe_to_close(&app), "a drag with a tool"); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 180.0), view).unwrap(); + assert!(!app.session.tool_busy()); + assert!(safe_to_close(&app)); + + // Enough segments for the merge to run on another thread. + for k in 0..40 { + app.run("shape.rectangle", json!({"x": 10 * k, "y": 100, "width": 20, "height": 20})).unwrap(); + } + app.run("file.save", json!({"path": "/docs/saved.vectorcraft"})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.select_tool("shapeBuilder"); + app.session.pointer(&PointerEvent::new(PointerKind::Move, 15.0, 110.0), view).unwrap(); + app.session.tool_poll(view, true).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 15.0, 110.0), view).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 15.0, 110.0), view).unwrap(); + assert!(app.session.tool_editing() && !crate::unsaved::any_dirty(&app), "the click starts a merge on another thread"); + assert!(!safe_to_close(&app), "a tool's edit"); + crate::unsaved::finish_pending(&mut app); + } } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 4f3243c756..c70cca1736 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, @@ -72,6 +73,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/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..3e4f2119fc 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 @@ -247,9 +248,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 +268,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 +281,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 +310,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 +343,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). @@ -855,13 +1051,14 @@ fn spin_generic( 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 // 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) { 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 +1111,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/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 104d952165..4fa8de6dac 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -216,7 +216,8 @@ the `effect` dialog (`effect.dialog {effect: "plugin."}`). An exporter plug- export's own parameters); `ui.dialog.confirm` writes the file. An importer plug-in with parameters opens the `pluginImport` dialog when `file.openWith` is given no `params`: one field per parameter, `__plugin`, and `__open` (`path` and `importer`); `ui.dialog.confirm` opens the file. `ui.installPlugin {path?}` installs a `.wasm` (without -a path it asks for one); see [plugins.md](plugins.md). +a path it asks for one); one that needs approval opens the `pluginInstall` dialog, which only a person can confirm +(`ui.dialog.confirm` and injected input are refused); see [plugins.md](plugins.md). Overprint Black: the Edit → Edit Colors → Overprint Black… menu item opens a `command` parameter dialog for `edit.colors.overprintBlack` (fields `remove`, `percentage`, `fill`, `stroke`, `includeCmyBlacks`, @@ -528,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, @@ -571,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/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 e269f1a68b..10dded6237 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-07 · **Change:** minor (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-09 · **Change:** minor (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 @@ -223,6 +223,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,8 +283,8 @@ 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) | -| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #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); 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 set other descendants' characters as type at the composite font's size (other mappings and CID-keyed fonts are still set as type in the font of their name); 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) | +| 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`) | | 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 | @@ -310,6 +313,10 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, ## 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,6 +327,21 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Date | Change | Summary | |---|---|---| +| 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. | +| 2026-11-07 | minor | EPS import: CMap mappings to base fonts (`beginbfchar` … `endbfchar`, `beginbfrange` … `endbfrange` after `usefont`: [Adobe Technical Note #5099](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5099.CMapResources.pdf); PLRM 3rd ed., §5.11.4) are read instead of dropped: a code mapped to a character code (a range's codes counting up from its last byte) or to a glyph name (one, or an array of them) draws that glyph of the base font it names, a Type 3, Type 42 or embedded Type 1 font's own glyph or, in a font found by name, its character as type. Such codes took font 0's CID 0 and drew nothing. | +| 2026-11-07 | minor | EPS import: a FontSet's Compact Font Format data (`/name n StartData` in the FontSetInit procedure set: PLRM 3rd ed., §5.8.1; [Adobe Technical Note #5176](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf)) is read instead of skipped: each CID-keyed font in it (a top DICT with `ROS`) is defined as a CIDFont of its name, and type in a CID-keyed font over it draws its glyphs, picked by CID through the charset and drawn from their Type 2 charstrings with their FDSelect subfont's subroutines and widths. Name-keyed fonts in a FontSet are still set as type by name. | +| 2026-11-07 | minor | EPS import: `kshow` (PLRM 3rd ed., chapter 8) runs its procedure between each two characters of type in a base font (not a Type 3 or composite font), with the two character codes, instead of only between a Type 3 font's glyphs: where it moves the current point (kerning), the next character follows, kept on the live type as tracking, and what it draws is drawn over the type. | +| 2026-11-07 | minor | EPS import: an embedded Type 1 font's encrypted part (`eexec`, [Adobe Type 1 Font Format](https://adobe-type-tools.github.io/font-tech-notes/pdfs/T1_SPEC.pdf), chapter 7) is no longer only skipped: its charstrings are read, and the font dictionary gets the `CharStrings` dictionary the part would have given it. Its type then takes its characters from its glyph names (the standard and ISO Latin-1 encodings by their codes' names, PLRM 3rd ed., Appendix E), its widths move the current point and space the live type as tracking (as Type 42 fonts do), `stringwidth` and `charpath` read its glyphs, glyphs whose names say no character are drawn from its outlines, and a composite font's Type 1 descendants draw their glyphs. A font found by name, re-encoded with glyph names at other codes (codes 1 to 12 for `T`, `r`, `a`… in pdftocairo's subsets), sets the characters its names say instead of its codes read as Latin-1 (such type was left out). | +| 2026-11-07 | minor | EPS import: CID-keyed fonts (PLRM 3rd ed., §5.11; [Adobe Technical Note #5014](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5014.CIDFont_Spec.pdf)) draw from the font data the file carries instead of stopping the program at `composefont` or the CIDInit operators: CMaps built with `begincmap` … `endcmap` (codespace ranges, CID and notdef mappings, `usefont`, `usecmap`; mappings to base-font codes are not read) and the predefined `Identity-H` and `Identity-V`; `composefont` and `FMapType` 9 fonts, whose codes take as many bytes as their codespace range says, an invalid or unmapped code falling back as §5.11.5 says; Type 0 CIDFonts' Type 1 charstrings, read by `StartData` (binary or hexadecimal) or from a `GlyphDirectory`, with their FDArray dictionaries' matrices and subroutines (`Subrs` or the binary data's subroutine table); Type 2 CIDFonts' TrueType glyphs through `CIDMap` (strings, a dictionary or an offset); `Metrics` widths; vertical writing mode set downwards. A CIDFont the file doesn't carry draws nothing, with a warning; FontSet (Compact Font Format) data is skipped. | +| 2026-11-07 | minor | EPS import: a plain Type 42 font that carries its TrueType font ([Adobe Technical Note #5012](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5012.Type42_Spec.pdf)) gives each code its character by its glyph name (single characters, `uniXXXX`, the standard encoding's and Windows-1252's names) or, when the name says nothing (`/g12`), by the glyph `CharStrings` gives it in the font's own character map or `post` names, instead of reading the code as Latin-1 (a Euro at code 128 was dropped); the font's own widths move the current point (`stringwidth`, `show`), `charpath` outlines its glyphs, and a string with a glyph that stands for no character is drawn from the font's outlines. Live type keeps the spacing the file gives it: where the show operator's numbers (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`: PLRM 3rd ed., chapter 8) or the embedded font's widths differ from the installed or fallback font's advances, each character's tracking makes up the difference, as PDF import does, so justified type in a font that isn't installed no longer drifts (pdftocairo and pdftops EPS of a justified PDF page set in a missing font: 10.2% and 9.0% of the page differing from Ghostscript's render, now 6.2% and 5.8%). Type under `nulldevice` no longer shows. | +| 2026-11-06 | minor | EPS import: the buffers an image decoder makes for itself (its sample planes, its copies of the strings a procedure data source hands back, and the split buffers of an interleaved masked image) stop counting against the PostScript reader's 1 GiB memory budget once the image is decoded, as they are freed then; the pixels kept, and anything the program's own procedures allocate, still count. A user's Illustrator 25.2 EPS with 71 CMYK images (used locally, not committed) used to stop with "the program uses too much memory" and come in as its screen preview; it now opens with its art. The budget itself is unchanged. Scores and estimates unchanged. | | 2026-11-07 | minor | EPS import: a sampled function (type 0) of two or more inputs took the nearest sample, so a function-based shading (type 1) over one came in as flat blocks; it is now interpolated between its samples (multilinearly), and with `Order 3` by cubics through them (Catmull-Rom, kept in the function's range), as the PostScript Language Reference (3rd ed., §3.10.1, type 0 functions) defines. An axial or radial shading whose function is a linearly interpolated sampled function of one input has a stop at each sample, not 33 evenly spaced ones. Tests `sampled_functions_interpolate_linearly_or_by_cubics`, `mesh_and_function_shadings_become_gradient_meshes`; a 2 × 2 function-based shading is 1.2% from Ghostscript's render (it was 45.9%); scores unchanged | | 2026-11-07 | minor | EPS and `.ai` type from the text document keeps its paragraphs' tab stops (positions and alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. A user's `.ai` (used locally, not committed) whose price lists came in on the default stops now lays them out as its page has them (its type 0.8% from its page, from 1.5%; what differs is hyphenation in Hungarian and type in a font that isn't installed). Scores and estimates unchanged. | | 2026-11-07 | minor | EPS and `.ai` type from the text document: auto leading stays auto at the paragraph's share (it was the first two lines' distance for every line, so 10 pt lines under a 15 pt heading came in 18 pt apart), the paragraph's hyphenation options are read, and area type of one frame whose last lines the file sets in too short a frame for them here may get a frame taller by its lines' deepest descent plus 0.05 pt, when that shows more of them. A user's `.ai` (used locally, not committed) whose type differed from its page by 6.6%, so that it opened from its PDF part, now opens from its layers (4.9%; type with tab stops in right-aligned paragraphs still differs, a separate issue) (#6137). Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index fc421cf5d1..cd3a77db6f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,11 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** 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 (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-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-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. @@ -94,10 +95,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) | 15–25 | no | [target-app-parity.md](target-app-parity.md) | +| 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 11–21 | 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) | @@ -115,6 +116,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G1 Interaction fidelity +macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. + - **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. - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. @@ -195,6 +198,9 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G9 Illustrator `.ai` and EPS files from real users +- **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. @@ -310,6 +316,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## 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 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`. - **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. Broader scope and estimates unchanged. @@ -441,7 +449,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall own pixels until a document takes them in; estimate unchanged. - **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 with an open dictionary, + 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`, with a right-click on an underlined word offering its suggestions, Ignore All and Add to Dictionary; the Check Spelling and Edit Custom Dictionary dialogs remain), 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. @@ -504,7 +513,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## 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. @@ -512,7 +521,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **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 @@ -570,6 +579,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall built-in gradient libraries' presets (by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the gradient as a preset (kept with the preferences) and deletes saved ones; `gradient.presets.*` commands. +- **Improved (#6164):** Control bar › Snapping also exposes the existing Snap to Glyph and Alignment Guides + toggles through their existing commands. Floating-panel parity remains unverified; the estimate is unchanged. - **Missing:** the consolidated snapping options (30.0); artboard colors in exports and print, and managing artboards from the canvas other than locking and unlocking them from the Artboard tool's right-click menu (30.0); the Blend panel with ease @@ -618,8 +629,9 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall 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 (one original library generated in code, - Basic Shapes; User Defined; Other Library… reads the symbols of any document VectorCraft opens); a click + 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 + 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 document's symbols as a `.vectorcraft` library into the user library folder (listed under User Defined) or @@ -633,14 +645,19 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall 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 as a `.vectorcraft` library into the user library folder (listed under User Defined) or a file - (`brush.libraries`, `brush.addFromLibrary`, `brush.saveLibrary`, `brush.loadLibrary`). -- **Missing:** the Art brush's Overlap; more built-in brush, symbol and graphic-style libraries (original, - generated in code, never Adobe's); dynamic symbols' on-canvas editing beyond a solid fill and stroke on a path, - compound path or type object inside a dynamic instance (Direct Selection selects it, and the Fill/Stroke controls set - its change) and their `.ai` read and write; Global Edit of groups holding type or - images, rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; - 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). -- **Estimate:** 14–24 h. + (`brush.libraries`, `brush.addFromLibrary`, `brush.saveLibrary`, `brush.loadLibrary`); + Art Brush Options › Overlap (`ArtBrush.overlap`, splits art at sharp corners so folds do not overlap; + `art_brush_overlap_splits_at_corners`); Pattern Brush Options Outer/Inner Corner Tile Auto-Centered, + Auto-Between, Auto-Sliced and Auto-Overlap (`CornerSource`, `pattern_auto_corners_*`); while Global Edit + 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; + 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. ## G3 3D and Materials @@ -837,7 +854,19 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 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 | 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. | +| 2026-11-09 | minor | 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 | G4 type: the spell check engine is done (`text.spelling.check`, `text.spelling.suggest` on craft-proof, #4936); the Check Spelling 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-07 | minor | Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); 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 | G15: nearby hits on plain long strokes and outlines check their candidate segments directly; a 200,000-anchor middle hit took about 11–13 ms before and 1.0–1.4 ms after in paired runs. An inside-bounds miss fell from 18.7 ms to 1.6 ms. Estimate unchanged; idle budget run still open. | | 2026-11-05 | minor | G15: an image zoomed in on is separated, colorized or proofed only for the tiles in view (#4155); 100% zoom on that file 8.6 s → 0.05 s. Estimate unchanged. | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 5f6c87145e..ce9f55cf50 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Windows: the pen's tilt and barrel rotation from Windows Ink, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Windows: the pen's tilt and barrel rotation from Windows Ink, #372) · **Target:** Adobe Illustrator 2026 (30.x) What hardware Illustrator uses, per platform, against VectorCraft. Illustrator's side is from its public documentation (GPU Performance, touch workspace, pen pressure pages); ours from the code @@ -26,7 +26,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585) | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch workspace and touch-screen rotation missing, 3–5 h | | Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | -| HiDPI / Retina, per-monitor scale | yes | yes | yes | yes | yes | done; a window dragged between monitors of different scale can still grow on Windows (#1459, open); the custom title bar's window on Windows stays truly borderless so the pointer lines up with what is drawn (#1791, #1758; awaiting the reporter's confirmation) | +| HiDPI / Retina, per-monitor scale | yes | yes | yes | yes | yes | done; a window dragged between monitors of different scale can still grow on Windows (#1459, open); the custom title bar's window on Windows stays truly borderless so the pointer lines up with what is drawn (#1791, #1758; awaiting the reporter's confirmation) ; macOS cursors use aligned 1×/2× native image representations (#2292), covered by headless construction tests; mixed-display transitions and physical cursor sizing remain unverified, no additional hardware validated | | Multiple monitors: panels and document windows on another screen | yes | no (one OS window) | no | no | — | missing: 6–10 h (with multiple windows, gap G7) | | Display colour profile (proof and display through the monitor's ICC) | yes | no | no | no | — | missing: 3–5 h | | 3D GPU rendering (Materials, ray tracing) | yes | — | — | — | — | blocked on 3D (gap G3) | @@ -35,6 +35,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Date | Change | Summary | |---|---|---| +| 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-05 | minor | Windows (#372): with Windows Ink, each pen pointer message's `POINTER_PEN_INFO` gives the pen's tilt (`tiltX`, `tiltY`) and barrel rotation where its pen mask says the pen reports them, written into the canvas's pen feed as on macOS and Linux, so a 6D Art Pen's barrel turns a Calligraphic brush's nib. Unit-tested (`windows_stylus::tests::a_pens_tilt_and_rotation_come_where_it_reports_them`); not yet tried with a pen, so the score is unchanged (estimated) | | 2026-11-01 | patch | Linux (#4967): on a Wayland session, Linux Display Server › Automatic opens the window through XWayland when a pen is attached as the app starts, as X11 (XWayland) When a Pen Is Attached does and as PhotoCraft does; on native Wayland winit 0.30 gets no tablet input and KWin 6.3+ and Mutter emulate no pointer, so the pen moved only the compositor's cursor. `VECTORCRAFT_NATIVE_WAYLAND=1` keeps Wayland. Unit-tested (`xwayland::tests`); not tried with a tablet; score unchanged (estimated) | | 2026-10-30 | patch | Touch (#4198): a second finger landing cancels the tool press the first finger began, also in the same frame (the Pencil's stroke and a Selection move are rolled back, nothing enters the undo history), and a finger landing while another is down presses nothing, so a pinch or two-finger pan only navigates. Headless canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`; not tried on a touch screen; score unchanged (estimated) | diff --git a/docs/mcp.md b/docs/mcp.md index 72c211b75a..cb0157715b 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 @@ -1382,6 +1385,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 @@ -1786,6 +1854,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). @@ -1859,16 +1932,23 @@ already walks Image Trace. Short agent entry points: one back to the symbol. It is refused for a static symbol and for a path that names no object. On the canvas (VectorCraft's own rule), a Direct Selection click on an instance of a dynamic symbol selects the path, compound path or type object of its art under the pointer and outlines it (`symbol.instance.selectPart {id, path}`; Alt or Shift selects the instance whole). While it is selected, - `paint.setFill` and `paint.setStroke` with a solid color or none, `paint.invert` and `paint.complement` on a solid - color, all without `ids`, `id` or `item`, and the Eyedropper's `appearance.copyFrom` with a solid fill and stroke - change that object's fill or stroke for this instance only, each as one undo step. A painted stroke on type without a - weight gets 1 pt. A gradient or pattern for the object is refused with a status message, and so are `paint.invert` and - `paint.complement` on type whose characters differ in color, Eyedropper options that pick up neither color, an - Eyedropper source that is not a path, compound path or type (a symbol instance or a group, for which the paint defaults - stay as they are too), and a click - or `symbol.instance.selectPart` on any other object of the art (a group, image, blend or nested instance among them). + `paint.setFill` and `paint.setStroke` (solid, none, gradient or pattern) and `paint.invert` and `paint.complement` + on a solid color change that object's fill or stroke for this instance only when `ids`, `id` and `item` are omitted. + `transparency.set` with opacity and/or blend does the same when `ids`, `id` and `item` are omitted; with `ids` or + `id` it edits those objects, so the instance's id changes the instance. `appearance.copyFrom` takes the source's + fill and stroke (including a gradient or pattern) for this instance only when `ids` is omitted and `reverse`, + `append` and `defaultsOnly` are false or omitted, and only for each paint the Eyedropper Options pick up and + apply; a paint disabled in either tree stays as it was. With `ids`, and `reverse` false or omitted, it copies + onto those objects; with `reverse` true it copies from the first of `ids` onto `source`. The paint commands, + Transparency and the Eyedropper each record an undo step only when the override changes; an unchanged override + records none. A painted stroke on type without a weight gets 1 pt. `paint.invert` and `paint.complement` + on a gradient or pattern, or on type whose characters differ in color, are refused with a status message, and so are + Eyedropper options that pick up neither color, an Eyedropper source that is not a path, compound path or type (a + symbol instance or a group, for which the paint defaults stay as they are too), isolate, knockout, knockoutShape, + aligned and target on `transparency.set`, and a click or `symbol.instance.selectPart` on any other object of the art + (a group, image, blend or nested instance among them). The commands that change the selected objects without `ids` are refused the same way and change nothing, among them - opacity and blending mode, moving and transforming, `path.moveAnchors`, `file.place` with `replace`, Puppet Warp, Delete + moving and transforming, `path.moveAnchors`, `file.place` with `replace`, Puppet Warp, Delete and Cut, Group, Hide, Lock, Arrange, Expand, Recolor Artwork, plug-in filters, effects, the gradient commands, `gradient.selectStop`, the Appearance panel's rows and `symbol.instance.setAppearance`. A Cmd-drag that lends the Selection or Group Selection tool selects the instance whole @@ -2340,10 +2420,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, 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 group holding a clipping group, an image, a symbol instance or 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` @@ -2416,7 +2498,8 @@ 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. `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` @@ -2464,6 +2547,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. @@ -2865,7 +2950,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`) @@ -3181,7 +3266,11 @@ the `…Open` rings…) and marks (`Bar`, `DoubleBar`, `DotOnBar`, `Slash`, `Dou 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, @@ -3910,6 +3999,35 @@ 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 scale, so `object.setBounds {height: 72}` on "H" gives the cap height 72 pt, not a 72 pt +font. 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: @@ -3988,9 +4106,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. @@ -4199,8 +4319,8 @@ selected) on top of a template. With nothing selected, `stroke.set` / `stroke.se arrowheads, profile…) and `graphicStyle.apply` (every fill, stroke and effect, opacity, blend mode and the link to the style; `add: true` stacks it) set that template instead of editing art. With the Appearance panel's New Art Has Basic Appearance on (the default), a `select.*` command or `layer.target` that changes the selection loads the proxies and -the weight from it: only a paint or weight the selected objects share, and art without paint (a placed image) changes -nothing. With the option off (`appearance.setNewArtBasic {on: false}`, the preference `newArtBasic`) new art takes the +the weight from it: only a paint or weight the selected objects share, and art without paint (a placed image that isn't +colorized) changes nothing. With the option off (`appearance.setNewArtBasic {on: false}`, the preference `newArtBasic`) new art takes the whole appearance of the last selected object. `appearance.newArt` reports what the next object gets; `paint.default` resets it. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. @@ -5119,7 +5239,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"` @@ -5554,7 +5679,7 @@ dictionaries (the standard ones are values in `systemdict`; `dictstack`, `intern intervals share storage, resources (categories made from `Generic`, `resourceforall`), executable filters (`cvx exec` runs their data; `flushfile` skips it), axial and radial shadings and shading patterns (gradients), images and image masks (data in the file through ASCII85, hex, run-length, Flate, LZW or DCT filters, or from procedures), and type as -point type in the font the file names (embedded font programs are skipped). In a file in Illustrator's own format +point type in the font the file names (embedded Type 1 and Type 42 fonts' characters and widths come from the font program they carry, and the show operators' spacing along the baseline is kept as tracking, while spacing that moves characters off it (`yshow`, `xyshow`) makes a text object per character; CID-keyed fonts draw the glyphs of the Type 0 and Type 2 CIDFonts the file carries, CIDFonts in a FontSet's Compact Font Format data included). In a file in Illustrator's own format (Illustrator 3–8 `.ai` and their EPS, written with the prolog that defines its operators) the groups it writes (`u` … `U`) come in as groups, nested as they were; clips and groups nest at most 128 deep. The artboard is the `%%HiResBoundingBox` (else `%%BoundingBox`; a letter page without one). A program the interpreter can't run (an operator it doesn't know, @@ -5893,6 +6018,48 @@ returns the new value. ``` +## Spelling + +`text.spelling.check {ids?}` lists the words of the document's type that its dictionaries don't know: every +visible, unlocked type object in paint order, or those in `ids` (and in the groups `ids` names). Each run is checked +in its Character panel Language (English when it has none) by craft-proof, one paragraph at a time; a language without +a spelling dictionary marks nothing. English words come from the first dictionary craft-proof finds: a Hunspell +dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a +system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof. Words in capitals, words with digits and web addresses are taken as correct. The result is +`{words: [{id, start, end, word, lang}], more}`: `start` and `end` are byte offsets in the type object's text, the +ones `text.editRange` takes, so `text.editRange {id, start, end, insert}` changes a word as one undo step. At most +10,000 words are listed; `more` is `true` when there were more. `text.spelling.suggest {word, max?, lang?}` gives +the words the dictionary of `lang` (default English) suggests instead of `word`, best first, at most `max` (1 to 20, +default 5). Both only read the document. + +```json +{"name":"run_command","arguments":{"command":"text.spelling.check","params":{}}} +{"name":"run_command","arguments":{"command":"text.spelling.suggest","params":{"word":"drawng","lang":"en"}}} +``` + +The custom dictionary holds words every check takes as right, in every language. `text.spelling.addWord {word}` +adds one (Check Spelling's Add; one word of at most 64 characters, kept in lower case) and says whether it was new; +`text.spelling.removeWord {word}` deletes one and `text.spelling.changeWord {word, to}` replaces one (Edit Custom +Dictionary's Delete and Change; an error when `word` isn't there); `text.spelling.dictionary` lists them, sorted. The +desktop app and `vectorcraft-cli` (its `mcp` and `run` sessions) keep them in `Custom Dictionary.txt` next to the +preferences, one word per line; without preferences (`VECTORCRAFT_NO_PREFS`, the web app) they last until the app +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. + +```json +{"name":"run_command","arguments":{"command":"text.spelling.addWord","params":{"word":"VectorCraft"}}} +{"name":"run_command","arguments":{"command":"text.spelling.ignoreAll","params":{"word":"Zqvwkx"}}} +``` + +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. + + ## Justification options `text.setFormat` sets the Paragraph panel menu's Justification… options of the selected type (or `ids`, or the @@ -6670,11 +6837,12 @@ them again at startup (`plugin.remove` deletes them there): schema, defaults). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one undo step; it may change, delete or add objects, and the result is selected). A filter whose manifest lists `inputs` (`type`, `image`, `symbolInstance`; `inputs` in its `plugin.list` entry) also lists `doc.read` in its `permissions`, so -`plugin.install` needs `grant`. It is also given the selected objects of those kinds to read, with at most 16 MiB of -pixels and 16 MiB of type runs over one run (later ones come with `pixelsOmitted` or `truncated`). Every object counts -toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included: pixels and runs that -don't fit come the same way, and an object whose other fields don't fit makes `plugin.run` return a memory-budget error -naming the object and its size, with nothing changed. A path or compound path that doesn't fit makes it return the +installing it needs a person's approval. It 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 over one 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: pixels and runs that don't fit come the same way, and an object whose other fields don't +fit makes `plugin.run` return a memory-budget error naming the object and its size, with nothing changed. A path or compound path that doesn't fit makes it return the 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 @@ -6700,15 +6868,26 @@ on the desktop a picked file is read off the UI thread and the reply is `{backgr `pluginImport` dialog. `params` holds the importer's parameters (their defaults when omitted). A failing plug-in returns an error and leaves the document as it was (an export writes no file, and an import opens no document). A filter whose manifest asks for a heavy budget (minutes rather than a minute, `budget: "heavy"` in its -`plugin.inspect {path | dataBase64}` entry) installs only with `allowHeavy: true`: ask the user first. `plugin.run` +`plugin.inspect {path | dataBase64}` entry) needs a person's approval, and `plugin.install` refuses `allowHeavy: true` +from a request. `plugin.run` runs it where it is called, so the call may take minutes; `notifications/cancelled` stops it. A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) -installs only with `grant: [permission]` listing every one of them: show the user the list and ask first, and pass -the entry's `hash` as `hash` so that a module that changed since is refused. Without `grant`, `plugin.install` returns -an error naming the permissions needed. The grant is kept with the module's hash and covers only that module: the -same bytes install again without `grant`, and a module with other bytes has `needsApproval: true` and needs a new -`grant` even when it lists the same permissions. `plugin.install` does not check that a person approved `grant`: it -trusts the client that sends it. `plugin.remove` forgets the grant. A +needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop +app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, +`ui.dialog.confirm` and injected input can't confirm it. A `vectorcraft-cli mcp` started with `--allow-plugin-grants` +accepts `grant` and `allowHeavy` from any request, in that session only (headless; it can't be combined with +`--connect`, `--automation-read-root` or `--automation-write-root`). A server confined to folders has no plug-in +store, so it reads no `grants.json`, and a module that lists permissions or asks for a heavy budget does not install +there. Without `--allow-plugin-grants` and without a recorded grant for the module, `plugin.install` returns an error +naming the permissions needed. With `VECTORCRAFT_NO_PREFS` set there is no store, and a `grant` accepted under the +flag lasts for that session only. In other sessions the approval, or a `grant` accepted under the flag, is kept with the module's +hash, counts as approved in later sessions and in the desktop app, and covers only that module: the +same bytes install again without one, also from a headless session that reads the same `grants.json`, and a module +with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. `plugin.remove` +forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then +need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the +grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When +`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed. A filter without `doc.write` or `state` that returns output needing them gets an error and the document is unchanged. A plug-in of API level 2 (`api: 2` in its entry) that lists `progress` may report its progress, see Cancel and write log lines: `notifications/cancelled` makes its `vc_cancelled` return 1, and its log lines go to the server's log @@ -7585,7 +7764,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 c5423e511a..890183c7fb 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -30,8 +30,8 @@ This page is the contract for plug-in authors and the reference for the host (`c | `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.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`, once the user agreed. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, once the user agreed, unless the user already granted a module with the same SHA-256. 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 `plugin.install` needs `grant`) 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. | +| `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.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). | @@ -147,8 +147,9 @@ an importer an import's). Each of its runs gets 1 G instructions (20 times a lig much there is only once the run has ended. - **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, and install it once the - user clicks OK; `plugin.install` refuses it without `allowHeavy: true`, which an agent passes once the user agreed - (`plugin.inspect` tells it beforehand). A filter kept in the `Plug-ins` folder was agreed to and is installed again + user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`, + and refuses `allowHeavy` from a request except in a session started with `vectorcraft-cli --allow-plugin-grants` + (`plugin.inspect` shows the budget beforehand). A filter kept in the `Plug-ins` folder was agreed to and is installed again at startup. The Additional Plug-ins Folder skips heavy filters with a note in its report, since loading a folder asks nobody. - **It runs in the background.** Its dialog has no Preview. OK (or the menu item, without parameters) runs it on a @@ -194,16 +195,29 @@ capability model proposed for PhotoCraft plug-ins the file and each permission in plain words, and install it once the user clicks OK, if the file still has the SHA-256 shown; Cancel installs nothing. The names shown have control and bidirectional characters escaped (`\u{202E}`) and are cut to 64 characters. - `plugin.install` refuses the module, naming the permissions it needs, unless `grant` lists them all, which an agent - passes once the user agreed (`plugin.inspect`'s `needsApproval` tells it beforehand), with `hash` set to the - `plugin.inspect` entry's `hash` so that the module installed is the one the user saw. `plugin.install` does not - check that a person approved `grant`: it trusts the client that sends it. + Only a person can press its OK: `ui.dialog.confirm`, MCP's `answer_dialog` and injected input (`ui.key`, `ui.click`) + are refused and the dialog stays open. Enter confirms it only when OK has the keyboard focus. `ui.dialog.set` can't + change what it installs. +- `plugin.install` refuses the module, naming the permissions it needs, unless this module already has a recorded grant + (`plugin.inspect`'s `needsApproval` tells it beforehand). A request's `grant` is refused too: `plugin.install` takes + it only with the approval the dialog gives. A `vectorcraft-cli mcp` or `run` started with `--allow-plugin-grants` + takes `grant` and `allowHeavy` from any request; only the person starting the process can set that flag, and it + doesn't apply to a running app. `mcp` refuses the flag together with `--automation-read-root` or + `--automation-write-root`: a server confined to folders has no plug-in store, so it reads no `grants.json`, and a + module that lists permissions or asks for a heavy budget does not install there. Without the flag, MCP in headless + mode and the CLI install a module that lists permissions only when its hash is recorded in the shared `grants.json`. + A person's approval in the desktop app records it, and so does a `grant` accepted under `--allow-plugin-grants`. A + recorded grant counts as approved in later sessions without the flag and in the desktop app. With + `VECTORCRAFT_NO_PREFS` set there is no store, and a `grant` accepted under the flag lasts for that session only. + With `--allow-plugin-grants`, pass `hash` set to the `plugin.inspect` entry's `hash` so that the module installed is + the one the user saw. - **Replacing asks first.** When the file is another module than the plug-in installed with its id, or, with none installed, its id has settings and a cache in the `Plug-ins` folder, Install Plug-in… and File › Open show its id and SHA-256 and ask whether to install it in place of that plug-in, which gives it the settings and cache kept for - the id. `plugin.install` refuses such a module, naming it, unless `replace` is `true`, which an agent passes once - the user agreed (`plugin.inspect`'s `needsReplace` tells it beforehand). The Additional Plug-ins Folder and - `plugin.reload` do not ask. + the id. When the same module also needs its permissions or a heavy budget approved, the one approval dialog asks + about all of them, and only a person can press its OK. `plugin.install` refuses such a module, naming it, unless + `replace` is `true`, which an agent passes once the user agreed (`plugin.inspect`'s `needsReplace` tells it + beforehand). The Additional Plug-ins Folder and `plugin.reload` do not ask. - The grant is recorded with the plug-in's id, the module's hash and the permissions, in `grants.json` in the `Plug-ins` folder, and covers only that module. Installing the same bytes again needs no new approval. A module with other bytes asks again, even when it lists the same permissions, and does not get the id's settings and cache until @@ -212,9 +226,29 @@ capability model proposed for PhotoCraft plug-ins the old module and its grant, and the old module loads at the next start. If the write that puts the old module back fails as well, the folder holds the new module with the old grant, the grant does not cover that module, and the plug-in is skipped at the next start until it is approved again. A grant whose hash is not 64 lower-case - hexadecimal digits covers nothing. `plugin.remove` forgets the grant. An entry of `grants.json` that this version can't use (a - permission it doesn't know, an invalid id) is skipped and stays in the file until its plug-in is granted again or - removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written larger than + hexadecimal digits covers nothing. `plugin.remove` forgets the grant, and so does a successful `plugin.install` of a + module that lists no permissions under that id, so the earlier bytes need a new approval. When `plugin.remove` can't + remove the grant from `grants.json`, it returns an error, the plug-in stays installed, and a second `plugin.remove` + tries again. A refused install leaves the grant as it is. When an install of a module that lists no permissions can't + write the module to the `Plug-ins` folder, or can't remove the grant from `grants.json`, the folder keeps the module + it held and `grants.json` keeps the grant. The new module runs until the session ends. When the grant can't be + removed and the module already stored can't be read back or written back, the new module stays in the folder, and + the grant does not count for the rest of the session. The grant also does not count when the folder held no module + for that id. A + `grants.json` larger than 1 MiB, or one that is not a JSON list, grants nothing: the new module stays in the folder, + and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be + removed. When VectorCraft loads the `Plug-ins` folder, it forgets any grant for an id whose stored module lists no + permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant does not count for + the rest of the session, or until the plug-in is granted again, including for the next load, which tries the removal + again. In Safe Mode, and for + a stored module that the user disabled, + VectorCraft does not read the module, and `grants.json` keeps the grant for its id. The Additional Plug-ins Folder + and `plugin.reload` do not change the `Plug-ins` folder: when they leave a module that lists no permissions under an + id, the process forgets its own grant for that id, and a grant kept in `grants.json` stays with the stored module it + covers. An entry of `grants.json` that this version can't use (a permission it doesn't know, an invalid id) is + skipped and stays in the file until its plug-in is granted again, replaced by a module that lists no permissions, or + removed. When such an entry can't be removed from the file, `plugin.install` and `plugin.remove` treat it as a grant + that can't be removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for `plugin.install`, `plugin.inspect`, `plugin.reload` and the Additional Plug-ins Folder. At startup, a stored plug-in is skipped when no grant covers its bytes and the permissions it lists. The Additional Plug-ins @@ -524,14 +558,15 @@ In this example the character and paragraph styles are cut short; a filter gets - An image (`"image"`): `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or `"unknown"`, read from the image itself. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 pixels fit) has them in `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top, and - `pixelsOmitted: false`. A CMYK image's pixels are its inks through the working CMYK profile. The pixels of all the - images in one input take at most 16 MiB in base64. A larger image, one whose pixels don't fit what the images before + `pixelsOmitted: false`. A CMYK image's pixels are its inks through the working CMYK profile, as sRGB. The pixels of + all the images in one input take at most 16 MiB in base64, and an image the host starts to decode takes its size + from those 16 MiB even when decoding fails. A larger image, one whose pixels don't fit what the images before it in paint order left, and a linked image (`linked: true`) have `pixelsOmitted: true` and no pixels; the host checks an image's size before it decodes the image. An image of any size also has `pixelsOmitted: true` when its data is missing from the document, when its width or height is 0, when - its data cannot be decoded (or needs more than 64 MiB of decoder memory, or is a TIFF the host rejects as too - large), or when the dimensions in its data differ from `pixelSize`. A plug-in checks `pixelsOmitted` before it - reads `pixelsBase64`, which is present only when `pixelsOmitted` is `false`. The host never + its data cannot be decoded (including a non-CMYK image whose decoder enforces the host's 64 MiB memory limit and + needs more, and a TIFF the host rejects as too large), or when the dimensions in its data differ from `pixelSize`. + A plug-in checks `pixelsOmitted` before it reads `pixelsBase64`, which is present only when `pixelsOmitted` is `false`. The host never reads a linked image's file for a filter and never gives its path. - A symbol instance (`"symbolInstance"`): `symbolId` is the name of the symbol it shows, with `missing: true` when the document has no symbol of that name. `overrides` is `{}`. diff --git a/docs/revolve.md b/docs/revolve.md index 2ea788f905..6ecd4957eb 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, 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, and groups or layers of them only. Images and other objects must be converted to paths first. - 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 642a8935c8..a0361d72a6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,8 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** 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 (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) + +> Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). ## Feature submission evidence @@ -40,6 +42,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 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-07 | minor | M4/M7: `.ai`/EPS type from the text document keeps its paragraphs' tab stops, 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 from the left edge (#6147). Scores and estimates unchanged. | | 2026-11-07 | minor | M4/M7: `.ai`/EPS type from the text document keeps auto leading at the paragraph's share, the paragraph's 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, and a line a soft return ends is justified as a wrapped line is (#6137); a user's `.ai` that opened from its PDF part now opens from its layers. 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 | Character Styles panel: a double-click on a user style's row opens its Character Style Options (`ui.charStyleOptions`); the 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. | @@ -113,7 +116,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 @@ -131,15 +134,15 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | | 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); 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 | +| 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) | `.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) | 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; tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 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; tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 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; 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 (#4936; the dialogs 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 with its right-click suggestions, Ignore All and Add to Dictionary (#4936; the dialogs 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 with its right-click suggestions, Ignore All and Add to Dictionary (#4936; the dialogs 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 | | 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 | @@ -153,7 +156,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | 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 | | 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) | 🟡 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) | 🟡 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,9 +193,19 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 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-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. | | 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-04 | minor | New Document: the units chosen in Preset Details belong to the chosen preset; Recent and Saved cards keep their own units; scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index effe043467..2e8b46178b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,9 +1,11 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** 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 (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) ## Feature submission evidence +EPS embedded fonts, 2026-11-09 (#6023–#6067): 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. Evidence: `crates/eps/src/import/tests_composite.rs`, `tests_type42.rs`, `tests_cid.rs`, `tests_type1.rs`; details in [file-format-parity.md](file-format-parity.md). + Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow keys still require focus; modifiers, units, limits, mixed values and existing rounding stay in the shared stepping path. Headless regressions in `tests/numfields.rs` cover hovered unfocused fields, focused fields, trackpad accumulation and panel scroll exclusion. A canvas-first/panel-second regression also checks that a field turn cannot start a canvas zoom glide when the pointer enters the canvas on the next frame. 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. @@ -39,6 +41,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 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-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. | @@ -77,6 +81,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-05 | minor | Optical kerning moves each pair part of the way toward the font's own stem spacing, with a minimum gap and tighter limits, and leaves ideographs, kana, fullwidth forms and dashes on the font's spacing, so text is no longer squeezed (#5336). Scores and estimates unchanged. | | 2026-11-05 | minor | Gradient panel: Delete Stop sits at the right end of the ramp, so it shows whenever the ramp does instead of under the stop fields, where a short panel hid it (#5403); scores and estimates unchanged | | 2026-11-04 | minor | Record Select Text by Font's artboard and layer scope (#5529, a VectorCraft addition); scores and estimates unchanged. | +| 2026-11-07 | minor | Type: paint-only Arabic harakat keep joining forms; a matching character-level pass assigns a later in-cluster run only for GDEF mark glyphs on harakat characters (otherwise cluster start); Insert Kashidas tatweels take the base letter's paint (`tests::harakat`). Scores and estimates unchanged. Marks may retain letter paint without GDEF mark classes or with some AAT/`morx` ligatures. | | 2026-11-04 | minor | Type core: a Type-range Copy or Cut publishes styled art alongside plain text, so canvas Paste keeps font family, size and color after editing ends (#5636); scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | | 2026-11-04 | minor | Raster/PSD defaults honor document resolution; CLI run/convert accept --ppi, matching MCP options.ppi precedence. Synthetic regressions added; scores and hours unchanged. | @@ -205,37 +210,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); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 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 (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) | | 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) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | 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; scores and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | 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; scores and hours unchanged | +| 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 with its right-click suggestions done, #4936; the dialogs 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 with its right-click suggestions done, #4936; the dialogs 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 | | 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, 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, 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 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | 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 done, #4936; the dialogs 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 with its right-click suggestions done, #4936; the dialogs 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 | 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 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 | | 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 | 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 | 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 | 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); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score 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), global/artboard ruler mode switch, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score 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), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | -| 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), global/artboard ruler mode switch and video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | +| 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 | +| 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 | | 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 +389,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) | | 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 +479,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% | the Art brush's Overlap, auto-generated Pattern brush corners and new tile art in Pattern Brush Options (Brush Options for every brush type done), more built-in brush libraries (four generated in code are done), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 8–15 | +| 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 | | 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 (open dictionary), 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 and Auto Spell Check are done, #4936: the Check Spelling and Edit Custom Dictionary dialogs remain; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary), 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 (open dictionary), 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 and Paragraph Direction (the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); 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% | more built-in symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | +| 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 remain; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary), 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 | | 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 +531,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 | ~30% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have one (Basic Shapes) 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 | ~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… | | **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,6 +543,9 @@ 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. @@ -575,6 +580,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 +596,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 +653,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 +672,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. @@ -763,12 +777,12 @@ 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 library, Basic Shapes, is 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 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`. - **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`. - Symbol editing mode keeps every instance in step: instances of a dynamic symbol inside other symbols' art, pattern tiles, graph designs, stored brushes and opacity masks keep their appearance changes on the objects an edit reorders and drop the changes to objects it deletes. The view does not draw the instance the edit was entered from. Area type in the symbol's art takes the text wrap that moving a wrap object gives it. Editing another symbol at a place that fails keeps the current edit open, and only the editing layer or art on it can be isolated. Tests: `crates/engine/src/tests/symboledit.rs`, `isolation::symbol_editing_does_not_draw_the_instance_it_was_entered_from`, `panels::symbols::tests::double_clicking_a_symbol_in_the_panel_edits_it_in_either_view`, `the_panel_menus_edit_symbol_edits_the_instances_symbol_or_the_panels`, `the_control_bars_edit_symbol_edits_the_selected_instances_symbol`, `chrome::tests::the_control_bar_exits_symbol_editing_mode`. - - **Dynamic symbol instances on the canvas** ([Symbols, archived copy](https://web.archive.org/web/20240206075757/https://helpx.adobe.com/illustrator/using/symbols.html)): each instance of a dynamic symbol can have an appearance of its own while it shares the symbol's shape. The rest of this entry is VectorCraft's own rules. A Direct Selection click on an instance of a dynamic symbol selects the path, compound path or type object of the symbol's art under the pointer and outlines it (`symbol.instance.selectPart`); the Swatches and Color panels, the Control bar, the Eyedropper and the other fill and stroke controls then change that object's solid color fill or stroke for this instance only, each as one undo step, and the symbol's art and its other instances stay as they were. Alt or Shift picks the instance whole. A gradient or pattern for the object, an Eyedropper source that is not a path, compound path or type, a click on any other object of the art (a group, image, blend or nested instance) and the commands that change the selected objects (opacity, moving, Delete, Group, Hide, Lock, Arrange, Expand, the gradient commands, the Appearance panel's rows and others) are refused with a status message. Copy, Export Selection, Fit to Selection, Liquify, Isolate, Add to Library and Save Selection use the whole instance (`docs/mcp.md`), and another selection tool selects the instance whole again. Tests: `crates/engine/src/tests/dynamic_symbols.rs`, `direct::tests::a_click_on_a_dynamic_instance_picks_the_object_under_the_pointer`. + - **Dynamic symbol instances on the canvas** ([Symbols, archived copy](https://web.archive.org/web/20240206075757/https://helpx.adobe.com/illustrator/using/symbols.html)): each instance of a dynamic symbol can have an appearance of its own while it shares the symbol's shape. The rest of this entry is VectorCraft's own rules. A Direct Selection click on an instance of a dynamic symbol selects the path, compound path or type object of the symbol's art under the pointer and outlines it (`symbol.instance.selectPart`); the Swatches and Color panels, the Control bar, the Eyedropper and the other fill and stroke controls then change that object's fill or stroke (solid, none, gradient or pattern) for this instance only, each as one undo step, and `transparency.set` changes its opacity and blend the same way; the symbol's art and its other instances stay as they were. Alt or Shift picks the instance whole. An Eyedropper source that is not a path, compound path or type, a click on any other object of the art (a group, image, blend or nested instance) and the commands that change the selected objects (moving, Delete, Group, Hide, Lock, Arrange, Expand, the gradient annotator, isolate/knockout on Transparency, the Appearance panel's rows and others) are refused with a status message. Copy, Export Selection, Fit to Selection, Liquify, Isolate, Add to Library and Save Selection use the whole instance (`docs/mcp.md`), and another selection tool selects the instance whole again. Tests: `crates/engine/src/tests/dynamic_symbols.rs` (`gradients_and_patterns_on_a_picked_object_are_taken`, `opacity_and_blend_on_a_picked_object_go_through_transparency_set`), `direct::tests::a_click_on_a_dynamic_instance_picks_the_object_under_the_pointer`. - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it stays within the art's box (guides outside the art are not supported yet) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. @@ -781,11 +795,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). @@ -795,7 +811,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. @@ -805,6 +821,7 @@ 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`). - 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. @@ -963,7 +980,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. @@ -1034,13 +1051,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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)). - 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, and the font size changes by the scale. 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)). @@ -1105,6 +1126,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur PDF export with type as text writes the hyphen that ends a line broken inside a word as a hyphen character where the line draws it, and the file opens with the hyphen in the line's text; kashidas are drawn as paths. The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. The Character panel menu's Kashidas switch (with the Indic options; `text.setFormat` / `text.setRangeStyle {kashidas}`) allows Kashidas on selected characters, on by default for new and old text. A pair of joined letters receives one only when both characters allow it; turning one off leaves other eligible pairs in the word available. Character styles and the native file keep the switch. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html) documents the menu control and the separate paragraph length choices; the default and pair rule are VectorCraft choices. + Paint-only Arabic harakat (marks whose character styles differ only in fill, stroke and related paint) stay inside one shaping cluster so letters keep their joining forms; when a second character-level shaping pass matches the monotone glyphs, a glyph may take a later in-cluster character's run only when GDEF classifies it as a mark (class 3) and that character is a harakat; otherwise it keeps the shaping cluster's first character. Insert Kashidas tatweels take the base letter's paint rather than a trailing mark's. Fonts without GDEF and some AAT/`morx` ligatures can leave a mark painted as its letter (`crates/text/src/tests/harakat.rs`). The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Bullets and Numbering dialog, levels and Convert to Text are not built yet. The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. @@ -1230,7 +1252,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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. - - **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) 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. Still to come: the Art brush's Overlap, Stylus Wheel, and the pen's tilt, bearing and rotation on Windows, native Wayland and the web. + - **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). - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). @@ -1304,6 +1326,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 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`). @@ -1456,7 +1479,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur anchor or with Alt held over a path (convert) and over another open path's end (join). The Eyedropper has an original pipette glyph with its tip at the hotspot; Use Precise Cursors restores the crosshair. The same glyph feeds OS bitmaps and painted cursors. DPI/hotspot and preference checks in `cursors.rs` and `tests/prefs.rs` cover #1269; - actual OS display and Caps Lock remain unverified. Behaviour reference: [public tool-pointer documentation](https://helpx.adobe.com/illustrator/using/tools.html#change_tool_pointers). Tool cursors are painted into the window on Wayland (#1652; not run on Linux, #1645 stays open until confirmed). A Precise Cursors command toggles the preference and can take a shortcut (#1663). On macOS the tool cursor is painted only while the window has the focus. Over a window behind another app, or under the File › Open… sheet, the system pointer shows alone instead of next to the painted cursor (#2020). + actual OS display and Caps Lock remain unverified. Behaviour reference: [public tool-pointer documentation](https://helpx.adobe.com/illustrator/using/tools.html#change_tool_pointers). Tool cursors are painted into the window on Wayland (#1652; not run on Linux, #1645 stays open until confirmed). A Precise Cursors command toggles the preference and can take a shortcut (#1663). On macOS the root document canvas now requests native AppKit delivery of the existing artwork, with aligned 1×/2× representations and a visible system fallback (#2292). `cursors/native_request` and `canvas` tests cover pixel/hotspot alignment, preferences and fallback routing; `mac_cursor` tests cover real AppKit image construction and the ownership protocol against a fake backend. The host releases on native-menu tracking and loss of eligibility; detached document viewports retain the visible system fallback. The pre-platform-output rectangle strategy, real focus/menu/handback behavior, mixed displays, Spotlight and native full-screen Spaces remain unverified; #2020 and #2292 are not declared closed. In a rotated view the resize and rotate cursors turn with the view, to the nearest 45°. - **Performance:** 20k shapes + 1k texts render in 27 ms per full-retina frame (7.8 ms zoomed), 7× faster than the first version. The UI thread never blocks. The web build is 7.1 MB gzipped. Print-size images (more than 512 MB decoded, up to 2 GB) draw in the canvas and in raster exports and can be trimmed with Crop Image; an image with a side past 65,535 px is shrunk to fit, a raster export says when an image could not be decoded, and Crop Image's trim leaves CMYK images alone (#1517). On Windows `vectorcraft-cli perf` reports the cores busy and, with `--deep`, its working set, and warns on a busy machine as it does on macOS and Linux (#1502). Hard-edge rendering, including the internal hard-edge frame of Art Optimized supersampled raster exports, draws a knockout element with one opaque solid fill once instead of erasing and adding it through separate layers. Analytical antialiasing keeps the existing compositor and rounding. Synthetic path/compound-hole tests compare exact pixels against the general knockout path across precision, supersampling, translucent parent groups and backdrop blending; translucent fills retain their knockout behavior. @@ -1471,6 +1494,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). @@ -1479,6 +1503,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. @@ -1583,8 +1608,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode <subcommand>` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Plug-in instruction budget at a bulk memory instruction:** a run that pauses where one slice of its instruction budget ends keeps the instructions the slice still held. A `memory.fill` or `memory.copy` that the slice can't pay for in full runs on the next slice, so a run whose budget covers its work finishes; a run ends with `Limit("instruction budget")` only when the instructions it has left can't pay for the next instruction. Regressions: `crates/plugins/tests/abi.rs`. Scores and hours unchanged. - **Plug-in permissions (G17):** a manifest may list `permissions` (`doc.read`, `doc.write`, `state`, `effect.render`, `export.write`; the first three follow storytold/photocraft#662) and an `api` level; without the list a plug-in gets what its kind implies and installs as before. Install Plug-in… and File › Open show the name, id, version, file SHA-256 and each permission in plain words, with control and bidirectional characters escaped, and install nothing on Cancel; for a plug-in that lists permissions, `plugin.install` needs `grant` and folders install it only when it is granted. The grant is kept with the module's hash, a module asking for more asks again, and a filter run refuses output its permissions don't allow. Regressions: `crates/plugins/src/permissions.rs`, `crates/plugins/src/manifest.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 read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. +- **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/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 grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **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. - **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. @@ -1875,6 +1902,16 @@ While a corner widget is pressed or dragged with the Selection or Direct Selecti A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool enters isolation mode on it ([isolate objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html): a double-click with the Selection tool isolates an object; [repeat patterns overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/repeat-patterns-overview.html): every instance follows edits to the original object); there the source art is selected and edited as usual (a double-click on type in it switches to the Type tool on that text) and every copy follows, with the repeat's settings kept (#5054). Test: `tests::repeat_edit::a_double_click_on_a_repeat_isolates_it_to_edit_its_text`. +## Spell check engine (2026-11-08) + +Edit › Spelling has the commands its Check Spelling dialog will use, as the public documentation describes checking the document's text, suggesting replacements and changing a word ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)). `text.spelling.check` lists the words the dictionaries don't know in every visible, unlocked type object, or in the ones given by `ids`, in paint order, each run checked in its Character panel Language (English when it has none; nothing in a language without a dictionary). Each word comes with its object and byte range, which `text.editRange` changes as one undo step. `text.spelling.suggest` gives one word's suggestions. Both come from craft-proof in [storytold/craft-libs](https://github.com/storytold/craft-libs), which checks each paragraph on its own. English words come from the first dictionary craft-proof finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof (#4936; `tests/spelling.rs`). The Check Spelling dialog, Auto Spell Check and Edit Custom Dictionary remain, so the Edit › Spelling menu items are still placeholders. + +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 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 and the context menu's Spelling › Auto Spell Check remain. + ## Control bar: Paragraph section while type is selected (2026-11-06) With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1440 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). @@ -1891,12 +1928,27 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 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 | 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. | +| 2026-11-09 | minor | File formats: 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 | Type advanced: spell check engine, `text.spelling.check` lists unknown words per run language at `text.editRange` byte offsets and `text.spelling.suggest` gives suggestions, from craft-proof (#4936); evidence added; the dialog, Auto Spell Check and the custom dictionary remain; scores and hours 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-07 | minor | File formats and Type core: `.ai`/EPS type keeps its paragraphs' tab stops, 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 (#6147); evidence added; scores unchanged. | | 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. | | 2026-11-06 | minor | Direct Selection: with Snap to Grid, a dragged straight segment lands its anchors on the grid (#3835); evidence added; scores unchanged. | | 2026-11-06 | minor | Snap to Glyph › Glyph Bounds: the corners of each glyph's box are points a drawn point lands on, also on a curved side (`B`), and the box turns with rotated type, its edges then Angular Guides (#5112; [Snap to Glyph options](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph-options.html)); scores and estimates unchanged. | | 2026-11-06 | minor | Drop Shadow: a swatch beside Color opens the Color Picker over the dialog, as the other effect colour fields do (#5364); correction: the #5365 entry listed Drop Shadow, whose Color is drawn outside the shared grid and had no swatch; scores unchanged. | @@ -2248,4 +2300,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..0e99010613 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -232,8 +232,8 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. 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. + clipping groups and other live objects have to be converted first. 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, diff --git a/docs/type-parity.md b/docs/type-parity.md index fa4da7a85d..bb64f08c47 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 (remaining language-list additions and public sources, #4943; 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 (remaining language-list additions and public sources, #4943; 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,7 +18,7 @@ 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)) | @@ -47,17 +47,17 @@ 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) | missing | menu stubs; needs an openly licensed dictionary | +| 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. The Check Spelling and Edit Custom Dictionary dialogs and the context menu's Spelling › Auto Spell Check remain. 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). | | 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 | | +| 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` | -| Middle Eastern: Kashidas | done | Paragraph Insert Kashidas sets the length for justified Arabic area type; Character-menu Kashidas allows or excludes selected characters, on by default. A kashida is inserted only between two allowed joined characters. The character switch is retained in character styles and the native file; the length is retained in paragraph styles and the native file. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html). | +| Middle Eastern: Kashidas | done | Paragraph Insert Kashidas sets the length for justified Arabic area type; Character-menu Kashidas allows or excludes selected characters, on by default. A kashida is inserted only between two allowed joined characters. The character switch is retained in character styles and the native file; the length is retained in paragraph styles and the native file. Paint-only harakat (coloured or hidden marks) stay in one shaping cluster so letters keep joining; when the character-level pass matches, a glyph may take a later in-cluster character's run only if GDEF names it a mark (class 3) and that character is a harakat—otherwise the cluster start (a mark may miss its colour; a base never takes a mark's). Inserted tatweels take the base letter's paint—not a trailing mark's. Fonts without GDEF and some AAT/`morx` ligatures (e.g. Geeza Pro Allah) can leave a mark painted as its letter. No Character-panel harakat colour command yet. Evidence: `tests::harakat`. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html). | | Middle Eastern: Middle Eastern composers, split caret | missing | Character Direction is done; editable bidirectional SVG text remains incomplete. | | CJK: input methods (marked text, candidate window) | done | | | CJK: kinsoku (Hard, Soft, None), Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets, the Mojikumi Settings dialog and the other mojikumi sets missing | @@ -68,7 +68,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per class; SVG and legacy `.ai` write it as outlines. Not yet: custom character sets, the Units menu, Show Sample. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: spelling by it, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages` | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | Inline symbols in text | beyond Illustrator | not scored | | Align Stroke (inside, outside) on live type's character stroke | beyond Illustrator | not scored; `stroke.set {align}` and `text.setRangeStyle {strokeOptions: {align}}`; saved natively, drawn around the glyphs on the canvas and in PDF, EPS and SVG (live text, stroke on the glyph outlines); visual bounds grow with it (#2294) | @@ -80,7 +80,12 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| -| 2026-11-09 | minor | Nepali (`ne`), Konkani (`kok`) and Sindhi (`sd`) complete the remaining language-list additions (#4943); Assamese and Sanskrit already landed in #5946. The five languages use quotes inherited from [CLDR root](https://github.com/unicode-org/cldr/blob/main/common/main/root.xml). Hyphenation behavior from #4947 is retained; scores 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. | +| 2026-11-08 | minor | Spell check engine (#4936): `text.spelling.check` lists unknown words per run language at `text.editRange` byte offsets and `text.spelling.suggest` gives suggestions, from craft-proof; the dialog, Auto Spell Check and the custom dictionary remain. Spelling noted in the Language per character rows, which no longer list it as not yet done; their hyphenation note names the languages that still lack it. Scores and estimates unchanged. | +| 2026-11-10 | minor | Nepali (`ne`), Konkani (`kok`) and Sindhi (`sd`) complete the remaining language-list additions (#4943); Assamese and Sanskrit already landed in #5946. The five languages use quotes inherited from [CLDR root](https://github.com/unicode-org/cldr/blob/main/common/main/root.xml). Hyphenation behavior from #4947 is retained; scores unchanged | | 2026-11-07 | minor | Tabs: in right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none, when the tab ends the line) against the right edge; the line was aligned as a whole, which moved its start off the left edge. Illustrator's own layout in a user's `.ai` (used locally, not committed) sets its price lists so. Centred and justified lines keep their alignment as a whole. Scores and estimates unchanged. | | 2026-11-07 | minor | Soft return: in Justify Left, Center or Right, the line a soft return ends is justified as a wrapped line is; only the paragraph's last line keeps its alignment. Illustrator's own layout in a user's `.ai` (used locally, not committed) justifies those lines. 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. | @@ -95,6 +100,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | 2026-11-04 | minor | A Type-range Copy or Cut publishes styled art alongside plain text, so a later canvas Paste keeps its character formatting after editing ends (#5636). Scores and estimates unchanged. | | 2026-11-03 | minor | Glyphs panel adds Alternates for Current Selection. A chosen alternate changes one character's drawn glyph while keeping its Unicode text; character-style capture does not copy that per-character choice. Scores and estimates unchanged. | | 2026-11-04 | minor | Find Font's Replace With Font lists family and style rows, one click setting both, with a search over them; the list scrolls apart from the document's font list and refreshes after each replacement (#4972); scores and estimates unchanged. | +| 2026-11-07 | minor | Paint-only Arabic harakat stay in one shaping cluster; a matching character-level pass assigns a later in-cluster run only for GDEF mark glyphs on harakat characters (otherwise cluster start); Insert Kashidas tatweels take the base letter's paint (AAT/no-GDEF marks may keep the letter's colour). Evidence: `tests::harakat`. Scores and estimates unchanged. | | 2026-11-03 | minor | The OpenType panel lists the selected font's available Stylistic Sets with its custom names or numbered labels; sets can be combined and deselected. Scores and estimates unchanged. | | 2026-11-03 | minor | Character-menu Kashidas controls selected characters separately from the paragraph's Insert Kashidas length. Existing text allows Kashidas by default; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox: the type follows the fields while it is on, Cancel restores it, OK is one undo step (#5360, as public tutorials of the dialog show); scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8a3633cb04..f2e1274fa6 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,8 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (remaining language-list additions and public sources, #4943; 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-10 · **Change:** minor (remaining language-list additions and public sources, #4943; 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) + +> Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). ## Feature submission evidence @@ -223,9 +225,9 @@ 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; no View › Snapping submenu. Floating-panel parity remains unverified. | +| 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 | | Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | @@ -265,10 +267,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) | @@ -317,6 +320,7 @@ tools, never checked side by side) isn't captured row by row. | Tool double-click opens its options | done | | | Per-platform mapping (Cmd ↔ Ctrl, Option ↔ Alt) | done | | | Eyedropper cursor; Use Precise Cursors | partial | original pipette at the sampling tip, distinct from the precise crosshair at five DPI scales (#1269); OS cursor display unverified; while Caps Lock is on, the tools that Use Precise Cursors changes show the crosshair, and the saved preference does not change (the desktop app reads the lock state on macOS, Windows and Linux X11, not on native Wayland; `view.capsLock` reads or sets it); a Use Precise Cursors command toggles the preference and can take a shortcut (#1663); cursors are painted into the window on Wayland (#1652, not run on Linux) | +| macOS canvas cursor delivery (#2292) | partial | The UI prepares the existing glyphs as aligned 1×/2× RGBA requests; the desktop host builds AppKit cursors and owns cursor rectangles for the root document window. Detached document viewports and requests without a usable native bitmap retain the visible system fallback; precise-cursor and UI-scale preferences retained. Headless regressions cover routing, pixels/hotspots and lifecycle; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain unverified. Wayland still paints its glyphs. | | Every tool's modifiers checked against the shortcut reference | missing | this is the fidelity pass | ## Keyboard shortcuts @@ -494,10 +498,13 @@ 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. | | 2026-11-07 | minor | Pen and Curvature tool with Cmd/Ctrl held: Edit › Copy and Cut take the anchors and segments the lent Direct Selection picked, as with Direct Selection chosen, not the whole path; with the Pen's own last anchor selected Copy still takes the whole path (#6123); scores and estimates unchanged | | 2026-11-07 | minor | Live Corners: with Direct Selection, while every corner of a path is selected, a Shift-click on a corner widget picks that corner alone instead of deselecting it (#5188); adding a hidden corner's widget by Shift-click stays open (#1232); scores and 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 | Keyboard shortcuts: Cmd/Ctrl+Alt+. and Cmd/Ctrl+Alt+, (Stroke Weight Up and Down) step each selected stroke's weight, or the next object drawn's (#5797); scores and estimates unchanged | | 2026-11-06 | minor | Properties: Quick Actions has Repeat Options for one selected radial, grid or mirror repeat, opening Object › Repeat › Options with its values (#5181); scores and estimates unchanged | | 2026-11-06 | minor | Control bar: with type selected, a Paragraph: link (the Paragraph panel in a popover) and the Align left, Align center and Align right buttons follow the Character controls; the bar leaves them out from its right end when short of room, after X/Y/W/H and the Align buttons (#5372); 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).