diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..75c87011b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "accesskit" -version = "0.25.1" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ "uuid", ] @@ -27,9 +27,9 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.39.1" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" dependencies = [ "accesskit", "hashbrown 0.17.1", @@ -51,9 +51,9 @@ dependencies = [ [[package]] name = "accesskit_macos" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" dependencies = [ "accesskit", "accesskit_consumer", @@ -1836,6 +1836,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-pbr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +dependencies = [ + "craft-texture", + "thiserror 2.0.21", +] + [[package]] name = "craft-pcraft-format" version = "0.1.0" @@ -2079,6 +2088,14 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "craft-texture" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-theme" version = "0.1.0" @@ -8741,6 +8758,7 @@ dependencies = [ "skrifa 0.47.0", "thiserror 2.0.21", "tiff", + "unicode-normalization", "vectorcraft-affinity", "vectorcraft-apischema", "vectorcraft-brush", @@ -9101,6 +9119,7 @@ dependencies = [ name = "vectorcraft-three-d" version = "0.25.1" dependencies = [ + "craft-pbr", "proptest", "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", @@ -10418,7 +10437,9 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" name = "xtask" version = "0.25.1" dependencies = [ + "craft-fonts-build", "serde_json", + "tempfile", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 843f9cbb53..7dab0c8895 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,8 @@ craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ec craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } diff --git a/README.md b/README.md index 366b0711a8..3280824dc8 100644 --- a/README.md +++ b/README.md @@ -257,7 +257,7 @@ All 57 approximated Photoshop-style raster filters are available. The Effect Gal **What's missing:** - reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on 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 (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; -- the rest of 3D and Materials (base and Adobe Substance materials, shadows from lights after the first, ray-traced rendering, Turntable; see [docs/three-d.md](docs/three-d.md)); +- the rest of 3D and Materials (Adobe Substance materials, adding or deleting materials, shadows from lights after the first, ray-traced rendering, Turntable; the base material's Roughness and Metallic are built; see [docs/three-d.md](docs/three-d.md)); - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. diff --git a/ROADMAP.md b/ROADMAP.md index 2b9961f821..f74399f93a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # VectorCraft Roadmap -**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away +**Stage: alpha** · next: beta, ~8 points (ready for real work ~67% → ~75%, and reliable `.ai` exchange) and ~170–270 h away > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Upcoming: G11 names what is left (#864's unit preference, #885), not the fixed Shape Builder regions and Asset Export borders, with docs/roadmap.md's 6–13 h, and the Essentials row names Shape Builder's remaining depth, #8314; previously: G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) @@ -95,7 +95,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Language | Code | Status | Translated | |---|---|---|---:| | English | `en` | full | 100% | -| Simplified Chinese | `zh-hans` | partial (messages translated, #2578) | 85% | +| Simplified Chinese | `zh-hans` | partial (most messages translated, #2578; some remain untranslated) | 85% | | Spanish | `es` | full | 100% | | Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner | | Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial | @@ -127,6 +127,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. - 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. +- 2026-11-29: 3D and Materials › Materials › Properties: Roughness and Metallic for Extrude & Bevel, Revolve, Inflate and Rotate, shaded with glTF 2.0's metallic-roughness BRDF and written into glTF and USD exports ([three-d.md](docs/three-d.md#material-properties)); scores and estimates unchanged. - 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. @@ -174,6 +175,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke (a chosen RGB color goes into the document's color model, or stays RGB with `keepModel`), on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when no top-level layer has that name and otherwise keeps its lock and visibility (a layer that holds a clipping mask is refused). A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 3ec7da1b75..bc000f0bd6 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -130,3 +130,5 @@ winresource = "0.1" [dev-dependencies] tempfile = "3" +# The framework's test frames (`craft::ui::testing`), for the Alt-code hook's tests. +craft = { workspace = true, features = ["ui-testing"] } diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 2715e08125..fbe339937f 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -46,7 +46,7 @@ impl eframe::App for App { } // The keypad digits of Alt + keypad codes leave the frame (#5108). #[cfg(windows)] - super::windows_alt_codes::raw_input_hook(raw); + super::windows_alt_codes::raw_input_hook(ctx, raw); // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). #[cfg(windows)] super::windows_symbol_chars::raw_input_hook(raw); diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 4eb39067a0..651be6f6a3 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -177,9 +177,10 @@ mod system { return Vec::new(); } let named = cups_server(); + let sockets = local_sockets(); // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, // so its sizes come from the server. - if scheduler_is_local(named.as_deref()) { + if scheduler_is_local(named.as_deref(), &sockets, real_path) { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); @@ -199,7 +200,7 @@ mod system { } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); - let server = ipp_server(named, |s| std::path::Path::new(s).exists()); + let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; @@ -234,17 +235,52 @@ mod system { /// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`. #[cfg(not(windows))] const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; - /// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server - /// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default - /// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local - /// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job - /// does not go to. + /// The real path of a socket path, through symbolic links (`/var/run/cupsd` is `/private/var/run/cupsd` on macOS). + #[cfg(not(windows))] + pub(super) fn real_path(path: &str) -> Option { + std::fs::canonicalize(path).ok().map(|p| p.to_string_lossy().into_owned()) + } + /// The domain sockets of the local scheduler: CUPS's own, and those the `Listen` lines of `/etc/cups/cupsd.conf` add. + #[cfg(not(windows))] + pub(super) fn local_sockets() -> Vec { + use std::io::Read as _; + let mut text = String::new(); + let read = std::fs::File::open("/etc/cups/cupsd.conf").and_then(|f| f.take(1 << 20).read_to_string(&mut text)); + cupsd_listen_sockets(if read.is_ok() { &text } else { "" }) + } + /// CUPS's own domain sockets and the socket paths of the `Listen` lines of a `cupsd.conf`. + #[cfg(not(windows))] + pub(super) fn cupsd_listen_sockets(text: &str) -> Vec { + let listed = text.lines().filter_map(|line| { + let line = cups_conf_line(line); + let (key, value) = line.trim().split_once(char::is_whitespace)?; + let value = value.trim(); + (key.eq_ignore_ascii_case("Listen") && value.starts_with('/')).then(|| value.to_string()) + }); + CUPS_SOCKETS.iter().map(|s| (*s).to_string()).chain(listed).collect() + } + /// Whether the socket path `path` is one of the local scheduler's `sockets`, as written or as `resolve` gives the + /// real paths of both. + #[cfg(not(windows))] + fn is_local_socket(path: &str, sockets: &[impl AsRef], resolve: impl Fn(&str) -> Option) -> bool { + let path = path.trim(); + let real = resolve(path); + sockets.iter().any(|s| { + let s = s.as_ref(); + s == path || real.as_ref().is_some_and(|real| real == s || resolve(s).as_ref() == Some(real)) + }) + } + /// The server for the IPP lookup, given the one `cups_server` names, whether a path exists and a socket path's real path. + /// With no server named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` + /// on the IPP default port), and `localhost` on `IPP_PORT` otherwise. A + /// named socket in `CUPS_SOCKETS`, or a link to one, also returns `None`. Any other socket path stays as named, + /// and the lookup is skipped. /// /// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri #[cfg(not(windows))] - pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool) -> Option { + pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option) -> Option { match named { - Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None, + Some(server) if server.trim().starts_with('/') && is_local_socket(&server, &CUPS_SOCKETS, resolve) => None, Some(server) => Some(server), None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()), } @@ -268,14 +304,15 @@ mod system { client_conf_server_name(&text) }) } - /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, - /// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback - /// name on another port is a second scheduler, whose queues the local PPD folder does not describe. + /// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain + /// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. + /// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder + /// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket. #[cfg(not(windows))] - pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { + pub(super) fn scheduler_is_local(server: Option<&str>, sockets: &[String], resolve: impl Fn(&str) -> Option) -> bool { let Some(server) = server.map(str::trim) else { return true }; if server.starts_with('/') { - return true; + return is_local_socket(server, sockets, resolve); } // A network name may end in `/version=1.1`. let server = server.split_once('/').map_or(server, |(server, _)| server); @@ -289,17 +326,22 @@ mod system { let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"; loopback && port.is_none_or(|port| port.trim() == "631") } - /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a + /// A line of a CUPS configuration file without its comment. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is /// dropped and the rest of the line is kept as written. #[cfg(not(windows))] + fn cups_conf_line(line: &str) -> String { + match line.find('#') { + Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), + Some(at) => line[..at].to_string(), + None => line.to_string(), + } + } + /// The last `ServerName` in a `client.conf`. + #[cfg(not(windows))] pub(super) fn client_conf_server_name(text: &str) -> Option { text.lines().rev().find_map(|line| { - let kept = match line.find('#') { - Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), - Some(at) => line[..at].to_string(), - None => line.to_string(), - }; + let kept = cups_conf_line(line); let (key, value) = kept.trim().split_once(char::is_whitespace)?; (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) }) @@ -604,18 +646,47 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, ipp_server, scheduler_is_local}; + use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local}; #[test] fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { let none = |_: &str| false; let socket = |s: &str| s == "/run/cups/cups.sock"; - assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631"); - assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None); - assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); - assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631")); - assert_eq!(ipp_server(None, socket), None); - assert_eq!(ipp_server(None, none).as_deref(), Some("localhost")); + let real = |_: &str| None; + assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none, real), None, "CUPS's socket is asked as localhost:631"); + assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none, real), None); + assert_eq!(ipp_server(Some("/var/run/cupsd".into()), none, linked), None, "a link to CUPS's socket is that socket"); + let other = ipp_server(Some("/tmp/other.sock".into()), socket, linked); + assert_eq!(other.as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); + assert_eq!(ipp_server(Some("localhost:8631".into()), socket, real).as_deref(), Some("localhost:8631")); + assert_eq!(ipp_server(None, socket, real), None); + assert_eq!(ipp_server(None, none, real).as_deref(), Some("localhost")); + } + + #[test] + fn a_socket_the_local_cupsd_listens_on_counts_as_local() { + let real = |_: &str| None; + let sockets = cupsd_listen_sockets( + "Listen localhost:631\nListen /srv/cups/print.sock # office\n# Listen /tmp/off.sock\nListen /run/cups/office\\#2.sock\n", + ); + assert!(scheduler_is_local(Some("/srv/cups/print.sock"), &sockets, real), "its PPD folder describes the queue"); + assert!(!scheduler_is_local(Some("/tmp/off.sock"), &sockets, real), "a commented-out Listen line adds nothing"); + assert!(sockets.iter().any(|s| s == "/run/cups/office#2.sock")); + assert_eq!(ipp_server(Some("/srv/cups/print.sock".into()), |_| false, real).as_deref(), Some("/srv/cups/print.sock")); + } + + /// The real path of a socket path on a macOS-like system, where `/var` is a link to `/private/var`. + fn linked(path: &str) -> Option { + path.strip_prefix("/var/").map(|rest| format!("/private/var/{rest}")) + } + + #[test] + fn a_socket_path_counts_as_local_only_when_it_is_cups_own() { + let real = |_: &str| None; + let own = cupsd_listen_sockets(""); + assert!(scheduler_is_local(Some("/var/run/cupsd"), &own, linked), "a link to CUPS's socket reads the local PPD folder"); + assert!(!scheduler_is_local(Some("/var/run/cupsd"), &own, real), "an unresolved unknown path is another scheduler"); + assert!(!scheduler_is_local(Some("/var/run/other.sock"), &own, linked)); } #[test] @@ -623,6 +694,8 @@ mod client_conf_tests { for local in [ None, Some("/run/cups/cups.sock"), + Some(" /var/run/cups/cups.sock "), + Some("/private/var/run/cupsd"), Some("localhost"), Some("LocalHost:631"), Some("localhost:631"), @@ -633,7 +706,7 @@ mod client_conf_tests { Some("localhost/version=1.1"), Some("localhost:631/version=1.1"), ] { - assert!(scheduler_is_local(local), "{local:?}"); + assert!(scheduler_is_local(local, &cupsd_listen_sockets(""), |_| None), "{local:?}"); } for remote in [ "print.example.com", @@ -647,8 +720,10 @@ mod client_conf_tests { "127.0.0.1:8631", "[::1]:8631", "localhost:8631/version=1.1", + "/tmp/other.sock", + "/home/me/.cups/second.sock", ] { - assert!(!scheduler_is_local(Some(remote)), "{remote}"); + assert!(!scheduler_is_local(Some(remote), &cupsd_listen_sockets(""), linked), "{remote}"); } } diff --git a/apps/vectorcraft/src/windows_alt_codes.rs b/apps/vectorcraft/src/windows_alt_codes.rs index c358a65653..bd7110a48c 100644 --- a/apps/vectorcraft/src/windows_alt_codes.rs +++ b/apps/vectorcraft/src/windows_alt_codes.rs @@ -5,11 +5,15 @@ //! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code //! with a leading 0, else its OEM code page), the convention every Windows text field follows //! (). winit reports -//! that character as a key press of its own with the character as its text (storytold/winit W36), -//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives -//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message -//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad -//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame. +//! that character as a key press of its own after Alt's release, and egui hands it to the frame as +//! typed text, so the Type tool (or a panel's text field) types it like any other character, in the +//! same undo step as the typing round it. winit's message hook ([`msg_hook`]) sees each keyboard +//! message before winit handles it: [`AltCodes`] notes the keypad digits typed with Alt held, and +//! [`raw_input_hook`] takes them out of the frame, so they don't run a shortcut bound to Alt and a +//! digit and the framework does not compose the same code a second time. [`raw_input_hook`] also +//! tells the framework that the Alt hold had digits typed in it (`alt_code_digits_taken`), so it +//! does not read Alt's release as a lone Alt (an alert in a field that holds drafts, or the menu bar +//! taking the focus). //! //! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right, //! Home, Up and Page Up, and Windows still composes the code from them. They are told from the @@ -18,8 +22,10 @@ //! so with Alt held they count as digits and are taken out of the frame too, rather than moving //! the caret before the character arrives. //! -//! egui reports a keypad digit as the same key as the digit above the letters, so the other -//! platforms, whose systems have no such convention, can't tell them apart either. +//! egui reports a keypad digit as the same key as the digit above the letters and tells them apart +//! only by the physical key. On the other platforms the framework types keypad codes itself, and on +//! every platform Alt with a top-row digit stays a key press (`AltCodeKeys::Keypad`, set in the +//! app's root values). #![cfg_attr(not(windows), allow(dead_code))] @@ -39,11 +45,9 @@ const VK_NUMPAD9: usize = 0x69; /// The keypad's virtual keys with NumLock off, by digit (`winuser.h`): `VK_INSERT`, `VK_END`, /// `VK_DOWN`, `VK_NEXT`, `VK_LEFT`, `VK_CLEAR`, `VK_RIGHT`, `VK_HOME`, `VK_UP` and `VK_PRIOR`. const NUMLOCK_OFF_KEYS: [usize; 10] = [0x2D, 0x23, 0x28, 0x22, 0x25, 0x0C, 0x27, 0x24, 0x26, 0x21]; -/// The keys egui reports for the keypad with NumLock off, by digit (Clear has no egui key, so it -/// comes as the top-row digit key, `Num5`). -const NUMLOCK_OFF_EGUI_KEYS: [Key; 10] = - [Key::Insert, Key::End, Key::ArrowDown, Key::PageDown, Key::ArrowLeft, Key::Num5, Key::ArrowRight, Key::Home, Key::ArrowUp, Key::PageUp]; -const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; +/// The physical keys egui reports for the keypad's keys, by digit, with NumLock on or off. +const KEYPAD_KEYS: [Key; 10] = + [Key::Numpad0, Key::Numpad1, Key::Numpad2, Key::Numpad3, Key::Numpad4, Key::Numpad5, Key::Numpad6, Key::Numpad7, Key::Numpad8, Key::Numpad9]; /// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the /// keypad (the keypad's own keys clear it). const EXTENDED_KEY: isize = 1 << 24; @@ -53,7 +57,7 @@ thread_local! { static CODES: RefCell = RefCell::new(AltCodes::default()); } -/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue. +/// The keypad digits of Alt + keypad codes, from the keyboard messages of the thread's queue. #[derive(Default)] struct AltCodes { /// The digits of the keypad presses and releases with Alt held since the last frame, which @@ -86,23 +90,27 @@ impl AltCodes { } } - /// Take out of the frame `events` the keypad digits typed with Alt held since the last frame. - /// The character a code types comes from winit, as typed text. - fn drain(&mut self, events: &mut Vec) { + /// Take the keypad digits typed with Alt held since the last frame out of the frame `events`. + /// The characters the codes type stay in `events` as winit reported them. Returns whether it + /// took any digit out. + fn drain(&mut self, events: &mut Vec) -> bool { let mut keypad = std::mem::take(&mut self.keypad_events); if keypad.is_empty() { - return; + return false; } + let before = events.len(); events.retain(|e| { - let Event::Key { key, modifiers, .. } = e else { + let Event::Key { physical_key, modifiers, .. } = e else { return true; }; if !modifiers.alt { return true; } - // The first keypad key still to take out that egui reports as `key`. - let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); - match keypad.iter().position(stands_for) { + // The first keypad key still to take out on the physical key `physical_key`. egui reports a + // keypad digit as the same logical key as the top-row digit, so a top-row Alt and digit in + // the same frame is left in the frame. + let on_key = |d: &usize| KEYPAD_KEYS.get(*d).is_some_and(|k| *physical_key == Some(*k)); + match keypad.iter().position(on_key) { Some(i) => { keypad.remove(i); false @@ -110,6 +118,7 @@ impl AltCodes { None => true, } }); + events.len() < before } } @@ -135,13 +144,14 @@ pub fn msg_hook(msg: *const std::ffi::c_void) { } } -/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out. -pub fn raw_input_hook(raw: &mut egui::RawInput) { - CODES.with(|c| { - if let Ok(mut c) = c.try_borrow_mut() { - c.drain(&mut raw.events); - } - }); +/// Before egui reads the main window's frame: takes the keypad digits typed with Alt held out of +/// it. When it takes any out, it tells the framework in `ctx` that the Alt hold had digits typed in +/// it. +pub fn raw_input_hook(ctx: &egui::Context, raw: &mut egui::RawInput) { + let taken = CODES.with(|c| c.try_borrow_mut().is_ok_and(|mut c| c.drain(&mut raw.events))); + if taken { + craft::ui::runtime::egui::input::alt_code_digits_taken(ctx, raw.viewport_id); + } } #[cfg(test)] @@ -165,43 +175,76 @@ mod tests { c.message(WM_CHAR, usize::from(posted), 0); } + /// The top-row digit keys, by digit: the logical keys egui reports for the keypad digits with + /// NumLock on. + const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; + + /// A key that is not on the keypad: egui reports `key` as both its logical and its physical key. fn key(key: Key, alt: bool, pressed: bool) -> Event { let modifiers = egui::Modifiers { alt, ..Default::default() }; Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers } } - #[test] - fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() { - let mut c = AltCodes::default(); - alt_code(&mut c, "0176", 0xB0); - alt_code(&mut c, "0151", 0x2014); - // winit reports each code's character as typed text. - let mut events = vec![ - key(Key::Num0, true, true), - key(Key::Num0, true, false), - key(Key::Num1, false, true), - Event::Text("°".into()), - Event::Text("—".into()), - ]; - c.drain(&mut events); - // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); - // the digit typed without Alt stays, and each character stays once. - assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]); - let mut events = vec![key(Key::Num0, true, true)]; - c.drain(&mut events); - assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); + /// The keypad's key for digit `d`, which egui reports as the logical key `key`. + fn keypad_key(key: Key, d: usize, alt: bool, pressed: bool) -> Event { + let modifiers = egui::Modifiers { alt, ..Default::default() }; + Event::Key { key, physical_key: Some(KEYPAD_KEYS[d]), pressed, repeat: false, modifiers } + } + + /// The keypad digit `d` with NumLock on. + fn keypad(d: usize, alt: bool, pressed: bool) -> Event { + keypad_key(DIGIT_KEYS[d], d, alt, pressed) } #[test] - fn characters_are_left_to_winit() { + fn an_alt_codes_keypad_digits_are_taken_out_and_its_character_stays() { let mut c = AltCodes::default(); - // A plain key press's character, Alt pressed and released alone, and a code's character. + alt_code(&mut c, "0176", 0xB0); + alt_code(&mut c, "0151", 0x2014); + // The characters as winit reports them after each Alt release. + let mut events = + vec![keypad(0, true, true), keypad(0, true, false), keypad(1, false, true), Event::Text("°".into()), Event::Text("—".into())]; + assert!(c.drain(&mut events)); + // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); + // the digit typed without Alt and the characters stay, each once. + assert_eq!(events, vec![keypad(1, false, true), Event::Text("°".into()), Event::Text("—".into())]); + let mut events = vec![keypad(0, true, true)]; + assert!(!c.drain(&mut events)); + assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); + } + + /// egui reports keypad 2 and the top-row 2 as the same logical key. When both come with Alt in + /// one frame, the keypad 2 is taken out and the top-row 2 stays for the shortcuts, whichever + /// comes first. + #[test] + fn a_top_row_alt_digit_in_the_same_frame_stays() { + let mut c = AltCodes::default(); + c.message(WM_SYSKEYDOWN, ALT, 0); + c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 2, 0); + let mut events = vec![key(Key::Num2, true, true), keypad(2, true, true)]; + assert!(c.drain(&mut events)); + assert_eq!(events, vec![key(Key::Num2, true, true)]); + + c.message(WM_SYSKEYUP, VK_NUMPAD0 + 2, 0); + let mut events = vec![keypad(2, true, false), key(Key::Num2, true, false)]; + assert!(c.drain(&mut events)); + assert_eq!(events, vec![key(Key::Num2, true, false)]); + } + + /// winit reports the character a code types, so the hook adds none of its own: a code's + /// `WM_CHAR`, the two halves of a code above the basic plane, and a character without a code + /// before it give the frame no text. + #[test] + fn the_hook_types_no_character_of_its_own() { + let mut c = AltCodes::default(); + alt_code(&mut c, "0176", 0xB0); + c.message(WM_SYSKEYDOWN, ALT, 0); + c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); + c.message(WM_KEYUP, ALT, 0); + c.message(WM_CHAR, 0xD83D, 0); + c.message(WM_CHAR, 0xDE00, 0); c.message(WM_KEYDOWN, 0x41, 0); c.message(WM_CHAR, usize::from(b'a'), 0); - c.message(WM_SYSKEYDOWN, ALT, 0); - c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, usize::from(b'b'), 0); - alt_code(&mut c, "0176", 0xB0); let mut events = vec![]; c.drain(&mut events); assert!(events.is_empty(), "{events:?}"); @@ -215,7 +258,7 @@ mod tests { // Alt+F: a shortcut, not a code. c.message(WM_SYSKEYDOWN, 0x46, 0); c.message(WM_KEYUP, ALT, 0); - let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)]; + let mut events = vec![keypad(1, true, true), key(Key::F, true, true)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::F, true, true)]); } @@ -238,15 +281,16 @@ mod tests { let mut c = AltCodes::default(); alt_code_numlock_off(&mut c, "0176", 0xB0); // What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a - // release each, then a plain Home typed after Alt came up. + // release each, then the character winit reports and a plain Home typed after Alt came up. let mut events = vec![]; - for k in [Key::Insert, Key::End, Key::Home, Key::ArrowRight] { - events.push(key(k, true, true)); - events.push(key(k, true, false)); + for (k, d) in [(Key::Insert, 0), (Key::End, 1), (Key::Home, 7), (Key::ArrowRight, 6)] { + events.push(keypad_key(k, d, true, true)); + events.push(keypad_key(k, d, true, false)); } + events.push(Event::Text("°".into())); events.push(key(Key::Home, false, true)); c.drain(&mut events); - assert_eq!(events, vec![key(Key::Home, false, true)]); + assert_eq!(events, vec![Event::Text("°".into()), key(Key::Home, false, true)]); } #[test] @@ -256,10 +300,16 @@ mod tests { // 0234 uses Insert, Down, Page Down and Left. alt_code_numlock_off(&mut c, "0151", 0x2014); alt_code_numlock_off(&mut c, "0234", 0xEA); - let mut events = - vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)]; + let mut events = vec![ + keypad_key(Key::Num5, 5, true, true), + Event::Text("—".into()), + keypad_key(Key::ArrowDown, 2, true, true), + keypad_key(Key::PageDown, 3, true, true), + keypad_key(Key::ArrowLeft, 4, true, true), + Event::Text("ê".into()), + ]; c.drain(&mut events); - assert!(events.is_empty(), "{events:?}"); + assert_eq!(events, vec![Event::Text("—".into()), Event::Text("ê".into())]); } #[test] @@ -272,11 +322,82 @@ mod tests { c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_KEYUP, ALT, 0); - let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; + let mut events = + vec![keypad_key(Key::End, 1, true, true), keypad_key(Key::End, 1, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]); } + /// One frame of the framework's test window: Windows' key `messages` reach [`msg_hook`]'s + /// state, then `events` pass through [`raw_input_hook`] before the frame reads them. + fn hooked_frame(frames: &mut craft::ui::testing::Frames, show: &mut dyn FnMut(&mut egui::Ui), messages: &[(u32, usize)], events: Vec) { + CODES.with(|c| { + let mut c = c.borrow_mut(); + for &(message, wparam) in messages { + c.message(message, wparam, 0); + } + }); + let mut raw = egui::RawInput { events, ..Default::default() }; + raw_input_hook(&frames.ctx, &mut raw); + frames.frame(raw.events, &mut *show); + } + + /// After a code Windows composed, the framework does not read Alt's release as a lone Alt: a + /// tool that claims the Alt tap gets none, and the code's character, which winit reports after + /// the release, is typed once. A lone Alt after it is a tap again. + #[test] + fn the_alt_release_after_a_composed_code_is_no_lone_alt() { + use craft::ui::runtime::env::{AltCodeKeys, RootEnv}; + use craft::ui::runtime::keys::{claim_alt_tap, take_alt_tap}; + use std::cell::Cell; + use std::rc::Rc; + + let mut frames = craft::ui::testing::Frames::new(); + craft::ui::testing::windows::set_os(&frames.ctx, craft::host::target::Os::Windows); + frames.root(RootEnv::default().alt_code_keys(AltCodeKeys::Keypad)); + let tool = craft::ui::testing::focus::named_id("alt tap tool"); + let (taps, text) = (Rc::new(Cell::new(0)), Rc::new(RefCell::new(String::new()))); + let mut show = { + let (taps, text) = (Rc::clone(&taps), Rc::clone(&text)); + move |ui: &mut egui::Ui| { + taps.set(taps.get() + usize::from(take_alt_tap(ui.ctx(), tool))); + claim_alt_tap(ui.ctx(), tool); + ui.input(|input| { + for event in &input.events { + if let Event::Text(t) = event { + text.borrow_mut().push_str(t); + } + } + }); + } + }; + frames.frame(vec![], &mut show); + frames.frame(vec![], &mut show); + + let alt = |down: bool| Event::ModifiersChanged(if down { egui::Modifiers::ALT } else { egui::Modifiers::NONE }); + let keypad = |d: usize, pressed: bool| Event::Key { + key: DIGIT_KEYS[d], + physical_key: Some(KEYPAD_KEYS[d]), + pressed, + repeat: false, + modifiers: egui::Modifiers::ALT, + }; + hooked_frame(&mut frames, &mut show, &[(WM_SYSKEYDOWN, ALT)], vec![alt(true)]); + for d in [0, 2, 3, 3] { + let vk = VK_NUMPAD0 + d; + hooked_frame(&mut frames, &mut show, &[(WM_SYSKEYDOWN, vk), (WM_SYSKEYUP, vk)], vec![keypad(d, true), keypad(d, false)]); + } + // Alt's release, then the character winit reports for the `WM_CHAR` that follows it. + hooked_frame(&mut frames, &mut show, &[(WM_KEYUP, ALT), (WM_CHAR, 0xE9)], vec![alt(false), Event::Text("é".into())]); + frames.frame(vec![], &mut show); + assert_eq!((taps.get(), text.take()), (0, "é".to_owned()), "the code's Alt release is no Alt tap, and its character is typed once"); + + hooked_frame(&mut frames, &mut show, &[(WM_SYSKEYDOWN, ALT)], vec![alt(true)]); + hooked_frame(&mut frames, &mut show, &[(WM_KEYUP, ALT)], vec![alt(false)]); + frames.frame(vec![], &mut show); + assert_eq!(taps.get(), 1, "a lone Alt after the code is a tap"); + } + #[test] fn numlock_off_keys_without_alt_are_left_alone() { let mut c = AltCodes::default(); diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index ae5b2d5804..5faad39835 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -140,6 +140,12 @@ fn units_choose_the_default_scale() { assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); } + // Miles and kilometers have no unit of their own, so they read as millimeters at their scale. + for (code, name, pt) in [("3", "Miles", 72.0 * 63_360.0), ("7", "Kilometers", 72.0 / 0.0254 * 1e3)] { + let i = info(&drawing(&[(9, "$INSUNITS"), (70, code)], &[], &[], LINE)).unwrap(); + assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); + assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); + } let survey_in = open(&drawing(&[(9, "$INSUNITS"), (70, "22")], &[], &[], LINE), &ImportOptions::default()).document; assert!((survey_in.artboards[0].rect.width() - 7200.0144000288).abs() < 1e-6, "{:?}", survey_in.artboards[0].rect); let imperial = info(&drawing(&[(9, "$MEASUREMENT"), (70, "0")], &[], &[], LINE)).unwrap(); diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 75a5fdc2a5..e7c613bf56 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -197,6 +197,11 @@ mod tests { assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary"); assert_eq!(Harmony::HighContrast3.id(), "highContrast3"); assert_eq!(parse("square"), None); + // The labels are written here and the ids come from the framework: a few shown labels read + // back as their rules. + for h in [Harmony::LeftComplement, Harmony::Monochromatic, Harmony::Compound2, Harmony::Pentagram] { + assert_eq!(parse(label(h)), Some(h), "{}", label(h)); + } } #[test] diff --git a/crates/doc/src/decode.rs b/crates/doc/src/decode.rs index 11d1b2d72b..f06ea81b00 100644 --- a/crates/doc/src/decode.rs +++ b/crates/doc/src/decode.rs @@ -2,6 +2,17 @@ //! File › Open and Place, SVG import, and embedded and linked images read their pixels with //! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`]. +thread_local! { + /// Images [`decode_image`] has decoded, or tried, on this thread ([`decodes`]). + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many images [`decode_image`] has decoded on this thread so far, failed decodes included. +/// Images other threads decode are not counted. +pub fn decodes() -> u64 { + DECODES.with(std::cell::Cell::get) +} + /// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds. pub type DecodedImage = (image::DynamicImage, Option>); @@ -10,6 +21,7 @@ pub type DecodedImage = (image::DynamicImage, Option>); /// The renderer, File › Open and Place, SVG import, and embedded and linked images read images /// with it. pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result { + DECODES.with(|n| n.set(n.get() + 1)); let opts = craft_image_codecs::DecodeOptions { limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance }, keep_orientation: true, diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 2a92cfb160..0c01fe03d6 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -669,9 +669,7 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & { return false; } - // How a click reaches it, if one does. let start = opt; - let Some(opt) = path_options(&nodes, &chain, opt) else { return false }; // Hidden by a mask: one of the containers around it clips, and not to `p`. A container // tests its clipping path in outline from the first layer with Preview off down to it, as // a click going down to it does ([`path_options`]). @@ -680,13 +678,19 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n))); n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline)) }); + // Art no mask hides doesn't count, so how a click reaches it is not looked up. + if !masked { + return false; + } + // How a click reaches it, if one does. + let Some(opt) = path_options(&nodes, &chain, start) else { return false }; // A click may reach it there ([`may_hit`]: not a guide while guides are locked or // hidden, nor a Shaper group's hidden part), and its own art is what a click would hit // in it: a group's hidden, locked or masked contents don't count. let [.., parent, n] = nodes.as_slice() else { return false }; let reachable = parent.children().and_then(|c| c.iter().position(|c| c.id == id)).is_some_and(|i| may_hit(parent, i, n, p, opt, &symbols, true)); - masked && reachable && object_hit(n, p, opt, &symbols, true) + reachable && object_hit(n, p, opt, &symbols, true) }) } @@ -695,6 +699,8 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & /// below a layer whose Preview is off. `None` when a Shaper group's part it can't reach lies on /// the way ([`shaper_hides`]). fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option { + #[cfg(test)] + PATHS_CHECKED.with(|c| c.set(c.get() + 1)); let scope_at = opt.scope.and_then(|s| chain.iter().position(|a| *a == s)); let child_index = |parent: &Node, child: &Node| parent.children().and_then(|c| c.iter().position(|c| c.id == child.id)); let hidden = nodes.windows(2).skip(scope_at.unwrap_or(0)).any(|w| match w { @@ -710,6 +716,12 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option = const { std::cell::Cell::new(0) }; +} + /// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost /// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind). pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option) -> Vec { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index a678797ff5..dc1e28cc6c 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1059,6 +1059,63 @@ fn a_selected_objects_art_hidden_by_a_mask_is_found_under_the_pointer() { assert_eq!(selected_hidden_at(&d, hidden, opt, &[art_id]), Some(art_id)); } +/// How a click reaches a selected object, which searches its parents' children, is looked up +/// only when a mask around it hides its art under the pointer: a press beside thousands of +/// selected objects under no clip looks up none of them. Art that one of several nested clip +/// groups hides is still found, also below thousands of selected objects no mask hides. +#[test] +fn only_selected_objects_a_mask_hides_are_checked_for_a_click_reaching_them() { + let count = |d: &Document, p: Point, selected: &[NodeId]| { + PATHS_CHECKED.with(|c| c.set(0)); + let found = selected_hidden_at(d, p, HitOptions::default(), selected); + (found, PATHS_CHECKED.with(std::cell::Cell::get)) + }; + // `art` (0..200 × 0..100) in five nested clip groups, each clipping to 0..200 but the one at + // `narrow` (counted from the inside), which clips to 0..100 and so hides the art at (150, 50). + let nested = |narrow: Option| { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::default_art()); + let art_id = art.id; + let mut inner = art; + for depth in 0..5 { + let right = if narrow == Some(depth) { 100.0 } else { 200.0 }; + let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, right, 100.0)), Appearance::default()); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(inner)]); + g.set_clips(true); + inner = g; + } + d.insert(Some(l), 0, inner).unwrap(); + (d, l, art_id) + }; + // 3,000 selected squares (0..10 × 0..10) on the layer, after whatever it holds. + let squares = |d: &mut Document, l: NodeId| { + let at = d.node(l).and_then(|n| n.children()).map_or(0, Vec::len); + (0..3000) + .map(|i| { + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + d.insert(Some(l), at + i, square).unwrap() + }) + .collect::>() + }; + let p = Point::new(150.0, 50.0); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let flat = squares(&mut d, l); + assert_eq!(count(&d, p, &flat), (None, 0), "a press beside them"); + assert_eq!(count(&d, Point::new(5.0, 5.0), &flat), (None, 0), "a press on them"); + let (d, _, art_id) = nested(None); + assert_eq!(count(&d, p, &[art_id]), (None, 0), "no clip hides it"); + for depth in 0..5 { + let (d, _, art_id) = nested(Some(depth)); + assert_eq!(count(&d, p, &[art_id]), (Some(art_id), 1), "hidden by the clip group {depth} levels out"); + } + let (mut d, l, art_id) = nested(Some(2)); + let mut selected = vec![art_id]; + selected.extend(squares(&mut d, l)); + assert_eq!(count(&d, p, &selected), (Some(art_id), 1), "below the squares"); +} + /// A selected group's own art is what a click would hit in it: not a hidden or locked child, nor /// art its own clipping mask hides, all under the pointer where an outer mask hides them. #[test] diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 4f19f09a5a..73321a7e09 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -43,8 +43,8 @@ pub(crate) fn catalog() -> Vec { id: HALFTONE, label: "Vector Halftone…", menu: &["Effect", "Color Effects"], - params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", - defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; a named style sets the shape and angle over the stored ones: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°; effect.apply and effect.setParams refuse an unknown style), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + defaults: json!({"shape": "circle", "style": "custom", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), raster: false, lengths: Lengths::default(), }] @@ -71,6 +71,23 @@ pub enum DotShape { Elliptical, } +/// The named styles: each sets a dot shape and a screen angle. +pub const STYLES: [(&str, DotShape, f64); 4] = [ + ("grid", DotShape::Euclidean, 0.0), + ("gridAngle", DotShape::Euclidean, 45.0), + ("gridDots", DotShape::Circle, 0.0), + ("gridDotsAngle", DotShape::Circle, 45.0), +]; + +/// The shape and angle of style `s`: `Some(None)` for `custom` (the shape and angle as given), +/// `None` for an unknown style. +pub fn style(s: &str) -> Option> { + if s.eq_ignore_ascii_case("custom") { + return Some(None); + } + STYLES.iter().find(|(name, ..)| name.eq_ignore_ascii_case(s)).map(|&(_, shape, angle)| Some((shape, angle))) +} + impl DotShape { pub fn parse(s: &str) -> Option { Some(match s.to_ascii_lowercase().as_str() { @@ -89,6 +106,10 @@ impl DotShape { /// running along x. fn path(self, t: f64, s: f64) -> PathData { let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side))); + // A full-tone dot is the cell itself; Line keeps its overlap along the row. + if t >= 1.0 && self != DotShape::Line { + return square(s); + } match self { DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle), DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse), @@ -413,6 +434,12 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { let i = (x.floor() as usize).min(SIZE_STEPS - 1); let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); let r = lo + (hi - lo) * (x - i as f64); + if matches!(kind, CellKind::Circle | CellKind::Ellipse) { + let (a, b) = if matches!(kind, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) }; + if t > 0.0 && a <= 1.0 && b <= 1.0 { + return shapes::ellipse(Rect::new(-a * h, -b * h, a * h, b * h)); + } + } let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h)); PathData::from_bezpath(&four_quadrants(&q1)) } @@ -423,8 +450,13 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { fn four_quadrants(q1: &[CubicBez]) -> BezPath { let mut bp = BezPath::new(); let mut end: Option = None; + // A piece lying on an axis would be drawn back over by its mirror image, so it is left out. + let on_axis = |c: &CubicBez| { + let pts = [c.p0, c.p1, c.p2, c.p3]; + pts.iter().all(|p| p.x.abs() < 1e-9) || pts.iter().all(|p| p.y.abs() < 1e-9) + }; let mut add = |curves: Vec| { - for (k, c) in curves.iter().enumerate() { + for (k, c) in curves.iter().filter(|c| !on_axis(c)).enumerate() { if k == 0 { match end { None => bp.move_to(c.p0), @@ -440,7 +472,9 @@ fn four_quadrants(q1: &[CubicBez]) -> BezPath { add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y)))); add(mapped(q1, |p| Point::new(-p.x, -p.y))); add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y)))); - bp.close_path(); + if end.is_some() { + bp.close_path(); + } bp } @@ -540,10 +574,12 @@ impl Halftone { } fn from_params(p: &Value) -> Self { + // A named style sets the shape and angle over the stored ones (which hold the defaults). + let styled = style(text(p, "style", "custom")).flatten(); Self { - shape: DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), + shape: styled.map_or_else(|| DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), |s| s.0), frequency: num(p, "frequency", 20.0).clamp(1.0, 300.0), - angle: num(p, "angle", 45.0), + angle: styled.map_or_else(|| num(p, "angle", 45.0), |s| s.1), mono: !text(p, "mode", "mono").eq_ignore_ascii_case("cmyk"), color: crate::raster::color_param(p, Color::BLACK), from_art: flag(p, "fromArt", false), @@ -781,6 +817,46 @@ mod tests { assert_eq!(h.color, Color::BLACK); } + #[test] + fn round_dots_inside_the_cell_have_four_anchors() { + for (shape, tone) in [(DotShape::Circle, 0.5), (DotShape::Ellipse, 0.3)] { + let dot = shape.path(tone, 10.0); + assert_eq!(dot.subpaths.len(), 1, "{shape:?}"); + let sp = &dot.subpaths[0]; + assert!(sp.closed, "{shape:?}"); + assert_eq!(sp.anchors.len(), 4, "{shape:?}: {:?}", sp.anchors); + } + } + + /// Dots whose quadrants meet on the axes have no extra anchors at the joins: a Circle dot small + /// enough to stay inside its cell has the anchors of its arcs only, all distinct. + #[test] + fn dot_quadrants_join_without_extra_anchors() { + let dot = DotShape::Circle.path(0.2, 10.0); + let anchors: Vec = dot.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(); + for (i, a) in anchors.iter().enumerate() { + assert!(anchors[i + 1..].iter().all(|b| a.distance(*b) > 1e-6), "{anchors:?}"); + } + for shape in [DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + for t in [0.2, 0.6, 0.9] { + for sp in &shape.path(t, 10.0).subpaths { + let n = sp.anchors.len(); + for i in 0..n { + let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p); + assert!(n < 2 || a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors); + } + } + } + } + } + + #[test] + fn zero_tone_quadrant_dots_have_empty_paths() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + assert!(shape.path(0.0, 10.0).is_empty(), "{shape:?}"); + } + } + #[test] fn values_out_of_range_are_brought_in() { let h = Halftone::of(&effect(json!({"frequency": 1e308, "angle": "NaN", "shape": 7, "mode": "CMYK", "color": "nope"}))).unwrap(); @@ -817,6 +893,51 @@ mod tests { fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1)) } + #[test] + fn grid_dots_fill_the_cell_at_full_tone() { + for name in ["gridDots", "gridDotsAngle"] { + let Some(Some((shape, _))) = style(name) else { panic!("{name} is not a style") }; + // At 100% the cell's corners are covered, so neighboring cells leave no holes. + assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{name}"); + // Below it the corners stay light. + assert!(!covers(shape, 0.9, (0.49, 0.49)), "{name}"); + } + } + + #[test] + fn full_tone_dots_have_exactly_the_cell_corners() { + let Some(Some((grid_dots, _))) = style("gridDots") else { panic!("gridDots is not a style") }; + let corners = [Point::new(-5.0, -5.0), Point::new(5.0, -5.0), Point::new(5.0, 5.0), Point::new(-5.0, 5.0)]; + for shape in [grid_dots, DotShape::Ellipse, DotShape::Square, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + let dot = shape.path(1.0, 10.0); + assert_eq!(dot.subpaths.len(), 1, "{shape:?}"); + let sp = &dot.subpaths[0]; + assert!(sp.closed, "{shape:?}"); + let anchors: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert_eq!(anchors.len(), 4, "{shape:?}: {anchors:?}"); + for corner in corners { + assert!(anchors.contains(&corner), "{shape:?}: {anchors:?}"); + } + } + } + + #[test] + fn styles_set_the_shape_and_angle() { + let defaults = crate::effect_info(HALFTONE).unwrap().defaults; + let with = |style: &str| { + let mut p = defaults.clone(); + p["style"] = json!(style); + let h = Halftone::of(&effect(p)).unwrap(); + (h.shape, h.angle) + }; + assert_eq!(with("grid"), (DotShape::Euclidean, 0.0)); + assert_eq!(with("gridAngle"), (DotShape::Euclidean, 45.0)); + assert_eq!(with("gridDots"), (DotShape::Circle, 0.0)); + assert_eq!(with("custom"), (DotShape::Circle, 45.0)); + assert_eq!(with("checker"), (DotShape::Circle, 45.0)); + assert_eq!((style("GRIDDOTS"), style("custom"), style("checker")), (Some(Some((DotShape::Circle, 0.0))), Some(None), None)); + } + #[test] fn spot_dots_cover_the_tone() { for shape in [DotShape::Euclidean, DotShape::Elliptical] { diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 474a6c0a0c..c07f3b0413 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,29 +241,29 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", - json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}), + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", - json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", - json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).", + json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", - json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( CLASSIC_EXTRUDE, diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index f4d05db96f..aef398c64e 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -98,13 +98,13 @@ pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, }; pub use solids::{ - BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, - RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, - classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, - mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, - solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, - three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, - validate_three_d_params, view_options, with_graphic, + BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic, + MeshGraphics, RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, + classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, + is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, + rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, + three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, + validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, }; pub use solids::{ GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 697a217da9..9ce14bbf47 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -136,6 +136,82 @@ pub(crate) fn facet_art( composed_art(id, path, paint, Ramp::Rgb(light), seam) } +/// The fills that screen `highlight`, the light a material reflects over a face's paint, over that +/// paint: one gray ramp when its three channels match, else one ramp per channel in that channel's +/// primary (Screen of disjoint primaries adds each channel on its own), or one flat color without +/// a ramp. A channel with no light anywhere on the face takes no fill. +fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec { + use vectorcraft_doc::color::BlendMode; + let screen = |paint: Paint| { + let mut fill = FillLayer::new(paint); + fill.blend = BlendMode::Screen; + AppearanceItem::Fill(fill) + }; + let lit = |g: &vectorcraft_three_d::ShadeGradient| g.brightness.iter().any(|b| *b > 0.0); + let Some(ramp) = highlight.ramp else { + let [r, g, b] = highlight.flat.map(|v| v.clamp(0.0, 1.0) as f32); + return if r > 0.0 || g > 0.0 || b > 0.0 { vec![screen(Paint::solid(Color::rgb(r, g, b)))] } else { vec![] }; + }; + let [r, g, b] = ramp.channels; + if r == g && g == b { + let light = vectorcraft_three_d::LightGradient { diffuse: r, ambient: 0.0, color: [1.0; 3] }; + return if lit(&r) { vec![screen(smooth_paint(light, Color::WHITE))] } else { vec![] }; + } + ramp.channels + .iter() + .enumerate() + .filter(|(_, g)| lit(g)) + .map(|(channel, g)| { + let mut color = [0.0; 3]; + if let Some(value) = color.get_mut(channel) { + *value = 1.0; + } + screen(smooth_paint(vectorcraft_three_d::LightGradient { diffuse: *g, ambient: 0.0, color }, Color::WHITE)) + }) + .collect() +} + +/// The path that screens `highlight` over a face of outline `path` closed by a seam `seam` wide: +/// the highlight's fills ([`highlight_fills`]) on the face and its seam ([`seamed_fill`], else the +/// outline alone). `None` without a highlight or when it holds no light. +pub(crate) fn highlight_over( + id: vectorcraft_doc::NodeId, + path: &vectorcraft_geom::PathData, + seam: f64, + highlight: Option, +) -> Option { + let items = highlight.map(highlight_fills).unwrap_or_default(); + if items.is_empty() { + return None; + } + let shape = seamed_fill(path, seam).unwrap_or_else(|| path.clone()); + Some(vectorcraft_doc::Node::path(id, shape, vectorcraft_doc::Appearance { items, ..Default::default() })) +} + +/// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight` +/// screened over it: a group of the face and the highlight's path on the face and its seam +/// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the +/// highlight too. `face` may hold the parts of graphics drawn on it: the highlight then lies over +/// them too. `face` as it is without a highlight or when it holds no light. The face is drawn +/// opaque: a transparent paint's coverage is a mask over the whole surface +/// ([`opaque_surface_paint`]), so the highlight and the face take it once. +pub(crate) fn highlighted( + id: vectorcraft_doc::NodeId, + mut face: vectorcraft_doc::Node, + path: &vectorcraft_geom::PathData, + seam: f64, + highlight: Option, +) -> vectorcraft_doc::Node { + use std::sync::Arc; + let Some(over) = highlight_over(id, path, seam, highlight) else { return face }; + let mask = if face.extras().mask.is_some() { face.extras_mut().mask.take() } else { None }; + let mut group = vectorcraft_doc::Node::group(id, vec![Arc::new(face), Arc::new(over)]); + if mask.is_some() { + group.extras_mut().mask = mask; + } + group +} + /// The width of the seam stroke of a facet's underlay: a round stroke that reaches 1 pt past each /// edge, over the pixels that the antialiased edges of two neighboring facets each cover only in /// part at 1:1. A clip to the surface's outline removes what it paints past the surface. @@ -231,17 +307,22 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio /// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed /// in a clip of its footprint, neither with an opacity mask. A face drawn with the parts of Inflate's /// graphics on it, a group of the facet and those parts, takes its facet's underlay and stays in the -/// order with its parts, which are cut to the facet's outline, so the clip keeps them. +/// order with its parts, which are cut to the facet's outline, so the clip keeps them. So does a +/// facet with a material's highlight screened over it ([`highlighted`]), which lies on the facet +/// and its seam. pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc]) -> Option { use std::sync::Arc; use vectorcraft_doc::{Node, NodeKind}; - let facets: Vec> = faces - .iter() - .map(|face| match &face.kind { - NodeKind::Group { children, clip: false } if face.extras().mask.is_none() => children.first().cloned(), - _ => Some(face.clone()), - }) - .collect::>()?; + let facet = |face: &Arc| { + let mut facet = face.clone(); + while let NodeKind::Group { children, clip: false } = &facet.kind + && facet.extras().mask.is_none() + { + facet = children.first()?.clone(); + } + Some(facet) + }; + let facets: Vec> = faces.iter().map(facet).collect::>()?; let (clip, mut underlay) = underlay(id, &facets)?; underlay.extend(faces.iter().cloned()); Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index dfaf8c35e6..5d49c52de2 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -103,6 +103,7 @@ pub fn revolve_options(p: &Value) -> Revolve { light_softness: num(p, "lightSoftness", 0.0) / 100.0, ambient: num(p, "ambient", 25.0) / 100.0, shade: flag(p, "shade", true), + material: crate::solids::material::read(p), smooth_shading: true, cap_ends: flag(p, "cap", true), fill_rule: FillRule::NonZero, @@ -316,9 +317,10 @@ fn paint_copies(faces: usize, paint: &Paint) -> usize { faces.saturating_mul(4).saturating_mul(paint_bytes(paint)) } -/// Do Revolve's `options` light its surface with colored lights? +/// Do Revolve's `options` light its surface with colored lights, or with a material other than the +/// default, which also shades in RGB? fn colored(options: &Revolve) -> bool { - options.light_color != [1.0; 3] || options.lights.is_some() + options.light_color != [1.0; 3] || options.lights.is_some() || (options.shade && !options.material.is_default()) } /// Do Revolve's `faces` in `paint` lie over an underlay of themselves ([`sealed_run`])? Under @@ -382,6 +384,7 @@ pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> { validate_revolve_params(p)?; crate::solids::graphics::validate(id, p)?; crate::solids::wireframe::validate_render(id, p)?; + crate::solids::material::validate(id, p)?; if id == CLASSIC_REVOLVE { classic::validate(p)?; } @@ -487,6 +490,8 @@ fn group_shadow( /// Geometry does ([`crate::solids::classic::surface`]). The last two values are whether the faces /// go over an underlay of themselves ([`seals`]): the caller seals them ([`sealed_surface`], /// [`sealed_runs`]) in the order it draws them; and whether the faces were left out. +/// A surface painted with a pattern takes no material highlight: a white coverage paint does not +/// keep the transparency of the pattern's tiles. #[allow(clippy::too_many_arguments, clippy::type_complexity)] fn surface( doc: Option<&Document>, @@ -551,6 +556,16 @@ fn surface( if copies.surfaces > MAX_PAINT_COPIES { return None; } + // Under a material's highlight the faces are drawn opaque under one mask of a transparent + // paint's coverage ([`crate::lighting::opaque_surface_paint`]), so the faces and their + // highlights take that coverage once. + let (paint, mask) = if options.shade && !options.material.is_default() { + crate::lighting::opaque_surface_paint(&paint, || { + faces.iter().filter_map(|f| f.path().bounds()).reduce(|a, b| a.union(b)).unwrap_or(Rect::ZERO) + }) + } else { + (paint, None) + }; let order = crate::solids::surface_order(faces.iter().map(|f| (f.points.as_slice(), f.plane, f.depth))); let faces = in_order(faces, &order); let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)); @@ -600,11 +615,14 @@ fn surface( illumination: f.illumination, light_gradient: f.light_gradient, rgb_gradient: f.rgb_gradient, + highlight: f.highlight, }) .collect(); (faces, keys) } }; + // A material's highlight goes over each face and the parts of graphics drawn on it. + let lights: Vec<_> = faces.iter().map(|face| (face.path.clone(), face.highlight)).collect(); let children = faces .into_iter() .map(|face| { @@ -667,9 +685,25 @@ fn surface( } else { children }; + let children = children + .into_iter() + .zip(lights) + .map(|(face, (path, highlight))| { + if highlight.is_none() || matches!(paint, Paint::Pattern { .. }) { + return face; + } + let face = Arc::unwrap_or_clone(face); + Arc::new(crate::lighting::highlighted(n.id, face, &path, SEAM_WIDTH, highlight)) + }) + .collect(); let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; + if let Some(mask) = mask { + let bounds = group.visual_bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0); + let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0)); + group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true))); + } Some((keys, group, kept, seal, false)) } @@ -689,13 +723,14 @@ fn sealed_surface(id: NodeId, surface: Node, seal: bool) -> Node { /// order with its part; the part is cut to its face's outline ([`crate::solids::graphics::surface_parts`]), /// so the clip keeps it. `None` when [`crate::lighting::underlay`] does not take the faces. fn sealed_run(id: NodeId, run: &[Arc]) -> Option { - let faces: Vec> = run - .iter() - .map(|face| match &face.kind { - NodeKind::Group { children, clip: false } => children.first().cloned(), - _ => Some(face.clone()), - }) - .collect::>()?; + let facet = |face: &Arc| { + let mut facet = face.clone(); + while let NodeKind::Group { children, clip: false } = &facet.kind { + facet = children.first()?.clone(); + } + Some(facet) + }; + let faces: Vec> = run.iter().map(facet).collect::>()?; if faces.is_empty() { return None; } @@ -881,6 +916,21 @@ fn surface_meshes( options: Revolve, (paint, opacity, member): (&Paint, f32, f32), graphics: bool, +) -> Result, String> { + let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params)); + surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics) + .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, ..m }).collect()) +} + +/// [`surface_meshes`] in the default material. +fn surface_meshes_of( + path: &PathData, + rule: FillRule, + b: Rect, + fx: &Effect, + options: Revolve, + (paint, opacity, member): (&Paint, f32, f32), + graphics: bool, ) -> Result, String> { let color = crate::solids::mesh_color(paint, opacity * member); let list: Vec = if graphics && fx.id == REVOLVE && options.map_surface { @@ -922,7 +972,7 @@ fn surface_meshes( if !side.is_empty() { let graphics = crate::MeshGraphics { face: crate::PlanarFace::Front, graphics: list, center: Point::ZERO, art, opacity, object: member.clamp(0.0, 1.0) }; - out.push(crate::SolidMesh { mesh: side, color, graphics: Some(graphics) }); + out.push(crate::SolidMesh { graphics: Some(graphics), ..crate::SolidMesh::plain(side, color) }); } Ok(out) } diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 97bfa67add..6afaf0f9bb 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -36,6 +36,7 @@ pub(crate) fn options(p: &Value) -> Revolve { smooth_shading: false, lights: None, light_color: [1.0; 3], + material: vectorcraft_three_d::Material::DEFAULT, map_surface: !map_art::surface_maps(p).is_empty(), ..super::revolve_options(p) } diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index 9088b25554..8c5630e31c 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -593,3 +593,66 @@ fn a_gradient_with_transparent_stops_takes_no_stroke_over_its_seams() { let clear = seams("Clear"); assert!(!clear.is_empty() && clear.iter().all(|s| !*s), "{clear:?}"); } + +/// Does node `n` screen its fills, as a material's highlight does? +fn screens(n: &Node) -> bool { + n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == vectorcraft_doc::color::BlendMode::Screen)) +} + +/// A material's highlight on a face lies over the parts of the graphics drawn on that face: each +/// blue part is drawn before the last child of a group whose last child is a highlight. +#[test] +fn a_material_highlight_lies_over_the_graphics_on_its_face() { + let d = document(); + let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Blue"}], "material": {"roughness": 0.5}})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + let blue = |n: &Node| { + let mut count = 0; + n.walk(&mut |c| { + count += c + .appearance + .items + .iter() + .filter(|i| matches!(i, AppearanceItem::Fill(f) if !screens(c) && shade_of(&f.paint, true).is_some())) + .count(); + }); + count + }; + let mut under = 0; + art.walk(&mut |g| { + if let NodeKind::Group { children, clip: false } = &g.kind + && let [before @ .., over] = children.as_slice() + && screens(over) + { + under += before.iter().map(|c| blue(c)).sum::(); + } + }); + assert!(blue(&art) > 0 && under > 0, "{} blue parts, {under} under a highlight", blue(&art)); +} + +/// A face painted with a gradient with transparent stops screens its highlight only as far as the +/// paint covers the face, and takes that coverage once: every highlight lies under an opacity +/// mask, and no face is drawn with the transparent stops themselves. +#[test] +fn a_material_highlight_on_a_transparent_gradient_is_masked() { + fn unmasked(n: &Node, masked: bool, out: &mut usize) { + let masked = masked || n.extras().mask.is_some(); + if screens(n) && !masked { + *out += 1; + } + n.children().into_iter().flatten().for_each(|c| unmasked(c, masked, out)); + } + // Open by a quarter turn and held off the axis, the solid has flat caps at both ends. + let mut n = revolved(&CYLINDER, json!({"shade": true, "angle": 270.0, "offset": 20.0, "rotationY": 30.0, "material": {"roughness": 0.5}})); + n.appearance.items = vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(ramp(2, 0.5)))]; + let art = revolve_art_in(None, &n).unwrap(); + let (mut highlights, mut bare, mut clear) = (0, 0, 0); + art.walk(&mut |c| { + highlights += usize::from(screens(c)); + clear += + c.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Fill(f) if crate::lighting::opaque_paint(&f.paint).1.is_some())).count(); + }); + unmasked(&art, false, &mut bare); + assert!(highlights > 0 && bare == 0, "{bare} of {highlights} highlights unmasked"); + assert_eq!(clear, 0, "faces drawn with transparent stops under their highlights"); +} diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 83bb1ca9f7..786d3954e4 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -43,6 +43,9 @@ pub(crate) mod shadow; pub(crate) mod wireframe; pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in}; +pub(crate) mod material; +pub use material::MATERIAL; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; @@ -176,6 +179,7 @@ pub fn view_options(p: &Value) -> View { light_softness: num(p, "lightSoftness", 0.0) / 100.0, ambient: num(p, "ambient", 25.0) / 100.0, shade: flag(p, "shade", true), + material: material::read(p), } } @@ -414,6 +418,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { shadow::validate(p)?; graphics::validate(id, p)?; wireframe::validate_render(id, p)?; + material::validate(id, p)?; if let Some(v) = p.get("bevel") && !v.as_str().is_some_and(|s| s == "none" || s == "custom" || BevelShape::parse(s).is_some()) { @@ -832,6 +837,25 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { /// opaque under one mask of its transparency, placed once on all the facets when it has no /// placement of its own ([`crate::lighting::opaque_surface_paint`]). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node { + surface_with_parts(n, facets, paint, (opacity, blend), colored, faces, vec![]) +} + +/// [`surface`] with each face followed by the parts of the graphics that `parts` holds for its +/// facet (on Extrude & Bevel's side [`graphics::surface_parts`], on Inflate's front and back +/// [`membrane_parts`]): a face with parts becomes a group of the face and its parts, so nearer +/// faces drawn after it cover them too, and a material's highlight lies over both. A surface +/// painted with a pattern takes no material highlight: a white coverage paint does not keep the +/// transparency of the pattern's tiles. `parts` is left out unless it holds one list for each facet. +fn surface_with_parts( + n: &Node, + facets: Vec, + paint: &Paint, + (opacity, blend): (f32, BlendMode), + colored: bool, + faces: bool, + parts: Vec>>, +) -> Node { + let mut parts = if parts.len() == facets.len() { parts } else { vec![] }.into_iter(); if !faces && composites_facets(&facets, paint, colored) { let mut group = crate::lighting::solid_surface(n.id, &facets, paint); group.opacity = opacity; @@ -847,10 +871,19 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble // Adjacent facets, antialiased on their own, would leave hairline seams: a narrow // stroke of the same paint closes them ([`seam_width`]). let seam = seam_width(&face); + let path = face.path(); + let extra = parts.next().unwrap_or_default(); + let lit = |art: Node| { + let art = if extra.is_empty() { art } else { Node::group(n.id, std::iter::once(Arc::new(art)).chain(extra).collect()) }; + if matches!(paint, Paint::Pattern { .. }) { + return Arc::new(art); + } + Arc::new(crate::lighting::highlighted(n.id, art, &path, seam, face.highlight)) + }; if let Some(g) = face.rgb_gradient && (paint.color().is_some() || matches!(paint, Paint::Gradient(_))) { - return Arc::new(crate::lighting::facet_art(n.id, &face.path(), paint, g, seam)); + return lit(crate::lighting::facet_art(n.id, &path, paint, g, seam)); } let items = crate::lighting::fills(paint, face.illumination, face.brightness, colored); let items = items @@ -862,7 +895,7 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble vec![item, AppearanceItem::Stroke(edge)] }) .collect(); - Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })) + lit(Node::path(n.id, path.clone(), Appearance { items, ..Default::default() })) }) .collect(); let mut group = Node::group(n.id, children); @@ -901,31 +934,6 @@ fn membrane_parts( Some(out) } -/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by -/// the parts of the graphics that `parts` holds for its facet (on Extrude & Bevel's side -/// [`graphics::surface_parts`], on Inflate's front and back [`membrane_parts`]): a face with parts -/// becomes a group of the face and its parts, so nearer faces drawn after it cover them too. -/// `surface` is returned as it is when no facet has a part or it is not such a group. -fn with_surface_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { - if parts.iter().all(Vec::is_empty) { - return surface; - } - let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface }; - if children.len() != parts.len() { - return surface; - } - for (child, extra) in children.iter_mut().zip(parts) { - if extra.is_empty() { - continue; - } - let mut list = Vec::with_capacity(extra.len() + 1); - list.push(child.clone()); - list.extend(extra); - *child = Arc::new(Node::group(id, list)); - } - surface -} - /// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) @@ -939,9 +947,9 @@ pub(crate) fn seam_width(face: &Facet) -> f64 { } /// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it -/// whole: a solid color under colored lights with smooth shading? +/// whole: a solid color under colored lights with smooth shading, and no material highlight? fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool { - colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some()) + colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some()) && facets.iter().all(|f| f.highlight.is_none()) } /// `item`'s paint, its opacity times `member` (the opacity of the objects it is in) and its blend. @@ -2273,8 +2281,8 @@ fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), b // Solids whose fills or strokes differ in opacity or blending mode get graphics of their // own, each drawn as its fill or stroke is. One member's solids share their graphics // whether or not their surfaces carry an opacity mask, and each graphic takes the mask of - // the surface it is drawn after ([`with_graphics`]). Solids of different members share - // them only when neither surface carries a mask. A solid joins only the group of the solid + // the surface it is drawn after ([`with_graphics`]). Solids of different members share them + // only when neither surface carries a mask. A solid joins only the group of the solid // before it, so a graphic is never drawn past a solid painted between. let joins = |g: &&Filled| { let member = g.member == f.member; @@ -2302,6 +2310,14 @@ fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), b out } +/// The ends of `facets` that the viewer sees, as the graphics on them are drawn: a surface painted +/// with `paint`, a pattern, takes no material highlight ([`surface_with_parts`]), so neither do +/// its caps' graphics. +fn graphic_caps(facets: &[Facet], paint: &Paint) -> Vec { + let pattern = matches!(paint, Paint::Pattern { .. }); + seen_ends(facets).cloned().map(|cap| if pattern { Facet { highlight: None, ..cap } } else { cap }).collect() +} + /// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's /// scopes, and for each face the end of a solid it is, when the viewer sees it. type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec>); @@ -2368,7 +2384,7 @@ fn surfaces_with( let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; - let colored = !classic && view_options(&p).has_colored_lights(); + let colored = !classic && (view_options(&p).has_colored_lights() || view_options(&p).shades_material()); let masks = has_masks(shapes); // The paint copies of every solid together: past the allowance the source path is drawn. let mut paint_bytes = 0usize; @@ -2392,7 +2408,7 @@ fn surfaces_with( return None; } if graphics_on { - let caps: Vec = seen_ends(&f).cloned().collect(); + let caps = graphic_caps(&f, &paint); if !caps.is_empty() { filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) }); } @@ -2512,8 +2528,8 @@ fn surfaces_with( .iter() .enumerate() .filter_map(|(at, (item, member, _, f, shape))| { - let caps: Vec = seen_ends(f).cloned().collect(); let (paint, opacity, blend) = paint_of(item, *member); + let caps = graphic_caps(f, &paint); let masked = masks_surface(&paint, colored); (!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked }) }) @@ -2591,7 +2607,7 @@ fn surfaces_with( classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![])) } else { let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); - with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) + surface_with_parts(n, f, &paint, (opacity, blend), colored, faces, parts) }; (depths, art, scopes, ends) }) @@ -3176,12 +3192,15 @@ pub struct SolidMesh { /// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries /// some ([`split_graphics`]); `None` otherwise. pub graphics: Option, + /// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`] + /// for the 3D (Classic) effects. + pub material: vectorcraft_three_d::Material, } impl SolidMesh { - /// A mesh painted `color`, with no graphics. + /// A mesh painted `color`, with no graphics, in the default material. pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { - Self { mesh, color, graphics: None } + Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT } } } @@ -3236,7 +3255,7 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity if !taken.is_empty() { let graphics = list.iter().filter(|g| g.face == face).cloned().collect(); let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 }; - out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) }); + out.push(SolidMesh { graphics: Some(graphics), ..SolidMesh::plain(taken, color) }); } } if !rest.is_empty() { @@ -3283,12 +3302,13 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; let p = crate::merged_params(&fx.id, &fx.params); let view = view_options(&p); + let material = material::of(&fx.id, &p); let mut out = vec![]; // A solid's parts with and without graphics count together against the limit. let mut keep = |out: &mut Vec, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| { split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) .into_iter() - .try_for_each(|part| keep_mesh(out, total, part, limit)) + .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, ..part }, limit)) }; if is_plane(&fx.id) { for s in shapes { @@ -3446,3 +3466,6 @@ mod tests_shadow; #[cfg(test)] mod tests_revolve_order; + +#[cfg(test)] +mod tests_material; diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 302180fdbc..88e950fc19 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -450,7 +450,8 @@ fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Opt /// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the /// object's solids that the viewer sees) through `map`, for an object whose bounds have -/// center `center`: one clipping group of every such graphic, shaded with the first cap's light. +/// center `center`: one clipping group of every such graphic, shaded with the first cap's light +/// and material highlight. /// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol /// `doc` does not have draws nothing. `elements` counts the path elements /// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by @@ -467,6 +468,7 @@ pub(super) fn face_art( ) -> Option { let doc = doc?; let light = caps.first()?.illumination; + let highlight = caps.first()?.highlight.map(|h| h.flat.map(|v| v.clamp(0.0, 1.0) as f32)); let affine = map.local_affine(center).filter(|_| map.is_affine()); let mut children = vec![]; for g in graphics.iter().filter(|g| g.face == face) { @@ -526,7 +528,12 @@ pub(super) fn face_art( }; *elements = before.saturating_add(mapped.elements().len()); let mut paint = piece.paint; - vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light)); + vectorcraft_doc::recolor::map_paint(&mut paint, &|c| { + let shaded = crate::lighting::shade(c, light); + let Some([hr, hg, hb]) = highlight else { return shaded }; + let [r, g, b] = shaded.to_rgb(); + vectorcraft_doc::color::Color::rgb(1.0 - (1.0 - r) * (1.0 - hr), 1.0 - (1.0 - g) * (1.0 - hg), 1.0 - (1.0 - b) * (1.0 - hb)) + }); // A pattern's tiles follow the graphic onto the face, as its gradients do below. if let Paint::Pattern { xf, .. } = &mut paint { *xf = gradient_map * *xf; diff --git a/crates/effects/src/solids/material.rs b/crates/effects/src/solids/material.rs new file mode 100644 index 0000000000..2d086eb610 --- /dev/null +++ b/crates/effects/src/solids/material.rs @@ -0,0 +1,54 @@ +//! The 3D and Materials panel's Materials › Properties: a 3D effect's Roughness and Metallic, the +//! `material` parameter. +use serde_json::Value; +use vectorcraft_three_d::Material; + +use super::{EXTRUDE, INFLATE, ROTATE}; + +/// The parameter that holds a 3D effect's material: an object of `roughness` and `metallic`, +/// each a number from 0 to 1. +pub const MATERIAL: &str = "material"; + +/// The 3D effects that take [`MATERIAL`]: the 3D and Materials panel's Extrude & Bevel, Revolve, +/// Inflate and Rotate. The 3D (Classic) effects have their own surfaces. +const TAKES_MATERIAL: [&str; 4] = [EXTRUDE, crate::REVOLVE, INFLATE, ROTATE]; + +const INVALID: &str = "`material` must be an object holding only `roughness` and `metallic`, each a number from 0 to 1"; + +/// The material `v` holds: each of `roughness` and `metallic` it gives, the default +/// ([`Material::DEFAULT`]) for each it leaves out. An error for anything else: a value that is not +/// an object, another key, or a value that is not a number from 0 to 1. +fn parse(v: &Value) -> Result { + let fields = v.as_object().ok_or(INVALID)?; + if fields.keys().any(|k| k != "roughness" && k != "metallic") { + return Err(INVALID.into()); + } + let number = |key: &str, default: f64| match fields.get(key) { + None => Ok(default), + Some(v) => v.as_f64().filter(|n| n.is_finite() && (0.0..=1.0).contains(n)).ok_or(INVALID), + }; + let d = Material::DEFAULT; + Material::new(number("roughness", d.roughness())?, number("metallic", d.metallic())?).ok_or_else(|| INVALID.into()) +} + +/// Check the material in 3D effect `id`'s parameters `p`: `material`, when given to one of the +/// effects in [`TAKES_MATERIAL`], is one [`parse`] takes. The 3D (Classic) effects refuse it as a +/// parameter they do not take. +pub(crate) fn validate(id: &str, p: &Value) -> Result<(), String> { + match p.get(MATERIAL).filter(|_| TAKES_MATERIAL.contains(&id)) { + Some(v) => parse(v).map(|_| ()), + None => Ok(()), + } +} + +/// The material parameters `p` hold, for the view every 3D effect shares: a loaded `material` +/// that [`validate`] would refuse is the default. The 3D (Classic) effects do not shade with it. +pub(crate) fn read(p: &Value) -> Material { + p.get(MATERIAL).and_then(|v| parse(v).ok()).unwrap_or_default() +} + +/// The material 3D effect `id` with parameters `p` exports with: [`read`] for the effects in +/// [`TAKES_MATERIAL`], the default for the others. +pub(crate) fn of(id: &str, p: &Value) -> Material { + if TAKES_MATERIAL.contains(&id) { read(p) } else { Material::DEFAULT } +} diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 504fe1d777..e5cc10de4f 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -794,6 +794,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { illumination: [1.0; 3], normal, rgb_gradient: None, + highlight: None, outline: None, side: true, away: false, diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index c03b8800cb..66af09b227 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -1029,6 +1029,157 @@ fn red_parts(art: &Node) -> Vec { out } +/// How many of `art`'s paths that [`red_parts`] counts lie under a material's highlight: before the +/// last child of a group whose last child screens its fills, or holds paths that do. +fn red_parts_under_highlight(art: &Node) -> usize { + let screens = + |n: &Node| n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == vectorcraft_doc::color::BlendMode::Screen)); + let mut count = 0; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: false } = &n.kind + && let [under @ .., over] = children.as_slice() + && (screens(over) || over.children().is_some_and(|c| !c.is_empty() && c.iter().all(|c| screens(c)))) + { + count += under.iter().map(|c| red_parts(c).len()).sum::(); + } + }); + count +} + +/// Inflate's material highlight lies over the graphic pieces on its puffed front. +#[test] +fn a_material_highlight_lies_over_the_graphics_on_its_face() { + let d = document(); + let n = object(INFLATE, json!({"shade": true, "graphics": [{"symbol": "Mark", "scale": 400.0}], "material": {"roughness": 0.5}})); + let art = solid_art_in(Some(&d), &n).unwrap(); + assert!(!red_parts(&art).is_empty()); + assert!(red_parts_under_highlight(&art) > 0, "every highlight is drawn under the graphic"); +} + +/// The screened paths covering an interior point of the front cap in a straight-on view. +fn front_cap_highlights(art: &Node) -> usize { + let mut count = 0; + art.walk(&mut |n| { + if n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == BlendMode::Screen)) + && n.path_data().is_some_and(|p| p.to_bezpath().contains(Point::new(47.0, 53.0))) + { + count += 1; + } + }); + count +} + +/// The fills of the mapped graphic pieces, independent of their shaded colors. +fn cap_graphic_fills(art: &Node) -> Vec { + let mut fills = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: true } = &n.kind + && let [_, inner] = children.as_slice() + && let Some(paths) = inner.children() + { + fills.extend(paths.iter().filter(|p| p.path_data().is_some()).flat_map(|p| { + p.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) if f.blend != BlendMode::Screen => Some(f.clone()), + _ => None, + }) + })); + } + }); + fills +} + +/// Cap graphics take the material's reflected light in their paint, keep their opacity, and +/// leave the surface's highlight paths in place, including on overlapping fill and stroke caps. +#[test] +fn cap_graphics_take_material_light_without_extra_highlight_paths() { + let mut d = document(); + if let AppearanceItem::Fill(fill) = &mut Arc::make_mut(&mut d.symbols[0].art).appearance.items[0] { + fill.opacity = 0.5; + } + for id in [EXTRUDE, ROTATE] { + for layers in ["fill", "two fills", "fill and stroke"] { + // Ambient light leaves room for the highlight in every channel of the red paint. + let params = json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "material": {"roughness": 0.5}}); + let mut bare = object(id, params.clone()); + if layers == "two fills" { + let fill = bare.appearance.items[0].clone(); + bare.appearance.items.push(fill); + } else if layers == "fill and stroke" { + bare.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 100.0))); + } + for item in &mut bare.appearance.items { + match item { + AppearanceItem::Fill(f) => f.opacity = 0.5, + AppearanceItem::Stroke(s) => s.opacity = 0.5, + } + } + let bare_art = solid_art_in(Some(&d), &bare).unwrap(); + let mut mapped = bare.clone(); + let mut mapped_params = params; + mapped_params["graphics"] = json!([{"symbol": "Mark", "face": "front"}]); + mapped.appearance.effects = vec![crate::new_effect(id, &mapped_params).unwrap()]; + let art = solid_art_in(Some(&d), &mapped).unwrap(); + mapped_params["material"] = json!({"roughness": 1.0, "metallic": 0.0}); + let mut default = mapped.clone(); + default.appearance.effects = vec![crate::new_effect(id, &mapped_params).unwrap()]; + let default_art = solid_art_in(Some(&d), &default).unwrap(); + let fills = cap_graphic_fills(&art); + let default_fills = cap_graphic_fills(&default_art); + let brighter = !fills.is_empty() + && fills.len() == default_fills.len() + && fills.iter().zip(&default_fills).all(|(f, before)| { + let (Some(c), Some(b)) = (f.paint.color(), before.paint.color()) else { return false }; + c.to_rgb().iter().zip(b.to_rgb()).all(|(a, b)| *a > b) && f.opacity == 0.5 && f.opacity == before.opacity + }); + let highlights = front_cap_highlights(&art); + let bare_highlights = front_cap_highlights(&bare_art); + // The graphic keeps its opacity and takes the highlight in its paint colors. + assert!( + brighter && highlights == bare_highlights && bare_highlights > 0, + "{id}, {layers}: highlights {highlights} vs {bare_highlights}, fills {fills:?} vs {default_fills:?}" + ); + } + } +} + +/// Missing and empty symbols leave the cap's highlight in place. A pattern surface gives +/// neither its cap nor its graphic a material highlight. +#[test] +fn missing_graphics_preserve_cap_highlights_and_patterns_take_none() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Empty".into(), art: Arc::new(Node::group(NodeId(0), vec![])) }); + for id in [EXTRUDE, ROTATE] { + for symbol in ["Mark", "Missing", "Empty"] { + let n = object( + id, + json!({ + "shade": true, "lightIntensity": 0.0, "ambient": 50.0, + "material": {"roughness": 0.5}, "graphics": [{"symbol": symbol, "face": "front"}] + }), + ); + let art = solid_art_in(Some(&d), &n).unwrap(); + if symbol != "Mark" { + assert_eq!(front_cap_highlights(&art), 1, "{id}, {symbol}: the cap keeps its highlight"); + assert!(red_parts(&art).is_empty()); + } + let mut patterned = n.clone(); + patterned.appearance = Appearance::basic(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, Paint::None, 0.0).into(); + patterned.appearance.effects = n.appearance.effects.clone(); + let patterned_art = solid_art_in(Some(&d), &patterned).unwrap(); + assert_eq!(front_cap_highlights(&patterned_art), 0, "{id}, {symbol}: a pattern"); + let mut default = patterned.clone(); + default.appearance.effects[0].params["material"] = json!({"roughness": 1.0, "metallic": 0.0}); + let default_art = solid_art_in(Some(&d), &default).unwrap(); + let fills = cap_graphic_fills(&patterned_art); + let default_fills = cap_graphic_fills(&default_art); + assert_eq!(fills, default_fills, "{id}, {symbol}: pattern graphics keep their colors"); + if symbol == "Mark" { + assert!(!fills.is_empty()); + } + } + } +} + fn reach(parts: &[PathData]) -> Rect { parts.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() } diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs index 5afdadf30f..a4444da583 100644 --- a/crates/effects/src/solids/tests_graphics_side.rs +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -180,6 +180,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() { illumination: [1.0; 3], normal, rgb_gradient: None, + highlight: None, outline: None, side: true, away: false, diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs index 9ffb264627..e62852acc4 100644 --- a/crates/effects/src/solids/tests_map_art.rs +++ b/crates/effects/src/solids/tests_map_art.rs @@ -201,6 +201,7 @@ fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() { illumination: [1.0; 3], normal: [0.0, 0.0, 1.0], rgb_gradient: None, + highlight: None, outline: Some(PathData::from_bezpath(&curved)), side: true, away: false, @@ -246,6 +247,7 @@ fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() { illumination: [1.0; 3], normal: [0.0, 0.0, 1.0], rgb_gradient: None, + highlight: None, outline: Some(PathData::from_bezpath(&curved)), side: true, away: false, @@ -286,6 +288,7 @@ fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() { illumination: [1.0; 3], normal: [0.0, 0.0, 1.0], rgb_gradient: None, + highlight: None, outline: None, side: true, away: false, diff --git a/crates/effects/src/solids/tests_material.rs b/crates/effects/src/solids/tests_material.rs new file mode 100644 index 0000000000..1c7141dc8d --- /dev/null +++ b/crates/effects/src/solids/tests_material.rs @@ -0,0 +1,402 @@ +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_doc::color::BlendMode; +use vectorcraft_geom::BezPath; + +use super::*; + +const RED: Color = Color::Rgb { r: 0.8, g: 0.2, b: 0.1 }; + +/// The 3D and Materials panel's effects, which take a material. +const TAKES: [&str; 4] = [EXTRUDE, crate::REVOLVE, INFLATE, ROTATE]; + +fn square_node() -> Node { + let mut b = BezPath::new(); + b.move_to((100.0, 100.0)); + b.line_to((200.0, 100.0)); + b.line_to((200.0, 200.0)); + b.line_to((100.0, 200.0)); + b.close_path(); + Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::solid(Color::BLACK), 4.0)) +} + +/// A square with effect `id` and `params`, drawn. +fn art(id: &str, params: Value) -> Node { + let mut n = square_node(); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap_or_else(|| panic!("{id}"))); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { solid_art(&n) }; + art.unwrap_or_else(|| panic!("{id} draws")) +} + +/// How many fills of `n` and its children screen their paint. +fn screened(n: &Node) -> usize { + let own = n.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Fill(f) if f.blend == BlendMode::Screen)).count(); + own + n.children().map_or(0, |c| c.iter().map(|c| screened(c)).sum()) +} + +fn check(id: &str, material: Value) -> Result<(), String> { + validate_three_d_params(id, &crate::merged_params(id, &json!({ MATERIAL: material }))) +} + +fn three_lights() -> Value { + json!([ + {"color": "#ff8080", "rotation": 125.0, "height": 30.0, "intensity": 60.0}, + {"color": "#80ff80", "rotation": -40.0, "height": 50.0, "intensity": 30.0}, + {"color": "#8080ff", "rotation": 10.0, "height": 15.0, "intensity": 20.0} + ]) +} + +fn extrude_scene() -> Value { + json!({"bevel": "rounded"}) +} + +fn inflate_scene() -> Value { + json!({"lights": three_lights()}) +} + +/// The colors of `n`'s fills and their gradient stops, depth first, other than the square's own +/// paint and stroke colors, with runs of one color kept once. +fn fill_colors(n: &Node) -> Vec<[f32; 3]> { + let mut colors: Vec<_> = n + .appearance + .items + .iter() + .flat_map(|item| match item { + AppearanceItem::Fill(f) => match &f.paint { + Paint::Solid { color, .. } => vec![color.to_rgb()], + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color.to_rgb()).collect(), + _ => vec![], + }, + AppearanceItem::Stroke(_) => vec![], + }) + .filter(|c| *c != RED.to_rgb() && *c != Color::BLACK.to_rgb()) + .collect(); + if let Some(children) = n.children() { + for child in children { + colors.extend(fill_colors(child)); + } + } + colors.dedup(); + colors +} + +/// [`fill_colors`] of [`extrude_scene`] and [`inflate_scene`] as `main` at `f1335a5f19` draws them, +/// before the 3D effects took a material: their count, and the first, second, middle and last. +const MAIN_EXTRUDE_LEN: usize = 24; +const MAIN_EXTRUDE_COLORS: [[f32; 3]; 4] = [ + [0.7347116, 0.1836779, 0.09183895], + [0.6111859, 0.15279648, 0.07639824], + [0.3282661, 0.08206653, 0.041033264], + [0.4674851, 0.116871275, 0.058435638], +]; +const MAIN_INFLATE_LEN: usize = 93524; +const MAIN_INFLATE_COLORS: [[f32; 3]; 4] = [[0.25, 0.0, 0.0], [0.40080008, 0.0, 0.0], [0.0, 0.5603895, 0.0], [0.0, 0.0, 0.5744827]]; + +fn sampled_colors(colors: &[[f32; 3]]) -> [[f32; 3]; 4] { + [colors[0], colors[1], colors[colors.len() / 2], colors[colors.len() - 1]] +} + +#[test] +fn a_material_takes_roughness_and_metallic_from_0_to_1() { + for id in TAKES { + for ok in [json!({}), json!({"roughness": 0.0}), json!({"metallic": 1}), json!({"roughness": 0.35, "metallic": 0.8})] { + assert_eq!(check(id, ok.clone()), Ok(()), "{id} {ok}"); + } + for bad in [ + json!({"roughness": 1.5}), + json!({"roughness": -0.01}), + json!({"metallic": 2}), + json!({"metallic": "0.5"}), + json!({"roughness": null}), + json!({"shine": 0.5}), + json!(0.5), + json!([0.5, 0.5]), + json!(null), + ] { + let Err(e) = check(id, bad.clone()) else { panic!("{id} takes {bad}") }; + assert!(e.contains("`material`"), "{id} {bad}: {e}"); + } + } +} + +#[test] +fn the_classic_effects_take_no_material() { + for id in [CLASSIC_EXTRUDE, CLASSIC_ROTATE, crate::CLASSIC_REVOLVE] { + let p = crate::merged_params(id, &json!({ MATERIAL: {"roughness": 0.5} })); + assert!(validate_three_d_params(id, &p).is_err(), "{id}"); + assert!(material::of(id, &p).is_default(), "{id}"); + } +} + +/// The default material, given or left out, draws exactly what the effects drew before materials. +#[test] +fn the_default_material_draws_as_before() { + for id in TAKES { + for lights in [None, Some(three_lights())] { + let mut params = if id == EXTRUDE { extrude_scene() } else { json!({}) }; + if let Some(lights) = lights { + params["lights"] = lights; + } + let plain = art(id, params.clone()); + for material in [json!({}), json!({"roughness": 1.0, "metallic": 0.0})] { + params[MATERIAL] = material; + assert_eq!(art(id, params.clone()), plain, "{id} {params}"); + } + assert_eq!(screened(&plain), 0, "{id}"); + } + } + for (id, params, len, expected) in + [(EXTRUDE, extrude_scene(), MAIN_EXTRUDE_LEN, MAIN_EXTRUDE_COLORS), (INFLATE, inflate_scene(), MAIN_INFLATE_LEN, MAIN_INFLATE_COLORS)] + { + let colors = fill_colors(&art(id, params)); + assert_eq!(colors.len(), len, "{id} fill count"); + for (got, want) in sampled_colors(&colors).iter().zip(expected) { + for c in 0..3 { + assert!((got[c] - want[c]).abs() <= 1e-6, "{id} channel {c}: {got:?} vs {want:?}"); + } + } + } +} + +#[test] +fn a_colored_inflate_with_no_stroke_keeps_its_highlight() { + let mut n = square_node(); + n.appearance = Appearance::basic(Paint::solid(RED), Paint::None, 0.0).into(); + let params = json!({"lights": [{"color": "#ff8080"}], "material": {"roughness": 0.3}}); + n.appearance.effects.push(crate::new_effect(INFLATE, ¶ms).unwrap_or_else(|| panic!("inflate"))); + let art = solid_art(&n).unwrap_or_else(|| panic!("inflate draws")); + assert!(screened(&art) > 0); +} + +fn loaded_art(id: &str, params: Value) -> Node { + let mut n = square_node(); + n.appearance.effects.push(Effect { id: id.into(), params, visible: true }); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { solid_art(&n) }; + art.unwrap_or_else(|| panic!("{id} draws")) +} + +#[test] +fn a_loaded_invalid_material_draws_the_default() { + for id in TAKES { + let default = art(id, json!({})); + for material in [ + json!({"roughness": 7}), + json!("shiny"), + json!({"metallic": -1}), + json!({"roughness": 7, "metallic": 0.6}), + json!({"roughness": 0.3, "metallic": -1}), + ] { + assert_eq!(loaded_art(id, json!({MATERIAL: material})), default, "{id} {material}"); + } + } +} + +#[test] +fn a_saved_effect_without_material_merges_to_the_default() { + for id in TAKES { + let effect = Effect { id: id.into(), params: json!({}), visible: true }; + assert_eq!(crate::merged_params(&effect.id, &effect.params)[MATERIAL], json!({"roughness": 1.0, "metallic": 0.0}), "{id}"); + assert_eq!(loaded_art(id, effect.params), art(id, json!({})), "{id}"); + } +} + +fn bevel_highlights_meet(facets: &[Facet]) { + let bevels: Vec<_> = facets.iter().filter(|f| f.side && !f.away).collect(); + let color = |f: &Facet, p: Point| { + let h = f.highlight.unwrap_or_else(|| panic!("a material highlight")); + h.ramp.map_or(h.flat.map(|c| c.clamp(0.0, 1.0)), |r| r.at(p)) + }; + let edges = + |f: &Facet| f.contours.iter().flat_map(|c| c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| (*a, *b))).collect::>(); + let mut shared = 0; + let mut diagonals = 0; + let mut bands = 0; + for (i, a) in bevels.iter().enumerate() { + for b in bevels.iter().skip(i + 1) { + for (p, q) in edges(a) { + if edges(b).iter().any(|(r, s)| (p.distance(*r) < 1e-7 && q.distance(*s) < 1e-7) || (p.distance(*s) < 1e-7 && q.distance(*r) < 1e-7)) + { + if let Some(cell) = &a.surface { + // Planar walls meet the bevel at a hard edge. + if a.rgb_gradient.is_none() || b.rgb_gradient.is_none() { + continue; + } + let uv = |p: Point| cell.page.iter().position(|v| v.distance(p) < 1e-7).map(|i| cell.uv[i]); + let (Some(u), Some(v)) = (uv(p), uv(q)) else { panic!("shared corners have side coordinates") }; + // Edges along the extrusion can cross a hard profile corner or a wall cut. + if (u.x - v.x).abs() < 1e-7 { + continue; + } + if (u.y - v.y).abs() < 1e-7 { + bands += 1; + } else { + diagonals += 1; + } + } + shared += 1; + for p in [p, p.lerp(q, 0.5), q] { + let (a, b) = (color(a, p), color(b, p)); + for c in 0..3 { + assert!((a[c] - b[c]).abs() <= 2.0 / 255.0, "shared corner {p:?} channel {c}: {a:?} vs {b:?}"); + } + } + } + } + } + } + assert!(shared >= 4, "neighboring bevel facets were compared: {shared}"); + if bevels.iter().any(|f| f.surface.is_some() && f.contours.first().is_some_and(|c| c.len() == 3)) { + assert!(diagonals > 0 && bands > 0, "triangle diagonals and neighboring bands were compared: {diagonals}, {bands}"); + } +} + +fn front_lit_bevel(shape: &str, roughness: f64) -> Value { + json!({ + "bevel": shape, "bevelWidth": 8.0, "bevelHeight": 8.0, + "rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, + "lightHeight": 90.0, "ambient": 0.0, "material": {"roughness": roughness} + }) +} + +#[test] +fn issue_1407_bevel_bands_meet() { + // #1407: the highlight agrees at the shared corners of neighboring rounded bevel bands. + let n = square_node(); + let path = n.path_data().unwrap_or_else(|| panic!("square path")); + let params = crate::merged_params(EXTRUDE, &front_lit_bevel("rounded", 0.4)); + let facets = + facets(EXTRUDE, path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), ¶ms).unwrap_or_else(|e| panic!("rounded bevel: {e}")); + bevel_highlights_meet(&facets); +} + +#[test] +fn issue_1407_twisted_perspective_bevel_bands_meet() { + let n = square_node(); + let path = n.path_data().unwrap_or_else(|| panic!("square path")); + let mut params = front_lit_bevel("rounded", 0.4); + params["perspectiveAngle"] = json!(60.0); + params["twist"] = json!(30.0); + params["rotationX"] = json!(20.0); + params["rotationY"] = json!(-30.0); + let params = crate::merged_params(EXTRUDE, ¶ms); + let facets = side_facets(path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), ¶ms) + .unwrap_or_else(|e| panic!("twisted perspective bevel: {e}")); + bevel_highlights_meet(&facets); +} + +/// Wireframe mode draws the same edges for every material: the bevel bands a material splits into +/// triangles for its highlight add no edges. +#[test] +fn a_material_leaves_the_wireframe_as_it_is() { + for id in TAKES { + let mut params = if id == EXTRUDE { extrude_scene() } else { json!({}) }; + params["render"] = json!({"mode": "wireframe"}); + let plain = art(id, params.clone()); + params[MATERIAL] = json!({"roughness": 0.4, "metallic": 0.5}); + assert_eq!(art(id, params), plain, "{id}"); + } +} + +fn finite_art_colors(n: &Node, counts: &mut [usize; 2]) { + let check = |color: Color| { + assert!(color.to_rgb().iter().all(|c| c.is_finite() && (0.0..=1.0).contains(c)), "finite unit color: {color:?}"); + }; + for item in &n.appearance.items { + let (paint, screen) = match item { + AppearanceItem::Fill(f) => (&f.paint, f.blend == BlendMode::Screen), + AppearanceItem::Stroke(s) => (&s.paint, s.blend == BlendMode::Screen), + }; + if let Paint::Gradient(g) = paint { + for stop in &g.gradient.stops { + check(stop.color); + counts[0] += 1; + } + } + if screen { + counts[1] += 1; + match paint { + Paint::Solid { color, .. } => check(*color), + Paint::Gradient(_) => {} + _ => panic!("a Screen layer has colors"), + } + } + } + if let Some(mask) = &n.extras().mask { + finite_art_colors(&mask.art, counts); + } + if let Some(children) = n.children() { + for child in children { + finite_art_colors(child, counts); + } + } +} + +#[test] +fn issue_2126_bevel_facets_are_finite_and_continuous() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_geom::{Shape, kurbo::RoundedRect}; + + // #2126: a curved outline with a Classic bevel shape keeps finite colors and joined highlights. + let path = PathData::from_bezpath(&RoundedRect::new(100.0, 100.0, 240.0, 200.0, 20.0).to_path(0.1)); + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, RED), GradientStop::new(1.0, Color::WHITE)], + )))); + let mut n = Node::path(NodeId(1), path.clone(), Appearance::basic(paint, Paint::None, 0.0)); + let params = front_lit_bevel("classic", 0.5); + n.appearance.effects.push(crate::new_effect(EXTRUDE, ¶ms).unwrap_or_else(|| panic!("extrude"))); + let art = solid_art(&n).unwrap_or_else(|| panic!("gradient extrusion draws")); + let mut counts = [0; 2]; + finite_art_colors(&art, &mut counts); + assert!(counts[0] > 0 && counts[1] > 0, "gradient stops and Screen layers: {counts:?}"); + let params = crate::merged_params(EXTRUDE, ¶ms); + let facets = + facets(EXTRUDE, &path, FillRule::NonZero, path.bounds().unwrap_or(Rect::ZERO), ¶ms).unwrap_or_else(|e| panic!("classic bevel: {e}")); + bevel_highlights_meet(&facets); +} + +/// Any other material screens its highlight over each lit face, and the paint keeps its hue on a +/// dielectric. +#[test] +fn a_shiny_material_screens_a_highlight_over_its_faces() { + for id in TAKES { + let shiny = art(id, json!({ MATERIAL: {"roughness": 0.3, "metallic": 0.0} })); + assert!(screened(&shiny) > 0, "{id}"); + assert_ne!(shiny, art(id, json!({})), "{id}"); + let unshaded = art(id, json!({ "shade": false, MATERIAL: {"roughness": 0.3, "metallic": 0.0} })); + assert_eq!(screened(&unshaded), 0, "{id} unshaded"); + } +} + +/// A surface painted with a pattern draws no material highlight, so no highlight covers the gaps +/// between the pattern's tiles. +#[test] +fn a_pattern_takes_no_material_highlight() { + for id in TAKES { + let mut n = square_node(); + let paint = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + n.appearance = Appearance::basic(paint, Paint::None, 0.0).into(); + n.appearance.effects.push(crate::new_effect(id, &json!({ MATERIAL: {"roughness": 0.3, "metallic": 0.0} })).unwrap_or_else(|| panic!("{id}"))); + let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { solid_art(&n) }; + let art = art.unwrap_or_else(|| panic!("{id} draws")); + assert_eq!(screened(&art), 0, "{id}"); + } +} + +/// The meshes a 3D export writes carry the material: the effects that take one keep it, and every +/// other is the default. +#[test] +fn meshes_carry_the_material() { + for id in TAKES { + let mut n = square_node(); + let Some(fx) = crate::new_effect(id, &json!({ MATERIAL: {"roughness": 0.25, "metallic": 0.75} })) else { panic!("{id}") }; + n.appearance.effects.push(fx); + let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("{id}: {e}")); + assert!(!meshes.is_empty(), "{id}"); + assert!(meshes.iter().all(|m| (m.material.roughness(), m.material.metallic()) == (0.25, 0.75)), "{id}"); + } + let mut n = square_node(); + let Some(fx) = crate::new_effect(EXTRUDE, &json!({})) else { panic!("extrude") }; + n.appearance.effects.push(fx); + assert!(three_d_meshes(&n).unwrap_or_default().iter().all(|m| m.material.is_default())); +} diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 409a5c1dc3..3c1b3f1f2e 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -243,7 +243,11 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result Result, String> { let label = label_of(&fx.id); let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; - let p = crate::merged_params(&fx.id, &fx.params); + let mut p = crate::merged_params(&fx.id, &fx.params); + // The edges are those of the faces the default material builds, whatever the effect's material. + if let Some(material) = p.get_mut(super::MATERIAL) { + *material = Value::Object(serde_json::Map::new()); + } let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; let face = |f: &Facet| WireFace { path: f.path(), stroke: if classic { super::classic::stroke_width(f, &p) } else { super::seam_width(f) } }; let mut out = vec![]; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 945e6c92be..0fe4f7d10e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -71,6 +71,9 @@ serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } +# Whether two file names differ only in their Unicode normalization form, in a folder that ignores +# it (`script::dom::raster_capture`). Already in Cargo.lock, so this adds no new crate. +unicode-normalization = "0.1.26" # Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a # file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile, diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 1ad17361af..586deb604c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -448,6 +448,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&' /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in /// ([`plugin::run_command`]), which needs the command's id. pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + if matches!(spec.id, "shape.rectangle" | "shape.ellipse" | "shape.polygon" | "shape.star" | "path.create") { + return create::on_layer(s, p, spec.id, |s| (spec.run)(s, p)); + } + if matches!(spec.id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + return paint::object_only(s, p, spec.id, |s| (spec.run)(s, p)); + } if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 25f950ef9a..ec18bbccd1 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use vectorcraft_render::effects; @@ -30,7 +30,11 @@ use super::super::colorcmds::edit_if_changed; use super::super::edit::selected_roots; use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; -use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; +use super::super::object::{ + aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, scaling, transform_node, + transform_patterns, +}; +use super::super::objects_on_path; use super::super::typecmd::refresh_bounds_of; use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; use crate::{EngineError, Result, Session}; @@ -62,7 +66,7 @@ pub fn specs() -> Vec { "Offset Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}", + "{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. An object aligned to the pixel grid snaps to it after it moves, so the gap before it can differ from `gap`, and the next one starts from where it snapped. An Objects on Path group is measured with its members put back on the path after it moves. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}", has_multi, offset ), @@ -295,15 +299,62 @@ fn offset(s: &mut Session, p: &Value) -> Result { } // The first stays; each later one starts `gap` past where the one before it now ends. let mut end: Option = None; - let xfs: Vec<(NodeId, Affine)> = items - .iter() - .map(|&(id, start, finish)| { + let mut moves = false; + for &(_, start, finish) in &items { + let shift = end.map_or(0.0, |e| e + gap - start); + moves |= shift.abs() > 1e-9; + end = Some(finish + shift); + } + if !moves { + return Ok(json!({ "count": items.len() })); + } + let p = json!({ "strokes": false }); + let ids: Vec = items.iter().map(|(id, _, _)| *id).collect(); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &ids)?; + let last = items.len().saturating_sub(1); + let natural = aligned_symbol_transforms(&s.doc()?.doc); + edit_if_changed(s, "Offset Objects", |before, d| { + // Each one is moved (a pixel-aligned object snaps as it moves) and measured again, so the + // next one starts from where the one before it ends up. + let mut end: Option = None; + let mut changed = false; + // One copy of the document, made at the first Objects on Path group, to measure the groups on. + let mut scratch: Option = None; + for (i, &(id, start, finish)) in items.iter().enumerate() { let shift = end.map_or(0.0, |e| e + gap - start); - end = Some(finish + shift); - (id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) })) - }) - .collect(); - transform_each(s, "Offset Objects", false, &xfs)?; + if shift.abs() <= 1e-9 { + end = Some(finish); + continue; + } + if let Some(n) = d.node_mut(id) { + transform_node(n, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) }), sc, true); + } + keep_symbol_instances_aligned(d, id, &natural); + changed |= before.node(id) != d.node(id); + if i < last { + // The edge of an Objects on Path group is measured as the edit leaves it, with its + // members back on the path and on the pixel grid, on a copy: the edit places them. + let groups = objects_on_path::groups_in(d, id); + let m: &Document = if groups.is_empty() { + d + } else { + let c = scratch.get_or_insert_with(|| d.clone()); + if let (Some(n), Some(slot)) = (d.node(id), c.node_mut(id)) { + *slot = n.clone(); + } + let placed = objects_on_path::place_groups(c, &groups); + if !placed.is_empty() { + keep_aligned_in_with(c, &placed, &natural); + } + c + }; + let now = effects::preview::bounds_of(m, &[id], true).map(|b| if row { b.x1 } else { b.y1 }); + end = Some(now.unwrap_or(finish + shift)); + } + } + Ok(((), changed)) + })?; Ok(json!({ "count": items.len() })) } diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs index f9bfa01329..894b6138cd 100644 --- a/crates/engine/src/cmd/addons/arrange/marks.rs +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -6,12 +6,12 @@ #[cfg(test)] mod tests; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; use vectorcraft_render::drawn_bounds_with; @@ -36,7 +36,22 @@ pub fn specs() -> Vec { "Mark Bounds of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \ + \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \ + \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 \ + (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), \ + color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object \ + (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, \ + stacked directly above its object (above the outermost clip group, clipping sublayer or live object that holds it: \ + a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, \ + mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or \ + clipping pieces group, so the clip does not hide them and the live object does not take them in; in isolation mode, \ + marks that would go outside the isolated art are an error). Selected parts of compound paths, envelopes, meshes, repeats, \ + Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost \ + such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. \ + A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds \ + such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; \ + one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", has_selection, mark_bounds )] @@ -81,13 +96,18 @@ fn corner_paths(r: Rect, length: f64) -> Vec { .collect() } -/// Where the marks of object `id` go: directly above it, or above the outermost clip group or -/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer -/// with a clipping mask holds its marks too, since nothing lies outside it. -fn anchor(d: &Document, id: NodeId) -> NodeId { +/// Where the marks of object `id` go: directly above it, or above the outermost clip group, +/// clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group, +/// Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group, +/// graph series, graph design copy or clipping pieces group) that holds it at any +/// depth, which would otherwise clip them or take them in as one of its parts. A top-level layer +/// with a clipping mask holds its marks too, since nothing lies outside it. `held` keeps each +/// container's answer, so that siblings selected together look each container up once. +fn anchor(d: &Document, id: NodeId, held: &mut HashMap) -> NodeId { let (mut at, mut outermost) = (id, id); while let Some(up) = d.parent_of(at) { - if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() { + let holds = *held.entry(up).or_insert_with(|| d.node(up).is_some_and(|n| n.clips() || !plain(n)) && d.parent_of(up).is_some()); + if holds { outermost = up; } at = up; @@ -95,6 +115,51 @@ fn anchor(d: &Document, id: NodeId) -> NodeId { outermost } +/// Whether `n` is a layer or a group with no live role, which keeps new art as an ordinary member. +fn plain(n: &Node) -> bool { + let e = n.extras(); + matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) + && !n.is_compound_shape() + && e.shaper.is_none() + && e.objects_on_path.is_none() + && e.dimension.is_none() + && e.graph.is_none() + && e.flare.is_none() + && e.trace.is_none() + && e.generated.is_none() + && e.series_index.is_none() + && !e.graph_design_art + && !e.clip_pieces + && e.live_paint_gaps.is_none() + && !vectorcraft_tools::builder::is_live_paint(n) +} + +/// The outermost live object that draws a selected part with different geometry or placement. +fn measured_object(d: &Document, id: NodeId) -> NodeId { + let (mut at, mut measured) = (id, id); + while let Some(up) = d.parent_of(at) { + if let Some(n) = d.node(up) { + let redraws = match &n.kind { + NodeKind::Compound { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => true, + NodeKind::Blend { spec, .. } => { + (spec.spine.is_some() && !spec.no_spine) || spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath + } + _ => { + n.extras().shaper.is_some() + || (n.extras().trace.is_some() + && n.children() + .is_some_and(|children| children.first().is_some_and(|c| c.id == at) && n.editing_children().len() < children.len())) + } + }; + if redraws { + measured = up; + } + } + at = up; + } + measured +} + fn mark_bounds(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle"); @@ -106,18 +171,39 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result { if roots.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); } - let d = &s.doc()?.doc; + let st = s.doc()?; + let (d, isolation) = (&st.doc, st.isolation); let symbols = d.symbol_boxes(); let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + let mut held: HashMap = HashMap::new(); + let mut measured = HashSet::new(); let mut too_small = false; for id in roots { + if d.node(id).is_none_or(|n| n.is_guide()) { + continue; + } + let id = measured_object(d, id); + if !measured.insert(id) { + continue; + } let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; + let placed = matches!(n.kind, NodeKind::Blend { .. }).then(|| { + let mut art = vectorcraft_render::effects::expand_live_deep(Some(d), n); + art.appearance = n.appearance.clone(); + art + }); + let n = placed.as_ref().unwrap_or(n); let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue }; // Corner legs are at most half a side, so an object too small for any leg gets no marks. let (lx, ly) = legs(r, length); if rectangle || lx > FLAT || ly > FLAT { - marked.push((anchor(d, id), r)); + let at = anchor(d, id, &mut held); + // Marks placed outside the isolated art could not be selected or edited there. + if isolation.is_some_and(|iso| iso == at || !d.ancestry(at).is_some_and(|a| a.contains(&iso))) { + return Err(bad(C, "the marks would go outside the isolated art: exit isolation mode first")); + } + marked.push((at, r)); } else { too_small = true; } diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index 13c9401464..186c433505 100644 --- a/crates/engine/src/cmd/addons/arrange/marks/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -288,6 +288,228 @@ fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() { assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}"); } +#[test] +fn marks_on_envelope_sources_follow_the_drawn_bounds_once_per_live_object() { + for nested in [false, true] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 20.0, 0.0, 20.0, 20.0); + let top = rect(&mut s, 180.0, 120.0, 100.0, 60.0); + select(&mut s, &[a, b, top]); + let r = s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap(); + let envelope = NodeId(r["id"].as_u64().unwrap()); + let outermost = if nested { + let r = s.execute("object.repeat.grid", &json!({"ids": [envelope.0], "rows": 2, "cols": 2})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + } else { + envelope + }; + let layer = parent(&s, outermost); + let before = node(&s, outermost); + let d = &s.doc().unwrap().doc; + let drawn = vectorcraft_render::drawn_bounds(d, d.node(outermost).unwrap()).unwrap(); + assert!(drawn.x0 > marks_bounds(&s, b).x1, "the visible art is away from its sources"); + for selected in [vec![a], vec![a, b], vec![a, envelope]] { + for style in ["corners", "rectangle"] { + for bounds in ["geometric", "visual"] { + select(&mut s, &selected); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1, "one set of marks for the live object"); + assert_eq!(marks.len(), 1); + assert_eq!(children(&s, layer), vec![outermost, marks[0]]); + assert_eq!(node(&s, outermost), before); + assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "{nested}, {style}, {bounds}"); + assert_eq!(steps(&s), n + 1); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![outermost]); + assert_eq!(node(&s, outermost), before); + } + } + } + } +} + +#[test] +fn marks_on_a_blend_key_or_compound_shape_operand_go_above_the_live_object() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let layer = parent(&s, blend); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, blend), vec![a, b], "the blend keeps its keys"); + assert_eq!(children(&s, layer), vec![blend, mark]); + assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 20.0, 20.0)), "the key's own bounds"); + s.execute("edit.undo", &json!({})).unwrap(); + + for stored_spine in [false, true] { + s.execute("object.blend.options", &json!({"id": blend.0, "orientation": if stored_spine { "page" } else { "path" }})).unwrap(); + if stored_spine { + s.execute("object.blend.spine.reshapeSegment", &json!({"id": blend.0, "segment": 0, "t": 0.5, "dx": 0, "dy": 60})).unwrap(); + } + let before = node(&s, blend); + let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") }; + let drawn = vectorcraft_doc::live::blend_expand(keys, spec).iter().filter_map(Node::visual_bounds).reduce(|a, b| a.union(b)).unwrap(); + select(&mut s, &[a, b]); + let r = s.execute(COMMAND, &json!({"bounds": "visual"})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1, "repositioned keys are measured as one live object"); + assert_eq!(marks.len(), 1); + assert_eq!(children(&s, layer), vec![blend, marks[0]]); + assert_eq!(node(&s, blend), before); + assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1))); + s.execute("edit.undo", &json!({})).unwrap(); + } + + let c = rect(&mut s, 100.0, 100.0, 30.0, 30.0); + let d = rect(&mut s, 110.0, 100.0, 30.0, 30.0); + select(&mut s, &[c, d]); + s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap(); + let shape = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[d]); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, shape), vec![c, d], "the compound shape keeps its operands"); + assert!(near(marks_bounds(&s, mark), (110.0, 100.0, 140.0, 130.0)), "the operand's own bounds"); + let stack = children(&s, parent(&s, shape)); + assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == shape).map(|i| i + 1), "{stack:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + + // With the compound shape isolated, the marks could only go outside the isolated art: refused. + s.execute("object.isolate", &json!({"id": shape.0})).unwrap(); + select(&mut s, &[d]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("outside the isolated art"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn marks_on_an_outlined_glyph_stay_directly_above_it_inside_the_outlines_group() { + for isolated in [false, true] { + let mut s = session(); + let text = + s.execute("text.create", &json!({"x": 20, "y": 60, "text": "AB", "size": 24, "font": "Source Sans 3", "style": "Regular"})).unwrap(); + select(&mut s, &[NodeId(text["id"].as_u64().unwrap())]); + let outlines = ids_of(&s.execute("type.createOutlines", &json!({})).unwrap())[0]; + let glyphs = children(&s, outlines); + if isolated { + s.execute("object.isolate", &json!({"id": outlines.0})).unwrap(); + } + select(&mut s, &[glyphs[0]]); + let bounds = marks_bounds(&s, glyphs[0]); + let mark = ids_of(&s.execute(COMMAND, &json!({})).unwrap())[0]; + assert_eq!(parent(&s, mark), outlines); + let mut expected = glyphs; + expected.insert(1, mark); + assert_eq!(children(&s, outlines), expected); + assert!(near(marks_bounds(&s, mark), (bounds.x0, bounds.y0, bounds.x1, bounds.y1))); + } +} + +#[test] +fn marks_measure_blend_keys_and_steps_placed_on_a_diagonal_spine() { + let mut s = session(); + let a = rect(&mut s, 20.0, 30.0, 40.0, 10.0); + let b = rect(&mut s, 120.0, 130.0, 20.0, 40.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 8})).unwrap(); + s.execute("object.blend.make", &json!({"spacing": "steps", "steps": 3, "orientation": "path"})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let before = node(&s, blend); + let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") }; + let placed = vectorcraft_doc::live::blend_expand(keys, spec); + assert!(placed.len() > keys.len()); + let geometry = placed.iter().map(|n| n.path_data().unwrap().bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let visual = placed.iter().map(|n| n.visual_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let stored = before.geometric_bounds().unwrap(); + assert!(geometry.y0 < stored.y0 || geometry.y1 > stored.y1); + assert!(visual.x0 < geometry.x0 && visual.y0 < geometry.y0 && visual.x1 > geometry.x1 && visual.y1 > geometry.y1); + + for selected in [vec![a], vec![a, b], vec![blend]] { + for style in ["corners", "rectangle"] { + for (bounds, expected) in [("geometric", geometry), ("visual", visual)] { + select(&mut s, &selected); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1); + assert_eq!(marks.len(), 1); + let actual = marks_bounds(&s, marks[0]); + assert!( + near(actual, (expected.x0, expected.y0, expected.x1, expected.y1)), + "{selected:?}, {style}, {bounds}: {actual:?}, {expected:?}" + ); + for shape in &placed { + let r = if bounds == "visual" { shape.visual_bounds().unwrap() } else { shape.path_data().unwrap().bounds().unwrap() }; + assert!(actual.x0 <= r.x0 + 1e-6 && actual.y0 <= r.y0 + 1e-6 && actual.x1 >= r.x1 - 1e-6 && actual.y1 >= r.y1 - 1e-6); + } + assert_eq!(node(&s, blend), before); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, blend), before); + } + } + } +} + +#[test] +fn marks_on_a_dimension_part_go_above_the_live_object() { + let mut s = session(); + let r = s.execute("dimension.create", &json!({"a": [0, 0], "b": [100, 0]})).unwrap(); + let dimension = NodeId(r["id"].as_u64().unwrap()); + let layer = parent(&s, dimension); + let parts = children(&s, dimension); + let before = node(&s, dimension); + select(&mut s, &[parts[0]]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, dimension), parts, "the dimension keeps its generated parts"); + assert_eq!(node(&s, dimension), before); + assert_eq!(children(&s, layer), vec![dimension, mark]); + + let before = node(&s, mark); + s.execute("dimension.update", &json!({"ids": [dimension.0], "offset": 40})).unwrap(); + assert_eq!(children(&s, layer), vec![dimension, mark]); + assert_eq!(node(&s, mark), before, "updating the dimension preserves the mark"); +} + +#[test] +fn marks_on_an_image_trace_part_go_above_the_live_object() { + let mut s = session(); + let art = rect(&mut s, 20.0, 30.0, 60.0, 40.0); + select(&mut s, &[art]); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let r = s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true}})).unwrap(); + let trace = NodeId(r["id"].as_u64().unwrap()); + let layer = parent(&s, trace); + let parts = children(&s, trace); + let before = node(&s, trace); + let part = before.children().unwrap().iter().find(|n| n.path_data().is_some()).unwrap().id; + select(&mut s, &[part]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, trace), parts, "the trace keeps its generated parts"); + assert_eq!(node(&s, trace), before); + assert_eq!(children(&s, layer), vec![trace, mark]); + + let before = node(&s, mark); + let r = s.execute("imageTrace.make", &json!({"id": trace.0, "params": {"ignoreWhite": true, "threshold": 100}})).unwrap(); + let retraced = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(children(&s, layer), vec![retraced, mark]); + assert_eq!(node(&s, mark), before, "retracing preserves the mark"); +} + #[test] fn flat_objects_get_lines_and_guides_and_empty_groups_none() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index a3c44bd9db..bb38e9437e 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -185,6 +185,67 @@ fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() { assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); } +#[test] +fn offset_chains_pixel_aligned_objects_from_where_they_snap() { + let mut s = session(); + let ids: Vec = (0..4).map(|i| rect(&mut s, 100.0 * f64::from(i), 0.0, 10.0, 10.0)).collect(); + select(&mut s, &ids); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + s.execute("addon.arrange.offset", &json!({"gap": 0.25})).unwrap(); + let b: Vec = ids.iter().map(|i| bounds(&s, *i)).collect(); + let gaps: Vec = b.windows(2).map(|w| w[1].x0 - w[0].x1).collect(); + assert!(gaps.iter().all(|g| *g < 2.0), "they moved together: {gaps:?}"); + // Each one starts from where the one before it snapped to, so every gap is the same. + assert!(gaps.iter().all(|g| (g - gaps[0]).abs() < 1e-6), "{gaps:?}"); + // Touching objects that all snap back where they were: no undo step. + let mut s = session(); + let ids: Vec = (0..4).map(|i| rect(&mut s, 10.0 * f64::from(i), 0.0, 10.0, 10.0)).collect(); + select(&mut s, &ids); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + let n = steps(&s); + s.execute("addon.arrange.offset", &json!({"gap": 0.25})).unwrap(); + assert_eq!(steps(&s), n); +} + +#[test] +fn offset_chains_from_where_a_pixel_aligned_symbol_instance_snaps() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + rect(&mut s, 100.0, 0.0, 10.0, 10.0); + let b = NodeId(s.execute("symbol.new", &json!({"name": "Pixel", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, b, c]); + let gap = 0.25; + let n = steps(&s); + s.execute("addon.arrange.offset", &json!({"gap": gap})).unwrap(); + let (a, b, c) = (bounds(&s, a), bounds(&s, b), bounds(&s, c)); + assert!((b.x0 - a.x1 - gap).abs() > 1e-6, "the instance snapped: {a:?} {b:?}"); + assert!((c.x0 - b.x1 - gap).abs() < 1e-6, "the next gap is {gap}: {b:?} {c:?}"); + assert_eq!(steps(&s), n + 1); + s.execute("addon.arrange.offset", &json!({"gap": gap})).unwrap(); + assert_eq!(steps(&s), n + 1, "snapping back in place adds no undo step"); +} + +#[test] +fn offset_chains_from_the_edge_an_objects_on_path_group_ends_with() { + for gap in [0.6, 0.3, 1.45] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let aligned = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + select(&mut s, &[aligned]); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + let loose = rect(&mut s, 100.0, 200.0, 10.0, 10.0); + let path = NodeId(s.execute("shape.line", &json!({"x1": 30.5, "y1": 50.0, "x2": 30.5, "y2": 150.0})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[aligned, loose]); + let g = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, g, c]); + s.execute("addon.arrange.offset", &json!({"gap": gap})).unwrap(); + let (gb, cb) = (bounds(&s, g), bounds(&s, c)); + assert!((cb.x0 - gb.x1 - gap).abs() < 1e-6, "gap {gap}: the next one starts {gap} past the group's final edge: {gb:?} {cb:?}"); + } +} + #[test] fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index a9f1b48166..8dff9593e9 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Randomize Fill Colors", ["Object", "Plug-ins", "Color Effects"], None, - "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. A user compound path or live compound shape directly inside a graph series group takes a color unless that series is set to draw a compound design: a marker design while it draws markers, or a column design while it draws columns. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", has_selection, random_fill::run ), diff --git a/crates/engine/src/cmd/addons/color/random_fill.rs b/crates/engine/src/cmd/addons/color/random_fill.rs index eaf78e5660..799da3c423 100644 --- a/crates/engine/src/cmd/addons/color/random_fill.rs +++ b/crates/engine/src/cmd/addons/color/random_fill.rs @@ -6,7 +6,7 @@ #[cfg(test)] mod tests; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; @@ -16,7 +16,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint}; #[cfg(test)] use super::super::super::graph::is_design_art; -use super::super::super::graph::{is_series_group, paint_targets}; +use super::super::super::graph::{is_series_group, paint_targets, series_drawn_designs}; use super::super::super::menucmds::whole_or; use super::super::super::paint::swatch_solid; use super::super::super::{bad, checked_ids_or_selection, number_or, text_param}; @@ -210,6 +210,39 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { } let series_groups = cached_series_groups(before, &targets); let mut seen = std::collections::HashSet::new(); + let compound_groups: HashSet = targets + .iter() + .filter_map(|id| { + let n = before.node(*id)?; + if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { + return None; + } + before.parent_of(*id).filter(|p| series_groups.contains(p)) + }) + .collect(); + let mut drawn_designs = HashMap::new(); + // The series groups whose compounds are marks: the series draws no compound design, so the graph made none of + // them from one. Only a design the series draws can have made a compound. Each series is checked once. + let compound_marks: HashSet = compound_groups + .iter() + .copied() + .filter(|group| { + let Some(index) = before.node(*group).and_then(|g| g.extras().series_index).and_then(|i| usize::try_from(i).ok()) else { + return false; + }; + let graph = before.parent_of(*group).and_then(|p| before.node(p)); + graph.is_some_and(|graph| { + let Some(spec) = graph.extras().graph.as_deref() else { return false }; + let drawn = drawn_designs.entry(graph.id).or_insert_with(|| series_drawn_designs(spec)); + let (marker, column) = drawn(index); + ![column, marker].into_iter().flatten().any(|name| { + before.graph_designs.iter().any(|design| { + design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()) + }) + }) + }) + }) + .collect(); // A compound directly in a series group is one of the series' marks unless the graph drew it from a design; // the rest of the series' art below its top level is design art. let series_compound = |id: NodeId| { @@ -217,19 +250,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { return false; } - let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false }; - let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; - let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref()); - graph.is_some_and(|spec| { - let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str()); - let marker = spec.series_markers.get(index).and_then(Option::as_deref); - ![column, marker].into_iter().flatten().any(|name| { - before - .graph_designs - .iter() - .any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape())) - }) - }) + before.parent_of(id).is_some_and(|p| compound_marks.contains(&p)) }; targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups))); let count = keeping_series_paint(d, &roots, |d| { diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs index 11b4f989be..61655534d7 100644 --- a/crates/engine/src/cmd/addons/color/random_fill/tests.rs +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -398,6 +398,54 @@ fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() { } } +#[test] +fn a_user_compound_in_a_column_series_naming_an_undrawn_compound_marker_takes_a_color() { + let mut s = session(); + let tile = rects(&mut s, 2); + select(&mut s, &tile); + let design = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[design]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Compound { .. })); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + // A column series keeps a marker design it was given as a line series, and does not draw it. + s.edit("Name a marker design on a column series", |d, _| { + let mut extras = d.node_mut(graph).unwrap().extras_mut(); + let spec = extras.graph.as_deref_mut().unwrap(); + spec.series_markers = vec![Some("Tile".into()), Some("Tile".into())]; + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group)); + for ids in [vec![compound], vec![group], vec![graph]] { + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{ids:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + #[test] fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() { for kind in ["column", "line", "scatter"] { diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 68681b50fa..167cc4a9d1 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -2,10 +2,12 @@ //! the document named with the date and time through File › Save a Copy's save; New Symbols from //! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a //! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces -//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu +//! each image of a folder and saves the results to another ([`batch_trace`], #4921); Flood Fill +//! Artboards puts an artboard-sized rectangle on a layer of its own ([`flood_fill`]). Its submenu //! (Object › Plug-ins › Document Tools) is the UI's. mod batch_trace; +mod flood_fill; #[cfg(test)] mod tests; @@ -60,9 +62,36 @@ pub fn specs() -> Vec { has_doc, symbols_from_layers ), + cmd!( + "addon.document.floodFillArtboards", + "Flood Fill Artboards", + ["Object", "Plug-ins", "Document Tools"], + None, + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), activeArtboard?: n (0-based index of an existing artboard; the journal records that default here, for a replay; takes precedence over the view's active artboard; ignored when artboards is given or all is true; omitted from recorded actions), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused, as is a component too large to be finite; explicit RGB colors convert to the document's color model as paint.setFill does; default: the current fill, using the live fill after earlier batch steps or the fill the preview began with in a Flood Fill preview, an error when that is None), keepModel?: bool (as paint.setFill: true keeps an explicit RGB color in RGB), layer?: name (default: \"Flood Fill\"; trimmed, nonempty, at most 255 characters after trimming)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A destination layer that holds a clipping mask is rejected before any edit. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked, hidden or a template, in which case the prior selection stays. The current layer stays as it was. One undo step. Params must be an object or null (omitted options). Every option used is checked: null and values of the wrong type are errors. Refused in isolation mode or while a symbol, pattern or opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + flood_fill_enabled, + flood_fill::flood_fill_artboards + ), ] } +fn flood_fill_enabled(s: &Session) -> std::result::Result<(), String> { + super::super::maskedit::outside_mask_editing(s)?; + let st = s.active().ok_or("no document open")?; + if st.doc.artboards.is_empty() { + return Err("the document has no artboards".into()); + } + if st.doc.symbol_edit.is_some() { + return Err("finish editing the symbol before filling artboards".into()); + } + if st.doc.pattern_edit.is_some() { + return Err("finish editing the pattern before filling artboards".into()); + } + if st.isolation.is_some() { + return Err("exit isolation mode before filling artboards".into()); + } + Ok(()) +} + /// A document is open and the time can be told. fn has_clock(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs new file mode 100644 index 0000000000..349cb65455 --- /dev/null +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -0,0 +1,147 @@ +//! Flood Fill Artboards (`addon.document.floodFillArtboards`): a rectangle exactly the size of each +//! chosen artboard, painted with the current fill or a given color and no stroke, on a layer kept +//! for these rectangles. The rectangles are editable art, unlike an artboard's background color +//! (`artboard.setProps {color}`), which is a property of the artboard. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; +use vectorcraft_geom::{Affine, FillRule}; + +use super::super::super::layer::make_layer; +use super::super::super::newart::NewArt; +use super::super::super::panelcmds::listed_artboards; +use super::super::super::{bad, color_value}; +use crate::{Result, Session}; + +const COMMAND: &str = "addon.document.floodFillArtboards"; +/// The layer the rectangles go on when `layer` is left out. +const LAYER: &str = "Flood Fill"; +/// The longest layer name taken, in characters. +const MAX_NAME: usize = 255; + +/// `{artboards?, all?, activeArtboard?, color?, keepModel?, layer?}`: see the command's params text in [`super::specs`]. +pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result { + if !p.is_null() && !p.is_object() { + return Err(bad(COMMAND, "params must be an object or null")); + } + let st = s.doc()?; + let d = &st.doc; + if d.symbol_edit.is_some() { + return Err(bad(COMMAND, "finish editing the symbol before filling artboards")); + } + if d.pattern_edit.is_some() { + return Err(bad(COMMAND, "finish editing the pattern before filling artboards")); + } + if st.isolation.is_some() { + return Err(bad(COMMAND, "exit isolation mode before filling artboards")); + } + if d.artboards.is_empty() { + return Err(bad(COMMAND, "the document has no artboards")); + } + if p.get("keepModel").is_some_and(Value::is_null) { + return Err(bad(COMMAND, "`keepModel` must be true or false")); + } + super::super::super::paint::check_keep_model(p, COMMAND)?; + let all = match p.get("all") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(COMMAND, "`all` must be true or false"))?, + }; + let boards = match p.get("artboards") { + Some(_) if all => return Err(bad(COMMAND, "give `artboards` or `all`, not both")), + Some(v) => listed_artboards(d, v, "artboards", COMMAND)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![match p.get("activeArtboard") { + Some(v) => { + let i = v.as_u64().ok_or_else(|| bad(COMMAND, "`activeArtboard` must be a whole number"))?; + usize::try_from(i).ok().filter(|i| *i < d.artboards.len()).ok_or_else(|| bad(COMMAND, "no such artboard"))? + } + None => active_artboard(st), + }], + }; + // In Flood Fill's own preview the current fill is the one the interaction began with: a + // preview's selected rectangles may have given their color to the new-art paints since. A + // batch step takes the live fill, as the steps before it left it. + let current = st.interaction.as_ref().filter(|_| s.previewing && s.batch_stash.is_none()).map_or(&s.paint.fill, |it| &it.paint.fill); + let fill = match p.get("color") { + Some(v) => { + let color = color_value(v).filter(finite).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?; + Paint::solid(super::super::super::paint::new_color(s, p, color)) + } + None => match current { + Paint::None => return Err(bad(COMMAND, "the current fill is None: pick a fill or give `color`")), + paint => paint.clone(), + }, + }; + let name = match p.get("layer") { + None => LAYER.to_string(), + Some(v) => { + let name = v.as_str().map(str::trim).ok_or_else(|| bad(COMMAND, "`layer` must be a string"))?; + if name.is_empty() { + return Err(bad(COMMAND, "`layer` must not be empty")); + } + if name.chars().count() > MAX_NAME { + return Err(bad(COMMAND, format!("`layer` must be at most {MAX_NAME} characters"))); + } + name.to_string() + } + }; + let found = d.layers.iter().find(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())); + if found.is_some_and(|l| l.clips()) { + return Err(bad(COMMAND, "the destination layer holds a clipping mask")); + } + let found = found.map(|l| l.id); + let rects: Vec<_> = boards.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.rect)).collect(); + let look = NewArt::plain(Appearance::basic(fill, Paint::None, 0.0)); + let (layer, created, ids) = s.edit("Flood Fill Artboards", |d, sel| { + let (layer, created) = match found { + Some(id) => (id, false), + // A new layer goes below every other, so the rectangles stay behind the art. + None => { + let n = make_layer(d, Some(&name)); + (d.insert(None, 0, n)?, true) + } + }; + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let live = LiveShape::Rectangle { + w: r.width(), + h: r.height(), + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate(r.origin().to_vec2()), + }; + let path = live.to_path(); + let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + // Rectangles on a locked, hidden or template layer are not selected. + if d.node(layer).is_some_and(|l| l.visible && !l.locked && !l.is_template()) { + sel.set(ids.iter().copied()); + } + Ok((layer, created, ids)) + })?; + if p.get("artboards").is_none() && !all { + s.note_journal("activeArtboard", json!(boards[0])); + } + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "created": created })) +} + +/// Whether every component of `c` is finite: a component too large for `f32` reads as infinite. +fn finite(c: &Color) -> bool { + match *c { + Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|v| v.is_finite()), + Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|v| v.is_finite()), + Color::Gray { k } => k.is_finite(), + } +} + +/// The index of the view's active artboard ([`crate::DocState::active_artboard`]): when the +/// document no longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &crate::DocState) -> usize { + let at = |id: Option| id.and_then(|id| st.doc.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(st.doc.opened_artboard)).unwrap_or(0) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index d1bd77727d..66cda25344 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -195,6 +195,706 @@ fn the_layers_highlighted_in_the_layers_panel_are_the_default() { assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); } +const FLOOD: &str = "addon.document.floodFillArtboards"; + +/// A document of three 100 × 80 artboards with one rectangle on `Layer 1`, and a red fill. +fn boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s +} + +/// The children of the layer `id`. +fn kids(s: &Session, id: u64) -> Vec> { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap().to_vec() +} + +#[test] +fn flood_fill_covers_the_active_artboard_on_a_new_layer_at_the_bottom() { + let mut s = boards(); + let (current, steps) = (s.doc().unwrap().active_layer, s.doc().unwrap().history.undo.len()); + let before = s.doc().unwrap().doc.clone(); + let second = before.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + let r = s.execute(FLOOD, &json!({})).unwrap(); + assert_eq!(r["created"], json!(true), "{r}"); + let st = s.doc().unwrap(); + let layer = &st.doc.layers[0]; + assert_eq!((layer.id.0, layer.name.as_deref()), (r["layer"].as_u64().unwrap(), Some("Flood Fill")), "a new layer below the others"); + assert_eq!(st.doc.layers.len(), 2); + let rects = kids(&s, layer.id.0); + assert_eq!(rects.len(), 1); + let rect = &rects[0]; + assert_eq!(r["ids"], json!([rect.id.0])); + assert_eq!(rect.geometric_bounds(), Some(second.rect), "exactly the active artboard"); + assert!(matches!(&rect.kind, NodeKind::Path { live: Some(live), .. } if matches!(**live, vectorcraft_doc::LiveShape::Rectangle { .. }))); + assert_eq!(rect.appearance.fill_paint(), s.paint.fill, "the current fill"); + assert_eq!(rect.appearance.stroke_paint(), vectorcraft_color::Paint::None, "no stroke"); + let st = s.doc().unwrap(); + assert_eq!((st.selection.objects.clone(), st.active_layer), (vec![rect.id], current), "the rectangle is selected; the current layer stays"); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + assert_eq!(st.history.undo.last().unwrap().label, "Flood Fill Artboards"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before, "undo removes the layer and the rectangle"); +} + +#[test] +fn flood_fill_journal_replays_the_resolved_active_artboard() { + for params in [Value::Null, json!({}), json!({"all": false})] { + let mut s = boards(); + let second = s.doc().unwrap().doc.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + s.execute(FLOOD, ¶ms).unwrap(); + let (command, params) = s.journal.last().unwrap().clone(); + assert_eq!(params["activeArtboard"], json!(1)); + assert!(params.get("artboards").is_none()); + let mut replay = boards(); + let first = replay.doc().unwrap().doc.artboards[0].id; + replay.doc_mut().unwrap().active_artboard = Some(first); + let r = replay.replay(&command, ¶ms).unwrap(); + let rects = kids(&replay, r["layer"].as_u64().unwrap()); + assert_eq!(rects.len(), 1); + assert_eq!(rects[0].geometric_bounds(), Some(second.rect)); + } +} + +#[test] +fn flood_fill_action_uses_the_active_artboard_when_played() { + for params in [Value::Null, json!({}), json!({"all": false})] { + let mut s = boards(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let start = s.journal.len(); + s.execute(FLOOD, ¶ms).unwrap(); + let action = s.journal_for_action(start); + assert_eq!(action.len(), 1); + let (command, params) = &action[0]; + assert!(params.get("artboards").is_none()); + assert!(params.get("activeArtboard").is_none()); + let mut playback = boards(); + let third = playback.doc().unwrap().doc.artboards[2].clone(); + playback.doc_mut().unwrap().active_artboard = Some(third.id); + let r = playback.execute(command, params).unwrap(); + let rects = kids(&playback, r["layer"].as_u64().unwrap()); + assert_eq!(rects.len(), 1); + assert_eq!(rects[0].geometric_bounds(), Some(third.rect)); + } +} + +#[test] +fn flood_fill_explicit_targets_override_the_replay_artboard_and_stay_in_actions() { + for params in [json!({"artboards": [2], "activeArtboard": null}), json!({"all": true, "activeArtboard": 99})] { + let mut s = boards(); + let start = s.journal.len(); + let r = s.execute(FLOOD, ¶ms).unwrap(); + let rects = kids(&s, r["layer"].as_u64().unwrap()); + let indices = if params.get("artboards").is_some() { vec![2] } else { vec![0, 1, 2] }; + let expected: Vec<_> = indices.iter().map(|i| s.doc().unwrap().doc.artboards[*i].rect).collect(); + assert_eq!(rects.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(), expected); + let action = s.journal_for_action(start); + assert_eq!(action[0].1.get("artboards"), params.get("artboards")); + assert_eq!(action[0].1.get("all"), params.get("all")); + assert!(action[0].1.get("activeArtboard").is_none()); + } +} + +#[test] +fn flood_fill_reuses_its_layer_and_keeps_its_lock_and_visibility() { + let mut s = boards(); + let layer = s.execute(FLOOD, &json!({})).unwrap()["layer"].as_u64().unwrap(); + let first = s.doc().unwrap().doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer 1")).unwrap().id.0; + let art = kids(&s, first)[0].id.0; + s.execute("select.set", &json!({"ids": [art]})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer, "locked": true})).unwrap(); + let selected = s.doc().unwrap().selection.objects.clone(); + assert_eq!(selected.len(), 1); + let r = s.execute(FLOOD, &json!({"all": true, "color": "#00ff00"})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(layer)), "{r}"); + let st = s.doc().unwrap(); + let node = st.doc.node(NodeId(layer)).unwrap(); + assert!(node.locked && node.visible, "the layer stays locked"); + assert_eq!(st.doc.layers.len(), 2, "no second layer"); + assert_eq!(st.selection.objects, selected, "art on a locked layer is not selected"); + let rects = kids(&s, layer); + let added: Vec<_> = rects[1..].iter().map(|n| n.geometric_bounds().unwrap()).collect(); + let artboards: Vec<_> = st.doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(added, artboards, "one rectangle per artboard, on top of the layer's art"); + let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap()); + assert!(rects[1..].iter().all(|n| n.appearance.fill_paint() == green)); + // Hidden: the layer stays hidden, and listed artboards are filled once each, in order. + s.execute("layer.setProps", &json!({"id": layer, "locked": false, "visible": false})).unwrap(); + let r = s.execute(FLOOD, &json!({"artboards": [2, 0, 2]})).unwrap(); + let bounds = |id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + let new: Vec<_> = r["ids"].as_array().unwrap().iter().map(bounds).collect(); + assert_eq!(new, [artboards[0], artboards[2]]); + assert!(!s.doc().unwrap().doc.node(NodeId(layer)).unwrap().visible); + assert_eq!(s.doc().unwrap().selection.objects, selected, "art on a hidden layer is not selected"); + // A layer named by `layer`, found or made. + let r = s.execute(FLOOD, &json!({"layer": "Layer 1", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(first))); + let r = s.execute(FLOOD, &json!({"layer": " Paper "})).unwrap(); + assert_eq!((r["created"].clone(), s.doc().unwrap().doc.layers[0].name.as_deref()), (json!(true), Some("Paper"))); +} + +#[test] +fn flood_fill_preserves_selection_on_an_unlocked_template_layer() { + let mut s = boards(); + let art = s.doc().unwrap().selection.objects[0]; + let layer = s.execute("layer.new", &json!({"name": "Paper"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": layer, "template": true, "locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let st = s.doc().unwrap(); + let selected = st.selection.clone(); + assert!(!selected.objects.is_empty()); + let r = s.execute(FLOOD, &json!({"layer": "Paper", "all": true})).unwrap(); + let st = s.doc().unwrap(); + let node = st.doc.node(NodeId(layer)).unwrap(); + assert!(node.is_template() && node.visible && !node.locked); + assert_eq!(r["created"], json!(false)); + assert_eq!(r["layer"].as_u64(), Some(layer)); + assert_eq!(kids(&s, layer).len(), st.doc.artboards.len()); + assert_eq!(st.selection, selected); +} + +#[test] +fn flood_fill_converts_explicit_rgb_to_cmyk_like_set_fill() { + let mut s = Session::new(); + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let expected = s.paint.fill.clone(); + assert!(matches!(expected.color(), Some(vectorcraft_color::Color::Cmyk { .. }))); + for color in [json!("#ff0000"), json!([1.0, 0.0, 0.0])] { + let r = s.execute(FLOOD, &json!({"color": color})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, expected); + } +} + +#[test] +fn flood_fill_keep_model_keeps_explicit_rgb_in_a_cmyk_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + let r = s.execute(FLOOD, &json!({"color": "#ff0000", "keepModel": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert!(matches!(fill.color(), Some(vectorcraft_color::Color::Rgb { .. })), "{fill:?}"); + let undo = s.doc().unwrap().history.undo.len(); + for bad in [json!("yes"), json!(null)] { + let error = s.execute(FLOOD, &json!({"color": "#ff0000", "keepModel": bad})).unwrap_err().to_string(); + assert!(error.contains("keepModel"), "{error}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + } +} + +#[test] +fn flood_fill_refuses_isolation_without_an_edit_and_is_disabled() { + let mut s = boards(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.isolation, Some(NodeId(group))); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + let info = crate::find_command(FLOOD).unwrap().info(&s); + assert!(!info.enabled); + assert!(info.disabled_reason.unwrap().contains("exit isolation mode")); + for params in [json!({}), json!({"layer": "Layer 1"}), json!({"layer": "Paper", "all": true})] { + let error = super::flood_fill::flood_fill_artboards(&mut s, ¶ms).unwrap_err().to_string(); + assert!(error.contains("exit isolation mode"), "{error}"); + let error = s.execute(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains("exit isolation mode"), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + assert_eq!(st.isolation, Some(NodeId(group))); + } +} + +#[test] +fn flood_fill_in_a_batch_uses_the_fill_set_by_an_earlier_step() { + for none in [false, true] { + for preview in [false, true] { + let mut s = boards(); + if none { + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + } + let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap()); + let params = json!({"commands": [ + {"command": "paint.setFill", "params": {"color": "#00ff00"}}, + {"command": FLOOD, "params": {}} + ]}); + let r = if preview { + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview("command.batch", ¶ms).unwrap(); + let r = s.preview("command.batch", ¶ms).unwrap(); + s.commit_interaction().unwrap(); + r + } else { + s.execute("command.batch", ¶ms).unwrap() + }; + let id = NodeId(r["results"][1]["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), green, "initial fill None: {none}, batch preview: {preview}"); + } + } +} + +#[test] +fn flood_fill_rejects_a_destination_layer_with_a_clipping_mask_without_an_edit() { + let mut s = boards(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone(), s.doc().unwrap().history.undo.len(), s.paint.clone()); + let error = s.execute(FLOOD, &json!({"layer": " Layer 1 "})).unwrap_err().to_string(); + assert!(error.contains("destination layer holds a clipping mask"), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); +} + +#[test] +fn flood_fill_refuses_symbol_and_pattern_editing_without_an_edit() { + for symbol in [true, false] { + let mut s = boards(); + if symbol { + s.execute("symbol.new", &json!({"name": "Flood Fill"})).unwrap(); + s.execute("symbol.edit", &json!({"name": "Flood Fill"})).unwrap(); + } else { + s.execute("object.pattern.make", &json!({"name": "Tile"})).unwrap(); + } + let st = s.doc().unwrap(); + let layer = if symbol { st.doc.symbol_edit.as_ref().unwrap().layer } else { st.doc.pattern_edit.as_ref().unwrap().layer }; + let name = st.doc.node(layer).unwrap().name.clone().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + for params in [json!({}), json!({"layer": name}), json!({"layer": "Paper"})] { + let error = s.execute(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains(if symbol { "finish editing the symbol" } else { "finish editing the pattern" }), "{error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + } + } +} + +#[test] +fn flood_fill_is_disabled_while_editing_symbols_or_patterns() { + let spec = crate::find_command(FLOOD).unwrap(); + for symbol in [true, false] { + let mut s = boards(); + assert!(spec.info(&s).enabled); + if symbol { + s.execute("symbol.new", &json!({"name": "Flood Fill"})).unwrap(); + s.execute("symbol.edit", &json!({"name": "Flood Fill"})).unwrap(); + } else { + s.execute("object.pattern.make", &json!({"name": "Tile"})).unwrap(); + } + let info = spec.info(&s); + assert!(!info.enabled); + assert!(info.disabled_reason.unwrap().contains(if symbol { "finish editing the symbol" } else { "finish editing the pattern" })); + } +} + +#[test] +fn flood_fill_is_disabled_without_artboards() { + let mut s = boards(); + let spec = crate::find_command(FLOOD).unwrap(); + assert!(spec.info(&s).enabled); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + let info = spec.info(&s); + assert!(!info.enabled); + assert_eq!(info.disabled_reason.as_deref(), Some("the document has no artboards")); + let before = s.doc().unwrap().doc.clone(); + for params in [json!({}), json!({"all": true})] { + assert!(s.execute(FLOOD, ¶ms).unwrap_err().to_string().contains("the document has no artboards")); + assert_eq!(*s.doc().unwrap().doc, *before); + } +} + +#[test] +fn flood_fill_action_batch_rejects_non_object_params_at_preflight() { + let mut s = boards(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len(), s.paint.clone()); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let batch = json!({"commands": [{"command": FLOOD, "params": params}]}); + for error in [s.check_params("action.batch", &batch).unwrap_err(), s.execute("action.batch", &batch).unwrap_err()] { + let error = error.to_string(); + assert!(error.contains("action step 1 (`addon.document.floodFillArtboards`)"), "{error}"); + assert!(error.contains("params must be an object or null"), "{error}"); + } + assert_eq!(*s.doc().unwrap().doc, *before.0); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + assert_eq!(s.paint, before.2); + } +} + +#[test] +fn flood_fill_requires_object_or_null_params_directly_and_in_a_batch() { + for batch in [false, true] { + let mut s = boards(); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + let result = if batch { + s.execute("command.batch", &json!({"commands": [{"command": FLOOD, "params": params}]})) + } else { + s.execute(FLOOD, ¶ms) + }; + assert!(result.is_err(), "batch: {batch}, params: {params}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + } + let result = if batch { + s.execute("command.batch", &json!({"commands": [{"command": FLOOD}]})).unwrap()["results"][0].clone() + } else { + s.execute(FLOOD, &Value::Null).unwrap() + }; + assert_eq!(result["ids"].as_array().unwrap().len(), 1); + } +} + +#[test] +fn flood_fill_replay_rejects_non_object_params_without_an_edit() { + let mut s = boards(); + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone(), s.journal.clone()); + for params in [json!([]), json!([{}]), json!(5), json!(true), json!("all")] { + let error = s.replay(FLOOD, ¶ms).unwrap_err().to_string(); + assert!(error.contains("params must be an object or null"), "{params}: {error}"); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + assert_eq!(s.journal, before.4); + } + assert_eq!(s.replay(FLOOD, &Value::Null).unwrap()["ids"].as_array().unwrap().len(), 1); +} + +#[test] +fn flood_fill_refuses_bad_params_and_a_none_fill() { + let mut s = boards(); + let long = "x".repeat(256); + for p in [ + json!({"color": "#ff000080"}), + json!({"color": "red-ish"}), + json!({"color": null}), + json!({"artboards": [3]}), + json!({"artboards": []}), + json!({"artboards": null}), + json!({"artboards": [0.5]}), + json!({"activeArtboard": null}), + json!({"activeArtboard": "1"}), + json!({"activeArtboard": true}), + json!({"activeArtboard": -1}), + json!({"activeArtboard": 0.5}), + json!({"activeArtboard": 3}), + json!({"activeArtboard": u64::MAX}), + json!({"all": null}), + json!({"all": "yes"}), + json!({"all": true, "artboards": [0]}), + json!({"layer": ""}), + json!({"layer": " "}), + json!({"layer": 5}), + json!({"layer": null}), + json!({"layer": long}), + ] { + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + assert!(s.execute(FLOOD, &p).is_err(), "{p}"); + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); + } + // Components too large for f32 become infinite once read. + for color in [json!({"c": 1e308, "m": 0, "y": 0, "k": 0}), json!([1e39, 0, 0]), json!({"gray": 1e41}), json!({"l": 1e39, "a": 0, "b": 0})] { + let p = json!({ "color": color }); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute(FLOOD, &p).unwrap_err().to_string(); + assert!(e.contains("bad color"), "{p}: {e}"); + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); + } + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let e = s.execute(FLOOD, &json!({})).unwrap_err().to_string(); + assert!(e.contains("the current fill is None"), "{e}"); + assert!(s.execute(FLOOD, &json!({"color": "#336699"})).is_ok(), "a given color needs no current fill"); +} + +/// With New Art Has Basic Appearance off, a preview in a color selects rectangles whose color the +/// new-art fill takes; a later preview without `color` still uses the fill the interaction began with. +#[test] +fn flood_fill_previews_without_color_use_the_fill_the_interaction_began_with() { + let mut s = boards(); + s.prefs.new_art_basic = false; + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red, "the previewed rectangles gave their color to the new-art fill"); + let r = s.preview(FLOOD, &json!({})).unwrap(); + s.commit_interaction().unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, red, "the fill the interaction began with, not the previewed color"); +} + +/// With New Art Has Basic Appearance off and nothing selected, rectangle previews that follow a fill +/// preview each draw with that preview's fill, not the fill the interaction began with. +#[test] +fn rectangle_previews_after_a_fill_preview_keep_its_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let blue = s.paint.fill.clone(); + assert_ne!(blue, red); + for n in 0..2 { + let r = s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, blue, "rectangle preview {n} draws with the previewed fill"); + } + s.commit_interaction().unwrap(); +} + +/// A cancel or a commit after a fill preview, a rectangle preview and a failed rectangle preview +/// puts back the fill the interaction began with. +#[test] +fn cancel_or_commit_after_a_failed_rectangle_preview_restores_the_starting_fill() { + for commit in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert!(s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": "wide", "height": 20})).is_err()); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + assert_eq!(s.paint, before, "commit {commit}"); + } +} + +/// A cancel or a commit puts back the fill the interaction began with when a deselect preview +/// started from the rectangle preview's paints and a failed rectangle preview followed it. +#[test] +fn cancel_or_commit_after_a_deselect_and_a_failed_rectangle_preview_restores_the_starting_fill() { + for commit in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.preview("select.none", &json!({})).unwrap(); + assert!(s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": "wide", "height": 20})).is_err()); + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + assert_eq!(s.paint, before, "commit {commit}"); + } +} + +/// A failed fill preview after a fill preview and a rectangle preview leaves the starting fill for +/// the next rectangle preview. +#[test] +fn rectangle_preview_after_a_failed_fill_preview_uses_the_starting_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Rectangle").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert!(s.preview("paint.setFill", &json!({"color": "not a color"})).is_err()); + let r = s.preview("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), red); + s.cancel_interaction().unwrap(); +} + +#[test] +fn paint_swap_previews_from_an_empty_selection_commit_one_swap() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + let before = s.paint.clone(); + assert_ne!(before.fill, before.stroke); + s.begin_interaction("Swap").unwrap(); + for _ in 0..2 { + s.preview("paint.swap", &json!({})).unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); + } + s.commit_interaction().unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); +} + +#[test] +fn paint_preview_replacement_from_an_empty_selection_uses_the_starting_defaults() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Paint").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, before.fill); + s.preview("paint.swap", &json!({})).unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); + s.commit_interaction().unwrap(); + assert_eq!((&s.paint.fill, &s.paint.stroke), (&before.stroke, &before.fill)); +} + +#[test] +fn paint_previews_from_an_empty_selection_restore_defaults_on_cancel() { + for (command, params) in + [("paint.swap", json!({})), ("paint.setFill", json!({"color": "#0000ff"})), ("paint.setStroke", json!({"color": "#0000ff"}))] + { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let before = s.paint.clone(); + s.begin_interaction("Paint").unwrap(); + s.preview(command, ¶ms).unwrap(); + assert_ne!(s.paint, before, "{command}"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint, before, "{command}"); + } +} + +#[test] +fn paint_preview_from_an_empty_selection_keeps_its_fill_for_the_next_step() { + for cancel in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Fill").unwrap(); + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let blue = s.paint.fill.clone(); + assert_ne!(blue, red); + assert!(s.doc().unwrap().selection.is_empty()); + if cancel { + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red); + } else { + let result = s.preview("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), blue); + assert_eq!(s.paint.fill, blue); + s.commit_interaction().unwrap(); + } + } +} + +#[test] +fn flood_fill_cancel_with_a_selection_preserves_the_opening_paint_defaults() { + for resume in [false, true] { + for params in [json!({}), json!({"color": "#00ff00"}), json!({"color": "invalid"})] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("paint.setFill", &json!({"color": "#0000ff", "defaultsOnly": true})).unwrap(); + let st = s.doc().unwrap(); + let before = (st.doc.clone(), st.selection.clone(), st.history.undo.len(), s.paint.clone()); + assert!(!before.1.is_empty()); + assert_ne!(st.doc.node(before.1.objects[0]).unwrap().appearance.fill_paint(), before.3.fill); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#00ff00"})).unwrap(); + let result = s.preview(FLOOD, ¶ms); + assert_eq!(result.is_err(), params["color"] == "invalid"); + s.cancel_interaction().unwrap(); + let st = s.doc().unwrap(); + assert_eq!(*st.doc, *before.0); + assert_eq!(st.selection, before.1); + assert_eq!(st.history.undo.len(), before.2); + assert_eq!(s.paint, before.3); + if resume { + s.begin_interaction("Flood Fill Artboards").unwrap(); + let r = s.preview(FLOOD, &json!({})).unwrap(); + s.commit_interaction().unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(), before.3.fill); + } + } + } +} + +/// With New Art Has Basic Appearance off and nothing selected, a canceled preview in a color puts +/// back the new-art fill that its selected rectangles had given their color to. +#[test] +fn flood_fill_cancel_from_an_empty_selection_keeps_the_new_art_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + assert!(s.doc().unwrap().selection.is_empty()); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red, "the previewed rectangles gave their color to the new-art fill"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red, "the cancel puts the new-art fill back"); + assert!(s.doc().unwrap().selection.is_empty()); +} + +#[test] +fn flood_fill_cancel_after_a_rejected_preview_keeps_the_new_art_fill() { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + assert!(s.doc().unwrap().selection.is_empty()); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red); + assert!(s.preview(FLOOD, &json!({"color": [1e39, 0, 0]})).is_err()); + assert_eq!(s.paint.fill, red); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, red); + assert!(s.doc().unwrap().selection.is_empty()); +} + +/// A commit after a fill preview with nothing selected and a failed flood fill preview puts back +/// the fill the interaction began with. +#[test] +fn flood_fill_commit_after_a_fill_preview_and_a_rejected_preview_restores_the_new_art_fill() { + for stroke_first in [false, true] { + let mut s = boards(); + s.prefs.new_art_basic = false; + s.execute("select.none", &json!({})).unwrap(); + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + if stroke_first { + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + } + s.preview("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red); + if !stroke_first { + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + } + let stroke = s.paint.stroke.clone(); + assert!(s.preview(FLOOD, &json!({"color": [1e39, 0, 0]})).is_err()); + assert_eq!(s.paint.fill, red, "stroke first {stroke_first}"); + s.commit_interaction().unwrap(); + assert_eq!(s.paint.fill, red, "stroke first {stroke_first}"); + assert_eq!(s.paint.stroke, stroke, "a command run outside the previews keeps its change (stroke first {stroke_first})"); + } +} + /// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be /// written lists every document in `failed`, and either way the active document stays active. #[test] diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index e8e512a448..ef010d7f32 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -71,7 +71,7 @@ pub fn specs() -> Vec { "Make Numbers Sequence…", ["Object", "Plug-ins", "Type Tools"], None, - "{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}", + "{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error, unless replace skips it because its story holds no number or placeholder. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}", has_selection, numbers::make_numbers ), diff --git a/crates/engine/src/cmd/addons/typetools/numbers.rs b/crates/engine/src/cmd/addons/typetools/numbers.rs index c83c306496..f8064b9ded 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -9,7 +9,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject, TextRun}; use vectorcraft_geom::Rect; use vectorcraft_render::effects; use vectorcraft_text::edit; @@ -273,6 +273,109 @@ pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect() } +thread_local! { + /// [`text_passes`] of this thread. + static TEXT_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times Make Numbers Sequence has gone over a type object's text or style runs on this +/// thread: once to build the text an object would read, and once for each part of the object it +/// changes, however many numbers the text holds. +#[cfg(test)] +pub(crate) fn text_passes() -> u64 { + TEXT_PASSES.get() +} + +/// Adds one to [`text_passes`]. +fn note_text_pass() { + TEXT_PASSES.set(TEXT_PASSES.get().saturating_add(1)); +} + +/// `text` with `changes` (from the last to the first, as [`edits`] gives them) made. +pub(crate) fn replaced(text: &str, changes: &[Edit]) -> String { + note_text_pass(); + let mut out = String::with_capacity(text.len()); + let mut at = 0; + for (a, b, n) in changes.iter().rev() { + out.push_str(text.get(at..*a).unwrap_or_default()); + out.push_str(n); + at = *b; + } + out.push_str(text.get(at..).unwrap_or_default()); + out +} + +/// Makes `changes` (from the last to the first, as [`edits`] gives them) in `t`, with the +/// paragraphs, style runs and ruby that replacing each range by itself with +/// [`edit::replace_range`] would give, in one pass over each. +pub(crate) fn apply(t: &mut TextObject, changes: &[Edit]) { + if changes.len() < 2 || !t.ruby.is_empty() || t.runs.iter().any(|r| r.inline.is_some()) || { + let text = t.plain_text(); + changes.iter().any(|(a, b, n)| n.contains('\n') || text.get(*a..*b).is_none_or(|s| s.contains('\n'))) + } { + // One change (a whole text), one that adds or removes paragraphs, or text with ruby or + // inline art, whose spans each replacement moves or drops in turn. + for (a, b, n) in changes { + note_text_pass(); + t.splice_paras(*a, *b, n); + edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + return; + } + // Changes inside paragraphs leave every paragraph's style where it is: one splice sets the + // paragraph list as each of them would. + if let Some((a, b, n)) = changes.first() { + t.splice_paras(*a, *b, n); + } + replace_runs(&mut t.runs, changes); +} + +/// The runs with each range of `changes` replaced by its number in the style of the range's first +/// character, without a glyph choice, as [`edit::replace_range`] gives it. +fn replace_runs(runs: &mut Vec, changes: &[Edit]) { + note_text_pass(); + let old = std::mem::take(runs); + let mut out: Vec = Vec::with_capacity(old.len()); + let mut pending = changes.iter().rev().peekable(); + // Where the run starts and where the last replaced range ends. + let (mut off, mut cut) = (0, 0); + for r in old { + let (start, end) = (off, off + r.text.len()); + off = end; + // The run's style without a glyph choice, for pieces that start inside it and numbers. + let plain = CharStyle { glyph_alternate: None, ..r.style.clone() }; + // A piece of the run from `a` to `b`: one that starts inside it has no glyph choice. + let piece = |out: &mut Vec, a: usize, b: usize| { + let style = if a == start { &r.style } else { &plain }; + push(out, r.text.get(a - start..b - start).unwrap_or_default(), style); + }; + let mut pos = start.max(cut).min(end); + while let Some((a, b, n)) = pending.next_if(|(a, _, _)| *a < end) { + if pos < *a { + piece(&mut out, pos, *a); + } + push(&mut out, n, &plain); + cut = *b; + pos = cut.min(end); + } + if pos < end { + piece(&mut out, pos, end); + } + } + edit::normalize(&mut out); + *runs = out; +} + +/// Adds `text` in `style` to the end of `out`, onto the last run when it has the same style, so a +/// style is copied once for each change of style rather than once for each number. +fn push(out: &mut Vec, text: &str, style: &CharStyle) { + match out.last_mut() { + Some(last) if last.style == *style && last.inline.is_none() && style.glyph_alternate.is_none() => last.text.push_str(text), + _ => out.push(TextRun { text: text.to_string(), style: style.clone(), inline: None }), + } +} + pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let o = Options::parse(p)?; @@ -292,24 +395,43 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { if texts.len() > MAX_TEXTS { return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}"))); } - let threads = threads::ThreadIndex::of(d); - if texts.iter().any(|id| threads.threaded(*id)) { - return Err(bad(C, "threaded type can't be numbered: its frames share one story")); - } let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => t.plain_text(), _ => String::new(), }; - // Only objects that hold a number or the placeholder count, for the order too. - let mut texts: Vec<(NodeId, String)> = texts - .into_iter() - .map(|id| (id, plain(id))) - .filter(|(_, t)| match o.replace { - "numbers" => t.bytes().any(|b| b.is_ascii_digit()), - "placeholder" => !placeholder_spans(t).is_empty(), - _ => true, - }) - .collect(); + let threads = threads::ThreadIndex::of(d); + let threaded = || bad(C, "threaded type can't be numbered: its frames share one story"); + if o.replace == "all" && texts.iter().any(|id| threads.threaded(*id)) { + return Err(threaded()); + } + let holds = |t: &str| match o.replace { + "numbers" => t.bytes().any(|b| b.is_ascii_digit()), + "placeholder" => !placeholder_spans(t).is_empty(), + _ => true, + }; + // Only objects that hold a number or the placeholder count, for the order too. Threaded type + // is skipped like other type when its whole story holds none, so a placeholder split across + // two frames is still refused. + let mut kept: Vec<(NodeId, String)> = Vec::with_capacity(texts.len()); + let mut checked_threads = std::collections::HashSet::::new(); + for id in texts { + if threads.threaded(id) { + if threads.first_thread_index(id).is_some_and(|index| !checked_threads.insert(index)) { + continue; + } + let frames = threads.story(id); + let story: String = frames.iter().copied().map(plain).collect(); + if holds(&story) { + return Err(threaded()); + } + continue; + } + let t = plain(id); + if holds(&t) { + kept.push((id, t)); + } + } + let mut texts = kept; if o.order != "stacking" && o.shuffle.is_none() { let placed: Vec<(NodeId, Rect)> = texts .iter() @@ -345,11 +467,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { _ => vec![(0, text.len(), number.clone())], }; // The text it would have, to leave out objects that already read so. - let mut after = text.clone(); - for (a, b, n) in &changes { - after.replace_range(*a..*b, n); - } - if after != *text { + if replaced(text, &changes) != *text { plans.push((*id, changes)); } } @@ -367,11 +485,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { s.edit("Make Numbers Sequence", |d, sel| { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; - for (a, b, n) in changes { - t.splice_paras(*a, *b, n); - edit::replace_range(&mut t.runs, *a, *b, n); - t.ruby_after_replace(*a, *b, n.len()); - } + apply(t, changes); refresh_bounds(t); } d.remove_many(&removed)?; diff --git a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs index e7d51d47b4..d472268049 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs @@ -2,9 +2,9 @@ //! orders, removed objects, one undo step, and bad params refused without a change. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, TextObject, TextRun}; -use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence}; +use super::{COMMAND as C, Options, apply, edits, number_spans, placeholder_spans, sequence, text_passes}; use crate::Session; fn session() -> Session { @@ -93,6 +93,51 @@ fn threaded_type_is_refused() { assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n)); } +/// Replacing numbers or placeholders skips threaded type that holds none, as it skips other type. +#[test] +fn threaded_type_with_nothing_to_replace_is_skipped() { + let mut s = session(); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a b c", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let seat = text_at(&mut s, 40.0, 300.0, "Seat 0"); + let scans = super::threads::thread_scans(); + let builds = super::threads::story_builds(); + let out = s.execute(C, &json!({"ids": [a, b, seat.0], "replace": "numbers", "start": 4})).unwrap(); + assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index"); + assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check"); + assert_eq!(out["count"], json!(1)); + assert_eq!((plain(&s, NodeId(a)), plain(&s, seat)), ("a b c".to_string(), "Seat 4".to_string())); + let n = steps(&s); + let scans = super::threads::thread_scans(); + let builds = super::threads::story_builds(); + assert!(s.execute(C, &json!({"ids": [a, b], "replace": "placeholder"})).is_ok(), "no placeholder in the story"); + assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index"); + assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check"); + assert!(s.execute(C, &json!({"ids": [a, b]})).is_err(), "the whole text of threaded type is still refused"); + assert_eq!(steps(&s), n); +} + +/// A placeholder in a threaded story is refused even when no one frame holds all of it. +#[test] +fn threaded_type_whose_story_holds_a_placeholder_is_refused() { + let mut s = session(); + let words = format!("{} {{%n}}", "word ".repeat(40)); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": words, "area": {"width": 60, "height": 30}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 300, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let first = plain(&s, NodeId(a)); + let second = plain(&s, NodeId(b)); + assert!(!first.contains("{%n}"), "the selected frame alone has no placeholder"); + assert!((first + &second).contains("{%n}"), "the story contains the placeholder in thread order"); + let n = steps(&s); + assert!(s.execute(C, &json!({"ids": [a], "replace": "placeholder"})).is_err()); + assert_eq!(steps(&s), n); +} + #[test] fn the_spans_find_numbers_and_placeholders() { assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]); @@ -335,3 +380,65 @@ fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() { } assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n)); } + +#[test] +fn a_long_text_is_numbered_in_a_few_passes() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, &"9 ".repeat(2_000)); + let before = text_passes(); + s.execute(C, &json!({"ids": [a.0], "replace": "numbers", "start": 1})).unwrap(); + let passes = text_passes() - before; + assert_eq!(plain(&s, a), "1 ".repeat(2_000)); + assert!(passes <= 4, "2,000 numbers in one object took {passes} passes over its text"); +} + +/// `t` with `changes` made one at a time, as the command made them before it made them in one pass. +fn one_at_a_time(t: &TextObject, changes: &[(usize, usize, String)]) -> TextObject { + let mut t = t.clone(); + for (a, b, n) in changes { + t.splice_paras(*a, *b, n); + vectorcraft_text::edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + t +} + +#[test] +fn numbers_made_in_one_pass_keep_the_styles_and_ruby_of_one_at_a_time() { + let mut s = session(); + let id = text_at(&mut s, 40.0, 100.0, "x"); + let NodeKind::Text(base) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") }; + let base = base.clone(); + let style = |size: f64, glyph: Option| { + let mut st = base.first_style(); + st.size = size; + st.glyph_alternate = glyph.map(|ch| serde_json::from_value(json!({"ch": ch.to_string(), "gid": 7, "font": "F"})).unwrap()); + st + }; + let ruby = |start: usize, end: usize| serde_json::from_value(json!({"start": start, "end": end, "text": "r"})).unwrap(); + // Runs that split numbers, start at them and end inside them, with glyph choices and ruby + // over, across and between the numbers. + type Case<'a> = (Vec<(&'a str, f64, Option)>, Vec<(usize, usize)>); + let cases: Vec = vec![ + (vec![("a12 b", 10.0, None), ("34 c5", 12.0, Some('3')), ("6 -7.8 9", 14.0, None)], vec![(1, 3), (0, 6), (7, 12), (12, 14), (16, 18)]), + (vec![("1", 10.0, Some('1')), ("2", 11.0, Some('2')), (" x ", 12.0, None), ("333", 13.0, None)], vec![(0, 2), (2, 4), (5, 8)]), + (vec![("no 1, 2 or 3", 10.0, None), ("", 11.0, None), ("44", 12.0, Some('4'))], vec![(3, 4), (4, 9), (13, 14)]), + (vec![("a", 10.0, Some('a')), ("a", 10.0, Some('a')), (" 12 34", 10.0, None)], vec![(3, 5), (6, 8)]), + ]; + for (runs, spans) in cases { + let mut t = base.clone(); + t.runs = runs.iter().map(|(text, size, glyph)| TextRun { text: text.to_string(), style: style(*size, *glyph), inline: None }).collect(); + let text = t.plain_text(); + // Without ruby the runs are rebuilt in one pass; with it each change is made in turn. + for with_ruby in [false, true] { + t.ruby = if with_ruby { spans.iter().map(|(a, b)| ruby(*a, *b)).collect() } else { Vec::new() }; + for number in ["0", "123456", "5", "123"] { + let changes = edits(&text, number_spans(&text), number); + let mut fast = t.clone(); + apply(&mut fast, &changes); + let slow = one_at_a_time(&t, &changes); + assert_eq!((&fast.runs, &fast.ruby, &fast.paras), (&slow.runs, &slow.ruby, &slow.paras), "{text:?} numbered {number}"); + } + } + } +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 20cb4c96ab..28a9fbaaa9 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -23,7 +23,7 @@ use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, Node use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; -pub use flavours::{ImageRead, read_image}; +pub use flavours::{ImageRead, read_image, read_pixels}; pub(crate) use resources::SwatchChoices; pub use resources::{ArtResources, SymbolOptions, art_resources}; @@ -320,17 +320,8 @@ impl Clipboard { if let Some(bounds) = gradient_box { piece.appearance.pin_gradients(bounds); } - piece.opacity = parent.opacity; - piece.blend = parent.blend; - piece.isolate = parent.isolate; - piece.knockout = parent.knockout; - piece.knockout_shape = parent.knockout_shape; - let (mask, pixel_aligned) = (parent.extras().mask.clone(), parent.extras().pixel_aligned); - { - let mut extras = piece.extras_mut(); - extras.mask = mask; - extras.pixel_aligned = pixel_aligned; - } + super::object::copy_transparency(&mut piece, parent); + piece.extras_mut().pixel_aligned = parent.extras().pixel_aligned; let link = parent .extras() .graphic_style diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index bf900adcf1..80e31e849e 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -461,6 +461,20 @@ pub fn read_image(bytes: &[u8]) -> Result { Ok(ImageRead(img)) } +/// [`read_image`] for a bitmap another app put on the clipboard as decoded pixels, on any thread: +/// the pixels are encoded once as the PNG the document keeps, and kept as the decoded image the +/// renderers share, so neither this read nor the first frame that draws the image decodes them. +/// When the renderers' store refuses the pixels (over its budget, or no room beside the images +/// being drawn), they are dropped, and the renderers decode the PNG as they decode any other image, +/// under the same memory limits. An error when the image is empty or too large to draw. +pub fn read_pixels(img: image::RgbaImage) -> Result { + let img = image::DynamicImage::ImageRgba8(img); + let read = fileio::pixels_png(&img).map_err(|e| bad("clipboard.importImage", e.to_string()))?; + // Refused pixels are not held anywhere else, so the store's budget stays the only one. + let _kept = vectorcraft_render::keep_decoded_image(&read.blob, img); + Ok(ImageRead(read)) +} + impl Session { /// `clipboard.importImage` with `p` (its `mime` and `center`) for an image [`read_image`] read /// (off the UI thread in the desktop app), which it loads instead of reading `dataBase64`. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 16ceda7d38..083cfa65d9 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -12,6 +12,25 @@ use super::{ }; use crate::EngineError; +pub(crate) fn on_layer(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if p.get("onLayer").is_none() { + return run(s); + } + let parent = object_param(p, "onLayer", cmd)?; + let d = &s.doc()?.doc; + if let Some(id) = parent + && !d.node(id).is_some_and(|n| n.is_layer() && d.is_editable(id)) + { + return Err(bad(cmd, "onLayer must name an editable layer")); + } + let mode = std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal); + let isolation = std::mem::replace(&mut s.doc_mut()?.isolation, parent); + let result = run(s); + s.doc_mut()?.isolation = isolation; + s.draw_mode = mode; + result +} + pub fn specs() -> Vec { vec![ cmd!( @@ -19,7 +38,7 @@ pub fn specs() -> Vec { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), @@ -28,7 +47,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -37,7 +56,7 @@ pub fn specs() -> Vec { "Polygon", [], None, - "{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", + "{cx, cy, radius, onLayer?: layer id|null (draw normally on this layer), sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", has_doc, polygon ), @@ -46,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", has_doc, star ), @@ -137,7 +156,7 @@ pub fn specs() -> Vec { "Create Path", [], None, - "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], closed?: bool, d?: SVG path data} → {id}", + "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], onLayer?: layer id|null (draw normally on this layer), closed?: bool, d?: SVG path data} → {id}", has_doc, path_create ), @@ -155,7 +174,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -956,7 +975,38 @@ fn path_create(s: &mut Session, p: &Value) -> Result { add_look(s, "Pen", path_kind(path, None), look, None) } +/// The shown, unlocked layer or group `text.create`'s `parent` names, if it names one. +fn text_parent(s: &Session, p: &Value) -> Result> { + const C: &str = "text.create"; + let Some(parent) = object_param(p, "parent", C)? else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + Ok(Some(parent)) +} + +/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected. +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result { + let id = s.edit("Type", |d, sel| { + let id = d.alloc_id(); + let mut n = Node::new(id, kind); + NewArt::plain(Appearance::default()).apply(d, &mut n); + super::object::align_new_object(d, &mut n); + n.bbox_angle = bbox_angle; + d.insert(Some(parent), usize::MAX, n)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + fn text_create(s: &mut Session, p: &Value) -> Result { + let parent = text_parent(s, p)?; let x = f64_req(p, "x", "text.create")?; let y = f64_req(p, "y", "text.create")?; super::paint::check_keep_model(p, "text.create")?; @@ -993,8 +1043,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = - insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?; + let made = match parent { + Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?, + None => { + insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)? + } + }; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ac500697be..55726c31c9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones; an unknown category, or one without preset, is an error), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index e5463f6c44..5d849cfed2 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -481,6 +481,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, id, ¶ms)?; super::params::check_effect_channel(C, id, ¶ms)?; super::params::check_effect_center(C, id, ¶ms)?; + super::params::check_effect_halftone_style(C, id, ¶ms)?; super::params::check_effect_pathfinder(C, id, ¶ms)?; // Crop Marks take their style from the preferences when applied. if id == effects::CROP_MARKS && params.get("style").is_none() { @@ -826,6 +827,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, effect, ¶ms)?; super::params::check_effect_channel(C, effect, ¶ms)?; super::params::check_effect_center(C, effect, ¶ms)?; + super::params::check_effect_halftone_style(C, effect, ¶ms)?; super::params::check_effect_pathfinder(C, effect, ¶ms)?; } if edited.iter().any(|e| texture_load_effect(e)) { diff --git a/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs b/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs index 122bbff3c3..fc6fc47756 100644 --- a/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs +++ b/crates/engine/src/cmd/effectcmd/three_d_type_tests.rs @@ -90,6 +90,16 @@ fn three_d_type_carries_depth_between_extrude_and_inflate_and_merges_params_afte assert!(params.get("bevel").is_none()); } +#[test] +fn the_material_survives_a_type_change() { + let material = json!({"roughness": 0.3, "metallic": 0.6}); + let (mut s, id) = setup("threeD.extrude", json!({"material": material})); + for kind in ["inflate", "revolve", "plane"] { + s.execute("effect.setParams", &json!({"index": 0, "item": null, "threeDType": kind})).unwrap(); + assert_eq!(effect(&s, id).1["material"], material, "{kind}"); + } +} + #[test] fn revolve_angles_outside_half_a_turn_wrap_when_the_type_leaves_revolve() { let (mut s, id) = setup("threeD.revolve", json!({"rotationX": 270.0, "rotationY": -200.0})); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 38654bb8ba..52871e23fa 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -44,7 +44,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_clip, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, pixels_png, preview_with_clip, size_note}; mod heifread; pub mod hpgl; mod jp2read; @@ -87,6 +87,7 @@ pub(crate) use load::decode_native_file; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; +pub(crate) use load::is_raster_image; pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ @@ -146,6 +147,8 @@ mod commands; mod export_names; mod formats; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use access::FILES_READ; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 649e8944f8..0a4cf89b18 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -283,10 +283,18 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX #[cfg(not(target_arch = "wasm32"))] pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB"; +#[cfg(all(test, not(target_arch = "wasm32")))] +thread_local! { + /// The paths [`read_file`] has read on this thread, in order. + pub(crate) static FILES_READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { use std::io::Read; may_read(path)?; + #[cfg(test)] + FILES_READ.with(|r| r.borrow_mut().push(path.to_string())); // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index aa3be78e2a..9beed7e8a2 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -872,6 +872,7 @@ mod tests { ("source", json!(1), "`source` must be a string"), ("source", json!("files"), "`source` must be `folder` or `datasets`"), ("destination", json!(true), "`destination` must be a string"), + ("destination", json!("nowhere"), "`destination` must be `none`, `saveAndClose` or `folder`"), ("folder", json!(5), "`folder` must be a string"), ("label", json!(5), "`label` must be a string"), ("datasetFileNaming", json!(3), "`datasetFileNaming` must be a string"), @@ -895,6 +896,17 @@ mod tests { .to_string(); assert!(e.contains("`destinationFolder` must be a string"), "{e}"); assert!(s.active().is_none(), "no file was opened"); + // Saving to a folder needs the folder. + let e = s + .execute( + "action.batch", + &json!({"folder": src.to_string_lossy(), "destination": "folder", "commands": [{"command": "object.unlockAll"}]}), + ) + .unwrap_err() + .to_string(); + assert!(e.contains("`destinationFolder` is required when destination is `folder`"), "{e}"); + assert!(s.active().is_none(), "no file was opened"); + assert_eq!(std::fs::read_dir(&src).unwrap().count(), 1, "nothing was written next to the source file"); } #[cfg(unix)] diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs index 36734dbe39..a6961c28c2 100644 --- a/crates/engine/src/cmd/fileio/affinity/nodes.rs +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -288,4 +288,33 @@ mod tests { assert!(!path_in_range(&path(&[(0.0, 0.0), (f64::NAN, 0.0)]), k)); assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0, 1.0)]), Affine::scale(1.0e9))); } + + fn blended(blend: Blend) -> af::Node { + af::Node { + class: vectorcraft_affinity::stream::Tag::of(b"GrpN"), + name: String::new(), + visible: true, + locked: false, + opacity: 1.0, + blend, + kind: Kind::Group, + mask: None, + pixel_mask: None, + effects: vec![], + children: vec![], + } + } + + /// A blend mode VectorCraft has keeps it; one it lacks imports as Normal with one warning. + #[test] + fn blend_modes_map_or_import_as_normal_with_a_warning() { + let group = || NodeKind::Group { children: vec![], clip: false }; + let mut b = Builder::new(1.0); + assert_eq!(b.base(&blended(Blend::Multiply), group()).blend, BlendMode::Multiply); + assert!(b.warnings.is_empty(), "{:?}", b.warnings); + for _ in 0..2 { + assert_eq!(b.base(&blended(Blend::LinearLight), group()).blend, BlendMode::Normal); + } + assert!(b.warnings.len() == 1 && b.warnings[0].contains("Linear Light"), "{:?}", b.warnings); + } } diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index aec75eb4c6..dcb26b94b5 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -28,6 +28,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); let active = s.active; + // A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record. + let swatch_renames = s.swatch_renames.clone(); let opens = s.plugin_events_mark(); s.batch_stash = Some(vec![]); let mut grouped = Vec::with_capacity(cmds.len()); @@ -42,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { results } Err(e) => { + s.swatch_renames = swatch_renames; roll_back(s, start, &stash); // The documents the steps opened are closed again: plug-ins are not told of them. s.forget_plugin_opens_since(opens); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index e902f4185a..bddd245b71 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index f44b390a70..19c754be4b 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -88,6 +88,9 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do if files.len() > 1 { for (p, _) in &files { super::access::may_write_file(p)?; + if std::fs::metadata(p).is_ok_and(|meta| meta.permissions().readonly()) { + return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))); + } } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index b0a6aab5fc..53cac16bee 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1160,6 +1160,20 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { (drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size")) } +/// Whether `bytes` start as a file in a format [`raster_image`] reads, whether or not the rest of +/// it can be decoded. +pub(crate) fn is_raster_image(bytes: &[u8]) -> bool { + super::pcraftread::is_pcraft(bytes) + || psdread::is_psd(bytes) + || jxlread::is_jxl(bytes) + || super::jp2read::is_jpeg2000(bytes) + || super::heifread::is_heif(bytes) + || super::pxrread::is_pxr(bytes) + || craft_image_codecs::detect(bytes).is_some() + || super::tgaread::is_targa(bytes) + || super::pcxread::is_pcx(bytes) +} + /// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as /// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); @@ -1338,6 +1352,18 @@ pub(super) fn as_png(img: impl Into, icc: Option>, stored(png, "image/png", size, ppi) } +/// Decoded pixels `img` stored as a PNG, without a resolution or an ICC profile. An image whose +/// pixels as RGBA need more than [`MAX_RASTER_ALLOC`] is refused as too large to draw. +pub(crate) fn pixels_png(img: &image::DynamicImage) -> Result { + let (w, h) = (img.width(), img.height()); + if u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC { + return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); + } + let mut png = Vec::new(); + img.write_with_encoder(image::codecs::png::PngEncoder::new(&mut png)).map_err(err)?; + stored(png, "image/png", (w, h), None) +} + /// Effect › Distort › Glass › Load Texture…: encoded image `bytes`, in any format [`raster_image`] /// reads, as the `textureImage` Glass stores ([`LoadedTexture::to_stored`]). The pixels are decoded /// within [`MAX_RASTER_ALLOC`], counted as RGBA, as the renderer decodes them (#1717); a CMYK image diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 205a3cec35..e30cd8750a 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -3,7 +3,8 @@ //! USDZ (the USDA layer in an uncompressed ZIP, its data on a 64-byte boundary). //! //! Each solid of the object ([`vectorcraft_render::effects::three_d_meshes`]) is its own mesh, with a -//! material in the color it is painted (solids of one color share it). Positions are y up and +//! material in the color it is painted. Parts of one color and picture share a material; glTF and +//! USD also distinguish Roughness and Metallic, which OBJ's MTL omits. Positions are y up and //! about the point the object turns about: in points in OBJ and USD (whose layer says how many //! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear, //! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since @@ -200,23 +201,32 @@ fn check_parts(parts: &[SolidMesh]) -> Result<(), String> { parts.iter().try_for_each(|p| p.mesh.check()) } -/// A material: a color, with a picture that replaces its red, green and blue. +/// A material: a color, with a picture that replaces its red, green and blue, and the surface's +/// Roughness and Metallic, written by glTF and USD and omitted by OBJ's MTL. #[derive(Clone, Copy, PartialEq)] struct Material { color: [f32; 4], image: Option, + roughness: f64, + metallic: f64, } -/// The distinct materials of `scene`'s parts in order, and each part's index among them. -fn materials(scene: &Scene) -> (Vec, Vec) { +/// The distinct materials of `scene`'s parts in order, and each part's index among them. With +/// `with_factors`, Roughness and Metallic distinguish materials; otherwise only color and picture do. +fn materials(scene: &Scene, with_factors: bool) -> (Vec, Vec) { let mut out: Vec = vec![]; let index = scene .parts .iter() .enumerate() .map(|(k, p)| { - let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) }; - out.iter().position(|c| *c == m).unwrap_or_else(|| { + let m = Material { + color: p.color, + image: scene.texture(k).map(|(_, i)| i), + roughness: p.material.roughness(), + metallic: p.material.metallic(), + }; + out.iter().position(|c| c.color == m.color && c.image == m.image && (!with_factors || *c == m)).unwrap_or_else(|| { out.push(m); out.len() - 1 }) @@ -237,7 +247,7 @@ fn num(v: f64) -> String { fn obj(stem: &str, scene: &Scene) -> (String, String) { let parts = scene.parts; - let (materials, material) = materials(scene); + let (materials, material) = materials(scene, false); let mut o = String::new(); let _ = writeln!(o, "mtllib {stem}.mtl"); let _ = writeln!(o, "o {stem}"); @@ -303,7 +313,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) { fn gltf(stem: &str, scene: &Scene) -> String { let parts = scene.parts; - let (materials, material) = materials(scene); + let (materials, material) = materials(scene, true); let mut buffer: Vec = vec![]; let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]); let mut view = |buffer: &mut Vec, bytes: Vec, target: u32| -> usize { @@ -348,8 +358,8 @@ fn gltf(stem: &str, scene: &Scene) -> String { "name": format!("Material_{}", k + 1), "pbrMetallicRoughness": { "baseColorFactor": [linear(c[0]), linear(c[1]), linear(c[2]), c[3]], - "metallicFactor": 0.0, - "roughnessFactor": 1.0, + "metallicFactor": mat.metallic, + "roughnessFactor": mat.roughness, }, "doubleSided": true, }); @@ -400,7 +410,7 @@ fn prim_name(name: &str) -> String { fn usda(stem: &str, scene: &Scene) -> String { let parts = scene.parts; - let (materials, material) = materials(scene); + let (materials, material) = materials(scene, true); let root = prim_name(stem); let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2])); let list = |items: Vec| items.join(", "); @@ -462,7 +472,11 @@ fn usda(stem: &str, scene: &Scene) -> String { let _ = writeln!(u, " float inputs:opacity = {}", c[3]); } } - let _ = writeln!(u, " float inputs:roughness = 1"); + // UsdPreviewSurface's metallic is 0 when it is not written. + if mat.metallic != 0.0 { + let _ = writeln!(u, " float inputs:metallic = {}", num(mat.metallic)); + } + let _ = writeln!(u, " float inputs:roughness = {}", num(mat.roughness)); let _ = writeln!(u, " token outputs:surface\n }}"); if let Some(i) = mat.image { let _ = writeln!(u, "\n def Shader \"Texture\"\n {{"); diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index f87625d9fe..c2bf782d8f 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -283,3 +283,38 @@ fn parts_sharing_a_picture_write_it_once() { assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]); assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png"); } + +/// A part in `roughness` and `metallic`. +fn shiny(color: [f32; 4], roughness: f64, metallic: f64) -> SolidMesh { + let Some(material) = vectorcraft_three_d::Material::new(roughness, metallic) else { panic!("material") }; + SolidMesh { material, ..square(color) } +} + +#[test] +fn gltf_and_usda_write_each_parts_roughness_and_metallic() { + let parts = [square(RED), shiny(RED, 0.25, 0.75)]; + let g: Value = serde_json::from_str(&text(&plain_files("Box", "gltf", &parts).unwrap(), "Box.gltf")).unwrap(); + let pbr = |k: usize| { + (g["materials"][k]["pbrMetallicRoughness"]["roughnessFactor"].as_f64(), g["materials"][k]["pbrMetallicRoughness"]["metallicFactor"].as_f64()) + }; + assert_eq!(g["materials"].as_array().map(Vec::len), Some(2), "one red material per surface"); + assert_eq!((pbr(0), pbr(1)), ((Some(1.0), Some(0.0)), (Some(0.25), Some(0.75)))); + let u = text(&plain_files("Box", "usda", &parts).unwrap(), "Box.usda"); + assert_eq!(u.matches("float inputs:roughness = 1\n").count(), 1, "{u}"); + assert_eq!(u.matches("float inputs:roughness = 0.25\n").count(), 1, "{u}"); + assert_eq!(u.matches("float inputs:metallic = 0.75\n").count(), 1, "the default material writes no metallic: {u}"); + // OBJ's materials carry no factors; both red parts share one material. + let files = plain_files("Box", "obj", &parts).unwrap(); + assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 1); + let o = text(&files, "Box.obj"); + assert_eq!(o.lines().filter(|line| line.starts_with("usemtl ")).collect::>(), ["usemtl Material_1", "usemtl Material_1"]); +} + +/// Parts in the default material write what they wrote before materials existed. +#[test] +fn the_default_material_writes_the_earlier_factors() { + let g = text(&plain_files("Box", "gltf", &[square(RED)]).unwrap(), "Box.gltf"); + assert!(g.contains("\"metallicFactor\": 0.0,") && g.contains("\"roughnessFactor\": 1.0\n"), "{g}"); + let u = text(&plain_files("Box", "usda", &[square(RED)]).unwrap(), "Box.usda"); + assert!(u.contains(" float inputs:roughness = 1\n") && !u.contains("inputs:metallic"), "{u}"); +} diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 453fed3971..8878456b5c 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1093,6 +1093,22 @@ impl SaveJob { { return Err(refused); } + // An existing destination that is a folder or a read-only file is refused before any file + // is written too. + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 { + for (p, _) in &files { + let Ok(meta) = std::fs::metadata(p) else { continue }; + let refused = if meta.is_dir() { + crate::EngineError::Other(format!("{p}: is a folder, not a file")) + } else if meta.is_file() && meta.permissions().readonly() { + super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } else { + continue; + }; + return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused }); + } + } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { write(p, bytes)?; @@ -1400,7 +1416,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when access to one of a save's files is refused, or it is a directory or an existing read-only file, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 7a6547890f..5369b34398 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -47,7 +47,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "\"layerNames\"", description: "layerNames (readable ids from names) | minimal (only referenced ids) | unique (content-hashed prefix on every id and class)", }, - FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" }, + FormatOption { + name: "decimals", + ty: "integer", + default: "3", + description: "coordinate precision, 1–7 decimal places; positive root width/height and viewBox size stay positive", + }, FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" }, FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" }, FormatOption { diff --git a/crates/engine/src/cmd/fileio/tests_pcraftread.rs b/crates/engine/src/cmd/fileio/tests_pcraftread.rs index 444ba06606..ba46f8040b 100644 --- a/crates/engine/src/cmd/fileio/tests_pcraftread.rs +++ b/crates/engine/src/cmd/fileio/tests_pcraftread.rs @@ -215,6 +215,14 @@ fn layers_that_cant_be_combined_leave_the_preview_with_a_note() { assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains(said), "{said}: {w:?}"); } + // A canvas whose combined pixels would take more memory than one image may use leaves the + // preview, saying so before any layer is read. + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + b.size = (12_000, 12_000); + let (r, _, pixels) = place(&b.bytes()); + let w = warnings(&r); + assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains("too large to combine"), "{w:?}"); + // A preview of the canvas's own size is not reduced, so nothing is said. let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); b.size = (30, 20); diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index ded0f137b3..fce524598e 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -374,6 +374,11 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { // The count follows the version, the bounds and the group's name. ([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"), (v7(8, vec![D::Long(3)]), "other than a slice"), + // A descriptor's list of more slices than are read, refused before any is looked at. + (v7(7, (0..10_001).map(|_| D::Long(0)).collect()), "more than the 10000 read"), + // Objects, and lists, nested one level deeper than are read. + (deep(17, |d| D::Obj(vec![("in", d)])), "nests too deep"), + (deep(17, |d| D::List(vec![d])), "nests too deep"), // A whole record whose name is longer than a slice's text may be. (v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"), ]; @@ -395,6 +400,21 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { // A file without slices opens without a word about them. let (s, r) = open(&psd(true), json!({})); assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); + // Objects and lists nested as deep as are read come in. + for data in [deep(16, |d| D::Obj(vec![("in", d)])), deep(16, |d| D::List(vec![d]))] { + let (_, r) = open(&with_resource(&psd(false), 1050, &data), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + } +} + +/// Resource 1050 in version 7 with no slices, whose descriptor also holds `levels` values nested +/// one in another by `wrap`, around a long. +fn deep(levels: usize, wrap: fn(D) -> D) -> Vec { + let nested = (0..levels).fold(D::Long(0), |d, _| wrap(d)); + let mut b = 7u32.to_be_bytes().to_vec(); + b.extend(16u32.to_be_bytes()); + b.extend(descriptor(&[("deep", nested), ("slices", D::List(vec![]))])); + b } #[test] diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs index ae9762efc3..a60e9841b2 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -28,6 +28,64 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() { } } +#[test] +fn readonly_sidecar_leaves_every_save_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("save-readonly-sidecar"); + for format in ["vectorcraft", "eps"] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let path = dir.join(format!("Poster.{format}")).to_string_lossy().into_owned(); + let params = if format == "eps" { json!({"path": path, "useArtboards": true}) } else { json!({"path": path, "separateArtboards": true}) }; + let saved = session.execute("file.saveAs", ¶ms).unwrap(); + let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect(); + assert!(files.len() > 1); + let before: Vec<_> = files.iter().map(std::fs::read).collect::>().unwrap(); + session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let sidecar = files.last().unwrap(); + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = session.execute("file.saveAs", ¶ms); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for (file, bytes) in files.iter().zip(before) { + assert_eq!(std::fs::read(file).unwrap(), bytes, "{file}"); + } + assert_eq!(*session.doc().unwrap().doc, *doc); + assert!(session.doc().unwrap().is_dirty()); + } +} + +#[test] +fn readonly_export_file_leaves_every_export_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("export-readonly-sidecar"); + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let enc = super::Encoded { files: vec![(None, b"new main".to_vec()), (Some(1), b"new board".to_vec())], ..Default::default() }; + let path = dir.join("Poster.svg").to_string_lossy().into_owned(); + let files: Vec = enc.named(&doc, &path).into_iter().map(|(p, _)| p).collect(); + assert_eq!(files.len(), 2); + for file in &files { + std::fs::write(file, b"old").unwrap(); + } + let sidecar = &files[1]; + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = super::write_encoded(Some(&path), "Poster.svg", &doc, &enc, json!({})); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for file in &files { + assert_eq!(std::fs::read(file).unwrap(), b"old", "{file}"); + } +} + #[test] fn readonly_failed_save_keeps_document_and_options() { let mut session = Session::new(); diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 01e0a5a732..90222aae4b 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -128,6 +128,13 @@ impl StopOwner { #[derive(PartialEq)] pub struct GradientEditPaints(Vec); +impl GradientEditPaints { + /// Whether every edited paint, including every text run's paint, satisfies `matches`. + pub fn all_paints_match(&self, matches: impl FnMut(&Paint) -> bool) -> bool { + self.0.iter().flat_map(|target| &target.paints).all(matches) + } +} + #[derive(PartialEq)] struct EditedPaint { id: NodeId, @@ -520,12 +527,20 @@ fn apply_gradient_edit_in_model( switched = true; } } - let recolor = p.get("stops").is_some() || bool_or(p, "reverse", false); + let reverse = bool_or(p, "reverse", false); + let recolor = p.get("stops").is_some() || reverse; if let Some(stops) = p.get("stops") { - gp.gradient.stops = parse_stops(stops)?; - gp.swatch = None; - } - if bool_or(p, "reverse", false) { + let stops = parse_stops(stops)?; + let before = std::mem::replace(&mut gp.gradient.stops, stops); + if reverse { + // Midpoints mirrored with their segments. + gp.gradient.reverse(); + } + // A paint whose final stops stay as they are keeps its gradient swatch. + if gp.gradient.stops != before { + gp.swatch = None; + } + } else if reverse { // Midpoints mirrored with their segments. gp.gradient.reverse(); } @@ -894,3 +909,39 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::>() })) } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_color::Color; + + fn linked(stops: &[(f32, &str)]) -> Paint { + let stops = stops.iter().map(|(offset, hex)| GradientStop::new(*offset, Color::from_hex(hex).unwrap())).collect(); + let mut paint = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + paint.swatch = Some("Linked".into()); + Paint::Gradient(Box::new(paint)) + } + + fn swatch(paint: &Paint) -> Option<&str> { + match paint { + Paint::Gradient(g) => g.swatch.as_deref(), + _ => None, + } + } + + #[test] + fn writing_the_stops_a_paint_already_has_keeps_its_gradient_swatch() { + let paint = linked(&[(0.0, "#ffffff"), (1.0, "#000000")]); + let same = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]}); + assert_eq!(swatch(&apply_gradient_edit(&paint, &same, None).unwrap()), Some("Linked")); + let other = json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]}); + assert_eq!(swatch(&apply_gradient_edit(&paint, &other, None).unwrap()), None, "new stops unlink the swatch"); + } + + #[test] + fn writing_the_same_stops_reversed_unlinks_the_gradient_swatch() { + let paint = linked(&[(0.0, "#ffffff"), (1.0, "#000000")]); + let reversed = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}], "reverse": true}); + assert_eq!(swatch(&apply_gradient_edit(&paint, &reversed, None).unwrap()), None, "reversed stops unlink the swatch"); + } +} diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index f348a97f3c..cb70427ef0 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,7 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; -pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs}; +pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs, series_drawn_designs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index f0d42808ab..6b7ac1e9ec 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -88,22 +88,36 @@ pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: sup /// on or the legend has an entry for the series, or as the columns of a series drawn as columns or /// bars. fn draws_with(g: &GraphSpec, name: &str) -> bool { + let count = g.series_markers.len().max(g.series_columns.len()); + let drawn = series_drawn_designs(g); + (0..count).any(|s| { + let (marker, column) = drawn(s); + marker == Some(name) || column == Some(name) + }) +} + +/// For each series `s` of graph `g`, the designs it draws with, as [`draws_with`] counts them: its +/// marker design and its column design, each only when the series draws it. +pub(crate) fn series_drawn_designs<'a>(g: &'a GraphSpec) -> impl Fn(usize) -> (Option<&'a str>, Option<&'a str>) + 'a { let scatter = g.kind == GraphKind::Scatter; let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); // The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank // (a scatter graph's entries are its pairs of series, labeled by the first of each pair). - let in_legend = |s: usize| { + let in_legend = move |s: usize| { let entries = if scatter { nser.div_ceil(2) } else { nser }; let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str); g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label) }; // Point markers use the same range of designs: a scatter graph plots a pair of series for each. let plotted = if scatter { nser.div_ceil(2) } else { nser }; - let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s)); - let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); - let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); - g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s)) - || g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s)) + let shown = move |s: usize| s < plotted && (g.mark_points || in_legend(s)); + let marked = move |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); + let columnar = move |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); + move |s: usize| { + let marker = g.series_markers.get(s).and_then(Option::as_deref).filter(|_| marked(s)); + let column = g.series_columns.get(s).and_then(Option::as_ref).map(|c| c.design.as_str()).filter(|_| columnar(s)); + (marker, column) + } } /// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index b41415ef02..95aa571b48 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6891,6 +6891,11 @@ fn new_design_rename_delete_and_select_unused() { assert_eq!(spec(&s, id).series_markers, [Some("Dot".to_string()), Some("Dot".to_string())]); assert!(s.execute("graph.design", &json!({"rename": "Dot", "to": "New Design 2"})).is_err(), "taken"); assert!(s.execute("graph.design", &json!({"rename": "Nope", "to": "X"})).is_err()); + // Renaming a design to its own name succeeds and records no undo step. + let (steps, designs) = (s.doc().unwrap().history.undo.len(), s.execute("graph.design", &json!({})).unwrap()["designs"].clone()); + assert_eq!(s.execute("graph.design", &json!({"rename": "Dot", "to": "Dot"})).unwrap()["name"], "Dot"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], designs); // Delete several at once. s.execute("graph.design", &json!({"delete": ["Dot", "New Design 2"]})).unwrap(); assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], json!([])); diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index 9677f23ad6..70a5b11b9f 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Color; use vectorcraft_doc::Node; -use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes}; +use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes, style}; use super::edit::selected_roots; use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param}; @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style?: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; sets shape and angle unless they are given: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -27,17 +27,24 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; + let styled = match p.get("style") { + Some(v) => { + let v = v.as_str().ok_or_else(|| bad(C, "style must be a string"))?; + style(v).ok_or_else(|| bad(C, format!("unknown style `{v}` (custom|grid|gridAngle|gridDots|gridDotsAngle)")))? + } + None => None, + }; let shape = match text_param(p, "shape", C)? { Some(v) => { DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))? } - None => DotShape::Circle, + None => styled.map_or(DotShape::Circle, |s| s.0), }; let frequency = number_or(p, "frequency", 20.0, C)?; if !(1.0..=300.0).contains(&frequency) { return Err(bad(C, "frequency must be between 1 and 300 lines per inch")); } - let angle = number_or(p, "angle", 45.0, C)?; + let angle = number_or(p, "angle", styled.map_or(45.0, |s| s.1), C)?; if !angle.is_finite() { return Err(bad(C, "invalid angle")); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 469ff2721e..3a52534ac8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -1017,13 +1017,22 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // The clipping path stays at the bottom of its clip group or clipping layer. + let from = d.parent_of(id); + let clips = |p: Option| p.and_then(|p| d.node(p)).filter(|p| p.clips()); + let is_mask = clips(from).and_then(Node::children).and_then(|c| c.first()).is_some_and(|c| c.id == id); + if is_mask && (parent != from || index != 0) { + return Err(bad(C, "the clipping path stays at the bottom of its clip group; release the clipping mask first")); + } + let index = if !is_mask && clips(parent).and_then(Node::children).is_some_and(|c| c.iter().any(|c| c.id != id)) { index.max(1) } else { index }; // An empty compound path takes the paint of the first path that goes into it: the path's own, // or the paint of the compound path it leaves, which is what painted it. let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); let into = compound.map(|c| c.id); - let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned); + // A compound path that is pixel-aligned already snaps the path it takes, too. + let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned) || compound.is_some_and(|c| c.extras().pixel_aligned); // A path that leaves a compound path for a layer or a group takes the compound path's paint and // pixel alignment, as Release Compound Path gives them to its paths. let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); @@ -1032,7 +1041,6 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; - let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index afc1a85f3d..a5e00eab67 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -174,6 +174,11 @@ struct Group { document: Option, /// An image placed from a DCS file: the plate files of their own its plates were read from. plate_files: Vec, + /// The stored relative paths of the group's objects other than `link`'s, each once: objects + /// with the same path and content can each keep a relative path of its own. + other_relatives: Vec, + /// `other_relatives` as a set, looked up for every object added to the group. + relatives_seen: std::collections::HashSet, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -203,6 +208,32 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } +/// Every place a linked image or placed document of `d` (a document looking from `base`) is read +/// from, wherever it is stored, brush art included, whether or not a file is there: each place +/// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, +/// as its plate-change check finds them. A link's absolute stored and relative paths are listed +/// too, for the relative path of every object in a group. Document-path restrictions apply before +/// any filesystem probe. +pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { + let mut out = vec![]; + for g in groups(d, None) { + let others = g.other_relatives.iter().map(|r| LinkInfo { relative: Some(r.clone()), ..g.link.clone() }); + for link in std::iter::once(g.link.clone()).chain(others) { + let mut mains: Vec = std::iter::once(link.path.as_str()) + .chain(link.relative.as_deref()) + .filter(|p| Path::new(p).is_absolute()) + .filter_map(|p| fileio::document_path(p, base.doc).ok()) + .collect(); + mains.extend(places(&link, base)); + for main in mains { + out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); + out.push(main); + } + } + } + out +} + /// The linked images and placed documents of `d` by file and content, wherever they are stored /// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object /// visited before it has (art being edited on a layer and its definition) counts once, by its @@ -220,10 +251,26 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), Some(_) => vec![], }; - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files }); + out.push(Group { + link: link.clone(), + key: key.to_string(), + ids: vec![], + document, + plate_files, + other_relatives: vec![], + relatives_seen: Default::default(), + }); out.len() - 1 }); - if let (Some(id), Some(g)) = (id, out.get_mut(i)) { + let Some(g) = out.get_mut(i) else { return }; + if let Some(r) = &link.relative + && g.link.relative.as_ref() != Some(r) + && !g.relatives_seen.contains(r) + { + g.relatives_seen.insert(r.clone()); + g.other_relatives.push(r.clone()); + } + if let Some(id) = id { g.ids.push(id); } }; @@ -399,6 +446,17 @@ fn found_at(path: String) -> Option { /// by name in the document's folder, then in that of [`LinkBase::relative`]. Only paths /// [`fileio::document_path`] follows from the document's own file are looked at. fn locate(link: &LinkInfo, base: LinkBase) -> Option { + let mut f = places(link, base).find_map(found_at)?; + f.relative = base.relative.map(|from| { + let from = absolute_path(from); + Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) + }); + Some(f) +} + +/// The places [`locate`] looks for the file of `link` at, in its order, whether or not a file is +/// there. +fn places<'a>(link: &'a LinkInfo, base: LinkBase<'a>) -> impl Iterator + 'a { let (relative, other) = (link.relative.as_deref(), base.doc != base.relative); let stored = [ (Some(link.path.as_str()), base.doc), @@ -407,12 +465,7 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { (Some(link.name()), base.doc), (other.then_some(link.name()), base.relative), ]; - let mut f = stored.into_iter().filter_map(|(p, from)| follow_from(p?, from, base.doc, fileio::document_path)).find_map(found_at)?; - f.relative = base.relative.map(|from| { - let from = absolute_path(from); - Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) - }); - Some(f) + stored.into_iter().filter_map(move |(p, from)| follow_from(p?, from, base.doc, fileio::document_path)) } pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option { @@ -2339,7 +2392,17 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } // Read before it is copied: a file that can't be shown isn't copied. - let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + let img = if images.is_empty() { + None + } else { + Some(linked_image(&bytes, Some(&path)).map_err(|e| { + // A file in no image format; a damaged image keeps its own error. + if s.image_only.get().is_some() && !fileio::is_raster_image(&bytes) && !super::place::dcs::is_dcs(&bytes) { + s.image_only.set(Some(false)); + } + bad(C, format!("{path}: {e}")) + })?) + }; // A copy beside the document would point at plate files it can't find there. if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) { return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are"))); @@ -3278,6 +3341,43 @@ mod tests { assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + /// Many objects of one file and content that each keep a relative path of their own make one + /// group, which lists every other relative path once, in the order the objects are stored. + #[test] + fn a_group_lists_each_other_relative_path_once_in_stored_order() { + let mut d = Document::new(612.0, 792.0); + let layer = d.default_layer(); + let relatives: Vec = (0..2_000).map(|i| format!("art/{}/pic.png", i % 1_000)).collect(); + for r in &relatives { + let link = LinkInfo { relative: Some(r.clone()), ..LinkInfo::new("/art/pic.png") }; + let im = ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + let id = d.alloc_id(); + d.insert(layer, 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + } + let groups = groups(&d, None); + assert_eq!(groups.len(), 1); + let g = &groups[0]; + assert_eq!(g.ids.len(), 2_000); + // Objects inserted at index 0 are stored last to first. + let first = g.link.relative.clone().unwrap(); + let mut expected: Vec = vec![]; + for r in relatives.iter().rev() { + if *r != first && !expected.contains(r) { + expected.push(r.clone()); + } + } + assert_eq!(expected.len(), 999); + assert_eq!(g.other_relatives, expected); + } + #[test] fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { for (name, stem) in [ diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 8385350b2e..661fe741e7 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the nearest clip group or clipped layer around each object must be the same one, or none for all; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -896,11 +896,39 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .collect(); // What the art draws, its geometry effects applied. - let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); - let b = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?.inflate(pad, pad); + let each: Vec = nodes.iter().filter_map(|n| vectorcraft_render::drawn_bounds(doc, n)).collect(); + let b = each.iter().fold(None, |acc, r| vectorcraft_geom::union_opt(acc, Some(*r))); + let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; + let mut b = drawn.inflate(pad, pad); + let mut clip_bounds = None; + if let Some(v) = p.get("clipBounds").filter(|v| !v.is_null()) { + let [x0, y0, x1, y1] = super::finite_numbers::<4>(v).ok_or_else(|| bad(cmd, "clipBounds must be four finite numbers [x0, y0, x1, y1]"))?; + if x1 <= x0 || y1 <= y0 { + return Err(bad(cmd, "clipBounds must have x1 greater than x0 and y1 greater than y0")); + } + let clip_rect = Rect::new(x0, y0, x1, y1); + // The rectangle must reach the art itself, not only the padding around it or the gap + // between two of the selected objects. + let reaches = |r: &Rect| { + let on = r.intersect(clip_rect); + on.width() > 0.0 && on.height() > 0.0 + }; + if !each.iter().any(reaches) { + return Err(bad(cmd, "clipBounds does not overlap the art")); + } + clip_bounds = Some(clip_rect); + b = b.intersect(clip_rect); + } let scale = ppi / 72.0; - // Snap to whole pixels. - let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); + // The image covers the bounds in whole pixels. + let px = |lo: f64, hi: f64| { + let pixels = (hi - lo) * scale; + let nearest = pixels.round(); + let error = 8.0 * f64::EPSILON * (lo.abs() + hi.abs()) * scale; + let pixels = if (pixels - nearest).abs() <= error { nearest } else { pixels }; + pixels.ceil().max(1.0) + }; + let region = Rect::new(b.x0, b.y0, b.x0 + px(b.x0, b.x1) / scale, b.y0 + px(b.y0, b.y1) / scale); // Create Clipping Mask: the image is clipped to the art's outline with its geometry effects // applied, as on the canvas. let clip = look @@ -918,7 +946,15 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .flatten() .map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)); - let tmp = isolated_doc(doc, nodes); + let mut tmp = isolated_doc(doc, nodes); + if let Some(rect) = clip_bounds { + let children = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()).map(std::mem::take).unwrap_or_default(); + let art = Node::group(tmp.alloc_id(), children); + let art = super::rasterfx::clip_group(&mut tmp, vectorcraft_geom::shapes::rectangle(rect), vectorcraft_geom::FillRule::NonZero, art); + if let Some(children) = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()) { + children.push(Arc::new(art)); + } + } let opts = raster.render_options(RasterFormat::Png); let (img, warning) = render_pixels(&tmp, region, scale, &opts, look.color_model)?; let png = @@ -937,9 +973,88 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p Ok(Rasterized { blob, alpha, width: img.width, height: img.height, xf, clip, warning }) } +/// The objects `ids` names for Rasterize, in paint order: each an object of the active document, +/// listed once, with no locks on it, its descendants, or a layer or group it is in. An object +/// inside another listed one is left out, as `edit::roots_of` leaves it out of a selection. +fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { + let ids = super::checked_ids_param(s, p, "ids", cmd)?; + let d = &s.doc()?.doc; + let mut listed = HashSet::with_capacity(ids.len()); + for id in &ids { + if !listed.insert(*id) { + return Err(bad(cmd, format!("id {} is listed twice", id.0))); + } + } + let mut roots = Vec::with_capacity(ids.len()); + let locks = d.locked_artboards(); + for id in &ids { + // The layers and groups from the top down to the object itself. + let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; + if d.node(*id).is_some_and(|n| n.is_layer()) { + return Err(bad(cmd, format!("id {} is a layer, not an object", id.0))); + } + if up.iter().any(|a| a != id && listed.contains(a)) { + continue; + } + let parent = up.len().checked_sub(2).and_then(|i| d.node(up[i])); + if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { + return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); + } + // A clipping path's image would clip its siblings to a rectangle. + if parent.is_some_and(Node::clips) && d.position(*id).is_some_and(|(_, i, _)| i == 0) { + let message = if parent.is_some_and(Node::is_layer) { + "is a layer's clipping path and cannot be rasterized on its own" + } else { + "is a clipping path; give its clip group's id" + }; + return Err(bad(cmd, format!("id {} {message}", id.0))); + } + let mut locked = false; + if let Some(node) = d.node(*id) { + node.walk(&mut |n| locked |= n.locked); + } + if locked || up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { + return Err(bad(cmd, format!("id {} is locked, in a locked layer or group, or contains locked art", id.0))); + } + if locks.holds_id(*id) { + return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); + } + if up.iter().any(|a| d.node(*a).is_some_and(|n| !n.visible)) { + return Err(bad(cmd, format!("id {} is hidden or in a hidden layer or group", id.0))); + } + roots.push(*id); + } + // The image goes where the last object is, so every object must share its clipping context: + // the nearest clip group or clipped layer around it, or none. + let clipper = |id: NodeId| d.ancestry(id).and_then(|up| up.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(Node::clips))); + if let Some(first) = roots.first() { + let context = clipper(*first); + if let Some(other) = roots.iter().find(|id| clipper(**id) != context) { + return Err(bad( + cmd, + format!( + "id {} is clipped differently from id {}: the nearest clip group or clipped layer around each object must be the same one, or none for all", + other.0, first.0 + ), + )); + } + } + Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) +} + +/// The id of the image in `node`, the node Rasterize makes: the image itself, or the image in its +/// clip group. +fn image_in(node: &Node) -> NodeId { + match &node.kind { + NodeKind::Group { children, .. } => children.iter().find(|c| matches!(c.kind, NodeKind::Image(_))).map_or(node.id, |c| c.id), + _ => node.id, + } +} + fn rasterize(s: &mut Session, p: &Value) -> Result { const C: &str = "object.rasterize"; - let roots = selected_roots(s)?; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = if given { rasterize_sources(s, p, C)? } else { selected_roots(s)? }; let st = s.doc()?; let nodes: Vec = roots.iter().filter_map(|id| st.doc.node(*id).cloned()).collect(); let image = rasterize_art(&st.doc, nodes, p, C, true)?; @@ -947,16 +1062,21 @@ fn rasterize(s: &mut Session, p: &Value) -> Result { if roots.is_empty() { return Err(bad(C, "nothing selected")); } - let id = s.edit("Rasterize", |d, sel| { + let (id, image_id) = s.edit("Rasterize", |d, sel| { let threaded = super::threads::frames(d); let node = image.into_node(d); + let image_id = image_in(&node); let id = d.wrap(&roots, |_| node)?; // Rasterized frames of threaded text leave their threads with the text they show. super::threads::leave_threads(d, &threaded); - sel.set([id]); - Ok(id) + if given { + sel.prune(d); + } else { + sel.set([id]); + } + Ok((id, image_id)) })?; - let mut out = json!({ "id": id.0, "width": w, "height": h }); + let mut out = json!({ "id": id.0, "imageId": image_id.0, "width": w, "height": h }); if let Some(w) = warning { out["warning"] = json!(w); } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index f420054d11..45b4dd9a79 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -408,6 +408,14 @@ impl Session { if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) { return; } + if self.previewing + && self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.selection.is_empty() && it.inherited_preview_paint.is_none()) + { + let before = self.paint.clone(); + if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) { + it.inherited_preview_paint = Some(before); + } + } let NewArtSource { appearance, opacity, blend, style, .. } = source; let kept_fill = fill.then(|| self.paint.fill.clone()); let kept_stroke = stroke.then(|| (self.paint.stroke.clone(), self.paint.stroke_width)); diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 26c5d2bbac..4dee23bcda 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -18,7 +18,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -395,7 +395,7 @@ impl DocSettings { } "rows" => { self.rows = if replaying { - v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) + v.as_f64().map(f64::round).filter(|n| *n >= 1.0).map(|n| n.min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } @@ -605,10 +605,10 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { - Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS)) + Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32) } /// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1 @@ -860,10 +860,34 @@ pub fn find(s: &Session, name: &str) -> Option { /// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names /// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without -/// `preset`. +/// `preset`. A `preset` or `presetCategory` that is not a string, a `presetCategory` that names no +/// category, and a `presetCategory` without a `preset` are errors, except in a replay, which reads +/// a saved step as earlier versions did: such a value is left out, and an unknown category finds no +/// preset. fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { - let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; - let found = match str_param(p, "presetCategory") { + if s.replaying() { + let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; + let found = match str_param(p, "presetCategory") { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + return found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))); + } + let name = text_param(p, "preset", cmd)?; + let wanted = text_param(p, "presetCategory", cmd)? + .map(|c| { + category_names() + .find(|n| n.eq_ignore_ascii_case(c)) + .ok_or_else(|| bad(cmd, format!("unknown category `{c}` ({})", category_names().collect::>().join(", ")))) + }) + .transpose()?; + let Some(name) = name else { + return match wanted { + Some(_) => Err(bad(cmd, "presetCategory needs a preset")), + None => Ok(s.default_settings()), + }; + }; + let found = match wanted { Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), None => find(s, name), }; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 2c875762a6..413405ba4f 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -35,10 +35,10 @@ pub(crate) use align::choice; pub(crate) use arrange::group_nodes; pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; pub use commands::specs; -pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; +pub(super) use compound::{as_clipping_path, copy_transparency, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ - align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, - snap_if_aligned, snap_symbol_art, + align_new_object, aligned_symbol_transforms, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned, keep_pixel_aligned, + keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 955520427c..8ed4656295 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -106,8 +106,8 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { } /// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a -/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The -/// selection stays as it is. +/// group (default: the current layer), on top of its contents or at `index` (0 = bottom; refused +/// in an Image Trace object, whose source image stays at the bottom). The selection stays as it is. pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { const C: &str = "object.newGroup"; // Only an omitted key takes its default; `null` is refused like any other bad value. @@ -132,6 +132,10 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { if !d.is_editable(parent) { return Err(bad(C, "the layer or group is hidden or locked")); } + // An Image Trace object keeps its source image first; a group below it would end the tracing. + if index == 0 && crate::cmd::is_trace_group(n) { + return Err(bad(C, "index 0 of an Image Trace object is its source image; use index 1 or more")); + } let label = if compound { "Compound Path" } else { "Group" }; let gid = s.edit(label, |d, _| { let gid = d.alloc_id(); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index bea69d1698..f20f4fc782 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -142,7 +142,7 @@ pub fn specs() -> Vec { "Group", [], None, - "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; 0 is refused in an Image Trace object, whose source image stays at the bottom; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", has_doc, new_group ), @@ -196,7 +196,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Compound Path"], Some("Cmd+8"), - "{ids?: [id…] (selected first; default: the selection)}", + "{ids?: [id…] (selected first; default: the selection)} make one compound path of the selected paths, with the backmost object's paint and transparency (opacity, blend mode, Isolate Blending, Knockout Group, Knockout Shape and opacity mask); a selected group's transparency applies to the backmost path in it, with the two opacities multiplied", has_selection, compound_make ), @@ -205,7 +205,7 @@ pub fn specs() -> Vec { "Release", ["Object", "Compound Path"], Some("Cmd+Alt+Shift+8"), - "{ids?: [id…] (selected first; default: the selection)} release the selected compound paths into their paths, each with the compound path's paint; a path of several subpaths (an SVG `d` with several `M`s) splits into one path per subpath", + "{ids?: [id…] (selected first; default: the selection)} release the selected compound paths into their paths, each with the compound path's paint and transparency (opacity, blend mode, Isolate Blending, Knockout Group, Knockout Shape and opacity mask; a path keeps its own opacity mask when the compound path has none); a path of several subpaths (an SVG `d` with several `M`s) splits into one path per subpath", has_selection, compound_release ), diff --git a/crates/engine/src/cmd/object/compound.rs b/crates/engine/src/cmd/object/compound.rs index 4f4b0739c2..1d522531cd 100644 --- a/crates/engine/src/cmd/object/compound.rs +++ b/crates/engine/src/cmd/object/compound.rs @@ -12,7 +12,7 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { let id = s.edit("Make Compound Path", |d, sel| { d.node(backmost).ok_or(EngineError::NoNode(backmost))?; let mut units: Vec>> = vec![]; - let mut appearance = None; + let mut backmost = None; // The compound path is pixel-aligned when any of its paths was, or any compound path whose // paths it takes; its paths snap with its stroke, so they do not keep the property themselves. let mut aligned = false; @@ -22,11 +22,19 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { return Err(EngineError::Other("compound paths can only contain paths".into())); } n.walk(&mut |c| aligned |= c.extras().pixel_aligned); - compound_members(n, &mut appearance, &mut units); + compound_members(n, &mut backmost, &mut units); } let cid = d.alloc_id(); let mut c = Node::new(cid, NodeKind::Compound { children: vec![], rule: FillRule::NonZero }); - c.appearance = appearance.unwrap_or_default(); + // The compound path takes the paint and the transparency of the backmost object, its opacity + // mask included. A backmost path gives its mask up: mask art is stored art, and its ids are + // in the document once. + let mut mask_from = None; + if let Some(b) = &backmost { + c.appearance = b.appearance.clone(); + copy_transparency(&mut c, b); + mask_from = matches!(b.kind, NodeKind::Path { .. }).then_some(b.id); + } let ch = c.children_mut().ok_or(EngineError::NoNode(cid))?; // The paths in front run against the backmost one, so where they overlap it they cut holes // under the non-zero fill rule (#1197). A compound path's paths turn together, by its @@ -45,6 +53,9 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { let pn = Arc::make_mut(&mut p); pn.appearance = Appearance::default().into(); pn.extras_mut().pixel_aligned = false; + if mask_from == Some(pn.id) { + pn.extras_mut().mask = None; + } if let NodeKind::Path { path, live, .. } = &mut pn.kind { *live = None; if flip { @@ -66,17 +77,50 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result { } /// The paths in `n` (a path, a compound path, or a group searched in depth) onto `out`, in paint -/// order: each path alone, a compound path's paths together. Into `paint` goes the appearance of -/// the backmost found so far: the path's own, or its compound path's, which is what painted it. A +/// order: each path alone, a compound path's paths together. Into `backmost` goes the backmost +/// path or compound path found so far, whose appearance and transparency are what painted it. A /// group has no paint of its own to give: a group of outlined type made a compound path that drew -/// nothing. -fn compound_members(n: &Node, paint: &mut Option>, out: &mut Vec>>) { +/// nothing. A group's transparency applies to all of its members, so the backmost found in it +/// takes that transparency too (see [`take_group_transparency`]). +fn compound_members(n: &Node, backmost: &mut Option, out: &mut Vec>>) { match (&n.kind, n.children()) { (NodeKind::Path { .. }, _) => out.push(vec![Arc::new(n.clone())]), (NodeKind::Compound { .. }, Some(paths)) if !paths.is_empty() => out.push(paths.clone()), - (_, children) => return children.into_iter().flatten().for_each(|c| compound_members(c, paint, out)), + (_, children) => { + let found = backmost.is_some(); + children.into_iter().flatten().for_each(|c| compound_members(c, backmost, out)); + if !found && let Some(b) = backmost { + take_group_transparency(b, n); + } + return; + } } - paint.get_or_insert_with(|| n.appearance.clone()); + backmost.get_or_insert_with(|| n.clone()); +} + +/// Give `member` the transparency of `group`, which holds it: the two opacities multiply, and the +/// group's blend mode, Knockout Group and opacity mask apply where the member has none of its own. +/// Isolate Blending and Knockout Shape are on when either has them on. +fn take_group_transparency(member: &mut Node, group: &Node) { + member.opacity *= group.opacity; + if member.blend == Default::default() { + member.blend = group.blend; + } + if member.knockout == Default::default() { + member.knockout = group.knockout; + } + member.isolate |= group.isolate; + member.knockout_shape |= group.knockout_shape; + if member.extras().mask.is_none() && group.extras().mask.is_some() { + member.extras_mut().mask = group.extras().mask.clone(); + } +} + +/// Give `to` the object-level transparency of `from` (Transparency panel): its opacity, blend +/// mode, Isolate Blending, Knockout Group, Knockout Shape and opacity mask. +pub(crate) fn copy_transparency(to: &mut Node, from: &Node) { + (to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (from.opacity, from.blend, from.isolate, from.knockout, from.knockout_shape); + to.extras_mut().mask = from.extras().mask.clone(); } /// Is `n` a compound path to release: a compound path, or a path of several subpaths (an SVG `d` @@ -105,9 +149,25 @@ pub(super) fn compound_release(s: &mut Session, _: &Value) -> Result { let mut parts = vec![]; match &n.kind { NodeKind::Compound { children, .. } => { - for c in children { + for (k, c) in children.iter().enumerate() { let mut c = (**c).clone(); c.appearance = n.appearance.clone(); + // A path keeps its own opacity mask when the compound path has none. + let own_mask = c.extras().mask.clone(); + copy_transparency(&mut c, &n); + if n.extras().mask.is_none() && own_mask.is_some() { + c.extras_mut().mask = own_mask; + } + // Each path keeps the compound path's opacity mask; after the first, a copy + // of its art with ids of its own. + if k > 0 + && let Some(m) = n.extras().mask.as_deref() + { + let art = Arc::new(d.reid(&m.art)); + if let Some(mask) = c.extras_if_any().and_then(|e| e.mask.as_mut()) { + mask.art = art; + } + } // Each path keeps the compound path's pixel-aligned property. if n.extras().pixel_aligned { c.extras_mut().pixel_aligned = true; diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 5b0d47baa2..72fc1a93da 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -402,6 +402,15 @@ fn snap_instance(n: &mut Node, natural: &HashMap) { /// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid /// again. pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { + if ids.is_empty() { + return; + } + let natural = aligned_symbol_transforms(doc); + keep_aligned_in_with(doc, ids, &natural); +} + +/// [`keep_aligned_in`] with the symbols' natural-size transforms from [`aligned_symbol_transforms`]. +pub(crate) fn keep_aligned_in_with(doc: &mut Document, ids: &[NodeId], natural: &HashMap) { for id in ids { if doc.node(*id).is_some_and(holds_aligned) && let Some(n) = doc.node_mut(*id) @@ -409,20 +418,42 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { keep_pixel_aligned(n, Scaling::default()); } } - let aligned = doc.pixel_aligned_symbols(); - if aligned.is_empty() { + if natural.is_empty() { return; } - let natural: HashMap = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); for id in ids { - if doc.node(*id).is_some_and(|n| holds_instance(n, &natural)) + if doc.node(*id).is_some_and(|n| holds_instance(n, natural)) && let Some(n) = doc.node_mut(*id) { - snap_instances_in(n, &natural); + snap_instances_in(n, natural); } } } +/// The natural-size transform of each symbol aligned to the pixel grid, by name. +pub(crate) fn aligned_symbol_transforms(doc: &Document) -> HashMap { + doc.pixel_aligned_symbols() + .into_iter() + .map(|name| { + let xf = doc.symbol_natural_xf(&name); + (name, xf) + }) + .collect() +} + +/// Snap the natural-size instances of the symbols in `natural` that object `id` holds to the pixel +/// grid again, except in a symbol's editing layer, whose instances the outer symbol places. +pub(crate) fn keep_symbol_instances_aligned(doc: &mut Document, id: NodeId, natural: &HashMap) { + if natural.is_empty() || doc.symbol_edit.as_ref().is_some_and(|e| doc.layer_of(id) == Some(e.layer)) { + return; + } + if doc.node(id).is_some_and(|n| holds_instance(n, natural)) + && let Some(n) = doc.node_mut(id) + { + snap_instances_in(n, natural); + } +} + /// The objects of `after` that differ from their counterparts in `before` (or are new) and are /// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the /// walk stops: [`keep_pixel_aligned`] visits what it holds. diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 299ed5f49c..daa5277633 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -467,6 +467,30 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Vec { placed } +/// The Objects on Path groups in object `id` and inside it, outer ones first; empty when it holds +/// none. +pub(crate) fn groups_in(doc: &Document, id: NodeId) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + if is_objects_on_path(n) { + out.push(n.id); + } + for c in n.children().into_iter().flatten() { + walk(c, out); + } + } + let mut out = vec![]; + if let Some(n) = doc.node(id) { + walk(n, &mut out); + } + out +} + +/// Put the objects of `groups` (outer ones first, from [`groups_in`]) back on their paths, inner +/// groups first, as [`refresh`] does. Returns the groups that placing changed. +pub(crate) fn place_groups(doc: &mut Document, groups: &[NodeId]) -> Vec { + groups.iter().rev().copied().filter(|id| place_in(doc, *id)).collect() +} + /// Members of the group `id` that the edit replaced with new art at the same index keep their /// place on the path ([`ObjectsOnPath::follow_replacements`]). fn follow_replacements(before: &Document, doc: &mut Document, id: NodeId) { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2a61f7fb74..73daebcbff 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,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|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), 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 counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; 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; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond 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), 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, 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, radial, conic or diamond `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 color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces 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; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is 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). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {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), or with an opacity alone how many took the opacity}", + "{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|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), 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 counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; 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; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond 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), 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, 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, radial, conic or diamond `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 color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces 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; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is 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). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {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), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -948,6 +948,22 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) apply_paint_opacity(s, p, Some(paint), None, fill) } +pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if !switch_or(p, "objectOnly", false, cmd)? { + return run(s); + } + if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { + return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); + } + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone(), s.pending_paint.clone()); + let result = run(s); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors, s.pending_paint) = kept; + if result.is_ok() { + s.note_defaults_only(); + } + result +} + /// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or /// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' /// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 7c1a46350d..427eb4ada7 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -525,9 +525,22 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> check_effect_color(id, effect, params)?; check_effect_channel(id, effect, params)?; check_effect_center(id, effect, params)?; + check_effect_halftone_style(id, effect, params)?; check_effect_pathfinder(id, effect, params) } +/// The `style` in `params` of Vector Halftone (`effect`), as command `id` was given it: a parameter +/// error unless it names Custom or one of the named styles, in any letter case. `effect.apply` and +/// `effect.setParams` run this themselves before they edit, as they run [`check_effect_channel`]. +pub(crate) fn check_effect_halftone_style(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects::addons::halftone::{HALFTONE, style}; + let Some(v) = params.get("style") else { return Ok(()) }; + if effect != HALFTONE || v.as_str().and_then(style).is_some() { + return Ok(()); + } + Err(bad(id, "`style` must be one of custom, grid, gridAngle, gridDots, gridDotsAngle")) +} + /// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given /// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and /// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves @@ -1089,6 +1102,9 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { /// `command.batch` or `action.batch` step aren't checked (running it reports that), however deep they go. fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; + if id == "addon.document.floodFillArtboards" && !params.is_null() && !params.is_object() { + return Err(bad(id, "params must be an object or null")); + } if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = (id, super::effectcmd::requested_effect(params), params.get("params")) { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index ba2b523f62..949b470263 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -841,6 +841,15 @@ fn place(s: &mut Session, p: &Value) -> Result { Some(read) => read, None => prepare(s, p)?.read()?, }; + let image = match read.loaded.art { + Art::Image(..) => read.loaded.link.is_some(), + Art::Dcs(_) => true, + _ => false, + }; + if s.image_only.get().is_some() && !image { + s.image_only.set(Some(false)); + return Err(bad(PLACE, "the file is not an image")); + } apply(s, read) } diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 8420e67d30..0ee0340542 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -371,6 +371,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ ), p!("autoCollapseIconPanels", "User Interface", "", "Auto-Collapse Iconic Panels", bool), p!("toolGroupLabels", "User Interface", "", "Show Tool Group Labels", bool), + p!("uiToolIcons", "User Interface", "", "Tool Icons", choice(&[("current", "Current"), ("classic", "Classic")])), p!("openDocumentsAsTabs", "User Interface", "", "Open Documents As Tabs", bool), p!("largeTabs", "User Interface", "", "Large Tabs", bool), p!("systemTitleBar", "User Interface", "", "System Title Bar", bool), diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index a0ba6d243c..c2b6bec7b6 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; with limitTo the library's swatch of the row's new color comes first; a global swatch of `group` that is rewritten with another color links nothing, and the row's art keeps the row's new color; a null `swatch` is no swatch, and any other `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Randomize Colors", [], None, - "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", + "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys; a row's tint and swatch move with its new color and are dropped when the color changes}", always, randomize ), @@ -1535,6 +1535,9 @@ struct Row { /// `added`: with no current colors, the new color is a color added to the group, which it /// joins after the colors of the rows with current colors. added: bool, + /// `swatch`: the library key ("document" for the document's swatches) and the name of the + /// swatch the new color was picked from. + swatch: Option<(String, String)>, } /// The color model a row's colors take (`model`): each color's own, the new color's, or the @@ -1590,7 +1593,9 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { match p.get("map") { Some(Value::Object(m)) => m .iter() - .map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false })) + .map(|(k, v)| { + Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false, swatch: None }) + }) .collect(), Some(Value::Array(rows)) => rows .iter() @@ -1603,7 +1608,21 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32; let model = ModelRule::param(r, cmd)?; let added = switch_or(r, "added", false, cmd)?; - Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added }) + let swatch = match r.get("swatch") { + None | Some(Value::Null) => None, + Some(w) => { + let name = w.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()); + let library = match w.get("library") { + None | Some(Value::Null) => Some(super::swatchlib::DOCUMENT_SWATCHES), + Some(l) => l.as_str().filter(|l| !l.is_empty()), + }; + match (name, library) { + (Some(n), Some(l)) => Some((l.to_string(), n.to_string())), + _ => return Err(bad(cmd, format!("a row's `swatch` must be {{name, library?}} with a name and a library id: {w}"))), + } + } + }; + Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added, swatch }) }) .collect(), _ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")), @@ -1681,7 +1700,9 @@ impl ColorMap { }; let i = out.rows.len(); let colors: Vec = r.from.iter().map(Match::color).collect(); - let link = links.get(n).cloned().flatten(); + // A global swatch of the rewritten group that takes another color links nothing, and the + // row recolors as it would with no swatch (its tint of the swatch left out). + let link = links.get(n).cloned().flatten().filter(|l| !(l.global && out.group.iter().any(|g| g.name == l.name && g.shown != l.color))); // Colors that can't link to the swatch take the row's tint of it too. let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint)); out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(r.model.unwrap_or(model) != ModelRule::Keep)); @@ -1792,10 +1813,33 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(k) => super::swatchlib::library_swatches(s, k).unwrap_or_default(), None => vec![], }; + // A row's own `swatch`, the one its new color was picked from: of the swatches with its name, the + // first with the row's new color (as a color key, which rounds), when that one is a global or + // spot swatch and no Global Adjust changes the colors the row maps. A swatch or library that is + // not there (deleted since the pick) links nothing, and the result names it. Limit to Library's + // swatch of that color comes first. + let same = |a: Color, b: Color| ColorKey::of(&a) == ColorKey::of(&b); + let mut not_found: Vec = vec![]; + let picked: Vec> = rows + .iter() + .map(|r| { + let (lib, name) = r.swatch.as_ref()?; + let list = super::swatchlib::library_swatches(s, lib).filter(|l| l.iter().any(|w| w.name == *name)); + if list.is_none() { + not_found.push(name.clone()); + } + let to = r.new_color()?; + let w = list?.into_iter().find(|w| w.name == *name && w.paint.color().is_some_and(|c| same(c, to)))?; + Some(w).filter(|w| (w.global || w.spot) && mapped_adjust.is_identity()) + }) + .collect(); // A row with no current colors recolors nothing, so its swatch does not join the document. let row_swatches: Vec> = rows .iter() - .map(|r| r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned())) + .zip(picked) + .map(|(r, own)| { + r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned().or(own)) + }) .collect(); // While an object of a dynamic symbol instance's art is selected, the selection is refused, as // `selected_roots` refuses it. @@ -1872,19 +1916,28 @@ fn apply(s: &mut Session, p: &Value) -> Result { // The rows' library swatches join the document (one it has with that name and colour is // used as it is). let mut added = vec![]; + // Each library swatch added under a free name, with its library name: rows that took two + // library swatches of one name both find theirs again. + let mut renamed: Vec<(String, Swatch)> = vec![]; let links: Vec> = row_swatches .iter() .zip(&rows) .map(|(w, row)| { let w = w.as_ref()?; + // A swatch is the same one when its paint, Global and spot are. + let alike = |x: &Swatch| x.paint == w.paint && x.global == w.global && x.spot == w.spot; let name = match d.swatch(&w.name) { - Some(x) if x.paint == w.paint => w.name.clone(), - _ => { - let name = d.free_swatch_name(&w.name); - d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); - added.push(name.clone()); - name - } + Some(x) if alike(x) => w.name.clone(), + _ => match renamed.iter().find(|(_, x)| x.name == w.name && alike(x)) { + Some((name, _)) => name.clone(), + None => { + let name = d.free_swatch_name(&w.name); + d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); + added.push(name.clone()); + renamed.push((name.clone(), w.clone())); + name + } + }, }; let color = d.global_color(&name).filter(|_| w.global).or(w.paint.color())?; Some(Link { name, global: w.global, color, tint: row.tint }) @@ -1932,6 +1985,9 @@ fn apply(s: &mut Session, p: &Value) -> Result { })?; let mut out = json!({ "changed": changed, "swatches": added }); not_changed.report(&mut out); + if !not_found.is_empty() { + out["swatchesNotFound"] = json!(not_found); + } if let Some(e) = edit { e.defaults(s)?; out["relinked"] = json!(e.relinked()); @@ -1950,21 +2006,21 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let rows = parse_rows(p, C)?; let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); - // Each new color with its row's tint and model: a tint moves with its color, and goes when - // the color changes; a model moves with its color. A row with no current colors recolors - // nothing, so it keeps its new color and takes no other row's. + // Each new color with its row's tint, model and swatch: a tint and a swatch move with their + // color, and go when the color changes; a model moves with its color. A row with no current + // colors recolors nothing, so it keeps its new color and takes no other row's. let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some(); - let mut news: Vec<(Color, f32, Option)> = - rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); + type New = (Color, f32, Option, Option<(String, String)>); + let mut news: Vec = rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model, r.swatch.clone()))).collect(); if order { rng.shuffle(&mut news); } if saturation_brightness { news = news .into_iter() - .map(|(c, tint, model)| { + .map(|(c, tint, model, swatch)| { let n = rng.saturation_brightness(c); - (n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }, model) + if ColorKey::of(&n) == ColorKey::of(&c) { (n, tint, model, swatch) } else { (n, 1.0, model, None) } }) .collect(); } @@ -1972,8 +2028,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let map: Vec = rows .iter() .map(|r| { - let (to, tint, model) = - if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; + let (to, tint, model, swatch) = if takes(r) { + news.next().map_or((None, 1.0, None, None), |(c, t, m, w)| (Some(c), t, m, w)) + } else { + (r.to, r.tint, r.model, r.swatch.clone()) + }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); @@ -1984,6 +2043,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result { if let Some(m) = model { row["model"] = json!(m.id()); } + if let Some((library, name)) = swatch { + row["swatch"] = json!({"name": name, "library": library}); + } if r.added { row["added"] = json!(true); } diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b007cde660..9cf80039db 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 931504dedb..0e937376bd 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1034,8 +1034,7 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } let mut members = Members::of(sel); for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); + let endpoints = sel.segments.remove(&id).and_then(|segments| segment_endpoints(d, id, &segments, "select.anchorsMany").ok()); let all: BTreeSet = d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); // Anything but a path is selected, toggled or deselected as a whole. @@ -1049,8 +1048,10 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } // From the anchors selected now (all of them for a path selected as a whole). let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), + Some(a) => match &endpoints { + Some(endpoints) => a.difference(endpoints).copied().collect(), + None => a.clone(), + }, None if members.contains(id) => all.clone(), None => BTreeSet::new(), }; diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 16684a3284..6b447fca7c 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -15,6 +15,16 @@ const MAX_CELLS: usize = 10_000; /// The most objects the copies may hold in all, counting every object inside each copy. const MAX_COPIED_OBJECTS: usize = 250_000; const EPS: f64 = 1e-9; +/// How far past a whole point a place may be and still count as on it, in points. +const GRID_EPS: f64 = 1e-6; + +/// Whether `n` or an object in it, the art of linked opacity masks included, is pixel-aligned: the +/// objects that the snap after a transform moves. +fn holds_pixel_aligned(n: &Node) -> bool { + n.extras().pixel_aligned + || n.children().is_some_and(|cs| cs.iter().any(|c| holds_pixel_aligned(c))) + || n.extras().mask.as_ref().is_some_and(|m| m.linked && holds_pixel_aligned(&m.art)) +} pub fn specs() -> Vec { vec![cmd!( @@ -22,7 +32,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); when the selection holds a pixel-aligned object, every cell moves by whole points (the pitch is rounded up, with fill the first cell's place is rounded toward the sheet's inside and only cells that still fit are counted, and a turned cell turns about a center up to half a point right of and below its own, with extra pitch only between alternating columns or rows and fill reserving the turn offset on both axes only where turned cells fit), so the copies stay on the pixel grid and the objects in each copy keep their places against each other; otherwise gaps are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; a single cell that neither moves nor groups the artwork and leaves the selection unchanged adds no undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -166,8 +176,75 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } else { None }; + // With a pixel-aligned object in the selection, every cell moves by whole points, so the snap + // leaves each copy as it moved it and the objects in a copy keep their places against each other. + // The pitch and the first cell's place are rounded up, so neighbors never come closer than asked + // and the first cell stays inside the sheet. + let aligned = roots.iter().filter_map(|r| d.node(*r)).any(holds_pixel_aligned); + let whole = |v: f64| if aligned { (v - GRID_EPS).ceil() } else { v }; + // A half turn about the center maps x to 2 × center − x. On the pixel grid, twice the center is + // rounded up to whole points, so a turned copy also moves its objects by whole points; it then + // sits up to a point right of and below its cell, and the pitch and the fill make room for that. + let c2 = b.center().to_vec2() * 2.0; + let turn = if aligned && alt != Alternate::None { + let mut rounded = Vec2::new(whole(c2.x), whole(c2.y)); + if rounded.x < c2.x - EPS { + rounded.x += 1.0; + } + if rounded.y < c2.y - EPS { + rounded.y += 1.0; + } + rounded - c2 + } else { + Vec2::ZERO + }; + let center = (c2 + turn) / 2.0; + let clearance = match alt { + Alternate::Columns => Vec2::new(turn.x, 0.0), + Alternate::Rows => Vec2::new(0.0, turn.y), + Alternate::None => Vec2::ZERO, + }; + let (gx, gy) = if aligned { + let pitch = |v: f64| { + let rounded = whole(v).max(1.0); + if rounded < v - EPS { rounded + 1.0 } else { rounded } + }; + (pitch(w + gx + clearance.x) - w, pitch(h + gy + clearance.y) - h) + } else { + (gx, gy) + }; + let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| { + let raw = Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0); + let mut origin = Vec2::new(whole(raw.x), whole(raw.y)); + if b.x0 + origin.x < sh.x0 + m - EPS { + origin.x += 1.0; + } + if b.y0 + origin.y < sh.y0 + m - EPS { + origin.y += 1.0; + } + origin + }); let (rows, cols) = match anchor { - Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy), + Some((sh, m)) => { + let lead = origin - Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0); + let (sw, sh) = (sh.width() - lead.x - 2.0 * m, sh.height() - lead.y - 2.0 * m); + let (rows, cols) = fill_counts(sw, sh, 0.0, w, h, gx, gy); + // Turned cells have odd indices; an unturned cell may follow the last one that fits. + let alternating_count = |room, size, gap, shift, count: usize| count.min((fit_count(room - shift, size, gap) / 2 * 2).saturating_add(1)); + match alt { + Alternate::Columns => { + let cols = alternating_count(sw, w, gx, turn.x, cols); + let turned_rows = fit_count(sh - turn.y, h, gy); + if cols > 1 && turned_rows > 0 { (rows.min(turned_rows), cols) } else { (rows, cols.min(1)) } + } + Alternate::Rows => { + let rows = alternating_count(sh, h, gy, turn.y, rows); + let turned_cols = fit_count(sw - turn.x, w, gx); + if rows > 1 && turned_cols > 0 { (rows, cols.min(turned_cols)) } else { (rows.min(1), cols) } + } + Alternate::None => (rows, cols), + } + } None => (rows, cols), }; if rows == 0 || cols == 0 { @@ -182,14 +259,20 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS { return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects"))); } - let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; + if rows == 1 && cols == 1 && origin == Vec2::ZERO && roots.len() == 1 { + let selection = &s.doc()?.selection; + let mut next_selection = selection.clone(); + next_selection.set([roots[0]]); + if next_selection == *selection { + return Ok(json!({ "ids": [roots[0].0], "rows": 1, "columns": 1, "count": 1 })); + } + } let cells = layout(w, h, gx, gy, rows, cols, alt); - let center = b.center().to_vec2(); let place = |c: &Cell| -> Affine { let t = Affine::translate(origin + Vec2::new(c.dx, c.dy)); if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t } }; - let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; let ids = s.edit("Step and Repeat", |d, sel| { if roots.len() > 1 { roots = vec![group_nodes(d, &roots)?]; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 133d79ff48..6114943a36 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -60,6 +60,158 @@ fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() { assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none())); } +#[test] +fn a_single_unchanged_cell_keeps_undo_and_redo() { + for fill in [false, true] { + let (mut s, id) = setup(); + let copies = s.execute(CMD, &json!({"columns": 2})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let steps = undo_steps(&s); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": {"x": 0, "y": 0, "width": 50, "height": 30}})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.doc().unwrap().history.redo.len(), redo); + s.execute("edit.redo", &json!({})).unwrap(); + let copy = copies["ids"][1].as_u64().unwrap(); + assert_eq!(bounds(&s, copy), (50.0, 0.0, 100.0, 30.0)); + } +} + +#[test] +fn a_single_unchanged_cell_clears_the_layer_target_in_one_undo_step() { + for fill in [false, true] { + let (mut s, id) = setup(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert_eq!(before.objects, [NodeId(id)]); + assert_eq!(before.target, Some(layer)); + let steps = undo_steps(&s); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + let mut expected = before.clone(); + expected.set([NodeId(id)]); + assert_eq!(s.doc().unwrap().selection, expected); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, expected); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_unchanged_cell_records_the_resolved_patterns_setting() { + for fill in [false, true] { + for patterns in [false, true] { + let (mut s, id) = setup(); + s.execute("object.pattern.make", &json!({"name": "Dots", "width": 50, "height": 30})).unwrap(); + s.execute("object.pattern.done", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "swatch": "Dots"})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.prefs.transform_pattern_tiles = patterns; + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + for explicit in [false, true] { + let mut params = json!({"fill": fill, "sheet": sheet}); + let expected = if explicit { !patterns } else { patterns }; + if explicit { + params["patterns"] = json!(expected); + } + let start = s.journal.len(); + let steps = undo_steps(&s); + let r = s.execute(CMD, ¶ms).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + params["patterns"] = json!(expected); + assert_eq!(s.journal_for_action(start), [(CMD.to_string(), params)]); + assert_eq!(undo_steps(&s), steps); + } + } + } +} + +#[test] +fn a_single_unchanged_cell_selects_the_compound_in_one_undo_step() { + for fill in [false, true] { + let (mut s, member) = setup(); + let inner_params = json!({"x": 10, "y": 5, "width": 20, "height": 10}); + let inner = s.execute("shape.rectangle", &inner_params).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [member, inner]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let before = bounds(&s, compound); + s.execute(CMD, &json!({"columns": 2})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.select(|_, sel| sel.set([NodeId(member)])).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]); + let steps = undo_steps(&s); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [compound], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps + 1); + assert!(s.doc().unwrap().history.redo.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_unchanged_cell_selects_the_whole_path_in_one_undo_step() { + for fill in [false, true] { + let (mut s, id) = setup(); + let id = NodeId(id); + s.select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 0), (0, 1)].into_iter().collect()); + }) + .unwrap(); + let before = s.doc().unwrap().selection.clone(); + let steps = undo_steps(&s); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id.0], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + assert!(s.doc().unwrap().selection.segments.is_empty()); + assert_eq!(bounds(&s, id.0), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_moved_cell_records_an_undo_step() { + let (mut s, id) = setup(); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "sheet": {"x": 5, "y": 5, "width": 50, "height": 30}})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(bounds(&s, id), (5.0, 5.0, 55.0, 35.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); +} + #[test] fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() { let (mut s, _) = setup(); @@ -211,6 +363,285 @@ fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_ assert!((pitch - pitch.round()).abs() < 1e-9); } +#[test] +fn pixel_aligned_pitch_preserves_requested_gaps_near_whole_points() { + for gap in [0.0, 0.25, -0.25] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let params = json!({"x": 0, "y": 0, "width": 50.0000005 - gap, "height": 30.0000005 - gap}); + let cut = s.execute("shape.rectangle", ¶ms).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gap": gap, "cutId": cut})).unwrap(); + assert_eq!(r["count"], json!(4)); + let d = &s.doc().unwrap().doc; + let cut_bounds = |id: &Value| { + let group = d.node(NodeId(id.as_u64().unwrap())).unwrap(); + group.children().unwrap()[0].geometric_bounds().unwrap() + }; + let ids = r["ids"].as_array().unwrap(); + for row in 0..2 { + let left = cut_bounds(&ids[row * 2]); + let right = cut_bounds(&ids[row * 2 + 1]); + assert!(right.x0 - left.x1 >= gap - EPS, "the horizontal gap shrank: {left:?} {right:?}"); + let pitch = right.x0 - left.x0; + assert!((pitch - pitch.round()).abs() < EPS); + } + for col in 0..2 { + let top = cut_bounds(&ids[col]); + let bottom = cut_bounds(&ids[col + 2]); + assert!(bottom.y0 - top.y1 >= gap - EPS, "the vertical gap shrank: {top:?} {bottom:?}"); + let pitch = bottom.y0 - top.y0; + assert!((pitch - pitch.round()).abs() < EPS); + } + } +} + +#[test] +fn a_pixel_aligned_cut_keeps_its_place_against_its_artwork_in_every_copy() { + let (mut s, cut) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [cut], "on": true})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 48, "height": 28})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gapX": 0.6, "gapY": 1.3, "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let inset = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + (rects[1].x0 - rects[0].x0, rects[1].y0 - rects[0].y0) + }; + let ids = r["ids"].as_array().unwrap(); + let first = inset(&ids[0]); + for id in &ids[1..] { + let (x, y) = inset(id); + assert!((x - first.0).abs() < 1e-9 && (y - first.1).abs() < 1e-9, "the artwork moved against the cut: {:?} against {first:?}", (x, y)); + } +} + +#[test] +fn pixel_aligned_art_stays_registered_in_turned_cells_and_gaps_never_shrink() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"columns": 3, "gapX": 0.1, "rotate": "columns", "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let rects = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + (rects[0], rects[1]) + }; + let ids = r["ids"].as_array().unwrap(); + let (c0, a0) = rects(&ids[0]); + let (c1, a1) = rects(&ids[1]); + let (c2, a2) = rects(&ids[2]); + // The turned cell mirrors the art inside its cut; the next unturned cell repeats it. + assert!(((c1.x1 - a1.x1) - (a0.x0 - c0.x0)).abs() < 1e-9, "turned art moved against its cut: {c1:?} {a1:?}"); + assert!(((a2.x0 - c2.x0) - (a0.x0 - c0.x0)).abs() < 1e-9); + assert!(c2.x0 - c0.x0 > 2.0 * (50.25 + 0.1) - 1e-9, "the pitch was rounded down: {c2:?}"); + assert!(c1.x0 - c0.x1 >= 0.1 - 1e-9 && c2.x0 - c1.x1 >= 0.1 - 1e-9, "a gap next to the turned cell shrank: {c0:?} {c1:?} {c2:?}"); +} + +#[test] +fn turned_pixel_aligned_cells_stay_on_the_sheet() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 101, "height": 30.75}); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!(r["columns"], json!(1)); + assert_eq!(r["count"], json!(1)); + assert_eq!(undo_steps(&s), steps + 1); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(matches!(s.doc().unwrap().doc.node(group).unwrap().kind, vectorcraft_doc::NodeKind::Group { .. })); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 102, "height": 31.75}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!(r["columns"], json!(2)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= 102.0 + 1e-9 && b.y1 <= 31.75 + 1e-9, "a cell runs past the sheet: {b:?}"); + } +} + +#[test] +fn fill_keeps_rounded_turn_offsets_inside_the_sheet_near_whole_points() { + for (height, columns) in [(30.0000005, 1), (31.0000005, 2)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.0000005})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 100, "height": height}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(columns), json!(columns))); + for id in r["ids"].as_array().unwrap() { + let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap()); + assert!(x0 >= -1e-9 && y0 >= -1e-9 && x1 <= 100.0 + 1e-9 && y1 <= height + 1e-9, "a cell runs past the sheet"); + } + } +} + +#[test] +fn fill_accepts_exact_fit_when_the_doubled_turn_center_has_roundoff() { + for (rotate, x, y, width, height, sw, sh, rows, columns) in + [("columns", 0.0, 0.1, 50.0, 29.8, 100.0, 29.8, 1, 2), ("rows", 0.1, 0.0, 29.8, 50.0, 29.8, 100.0, 2, 1)] + { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let params = json!({"x": x, "y": y, "width": width, "height": height}); + let cut = s.execute("shape.rectangle", ¶ms).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let b = s.doc().unwrap().doc.node(NodeId(cut)).unwrap().geometric_bounds().unwrap(); + let c2 = if rotate == "columns" { b.center().y * 2.0 } else { b.center().x * 2.0 }; + assert!(c2 > c2.round() && c2 - c2.round() < EPS); + let sheet = json!({"x": x, "y": y, "width": sw, "height": sh}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(rows), json!(columns), json!(2))); + for id in r["ids"].as_array().unwrap() { + let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap()); + assert!(x0 >= x - EPS && y0 >= y - EPS && x1 <= x + sw + EPS && y1 <= y + sh + EPS, "a cell runs past the sheet"); + } + } +} + +#[test] +fn fill_reserves_turn_clearance_only_for_turned_cells() { + for (rotate, width, height, rows, columns) in [ + ("columns", 101.25, 31.0, 1, 1), + ("columns", 102.0, 31.0, 1, 2), + ("columns", 152.25, 31.0, 1, 3), + ("columns", 152.25, 30.75, 1, 1), + ("rows", 51.0, 61.75, 1, 1), + ("rows", 51.0, 62.0, 2, 1), + ("rows", 51.0, 92.75, 3, 1), + ("rows", 50.25, 92.75, 1, 1), + ] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": width, "height": height}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(rows), json!(columns)), "{rotate} on {width} by {height}"); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= width + 1e-9 && b.y1 <= height + 1e-9, "a cell runs past the sheet: {b:?}"); + } + } +} + +#[test] +fn turned_columns_keep_the_vertical_pitch_without_turn_clearance() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gapY": 0.2, "rotate": "columns", "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let cut_bounds = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + rects[0] + }; + let ids = r["ids"].as_array().unwrap(); + for col in 0..2 { + let first = cut_bounds(&ids[col]); + let second = cut_bounds(&ids[col + 2]); + assert!((second.y0 - first.y0 - 31.0).abs() < 1e-9, "the vertical pitch includes turn clearance: {first:?} {second:?}"); + assert!(second.y0 - first.y1 >= 0.2 - 1e-9, "the vertical gap shrank: {first:?} {second:?}"); + } +} + +#[test] +fn fill_counts_only_the_pixel_aligned_copies_that_stay_on_the_sheet() { + let (mut s, id) = setup(); + // The 1 pt stroke puts the snapped rectangle at (0.5, 0.5), 50 by 30. + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(bounds(&s, id), (0.5, 0.5, 50.5, 30.5)); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 100.6, "height": 30}})).unwrap(); + assert_eq!(r["columns"], json!(1)); + assert_eq!(undo_steps(&s), steps); + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 101, "height": 30}})).unwrap(); + assert_eq!(r["columns"], json!(2)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x1 <= 101.5 + 1e-9, "a copy runs past the sheet: {b:?}"); + } +} + +#[test] +fn fill_rounds_pixel_aligned_origins_inside_the_sheet_near_whole_points() { + for (dx, dy) in [(0.0000005, 0.0), (0.0, 0.0000005), (-0.9999995, -0.9999995)] { + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let (x, y, _, _) = bounds(&s, id); + let (sx, sy) = (x + dx, y + dy); + let steps = undo_steps(&s); + let tight = json!({"x": sx, "y": sy, "width": 50, "height": 30}); + assert!(s.execute(CMD, &json!({"fill": true, "sheet": tight})).is_err()); + assert_eq!(undo_steps(&s), steps); + let sheet = json!({"x": sx, "y": sy, "width": 51, "height": 31}); + let r = s.execute(CMD, &json!({"fill": true, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + let (x0, y0, x1, y1) = bounds(&s, id); + assert!(x0 >= sx && y0 >= sy && x1 <= sx + 51.0 && y1 <= sy + 31.0); + } +} + +#[test] +fn fill_accepts_exact_fit_when_the_origin_subtraction_has_roundoff() { + for (x, y, sx, sy) in [(1.2, 0.0, 2.2, 0.0), (0.0, 1.2, 0.0, 2.2), (1.2, 1.2, 2.2, 2.2)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut_params = json!({"x": x, "y": y, "width": 50, "height": 30}); + let cut = s.execute("shape.rectangle", &cut_params).unwrap()["id"].as_u64().unwrap(); + let art_params = json!({"x": 10, "y": 5, "width": 20, "height": 20}); + let art = s.execute("shape.rectangle", &art_params).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": sx, "y": sy, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": true, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(1), json!(1))); + let (x0, y0, x1, y1) = bounds(&s, cut); + assert!((x0 - sx).abs() < EPS && (y0 - sy).abs() < EPS); + assert!((x1 - (sx + 50.0)).abs() < EPS && (y1 - (sy + 30.0)).abs() < EPS); + } +} + #[test] fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() { let first_x = |sheet: Option| { diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e1d64b2112..4ee4f01c10 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 9916ba569c..4e8b25f3f4 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -977,6 +977,13 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result { Ok(relinked) })?; relink.defaults(s)?; + if to != name && !s.previewing { + let uid = s.doc()?.uid; + if s.swatch_renames.len() == crate::MAX_SWATCH_RENAMES { + s.swatch_renames.remove(0); + } + s.swatch_renames.push((uid, name, to.clone())); + } Ok(json!({"name": to, "relinked": relinked})) } diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 1a79fbfbc9..1d15de3a3b 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -509,6 +509,17 @@ impl<'a> ThreadIndex<'a> { pub(crate) fn threaded(&self, id: NodeId) -> bool { self.first.get(&id).and_then(|i| self.live.get(*i)).is_some_and(|n| *n >= 2) && text_of(self.doc, id).is_some() } + + /// The index in the document's threads of the first thread that lists `id`. + pub(crate) fn first_thread_index(&self, id: NodeId) -> Option { + self.first.get(&id).copied() + } + + /// [`story_of`] for `id`, its thread found through the index. + pub(crate) fn story(&self, id: NodeId) -> Vec { + let Some(thread) = self.first.get(&id).and_then(|i| self.doc.text_threads.get(*i)) else { return vec![] }; + story_in(self.doc, thread, id) + } } /// `ids` followed by the other frames of the threads they are in, each once, in thread order. diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 228d23a0f0..753c315a9a 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -37,7 +37,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 37] = [ +const REPLAY_ONLY: [(&str, &str); 38] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), @@ -67,6 +67,7 @@ const REPLAY_ONLY: [(&str, &str); 37] = [ ("artboard.distribute", "activeArtboard"), ("artboard.distributeSpacing", "selectedArtboards"), ("artboard.distributeSpacing", "activeArtboard"), + ("addon.document.floodFillArtboards", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 55c06cc130..afc8c52e73 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -510,11 +510,43 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// A check every write on this thread must pass as well, given the path as written or, at the +/// moment a checked write commits on Unix, the opened folder's real path with the file's name +/// ([`with_write_guard`]). +pub(crate) type WriteGuard = std::rc::Rc Result<(), String>>; + +thread_local! { + static WRITE_GUARD: RefCell> = const { RefCell::new(None) }; +} + +/// Puts the write guard it replaced back when dropped (also when `f` panics). +struct RestoreWriteGuard(Option); + +impl Drop for RestoreWriteGuard { + fn drop(&mut self) { + let previous = self.0.take(); + WRITE_GUARD.with(|g| *g.borrow_mut() = previous); + } +} + +/// Runs `f` with `guard` checked on every write it makes on this thread, again at the moment each +/// checked write commits, so a destination that is changed after an earlier check is checked as it +/// is then. +pub(crate) fn with_write_guard(guard: WriteGuard, f: impl FnOnce() -> T) -> T { + let _restore = RestoreWriteGuard(WRITE_GUARD.with(|g| g.replace(Some(guard)))); + f() +} + +fn check_write_guard(path: &Path) -> Result<(), String> { + WRITE_GUARD.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g(path)) +} + /// [`check_write`] without adding `path` to the files a script run reports as written, for a /// check made before anything is written. pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write) + check_gate(path, Access::Write)?; + check_write_guard(Path::new(path)) } /// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been @@ -523,12 +555,14 @@ pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { #[cfg(unix)] pub(crate) fn check_write_real(real: &Path) -> Result<(), String> { current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?; - GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write)) + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))?; + check_write_guard(real) } -/// Whether a write here is checked: roots are in force, or a script's command runs. +/// Whether a write here is checked: roots are in force, a script's command runs, or a write guard +/// is in force ([`with_write_guard`]). pub(crate) fn writes_checked() -> bool { - current().is_some() || in_script_command() + current().is_some() || in_script_command() || WRITE_GUARD.with(|g| g.borrow().is_some()) } /// A file's modification time and length; `None` when there is no file at `path`. diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index d921008611..1ede3c2509 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -19,11 +19,26 @@ pub struct Interaction { /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an /// interaction runs its commands inside it. pub(crate) tool: bool, + /// A tool began or joined this interaction through `Action::Begin`. + pub(crate) tool_joined: bool, /// A replaced or canceled preview restores these new-art paints from before the interaction. pub(crate) paint: vectorcraft_tools::PaintDefaults, /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put /// `paint` back, whichever preview is the latest. pub(crate) used_defaults_only: bool, + /// A Flood Fill Artboards preview ran: a cancel puts `paint` back and does not take the + /// selection's appearance as the new-art paints. + pub(crate) preserve_paint_on_cancel: bool, + /// The preview inherited new-art paints from a selection absent at interaction start: the + /// new-art paints from before that, which the next preview starts from. + pub(crate) inherited_preview_paint: Option, + /// A successful preview started from `inherited_preview_paint`: the new-art paints changed + /// during the interaction, so a cancel, or a commit after a failed preview, puts `paint` back. + pub(crate) inherited_preview_paint_used: bool, + /// The new-art paints before the successful previews that built on each other, with the + /// changes made outside the previews, and the paints the last of them left. A failed preview + /// puts back the first where a field still holds what the previews left. + pub(crate) last_preview_paint: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1220649429..16e1e7f5a5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -54,6 +54,9 @@ pub use vectorcraft_tools as tools; pub use vectorcraft_doc::MAX_COORD; const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap"); +/// The maximum number of newest swatch renames a session keeps until they are taken. +pub(crate) const MAX_SWATCH_RENAMES: usize = 64; + pub struct Session { docs: Vec, active: Option, @@ -309,6 +312,9 @@ pub struct Session { /// appearance: the documents ([`DocState::uid`]) whose newest history step takes the colors the /// command finally left. pub(crate) batch_paint_docs: Vec, + /// Committed swatch renames as (document uid, old name, new name), in execution order until taken by the frontend. + /// The uid is [`DocState::uid`]; the record is never saved in documents or history. + pub(crate) swatch_renames: Vec<(u64, String, String)>, /// The composite fonts (lowercase names) that the open documents defined when the font /// database was last brought in step with them ([`cmd::compositefonts::sync`]). pub(crate) composite_names: Vec, @@ -322,6 +328,10 @@ pub struct Session { /// While [`Session::place_read`] runs `file.place`: the file read for it, which the command /// places instead of reading the file; `None` otherwise. pub(crate) place_hand_off: Option, + /// While a script places or relinks a file as an image: `Some(true)`, and `file.place` or + /// `links.relink` refuses a file that holds no image before the document changes, setting it to + /// `Some(false)`; `None` otherwise. + pub(crate) image_only: std::cell::Cell>, /// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which /// the command loads the place cursor with instead of reading them; `None` otherwise. pub(crate) queue_hand_off: Option, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 7a60028afc..4a85763667 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -86,8 +86,9 @@ struct Pending { to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, - /// The event this enqueue pushed out of the waiting queue. - displaced: Option, + /// The [`Pending::seq`] of the event that pushed this one out of the waiting queue, and whether + /// that event was a `document.opened`. + pushed_out_by: Option<(u64, bool)>, /// Queued by a command of the running script, whose run has not ended yet /// ([`Session::plugin_events_script_ended`]). by_script: bool, @@ -162,6 +163,8 @@ pub struct PluginEvents { /// The events dropped from `pending` since the last delivery, oldest first, which /// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room. evicted: VecDeque, + /// The [`Pending::seq`] of each `document.opened` the running script's commands queued. + script_opens: HashSet, /// How many events have been queued as their own entry. queued: u64, dispatching: bool, @@ -223,11 +226,10 @@ impl PluginEvents { } return; } - let mut displaced = None; if self.pending.len() >= MAX_PENDING - && let Some(dropped) = self.pending.pop_front() + && let Some(mut dropped) = self.pending.pop_front() { - displaced = Some(dropped.seq); + dropped.pushed_out_by = Some((self.queued, event == Event::DocumentOpened)); log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); // Kept until the next delivery, in case a rollback frees room for it again. // When that store is full, an open goes first, since only opens are rolled back. @@ -238,8 +240,37 @@ impl PluginEvents { self.evicted.push_back(dropped); } let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); - self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false }); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, pushed_out_by: None, by_script: false }); self.queued += 1; + self.prune_script_opens(); + } + + /// Drops the `document.opened` events, waiting or pushed out, whose [`Pending::seq`] `undone` + /// picks. The events those opens pushed out of the waiting queue return in their original + /// order, ahead of the events still waiting, while there is room. + fn drop_opens(&mut self, undone: impl Fn(u64) -> bool) { + let dropped = |p: &Pending| p.event == Event::DocumentOpened && undone(p.seq); + self.pending.retain(|p| !dropped(p)); + self.evicted.retain(|p| !dropped(p)); + let first = self.evicted.iter().filter(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq))).map(|p| p.seq).min(); + while self.pending.len() < MAX_PENDING + && let Some(at) = self.evicted.iter().rposition(|p| first.is_some_and(|seq| p.seq >= seq)) + && let Some(mut p) = self.evicted.remove(at) + { + p.pushed_out_by = None; + self.pending.push_front(p); + } + self.prune_script_opens(); + } + + /// Forgets the running script's opens that no waiting or pushed-out event refers to. + fn prune_script_opens(&mut self) { + if self.script_opens.is_empty() { + return; + } + let referenced: HashSet = + self.pending.iter().chain(self.evicted.iter()).flat_map(|p| std::iter::once(p.seq).chain(p.pushed_out_by.map(|(seq, _)| seq))).collect(); + self.script_opens.retain(|seq| referenced.contains(seq)); } fn notice(&mut self, n: Notice) { @@ -362,6 +393,9 @@ impl Session { && let Some(p) = self.plugin_events.pending.back_mut() { p.by_script = true; + if event == Event::DocumentOpened { + self.plugin_events.script_opens.insert(p.seq); + } } } @@ -370,12 +404,13 @@ impl Session { /// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since /// the documents they opened were discarded with its working copy. Its saves stay, since the /// files they wrote stay written, and so do the events of documents a frontend opened while the - /// run was paused. The next delivery gives what is left in the order it was queued. + /// run was paused. Events those opens pushed out of the waiting queue come back, as after + /// [`Session::forget_plugin_opens_since`]. The next delivery gives what is left in the order it was queued. pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { let events = &mut self.plugin_events; + let opens = std::mem::take(&mut events.script_opens); if !kept { - events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); - events.evicted.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + events.drop_opens(|seq| opens.contains(&seq)); } for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) { p.by_script = false; @@ -389,21 +424,9 @@ impl Session { /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The - /// saves stay, since the files they wrote stay written. - /// Events displaced by those opens return in their original order, ahead of the events still - /// waiting, while there is room. + /// saves stay, since the files they wrote stay written ([`PluginEvents::drop_opens`]). pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { - let events = &mut self.plugin_events; - let undone = |p: &Pending| p.event == Event::DocumentOpened && p.seq >= mark; - let displaced: Vec<_> = events.pending.iter().chain(&events.evicted).filter(|p| undone(p)).filter_map(|p| p.displaced).collect(); - events.pending.retain(|p| !undone(p)); - events.evicted.retain(|p| !undone(p)); - while events.pending.len() < MAX_PENDING - && let Some(at) = events.evicted.iter().rposition(|p| displaced.contains(&p.seq)) - && let Some(p) = events.evicted.remove(at) - { - events.pending.push_front(p); - } + self.plugin_events.drop_opens(|seq| seq >= mark); } /// Compares each open document with how the last check saw it and queues the events its changes @@ -489,7 +512,19 @@ impl Session { } let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); self.plugin_events.dispatching = true; - self.plugin_events.evicted.clear(); + // Events pushed out by the opens of a running script stay until its run ends, which puts + // them back if the run fails. + let events = &mut self.plugin_events; + let opens = &events.script_opens; + let restorable = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq)); + let first = events.evicted.iter().filter(|p| restorable(p)).map(|p| p.seq).min(); + events.evicted.retain(|p| { + restorable(p) + || (first.is_some_and(|seq| p.seq >= seq) + && (!p.by_script || p.event != Event::DocumentOpened || p.to.iter().any(|(r, _)| subs.contains_key(r)))) + }); + let frontend_barrier = events.evicted.iter().filter(|p| !p.by_script).map(|p| p.seq).min(); + events.prune_script_opens(); // A handler's calls are checked as calls from outside, also when the command that ended // played saved steps ([`Session::replay`] puts its flag back only after this delivery). let replaying = self.set_replaying(false); @@ -512,6 +547,11 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } + p.to.retain(|(r, _)| subs.get(r).is_some_and(|plugin| plugin.manifest().reacts_to(p.event))); + if !p.to.is_empty() && frontend_barrier.is_some_and(|seq| p.seq > seq) { + held.push_back(p); + continue; + } let mut served = 0; for (i, (r, reasons)) in p.to.iter().enumerate() { let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else { @@ -547,8 +587,10 @@ impl Session { self.depth = depth; self.set_replaying(replaying); self.plugin_events.dispatching = false; + self.plugin_events.prune_script_opens(); self.plugin_events.pending.iter().any(|p| { !p.by_script + && frontend_barrier.is_none_or(|seq| p.seq < seq) && (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)) && p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0)) }) @@ -854,6 +896,121 @@ mod tests { ); } + #[test] + fn a_failed_script_run_brings_back_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + // Enough opens to fill the store of pushed-out events, which then drops opens first. + for uid in 0..(MAX_PENDING + MAX_EVICTED + 8) as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + assert_eq!(s.plugin_events.evicted.len(), MAX_EVICTED); + assert_eq!(s.plugin_events.pending.len(), MAX_PENDING); + assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the saves were pushed out"); + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + #[test] + fn a_failed_script_keeps_the_newest_saves_when_its_open_displaced_a_save() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=MAX_PENDING as u64 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + queue_script_open(&mut s, 100, &r); + s.plugin_events.queue(Event::DocumentSaved, MAX_PENDING as u64 + 1, vec![], vec![r]); + s.plugin_events.pending.back_mut().unwrap().by_script = true; + s.plugin_events_script_ended(false); + let saves: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event, p.document)).collect(); + let expected: Vec<_> = (2..=MAX_PENDING as u64 + 1).map(|uid| (Event::DocumentSaved, uid)).collect(); + assert_eq!(saves, expected); + } + + #[test] + fn a_frontend_save_waits_for_its_restorable_open_between_script_slices() { + use vectorcraft_plugins::wat as tpl; + + let mut s = Session::new(); + let manifest = concat!( + r#"{"id":"test.events.frontend_order","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"#, + r#""events":["document.opened","document.saved"]}"# + ); + let wasm = wat::parse_str(tpl::reacting(manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = Arc::new(Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap()); + let r = recipient(&plugin); + s.plugin_events.test_subscribers = Some(vec![plugin]); + s.plugin_events.queue(Event::DocumentOpened, 1, vec![], vec![r.clone()]); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + s.plugin_events.queue(Event::DocumentSaved, 1, vec![], vec![r]); + assert!(!s.deliver_plugin_events(), "the blocked save must not request another frame"); + assert!(s.take_plugin_event_notices().is_empty(), "the save must wait for the earlier frontend open"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + s.deliver_plugin_events(); + let given: Vec = s.take_plugin_event_notices().iter().map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + let events: Vec<_> = given.iter().map(|event| (event["type"].as_str().unwrap(), event["document"].as_u64().unwrap())).collect(); + assert_eq!(events, [("document.opened", 1), ("document.saved", 1)]); + } + + #[test] + fn script_open_tracking_is_bounded_after_batch_rollbacks_and_queue_overflow() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 0..2 * MAX_PENDING as u64 { + let mark = s.plugin_events_mark(); + queue_script_open(&mut s, uid, &r); + s.forget_plugin_opens_since(mark); + assert!(s.plugin_events.script_opens.is_empty(), "a rolled-back open has no remaining references"); + } + for uid in 0..2 * (MAX_PENDING + MAX_EVICTED) as u64 { + queue_script_open(&mut s, uid, &r); + let events = &s.plugin_events; + assert!(events.script_opens.len() <= 2 * (events.pending.len() + events.evicted.len())); + } + s.plugin_events_script_ended(false); + assert!(s.plugin_events.pending.is_empty()); + assert!(s.plugin_events.evicted.is_empty()); + assert!(s.plugin_events.script_opens.is_empty()); + } + + #[test] + fn a_delivery_between_script_slices_keeps_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + // A save a frontend queued while the run is paused pushes out the first open. + s.plugin_events.queue(Event::DocumentSaved, 50, vec![], vec![r]); + s.deliver_plugin_events(); + assert_eq!(s.plugin_events.evicted.len(), 3, "kept while the run goes on"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + /// Queues a `document.opened` as a command of a running script does. + fn queue_script_open(s: &mut Session, uid: u64, r: &Recipient) { + s.plugin_events.queue(Event::DocumentOpened, uid, vec![], vec![r.clone()]); + if let Some(p) = s.plugin_events.pending.back_mut() { + p.by_script = true; + s.plugin_events.script_opens.insert(p.seq); + } + } + #[test] fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() { let mut s = Session::new(); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index fab9f5f06b..f5528f0471 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -243,6 +243,9 @@ pub struct Prefs { /// User Interface › Show Tool Group Labels: the toolbar's group names (Select, Shapes, Draw…); /// off (as it ships, #1736), the tools run on from group to group with nothing between them. pub tool_group_labels: bool, + /// User Interface › Tool Icons: "classic" (the default), the pictures the tools had in 0.24, + /// or "current", this version's pictures, which the toolbar, its flyouts, tool cards and the command palette show. + pub ui_tool_icons: String, pub open_documents_as_tabs: bool, pub large_tabs: bool, pub ui_scaling: f64, @@ -664,6 +667,7 @@ impl Default for Prefs { canvas_color: s("matchUi"), auto_collapse_icon_panels: false, tool_group_labels: false, + ui_tool_icons: s("classic"), open_documents_as_tabs: true, large_tabs: false, ui_scaling: 1.0, diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 8728bd76fb..0356db27d1 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -254,7 +254,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. // A document whose active artboard the script chose uses that choice, not the one the run - // started with. + // started with, nor the Artboard tool's selection from the start of the run. let chosen = h.session.borrow().active().and_then(|st| { h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; Some((st.uid, super::dom::active_artboard(st))) @@ -263,7 +263,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { Some(chosen) => std::slice::from_ref(chosen), None => h.active_artboards.as_slice(), }; - let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !chosen.as_ref().is_some_and(|(c, _)| c == uid)); + let start = Start { active, picks, batch: s.artboard }; let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 3549c5d2e4..67aa1c29f3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -54,7 +54,7 @@ //! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an //! error. A run that fails leaves the tool as it was. //! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of -//! the paths in the object; a clipping group counts its clipping path only. +//! the shown paths in the object; a clip group or clipping layer takes in only its clipping path's. //! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]), //! in view-number order, and none without one. View objects keep their window's identity when //! windows are renumbered. The screen mode is the app's: @@ -99,11 +99,17 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_ use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; mod clipboard; +mod colors; +mod defaults; mod images; pub(super) mod layers; mod matrix; +mod paths; pub mod preferences; mod print; +mod raster_capture; +#[cfg(test)] +pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT; mod save_open; mod tags; mod text; @@ -111,11 +117,15 @@ mod tracing; mod transform; mod variables; +#[cfg(test)] +pub(crate) use paths::POINT_LOOKS; + pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; /// What [`after_command`] compares with, taken before each command a script runs /// ([`variables::before_command`]). pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + tracing::before_command(h); variables::before_command(h, id) } @@ -124,13 +134,6 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec>>>, - /// The path whose points the object model is writing with `path.setAnchors`, the only path - /// that command changes ([`paths`]). - one_path: Cell>, /// Each document, by uid, as it was when the run last looked at all the paths in it whose /// points it read ([`paths`]). point_docs: RefCell>>, @@ -292,11 +292,13 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step /// and no change to the document's saved state, and the growth its commands were charged is not -/// counted. +/// counted. Point changes that wait in [`State`] are written first, so a failure in `f` does not +/// put them back. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } + flush(h)?; let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); let styles = text::styles::mark(h); let mark = h.growth_mark(); @@ -459,7 +461,7 @@ fn point_method(link: &Link, f: Member) -> HostMember { pub(super) type Described = (String, HostMember, MemberInfo); /// A property's or a method's result's type for `reflect`. -fn typed(data_type: &str) -> MemberInfo { +pub(super) fn typed(data_type: &str) -> MemberInfo { MemberInfo { data_type: data_type.into(), ..MemberInfo::default() } } @@ -470,7 +472,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, layer, page item, path point or text range `this` is still there. +/// the check that a document, layer, page item, path point, text range or `GroupItems` collection +/// `this` is still there. /// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and /// `reflect` leaves it out. pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { @@ -495,6 +498,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "TextRange" => { text::check_range(&h, arg(&a, 0))?; } + "GroupItems" => { + layers::check_groups(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -2333,13 +2339,17 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - (ids, refused, on_locked) + // A clipping layer emptied of its art releases its mask, so art added later is not made its + // clipping path. + let released = masks_cleared_by(&st.doc, &ids); + let tracing = release_makes_tracing(&st.doc, &released, &ids); + (ids, refused, on_locked, released, tracing) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -2349,8 +2359,11 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if tracing { + return Err(HostError::Error(NOT_A_TRACING.into())); + } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } Ok(Data::Undefined) } @@ -2638,26 +2651,39 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } -/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an -/// object with nothing in it. +/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths +/// in the item. fn item_control(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, true)?; - let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds)); - match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) { - Some(r) => Ok(f.bounds(h.dom.coords.get(), r)), - None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), - } + // An object with nothing in it reads zeros, as its other bounds do. + let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) }; + // Each object and anchor the walk visits is charged, so reading a large group's bounds again + // and again counts against the run. + let mut steps = 0u64; + let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps))); + h.charge_call(steps)?; + Ok(f.bounds(h.dom.coords.get(), r)) } -/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown -/// paths in its children (a clip group's from its clipping path). -fn handle_bounds(n: &crate::doc::Node) -> Option { - match &n.kind { - NodeKind::Path { path, .. } => path.control_bounds(), - NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)), - _ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))), +/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and +/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as +/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping +/// path's. +fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { + *steps += 1; + if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return r; } + for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) { + *steps += 1; + r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); + } + let children = n.children().map_or(&[][..], Vec::as_slice); + let children = if n.clips() { &children[..children.len().min(1)] } else { children }; + for c in children { + r = take_in_handles(c, r, steps); + } + r } fn item_position(h: &Host, a: &[Data]) -> Answer { @@ -2830,11 +2856,55 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { return Err(HostError::Error(NOT_A_TRACING.into())); } + let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id])); + // A clip group named as a tracing, released with an image left first, would become one too. + if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. - edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; + let params = json!({"ids": [item.id.0], "keepEmpty": true}); + paths::see_all_points(h); + let kept = h.dom.editing.replace(Some(item)); + let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, ¶ms))); + h.dom.editing.set(kept); + r?; Ok(Data::Undefined) } +/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping +/// path releases its mask, so the object above it does not become the clipping path. +pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter() + .filter_map(|i| { + let p = d.parent_of(*i)?; + let n = d.node(p)?; + (n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p) + }) + .collect() +} + +/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups +/// an ordinary group named as a tracing with an image first in it, which would make it a tracing. +pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool { + if released.is_empty() { + return false; + } + let removed: std::collections::HashSet = removed.iter().copied().collect(); + released.iter().filter_map(|g| d.node(*g)).any(|g| { + matches!(g.kind, NodeKind::Group { .. }) + && g.name.as_deref() == Some(crate::cmd::TRACE_NAME) + && g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) + }) +} + +/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`. +pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result { + for g in released { + command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?; + } + command(h, "edit.clear", params) +} + /// The error of `remove()` and `removeAll()` for an object on a locked artboard. pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; @@ -2983,6 +3053,19 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> } } +/// Whether deleting every object in `removed` together would leave one of their parents, an +/// ordinary group named as a tracing, with an image first in it, which would make it a tracing. +pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool { + let going: std::collections::HashSet = removed.iter().copied().collect(); + let mut parents: Vec = removed.iter().filter_map(|i| d.parent_of(*i)).collect(); + parents.sort_unstable_by_key(|p| p.0); + parents.dedup(); + parents + .into_iter() + .filter(|p| named_as_tracing(d, *p)) + .any(|p| d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { @@ -2998,6 +3081,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul return Err(HostError::Error("a tracing's source image cannot leave its tracing".into())); } let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0; + // The clipping path itself, put back where it is, stays the clipping path. + let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0); let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -3009,11 +3094,19 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul { i -= 1; } - if how == Placement::Above { i + 1 } else { i } + let at = if how == Placement::Above { i + 1 } else { i }; + // A place behind a clipping path is refused; an object put into the clip group + // itself goes directly above the clipping path. + if clips && at == 0 && !mask_stays { + return Err(HostError::Error("an object cannot go below a clipping mask".into())); + } + at } (_, None) => count, }; - let at = if clips { at.max(1) } else { at }; + // Any other place for the clipping path is left to `node.move`, which refuses it. + let stays = mask_stays && at == 0; + let at = if clips && !stays { at.max(1) } else { at }; // The index `node.move` puts the object at: art stays below the ruler guides. // This is `Node::insert_index` on the parent's children without the object, read in place // so that no list of them is copied. @@ -3172,7 +3265,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { } /// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name. -fn named_text(class: &str, name: Answer) -> Answer { +pub(super) fn named_text(class: &str, name: Answer) -> Answer { match name? { Data::String(n) => Ok(text(format!("[{class} {n}]"))), _ => Ok(text(format!("[{class} ]"))), @@ -3255,7 +3348,9 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { text::install_enums(realm)?; - for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) { + for (name, members) in + ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) + { let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name); items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}")))))); @@ -3386,6 +3481,7 @@ fn classes(link: &Link) -> Vec { document.extend(print::document_members(l)); document.extend(images::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); + document.extend(raster_capture::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "Views", @@ -3550,6 +3646,7 @@ fn classes(link: &Link) -> Vec { classes.extend(tracing::classes(l)); classes.extend(save_open::classes(l)); classes.extend(print::classes(l)); + classes.extend(raster_capture::classes(l)); classes.extend(tags::classes(l)); classes } diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index ec2c7997cf..60f322e79f 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -302,8 +302,8 @@ fn may_read(h: &Host, path: &str) -> bool { /// The real path of the `File` `d` gives as an image to place or relink: one the script may read /// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of -/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no -/// error names the path. +/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path. +/// What the file holds is checked by the command that places or relinks it, which reads it once. fn image_path(h: &Host, d: &Data, what: &str) -> Result { let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?; if path.len() > super::super::files::MAX_PATH_CHARS { @@ -321,13 +321,21 @@ fn image_path(h: &Host, d: &Data, what: &str) -> Result { if meta.len() > MAX_PLACED_BYTES { return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20))); } - let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned(); - // What the file holds, read the way `file.place` reads it, before the document changes. - let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?; - if field(&info, "pixelWidth").is_none() { - return Err(HostError::Error(NOT_AN_IMAGE.into())); + Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) +} + +/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink` +/// refusing a file that holds no image before the document changes: that refusal is +/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check +/// and for the image it places. +fn image_only(h: &Host, f: impl FnOnce(&Host) -> Result) -> Result { + let kept = h.session.borrow().image_only.replace(Some(true)); + let r = f(h); + let refused = h.session.borrow().image_only.replace(kept) == Some(false); + match r { + Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())), + r => r, } - Ok(path) } // ---- PlacedItem ---- @@ -397,7 +405,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { // The placement and its check run under one savepoint, so an error after the place leaves // no linked image behind. let id = super::atomically(h, |h| { - let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; + let (_, placed) = image_only(h, |h| on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true}))))?; let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); let linked = @@ -414,7 +422,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { fn placed_relink(h: &Host, a: &[Data]) -> Answer { let item = this_of(h, a, "PlacedItem")?; let path = image_path(h, arg(a, 1), "relink's file")?; - edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?; + image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?; Ok(Data::Undefined) } @@ -473,7 +481,8 @@ fn area_of(m: Affine) -> bool { /// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix. /// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted -/// image is refused before anything changes; the matrix the image has already changes nothing. +/// image is refused before anything changes, and so is a locked or hidden image or one on a locked +/// artboard, as the transform methods refuse them; the matrix the image has already changes nothing. fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { let item = this_of(h, a, cls)?; let m = matrix_value(arg(a, 1))?; @@ -484,6 +493,22 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { if n.is_distorted_image() { return Err(HostError::Error(DISTORTED.into())); } + // The transform methods' refusals: a locked or hidden image, one inside a locked or hidden + // layer or group, and one on a locked artboard, whether or not the matrix changes. + let d = &st.doc; + let line = d.ancestry(item.id); + let any = |f: fn(&vectorcraft_doc::Node) -> bool| { + line.as_ref().is_none_or(|l| l.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(f))) + }; + if any(|n| n.locked) { + return Err(HostError::Error(format!("{}: {}", super::transform::LOCKED, item.id.0))); + } + if any(|n| !n.visible) { + return Err(HostError::Error(format!("{}: {}", super::transform::HIDDEN, item.id.0))); + } + if super::on_locked_artboard(h, st, item.id) { + return Err(HostError::Error(format!("{}: {}", super::transform::ON_LOCKED_ARTBOARD, item.id.0))); + } let f = frame(st)?; let target = Affine::new(match h.dom.coords.get() { Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]], diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..59c4ea8ccf 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,8 +12,8 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's -//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the -//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. @@ -68,6 +68,8 @@ enum Kind { Compound, /// Paths (`PathItem`). Path, + /// Type (`TextFrame`), whose collection's other members are in `text.rs`. + Text, } impl Kind { @@ -77,6 +79,7 @@ impl Kind { Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", Kind::Path => "PathItems", + Kind::Text => "TextFrames", } } @@ -86,6 +89,7 @@ impl Kind { Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), Kind::Path => typename(n) == Some("PathItem"), + Kind::Text => typename(n) == Some("TextFrame"), } } } @@ -245,7 +249,9 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v})) + // The number the getter reports, or one that stores as the opacity the layer has, leaves the + // layer as it is. + set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v || n.opacity == (v / 100.0) as f32, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { @@ -289,14 +295,12 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { } /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. +/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop +/// lists the layers once. Each read is still charged for the search through the list. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let parent = st.doc.parent_of(id); - let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len)); - h.charge_call(count as u64)?; - let list = layer_list(&st.doc, parent); + let list = layers_listed(h, st, st.doc.parent_of(id))?; h.charge_call(list.len() as u64)?; Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) })?; @@ -305,7 +309,14 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer { fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; - Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)))))) + let selected = with_doc(h, doc, |_, st| { + // The scan is charged by every selected object it looks at. + let objects = &st.selection.objects; + let found = objects.iter().position(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))); + h.charge_call(found.map_or(objects.len(), |i| i + 1) as u64)?; + Ok::<_, HostError>(found.is_some()) + })?; + Ok(Data::Bool(selected)) } /// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every @@ -332,7 +343,7 @@ fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec) -> u64 { fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "hasSelectedArtwork")?; let (doc, id) = this_layer(h, a)?; - let (ids, over) = with_doc(h, doc, |_, st| { + let (ids, over) = with_doc(h, doc, |s, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); let selected = &st.selection.objects; h.charge_call(selected.len() as u64)?; @@ -345,10 +356,31 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { // The walk is charged by every node it looks at, hidden and locked ones included, whether // or not anything is added. h.charge_call(count)?; + // While an object is isolated, the art that holds it is replaced by the isolated object, + // or by what an isolated group or other container holds, as Select All takes it. + let isolated = st.isolation.and_then(|i| st.doc.node(i)); + let path = isolated.and_then(|c| st.doc.ancestry(c.id)).unwrap_or_default(); + let editable = path.iter().all(|i| st.doc.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template())); + let mut candidates = Vec::with_capacity(art.len()); + for o in art { + match isolated { + Some(_) if path.contains(&o) && !editable => {} + Some(c) if path.contains(&o) && c.is_container() => { + // The same walk as the layer's, through any sublayer the container holds. + let visited = collect_editable_art(c, &mut candidates); + h.charge_call(visited)?; + } + Some(c) if path.contains(&o) => candidates.push(c.id), + _ => candidates.push(o), + } + } let mut have: std::collections::HashSet = selected.iter().copied().collect(); let mut ids = Vec::new(); - for o in art { - if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + for o in candidates { + if have.contains(&o) + || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) + || (s.guides_locked() && crate::is_guide_path(&st.doc, o)) + { continue; } // Only art that would be added counts toward the limit. @@ -642,6 +674,10 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("a document needs at least one layer".into())); } let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?; + // `layer.delete` takes at most this many rows; more is refused before anything is deleted. + if ids.len() > crate::cmd::layer::MAX_ROWS { + return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -760,8 +796,17 @@ fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { }; } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) { + Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))), + // The text of a number that is not an array index is looked up as a name. + None => with_doc(h, doc, |_, st| { + let ids = art_list(h, st, kind, c)?; + h.charge_call(ids.len() as u64)?; + let name = vectorcraft_js::number_to_string(*n); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id))) + }), + } } fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { @@ -778,6 +823,11 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { match arg(a, 1) { Data::String(_) => art_by_name(h, a, kind), + // A number is a position only. A stale collection throws its stale error first. + Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => { + art_scope(h, arg(a, 0), kind.class())?; + Err(HostError::Error(NOT_FOUND.into())) + } Data::Number(_) => match art_at(h, a, kind)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -833,6 +883,10 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" ))); } + // Deleting the objects above an image in an ordinary group named as a tracing would make it one. + if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; } @@ -982,6 +1036,20 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +fn held_text(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Text) +} + +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + art_scope(h, d, Kind::Text.class()) +} + +/// The type objects directly in `container`, topmost first. +pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result>> { + art_list(h, st, Kind::Text, Some(container)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -1005,11 +1073,16 @@ fn group_clipped(h: &Host, a: &[Data]) -> Answer { } /// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the -/// clipping mask. The group keeps its id either way. +/// clipping mask. The group keeps its id either way. A hidden or locked topmost object is refused +/// before it loses its paint. fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "clipped")?; let item = this_item_of(h, a, "GroupItem")?; - let (now, ok) = with_doc(h, item.doc, |_, st| (st.doc.node(item.id).is_some_and(crate::doc::Node::clips), editable(&st.doc, item.id))); + let (now, ok, top) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let top = d.node(item.id).and_then(|n| n.children()).and_then(|c| c.iter().rev().find(|c| !c.is_ruler_guide())).map(|c| c.id); + (d.node(item.id).is_some_and(crate::doc::Node::clips), editable(d, item.id), top.filter(|t| !editable(d, *t))) + }); if now == on { return Ok(Data::Undefined); } @@ -1017,6 +1090,9 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { if !ok { return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); } + if let Some(t) = top.filter(|_| on) { + return Err(HostError::Error(format!("Cannot clip GroupItem {}: its topmost object {} is hidden or locked", item.id.0, t.0))); + } on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; Ok(Data::Undefined) } @@ -1035,8 +1111,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec { ("pageItems", get(l, held_page_items), listed("PageItems")), ("groupItems", get(l, held_groups), listed("GroupItems")), ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("textFrames", get(l, held_text), listed("TextFrames")), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]), @@ -1317,9 +1394,13 @@ fn layers_to_string(h: &Host, a: &[Data]) -> Answer { Ok(text("[Layers]")) } fn groups_to_string(h: &Host, a: &[Data]) -> Answer { - art_scope(h, arg(a, 0), Kind::Group.class())?; + check_groups(h, arg(a, 0))?; Ok(text("[GroupItems]")) } +/// Fails when `d` is not a `GroupItems` collection or the document, layer or group it lists is gone. +pub(super) fn check_groups(h: &Host, d: &Data) -> Result<()> { + art_scope(h, d, Kind::Group.class()).map(|_| ()) +} fn compounds_to_string(h: &Host, a: &[Data]) -> Answer { art_scope(h, arg(a, 0), Kind::Compound.class())?; Ok(text("[CompoundPathItems]")) @@ -1511,17 +1592,17 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items), listed("PageItems")), ("groupItems", get(l, held_groups), listed("GroupItems")), ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("textFrames", get(l, held_text), listed("TextFrames")), ("zOrderPosition", get(l, layer_z_position), typed("number")), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")), ("isIsolated", get(l, layer_is_isolated), typed("boolean")), - ("move", method(l, layer_move), typed("Layer")), + ("move", method(l, layer_move), returns("Layer", &[("relativeObject", "*"), ("insertionLocation", "ElementPlacement")])), ("remove", method(l, layer_remove), returns("undefined", &[])), - ("zOrder", method(l, layer_z_order), typed("undefined")), + ("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ("toString", method(l, layer_to_string), returns("string", &[])), ]); layer.extend( - ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] - .map(|m| later(l, "Layer", m)), + ["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), ); vec![ class("Layer", None, layer, None), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index a164dd93fc..cd00207c61 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -17,7 +17,8 @@ //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing //! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked -//! artboard. +//! artboard. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a +//! range error when it is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -52,9 +53,7 @@ //! throws an error that says it is not available yet on a path inside a compound path, throws //! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides //! are locked; assigning the value the path has runs no command. -//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and -//! `changeStrokePattern` given as different values throw an error; gradients move with the art, -//! so `changeFillGradients` false throws an error that says it is not available yet. +//! - The transforms are `PageItem`'s, with their rules in [`super::transform`]. use std::rc::Rc; use std::sync::Arc; @@ -69,9 +68,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value, - coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, num, - number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, + Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, + edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point, + point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -108,16 +107,27 @@ fn cannot_edit(id: NodeId) -> HostError { HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) } -/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or -/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one. -fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> { +/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is +/// hidden or locked, or it is on a locked artboard. +fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { if !editable(&st.doc, id) { - return Err(cannot_edit(id)); + Some(cannot_edit(id)) + } else if super::on_locked_artboard(h, st, id) { + Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) { + Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))) + } else { + None } - if super::on_locked_artboard(h, st, id) { - return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))); +} + +/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin. +fn in_canvas(p: Point, what: &str) -> std::result::Result { + if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { + Ok(p) + } else { + Err(HostError::Range(format!("{what} is outside the canvas"))) } - Ok(()) } /// The path `d` names, which must still be in its document. @@ -131,9 +141,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result std::result::Result { +/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them. +fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result { let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; path_of(h, &path_ref(h, Item { doc, id })) } @@ -149,12 +162,10 @@ fn read_path(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d }) } +/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count). fn path_ref(h: &super::Host, item: Item) -> Data { - let s = h.session.borrow(); - match s.documents().iter().find(|d| d.uid == item.doc.uid) { - Some(st) => host_ref("PathItem", &super::node_handle(h, st, item.id)), - None => Data::Null, - } + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + host_ref("PathItem", &handle) } /// The index of the first point of each subpath of `subs`, followed by the number of points. @@ -219,6 +230,8 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result Option<(usize, usize)> { for (s, sp) in subs.iter().enumerate() { + #[cfg(test)] + tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1)); if i < sp.anchors.len() { return Some((s, i)); } @@ -248,7 +261,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with /// the path's other point changes until [`flush`] writes them. The first change of a path writes /// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path +/// locked or is on a locked artboard ([`protected`]), unless it changes nothing. A path /// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its /// points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { @@ -264,10 +277,13 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); - (pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned) + let same = pd.subpaths == subs; + (same, if same { None } else { protected(h, st, item.id) }, aligned) })?; if !same { - refused?; + if let Some(e) = refused { + return Err(e); + } *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { flush(h)?; @@ -325,12 +341,29 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); - // Changes made before this one are looked at in full first. - see_all_points(h); - let kept = h.dom.one_path.replace(Some(item)); - let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})); - h.dom.one_path.set(kept); - r?; + super::atomically(h, |h| { + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + let selection = &mut st.selection; + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len())); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count())); + if segments.is_empty() { + selection.segments.remove(&item.id); + } + } + if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) { + selection.key_anchor = None; + } + if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id)) + && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty())) + { + selection.remove(item.id); + } + } + edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})) + })?; Ok(()) } @@ -340,26 +373,36 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) } -/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active -/// layer, then puts the drawing mode back. -fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { - let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); - let r = f(); - h.session.borrow_mut().draw_mode = kept; - r +/// Runs a path creation command with its layer placement recorded. +fn drawing_normally(h: &super::Host, parent: Option, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let mut params = params.clone(); + params["onLayer"] = json!(parent.map(|p| p.0)); + super::command_value(h, id, ¶ms) } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which -/// must be one the user could edit ([`refuse_path_edit`]). +/// must be one the user could edit ([`protected`]). /// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { - with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?; + if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) { + return Err(e); + } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + o.insert("objectOnly".into(), json!(true)); + } } - keeping_paint(h, || edit_item(h, item, id, ¶ms)) + let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; + let count = if id == "object.setOverprint" { "changed" } else { "objects" }; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); + } + Ok(result) } /// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color @@ -503,6 +546,11 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; + if h.session.borrow().menu.guides_locked + && let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))); + } let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); @@ -522,10 +570,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object, read from the command's own result so -/// that an id above 2^53 stays exact. -fn made_id(r: &Value) -> std::result::Result { - r["id"].as_u64().map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// The id in the JSON result of a command that made an object, read exactly, as the text creators +/// read it. +fn made_id(r: &(Data, Value)) -> std::result::Result { + r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } /// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, @@ -535,7 +583,8 @@ fn made_id(r: &Value) -> std::result::Result { fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = keeping_paint(h, || { on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -700,9 +749,10 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?; if unpainted { - command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]}))?; + command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?; } Ok(id) }) @@ -716,8 +766,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { fn path_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - let [high, low] = id_parts(item.id); - Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + Ok(host_ref("PathPoints", &handle)) } fn path_closed(h: &super::Host, a: &[Data]) -> Answer { @@ -728,7 +778,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, |subs| { + if subs.is_empty() && closed { + subs.push(SubPath::new(Vec::new(), closed)); + } else { + subs.iter_mut().for_each(|sp| sp.closed = closed); + } + })?; Ok(Data::Undefined) } @@ -835,8 +891,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; let c = h.dom.coords.get(); let anchors: Vec = - script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; - let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; + script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; + let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; cut_points(h, item); Ok(Data::Undefined) @@ -924,10 +980,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Ok(match linked { true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), true => json!({"swatch": name}), - false => json!({"color": colors::param(color)}), + false => json!({"color": colors::param(color), "keepModel": true}), }) } - Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})), Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { @@ -1180,6 +1236,20 @@ pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, c Ok(((new_width - width).abs() > 1e-9).then_some(new_width)) } +/// The largest stroke weight in the path `item`'s own appearance, in points. +pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result { + read_path(h, item, |_, n, _| { + n.appearance + .items + .iter() + .filter_map(|item| match item { + vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width), + vectorcraft_doc::AppearanceItem::Fill(_) => None, + }) + .fold(0.0, f64::max) + }) +} + /// Whether `item` is a path, so [`resized_stroke_weight`] applies to it. pub(super) fn is_path(h: &super::Host, item: Item) -> bool { with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) @@ -1200,8 +1270,8 @@ pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; - let item = path_at(h, *run, *uid, *high, *low)?; + let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; + let item = path_at(h, *run, *uid, *high, *low, *reverts)?; flush_other(h, item)?; Ok(item) } @@ -1240,8 +1310,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer { } fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))]) + let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec(); + handle.extend([float(i as u64), float(point_cuts(h, item))]); + host_ref("PathPoint", &handle) } /// How many times the points read of `item` have gone stale, after [`see_points`] notes a change @@ -1293,7 +1364,10 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { POINT_LOOKS.with(|n| n.set(n.get() + 1)); let node = { let s = h.session.borrow(); - s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()) + s.documents().iter().find(|d| d.uid == key.0).and_then(|st| { + h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone()); + node_arc(&st.doc, NodeId(key.1)).cloned() + }) }; // A path that is gone makes its points stale, so that an undo that brings it back leaves them // stale. @@ -1316,53 +1390,47 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// change that a later command reverses still makes the points stale. Paths under the object that /// the object model is changing ([`super::State`]), or that object itself, take the change as the /// object model's own, and their points stay valid. A document that is the one the run last looked -/// at is skipped, as are its paths. While the object model writes one path's points -/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing -/// Objects on Path group are looked at in its document. +/// at is skipped, as are its paths. pub(super) fn see_all_points(h: &super::Host) { let keys: Vec<(u64, u64)> = { - let seen = h.dom.point_nodes.borrow(); - if seen.values().all(|paths| paths.is_empty()) { - return; - } let s = h.session.borrow(); let mut docs = h.dom.point_docs.borrow_mut(); - let one = h.dom.one_path.get(); + let seen = h.dom.point_nodes.borrow(); let mut keys = Vec::new(); - // The documents that changed since the last look, kept as they are now. - for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) { - // Editing a path in an Objects on Path group can move other paths in the group. - let mut moved = Vec::new(); - match s.documents().iter().find(|d| d.uid == *uid) { - Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue, - Some(st) => { - if let Some(item) = one.filter(|i| i.doc.uid == *uid) { - let d = &st.doc; - let group = d.ancestry(item.id).and_then(|a| { - a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g)) - }); - if let Some(g) = group { - g.walk(&mut |n: &crate::doc::Node| { - if n.id != item.id && paths.contains_key(&n.id.0) { - moved.push((*uid, n.id.0)); - } - }); - } - } - docs.insert(*uid, st.doc.clone()); + docs.retain(|uid, before| { + let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); + if after.is_some_and(|after| Arc::ptr_eq(before, after)) { + return true; + } + // Editing a path in an Objects on Path group can move the other paths in the group, so + // the outermost such group is looked at in place of the path. + let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { + Some(item) => { + let group = before + .ancestry(item.id) + .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))); + node_arc(before, group.unwrap_or(item.id)).into_iter().collect() } - None => { - docs.remove(uid); + None => before.layers.iter().collect(), + }; + while let Some(node) = todo.pop() { + if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) { + continue; + } + if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) { + keys.push((*uid, node.id.0)); + } + if let Some(children) = node.children() { + todo.extend(children); } } - match one { - Some(item) if item.doc.uid == *uid => { - keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0))); - keys.append(&mut moved); - } - _ => keys.extend(paths.keys().map(|id| (*uid, *id))), + if let Some(after) = after { + *before = after.clone(); + true + } else { + false } - } + }); keys }; let editing = h.dom.editing.get(); @@ -1444,8 +1512,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { /// point of the path removed or replaced since `this` was read. pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let item = path_at(h, *run, *uid, *high, *low)?; + let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low, *reverts)?; flush_other(h, item)?; if whole(*cuts) != Some(point_cuts(h, item)) { return Err(HostError::Error(STALE_POINT.into())); @@ -1482,17 +1550,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul let p = point(arg(a, 1), what)?; let (item, _) = this_point(h, a)?; let fr = with_doc(h, item.doc, |_, st| frame(st))?; - on_canvas(fr.to_document(h.dom.coords.get(), p), what) -} - -/// `p`, a point a script gave in document coordinates, when it is on the canvas (within -/// [`crate::MAX_COORD`] of the origin); a `RangeError` otherwise. -fn on_canvas(p: Point, what: &str) -> std::result::Result { - if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { - Ok(p) - } else { - Err(HostError::Range(format!("{what} is outside the canvas"))) - } + in_canvas(fr.to_document(h.dom.coords.get(), p), what) } fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer { @@ -1560,12 +1618,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ if held { return true; } - if !sel.contains(id) || sel.segments.contains_key(&id) { + if !sel.contains(id) { return false; } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => locate(subs, i).is_some_and(|(s, j)| { + picked.contains(&(s, j)) + && !sel + .segments + .get(&id) + .is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j))) + }), } } @@ -1577,12 +1641,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point /// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in -/// [`super::State`] are written first only when they add or remove points of this path, since -/// the selection names anchors by their place in the document's path. +/// [`super::State`] are written first when they add or remove points of this path or invalidate +/// selected segments. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; let moved = match &*h.dom.pending.borrow() { - Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| { + !same_layout(subs, &pd.subpaths) + || st + .selection + .segments + .get(&item.id) + .is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count()))) + })?, _ => false, }; if moved { @@ -1650,22 +1721,31 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; let held = held_selected(&st.doc, sel, item.id); - if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { + if !held && !sel.contains(item.id) { return Vec::new(); } - let mut out = Vec::new(); - let mut first = 0; + let segments = sel.segments.get(&item.id); + let ends: std::collections::BTreeSet<_> = segments + .into_iter() + .flatten() + .filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())])) + .flatten() + .collect(); + let partial = sel.partial(item.id).filter(|_| !held); + let mut picked = Vec::new(); + let mut offset = 0; for (s, sp) in pd.subpaths.iter().enumerate() { - let n = sp.anchors.len(); - out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); - first += n; + for j in 0..sp.anchors.len() { + if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) { + picked.push(offset + j); + } + } + offset += sp.anchors.len(); } - out + picked })?; h.charge_call(picked.len() as u64)?; - let [high, low] = id_parts(item.id); - let cuts = float(point_cuts(h, item)); - let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect(); + let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); Ok(Data::Array(points)) } @@ -1723,10 +1803,13 @@ fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option Vec { ), ("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")), ("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")), - ("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")), + ("strokeMiterLimit", property(l, path_miter, path_set_miter), MemberInfo { min: Some(1.0), max: Some(500.0), ..typed("number") }), ("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")), ("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")), ("selectedPathPoints", get(l, path_selected_points), typed("Array")), @@ -1897,13 +1980,38 @@ pub(super) fn classes(l: &Link) -> Vec { #[cfg(test)] mod tests { + use std::cell::Cell; + use super::*; + use crate::Session; + + thread_local! { + pub(super) static LOCATE_STEPS: Cell = const { Cell::new(0) }; + } + + #[test] + fn selected_points_do_not_rescan_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128]; + s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap(); + LOCATE_STEPS.with(|steps| steps.set(0)); + let out = s + .execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"})) + .unwrap(); + assert_eq!(out["log"], json!([2])); + LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get())); + } #[test] fn a_made_id_above_two_to_the_53_stays_exact() { - assert_eq!(made_id(&json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993))); - assert_eq!(made_id(&json!({"id": 7})), Ok(NodeId(7))); - assert!(made_id(&json!({"id": 1.5})).is_err()); - assert!(made_id(&json!({})).is_err()); + let made = |v: Value| made_id(&(Data::Undefined, v)); + assert_eq!(made(json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993))); + assert_eq!(made(json!({"id": 7})), Ok(NodeId(7))); + assert!(made(json!({"id": 1.5})).is_err()); + assert!(made(json!({})).is_err()); } } diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs new file mode 100644 index 0000000000..f067b430d4 --- /dev/null +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -0,0 +1,696 @@ +//! Rasterizing art and capturing it as an image in the script object model: `Document.rasterize`, +//! `Document.imageCapture` and their option classes, as the help pages +//! , +//! , +//! and +//! describe. +//! +//! `rasterize` runs `object.rasterize` with the source art's ids, and `imageCapture` runs +//! `document.export` of an area of the page, inside the run's transaction. Every option is given to +//! the command, at the help page's default when the script leaves it out, so the document's raster +//! effects settings do not change the result. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as +//! `geometricBounds` gives them; the right edge must be right of the left one and the bottom edge +//! below the top one, and the numbers are never swapped. +//! - `rasterize` takes one page item or a list of at most [`super::MAX_LISTED`] of them, all of +//! this document, none listed twice, inside another listed one or a path of a compound path, and +//! none locked or in a locked layer or group. It keeps the selection, less the art it replaces, +//! and gives the new `RasterItem`: with `clippingMask`, the image inside its clip group. +//! `transparency` wins over `backgroundBlack`. `convertSpotColors`, `convertTextToOutlines` and +//! `includeLayers` true throw an error that says they are not available yet. +//! - `imageCapture` writes a PNG, and the file's name must end with `.png`. Without `clipBounds` it +//! captures the bounds of all the visible art, on the artboards or off them. With +//! `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with +//! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 +//! to 255. The file is written only where the script's `File` objects may write, and never over +//! an open document's file or a file one of them links, under any of its names (a hard link +//! included); on Unix it is never written over a file that has other hard links. Source paths +//! outside both the automation read and write roots are excluded before +//! filesystem probes. +//! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is +//! drawn; the resolution is never lowered to make it fit. +//! - `windowCapture` throws an error that says it is not available yet. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_geom::Rect; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; + +use super::{ + Answer, Described, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, class, command, command_value, coordinate, current, frame, given, + item_of, item_ref, later, method, named, num, on_doc, returns, text, this_doc, with_doc, +}; + +/// The lowest resolution the option classes take, in pixels per inch. +pub const MIN_RESOLUTION: f64 = 72.0; +/// The highest resolution the option classes take, in pixels per inch. +pub const MAX_RESOLUTION: f64 = 2400.0; +/// The most room `RasterizeOptions.padding` adds around the art, in points. +pub const MAX_PADDING: f64 = 1000.0; +/// The error of a source art object from another document. +pub const OTHER_DOCUMENT: &str = "The source art must be in this document"; + +/// The enumerations these members use, as `dom`'s are made. +pub(super) const ENUMS: &[(&str, &[&str])] = + &[("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]), ("RasterizationColorModel", &["BITMAP", "DEFAULTCOLORMODEL", "GRAYSCALE"])]; + +/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`). +fn member<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> { + let members = ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m); + let bad = || HostError::Type(format!("{what} must be a {enumeration} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?; + if members.contains(&m) { Ok(m) } else { Err(bad()) } +} + +/// A finite number from `lo` to `hi`. +fn number_in(d: &Data, what: &str, lo: f64, hi: f64) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => { + if (lo..=hi).contains(n) { + Ok(*n) + } else { + Err(HostError::Range(format!("{what} must be from {lo} to {hi}"))) + } + } + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// The fields of the options object `d` of `class`, or `None` when the script gave none. +fn options<'a>(d: &'a Data, class: &str) -> std::result::Result, HostError> { + match given(d) { + None | Some(Data::Null) => Ok(None), + Some(Data::Object(items)) if items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class)) => Ok(Some(items)), + Some(_) => Err(HostError::Type(format!("the options must be a {class} object"))), + } +} + +/// `clipBounds`, `[left, top, right, bottom]` in the run's script coordinates, as a rectangle in +/// document coordinates; `None` when the script gave none. +fn clip_bounds(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let a = match given(d) { + None | Some(Data::Null) => return Ok(None), + Some(Data::Array(a)) if a.len() == 4 => a, + Some(_) => return Err(HostError::Type("clipBounds must be an array of four numbers [left, top, right, bottom]".into())), + }; + let mut n = [0.0; 4]; + for (o, d) in n.iter_mut().zip(a) { + *o = coordinate(d, "clipBounds")?; + } + let f = with_doc(h, doc, |_, st| frame(st))?; + let c = h.dom.coords.get(); + let (p0, p1) = (f.to_document(c, [n[0], n[1]]), f.to_document(c, [n[2], n[3]])); + if p1.x <= p0.x || p1.y <= p0.y { + return Err(HostError::Range("clipBounds must have its right edge right of its left edge and its bottom edge below its top edge".into())); + } + Ok(Some(Rect::new(p0.x, p0.y, p1.x, p1.y))) +} + +/// Throws when an image of `region` at `ppi` would be more than 64 megapixels or longer than the +/// renderer draws on a side, before anything is drawn. +fn check_size(region: Rect, ppi: f64) -> std::result::Result<(), HostError> { + let scale = ppi / 72.0; + let (w, h) = ((region.width() * scale).round().max(1.0), (region.height() * scale).round().max(1.0)); + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if w * h > crate::cmd::menucmds::MAX_PIXELS || w > side || h > side { + return Err(HostError::Range(format!( + "the image would be {w} × {h} pixels; images are limited to 64 megapixels and {side} pixels a side: lower the resolution or the bounds" + ))); + } + Ok(()) +} + +// ---- Rasterize ---- + +/// `object.rasterize`'s params for the `RasterizeOptions` fields `items` (`None`: the defaults), +/// with every option given. +fn rasterize_params(items: Option<&[(String, Data)]>) -> std::result::Result, HostError> { + let (mut anti_alias, mut black, mut clear, mut clip, mut model, mut padding, mut ppi) = ("art", false, false, false, "document", 0.0, 300.0); + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("RasterizeOptions.{k}"); + match k.as_str() { + "antiAliasingMethod" => { + anti_alias = match member(v, "AntiAliasingMethod", &what)? { + "None" => "none", + "TYPEOPTIMIZED" => "type", + _ => "art", + } + } + "backgroundBlack" => black = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "clippingMask" => clip = boolean(v, &what)?, + "colorModel" => { + model = match member(v, "RasterizationColorModel", &what)? { + "BITMAP" => "bitmap", + "GRAYSCALE" => "grayscale", + _ => "document", + } + } + "padding" => padding = number_in(v, &what, 0.0, MAX_PADDING)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "convertSpotColors" | "convertTextToOutlines" | "includeLayers" if boolean(v, &what)? => { + return Err(HostError::Error(format!("{what} is not available yet"))); + } + _ => {} + } + } + let background = if clear { + "transparent" + } else if black { + "black" + } else { + "white" + }; + let mut p = Map::new(); + p.insert("ppi".into(), json!(ppi)); + p.insert("background".into(), json!(background)); + p.insert("antiAlias".into(), json!(anti_alias)); + p.insert("padding".into(), json!(padding)); + p.insert("colorModel".into(), json!(model)); + p.insert("clippingMask".into(), json!(clip)); + Ok(p) +} + +/// The ids of the source art `d` names for `rasterize` in the document `doc`: one page item, or a +/// list of them, none inside another listed one. The command checks that none is listed twice or +/// locked. +fn sources(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match d { + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("rasterize takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + Data::Undefined | Data::Null => return Err(HostError::Type("rasterize needs the source art, a page item or a list of them".into())), + d => vec![d], + }; + if list.is_empty() { + return Err(HostError::Error("rasterize needs at least one page item".into())); + } + h.charge_call(16 * list.len() as u64)?; + let mut ids = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error(OTHER_DOCUMENT.into())); + } + ids.push(item.id.0); + } + let listed: std::collections::HashSet = ids.iter().copied().collect(); + let inside = with_doc(h, doc, |_, st| { + ids.iter().find_map(|id| { + let up = st.doc.ancestry(crate::NodeId(*id))?; + up.iter().any(|a| a.0 != *id && listed.contains(&a.0)).then_some(()) + }) + }); + if inside.is_some() { + return Err(HostError::Error("a source page item is inside another one, which is listed too".into())); + } + Ok(ids) +} + +/// `document.rasterize(sourceArt, clipBounds?, options?)`: `object.rasterize` of the source art, +/// which the image replaces in one undo step. → the new `RasterItem`. +fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = sources(h, doc, arg(a, 1))?; + let clip = clip_bounds(h, doc, arg(a, 2))?; + let mut p = rasterize_params(options(arg(a, 3), "RasterizeOptions")?)?; + p.insert("ids".into(), json!(ids)); + if let Some(r) = clip { + p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); + } + // The image's id is read from the command's own result inside the run's savepoint, so an id + // that a script number cannot hold exactly still names the image, and a missing one undoes the edit. + let (r, image) = on_doc(h, doc.uid, true, |h| { + let (r, value) = command_value(h, "object.rasterize", &Value::Object(p))?; + let image = value.get("imageId").and_then(Value::as_u64).ok_or_else(|| HostError::Error("the image was not made".into()))?; + Ok((r, image)) + })?; + super::save_open::command_warnings(h, "rasterize", &r); + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(item_ref(h, st, crate::NodeId(image))) +} + +// ---- Image capture ---- + +/// A channel of `matteColor`: a finite number from 0 to 255. +fn channel(items: &[(String, Data)], key: &str) -> std::result::Result { + let d = items.iter().find(|(k, _)| k == key).map_or(&Data::Undefined, |(_, v)| v); + let n = number_in(d, &format!("ImageCaptureOptions.matteColor.{key}"), 0.0, 255.0)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = n.round() as u8; + Ok(byte) +} + +/// The capture's resolution and `document.export`'s `background` and `antiAlias` for the +/// `ImageCaptureOptions` fields `items` (`None`: the defaults). +fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f64, String, &'static str), HostError> { + let (mut anti_alias, mut matte, mut clear, mut ppi) = (false, false, false, 150.0); + let mut color = [255u8; 3]; + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("ImageCaptureOptions.{k}"); + match k.as_str() { + "antiAliasing" => anti_alias = boolean(v, &what)?, + "matte" => matte = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "matteColor" => { + let Data::Object(c) = v else { return Err(HostError::Type(format!("{what} must be an RGBColor"))) }; + color = [channel(c, "red")?, channel(c, "green")?, channel(c, "blue")?]; + } + _ => {} + } + } + let background = if clear { + "transparent".to_string() + } else if matte { + format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2]) + } else { + "white".to_string() + }; + Ok((ppi, background, if anti_alias { "art" } else { "none" })) +} + +/// The files a capture must not write over: the open documents' files and the files their linked +/// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns +/// and brushes included), with a DCS image's plate files, also when a file is missing, in the form +/// [`placed`] gives. A link's places are the ones opening the document looks at: its stored path +/// from the document's folder and its relative path from the folder of the file the document was +/// read from (a template opened as an untitled document has no file of its own), with a DCS +/// image's plate files beside each. The documents the interface has open while the run's slice +/// runs, such as one opened while the run was paused, count too. +fn sources_on_disk(h: &Host) -> Vec { + let s = h.session.borrow(); + let interface = h.interface_docs.borrow(); + let mut paths: Vec = Vec::new(); + for st in s.documents().iter().chain(interface.iter()) { + paths.extend(st.path.clone()); + paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st))); + } + paths.iter().filter_map(|p| source_place(p)).collect() +} + +/// An open document or linked file inside the automation read or write roots: one that only a write +/// root covers is compared too, since a capture may write there. A path outside both is left out +/// before it is looked up, as no capture can write it; the refusal names only the requested path. +fn source_place(path: &str) -> Option { + if crate::file_access::check_read(path).is_err() && crate::file_access::check_write_unrecorded(path).is_err() { + return None; + } + placed(std::path::Path::new(path)) +} + +/// A file as its folder's real path and its name. +type Placed = (std::path::PathBuf, std::ffi::OsString); + +/// `p` as its folder's real path and its file name: from its real path with links followed, or, +/// for a file that is not there, from its folder's real path. `None` when neither the file nor its +/// folder is there. +fn placed(p: &std::path::Path) -> Option { + let real = std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?)))?; + Some((real.parent()?.to_path_buf(), real.file_name()?.to_os_string())) +} + +/// Whether two [`placed`] files are one file: the same folder, and the same name, or names that +/// differ only in letter case in a folder whose volume ignores case, or only in their Unicode +/// normalization form in a folder whose volume ignores that. +fn same_file(a: &Placed, b: &Placed) -> bool { + if !same_folder(&a.0, &b.0) { + return false; + } + if a.1 == b.1 { + return true; + } + let (x, y) = (a.1.to_string_lossy(), b.1.to_string_lossy()); + let form = |s: &str| unicode_normalization::UnicodeNormalization::nfc(s).collect::(); + if form(&x) == form(&y) { + return ignores_normalization(&a.0); + } + let (lx, ly) = (x.to_lowercase(), y.to_lowercase()); + if form(&lx) != form(&ly) || !ignores_case(&a.0) { + return false; + } + lx == ly || ignores_normalization(&a.0) +} + +/// Whether file names in the real folder `folder` ignore their Unicode normalization form: the +/// first of the folder's first 256 entries whose name changes between the composed (NFC) and +/// decomposed (NFD) forms, and that is not a symbolic link, is looked up in the other form, and +/// names ignore the form when that finds the same entry. With no such entry, names ignore the form +/// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that +/// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the +/// form, as they are taken to when the flag can't be read. Elsewhere names keep the form. +fn ignores_normalization(folder: &std::path::Path) -> bool { + use unicode_normalization::UnicodeNormalization; + for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { + let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue }; + let (c, d): (String, String) = (name.nfc().collect(), name.nfd().collect()); + let other = if name == c { d } else { c }; + if other != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(other)); + } + } + #[cfg(target_os = "linux")] + { + casefolded(folder) + } + #[cfg(not(target_os = "linux"))] + { + cfg!(target_os = "macos") + } +} + +/// `FS_CASEFOLD_FL` from Linux's `include/uapi/linux/fs.h`: the folder looks names up casefolded. +#[cfg(target_os = "linux")] +const FS_CASEFOLD_FL: u32 = 0x4000_0000; + +/// Whether the Linux folder `folder` carries the casefold inode flag, read with +/// `FS_IOC_GETFLAGS`. `true` when the folder can't be opened or its flags can't be read: `false` +/// only when the flags are read and the flag is clear. +#[cfg(target_os = "linux")] +fn casefolded(folder: &std::path::Path) -> bool { + std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_none_or(|f| has_casefold(f.bits())) +} + +/// Whether the inode flags `bits` include `FS_CASEFOLD_FL`. +#[cfg(target_os = "linux")] +fn has_casefold(bits: u32) -> bool { + bits & FS_CASEFOLD_FL != 0 +} + +/// The check `imageCapture` makes on the file it writes, `p`, given as written or as the real path +/// of its folder with its name: it is none of the `sources` ([`sources_on_disk`]), not one of them +/// under another name, and has no other hard links. +fn capture_target_check(p: &std::path::Path, sources: &[Placed], shown: &str) -> Result<(), String> { + let real = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if placed(&real).is_some_and(|t| sources.iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { + return Err(format!("imageCapture cannot write over an open document or a file it links: {shown}")); + } + if has_other_links(&real) { + return Err(format!("imageCapture cannot write over a file that has other hard links: {shown}")); + } + Ok(()) +} + +#[cfg(test)] +thread_local! { + /// Run once in `imageCapture` after its checks and before its export, for tests that change the + /// destination in between. + pub(crate) static BEFORE_CAPTURE_EXPORT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and +/// file number, so a path spelled in another letter case on a volume that ignores case still +/// matches. On Windows a real path carries the letter case stored on disk. +fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if a == b { + return true; + } + if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { + return x.dev() == y.dev() && x.ino() == y.ino(); + } + false + } + #[cfg(not(unix))] + { + a == b + } +} + +/// Whether two existing paths name one file on disk, such as two hard links to it: the same device +/// and file number on Unix, or the same volume and file index on Windows. `false` when either is +/// missing. +fn same_identity(a: &std::path::Path, b: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + matches!((std::fs::metadata(a), std::fs::metadata(b)), (Ok(x), Ok(y)) if (x.dev(), x.ino()) == (y.dev(), y.ino())) + } + #[cfg(windows)] + { + same_file::is_same_file(a, b).unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (a, b); + false + } +} + +/// Whether the existing file at `p` has more than one name on Unix: writing into it in place, when +/// its folder refuses a replacement, would change the file under its other names too. Always +/// `false` off Unix, where [`same_identity`] compares the protected files instead. +fn has_other_links(p: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.nlink() > 1) + } + #[cfg(not(unix))] + { + let _ = p; + false + } +} + +/// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a +/// symbolic link or another file. +fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool { + if !std::fs::symlink_metadata(other).is_ok_and(|m| !m.file_type().is_symlink()) { + return false; + } + match (std::fs::canonicalize(entry), std::fs::canonicalize(other)) { + (Ok(a), Ok(b)) => same_folder(&a, &b), + _ => false, + } +} + +/// `name` with the letter case of every ASCII letter swapped, and other characters as they are. +fn swapped_case(name: &str) -> String { + name.chars().map(|c| if c.is_ascii_lowercase() { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() }).collect() +} + +/// Whether file names in the real folder `folder` ignore letter case. Names keep case when two of +/// the folder's first 256 entries differ only in the case of ASCII letters. Otherwise the first of +/// them whose name has an ASCII letter and that is not a symbolic link is looked up with the case +/// of those letters swapped: names ignore case when that finds the same entry. With no such entry +/// on macOS, where a whole volume either ignores or keeps case, the nearest folder at or above +/// `folder` whose name has an ASCII letter, with its parent on the same volume, is looked up the +/// same way in its parent. When neither tells, names are taken to ignore case. +fn ignores_case(folder: &std::path::Path) -> bool { + let entries: Vec = std::fs::read_dir(folder).into_iter().flatten().flatten().take(256).collect(); + let mut folded = std::collections::HashSet::new(); + let names: std::collections::HashSet = entries.iter().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + if !names.iter().all(|n| folded.insert(n.to_ascii_lowercase())) { + return false; + } + for entry in &entries { + let name = entry.file_name().to_string_lossy().into_owned(); + let swapped = swapped_case(&name); + if swapped != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(swapped)); + } + } + #[cfg(target_os = "macos")] + for dir in folder.ancestors() { + use std::os::unix::fs::MetadataExt; + let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { break }; + let device = |p: &std::path::Path| std::fs::metadata(p).map(|m| m.dev()).ok(); + let here = device(folder); + if here.is_none() || device(dir) != here || device(parent) != here { + break; + } + let name = name.to_string_lossy(); + let swapped = swapped_case(&name); + if swapped != name { + return finds_same(dir, &parent.join(swapped)); + } + } + true +} + +/// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the +/// art inside `clipBounds`, or of all the visible art. +fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = vectorcraft_js::file_ref_path(arg(a, 1)).ok_or_else(|| HostError::Type("imageCapture needs a File".into()))?; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); + if !name.ends_with(".png") || name.len() <= ".png".len() { + return Err(HostError::Error("imageCapture writes a PNG file: give it a name that ends with .png".into())); + } + let clip = clip_bounds(h, doc, arg(a, 2))?; + let (ppi, background, anti_alias) = capture_settings(options(arg(a, 3), "ImageCaptureOptions")?)?; + let region = match clip { + Some(r) => r, + None => with_doc(h, doc, |_, st| crate::cmd::fileio::export_art_bounds(&st.doc, "png")) + .ok_or_else(|| HostError::Error("the document has no visible art to capture".into()))?, + }; + check_size(region, ppi)?; + let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; + let sources = sources_on_disk(h); + let shown = path.to_string(); + // Checked here, and again as the export commits its file, so a destination changed into a link + // to a protected file while the art renders is refused too. + let guard = move |p: &std::path::Path| capture_target_check(p, &sources, &shown); + guard(&real).map_err(HostError::Error)?; + let plain = crate::cmd::findfiles::plain(real); + let Some(plain) = plain.to_str() else { + return Err(HostError::Error(format!("imageCapture cannot write to a path that is not valid UTF-8: {path}"))); + }; + let p = json!({ + "path": plain, + "format": "png", + "rect": [region.x0, region.y0, region.width(), region.height()], + "ppi": ppi, + "background": background, + "antiAlias": anti_alias, + "includeArtboardFill": false, + }); + #[cfg(test)] + BEFORE_CAPTURE_EXPORT.with(|f| f.borrow_mut().take().map(|f| f())); + h.disk.borrow_mut().exact = true; + let r = crate::file_access::with_write_guard(std::rc::Rc::new(guard), || on_doc(h, doc.uid, false, |h| command(h, "document.export", &p))); + h.disk.borrow_mut().exact = false; + super::save_open::command_warnings(h, "imageCapture", &r?); + Ok(Data::Undefined) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec { + let mut members = named(vec![ + ( + "rasterize", + method(l, doc_rasterize), + returns("RasterItem", &[("sourceArt", "*"), ("clipBounds", "Array"), ("options", "RasterizeOptions")]), + ), + ( + "imageCapture", + method(l, doc_image_capture), + returns("undefined", &[("imageFile", "File"), ("clipBounds", "Array"), ("options", "ImageCaptureOptions")]), + ), + ]); + members.push(later(l, "Document", "windowCapture")); + members +} + +/// The fields a new options object starts with. +type Starts = fn() -> Vec<(&'static str, Data)>; + +fn rasterize_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasingMethod", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("backgroundBlack", Data::Bool(false)), + ("clippingMask", Data::Bool(false)), + ("colorModel", text("RasterizationColorModel.DEFAULTCOLORMODEL")), + ("convertSpotColors", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("includeLayers", Data::Bool(false)), + ("padding", num(0.0)), + ("resolution", num(300.0)), + ("transparency", Data::Bool(false)), + ] +} + +fn capture_starts() -> Vec<(&'static str, Data)> { + let white = Data::Object(vec![ + ("typename".to_string(), text("RGBColor")), + ("red".to_string(), num(255.0)), + ("green".to_string(), num(255.0)), + ("blue".to_string(), num(255.0)), + ]); + vec![ + ("antiAliasing", Data::Bool(false)), + ("matte", Data::Bool(false)), + ("matteColor", white), + ("resolution", num(150.0)), + ("transparency", Data::Bool(false)), + ] +} + +/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its +/// help page gives. +pub(super) fn classes(link: &Link) -> Vec { + let all: [(&'static str, Starts); 2] = [("RasterizeOptions", rasterize_starts), ("ImageCaptureOptions", capture_starts)]; + all.into_iter() + .map(|(name, starts)| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + let mut items = vec![("typename".to_string(), text(name))]; + items.extend(starts().into_iter().map(|(k, v)| (k.to_string(), v))); + Ok(Data::Object(items)) + }); + HostClass { construct: Some(f), ..class(name, None, Vec::new(), None) } + }) + .collect() +} + +#[cfg(test)] +mod source_tests { + use super::*; + + #[test] + fn capture_sources_keep_files_outside_automation_read_roots() { + let dir = vectorcraft_testkit::TempDir::new("capture-source-roots"); + let readable = dir.join("readable"); + let writable = dir.join("writable"); + std::fs::create_dir(&readable).unwrap(); + std::fs::create_dir(&writable).unwrap(); + let inside = readable.join("doc.vectorcraft"); + // An open document that only a write root covers: a capture to its path must still be + // refused. + let outside = writable.join("other.vectorcraft"); + // Outside every root: no capture can write it, so it is not looked up. + let elsewhere = dir.join("linked.png"); + std::fs::write(&inside, b"document").unwrap(); + std::fs::write(&outside, b"document").unwrap(); + std::fs::write(&elsewhere, b"linked").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&readable], &[&writable]).unwrap(); + crate::file_access::confine(roots.as_ref(), || { + assert!(source_place(&inside.to_string_lossy()).is_some()); + assert!(source_place(&elsewhere.to_string_lossy()).is_none()); + let source = source_place(&outside.to_string_lossy()).expect("a source outside the read roots is still compared"); + let target = placed(&outside).unwrap(); + assert!(same_file(&target, &source)); + }); + } + + /// In an empty Linux folder, names that differ only in their normalization form are one file + /// only when the folder is casefolded. On a folder without the flag they are distinct, and + /// nothing is written into the folder to find out. + #[cfg(target_os = "linux")] + #[test] + fn names_in_another_normalization_form_match_only_in_a_casefolded_empty_folder() { + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-distinct"); + let folder = std::fs::canonicalize(&*dir).unwrap(); + let (linked, capture): (Placed, Placed) = ((folder.clone(), "cafe\u{301}.png".into()), (folder.clone(), "caf\u{e9}.png".into())); + assert_eq!(same_file(&capture, &linked), casefolded(&folder)); + assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 0); + } + + /// A casefolded folder, which looks a name up in either normalization form, is recognized by + /// its inode flag. A folder whose flags can't be read is taken for one, so a capture is never + /// written over a source under a name in another normalization form. + #[cfg(target_os = "linux")] + #[test] + fn a_casefolded_folder_is_recognized_by_its_inode_flag() { + assert!(has_casefold(FS_CASEFOLD_FL)); + assert!(has_casefold(FS_CASEFOLD_FL | 0x10)); + assert!(!has_casefold(0x10)); + assert!(!has_casefold(0)); + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-missing"); + assert!(casefolded(&dir.join("missing"))); + } +} diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b2f33027c5..34f7755d1a 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -19,8 +19,9 @@ //! commands may use. //! //! VectorCraft's own rules, which the help pages do not state: -//! - `saveAs` without options saves in the format the path's extension names; it writes the file -//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and +//! - `saveAs` without options selects the format from the script's file name before resolving +//! symbolic links. A name without a recognized extension uses the document's current format. +//! Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and //! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds. //! `exportFile` adds the format's extension unless the name already ends //! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes @@ -31,8 +32,8 @@ //! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not //! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page //! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to -//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one -//! `unit`, more than 0 and at most 1000. +//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is +//! one drawing unit. It is at least 0.0001 and at most 1000. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is @@ -738,10 +739,12 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result: Data::Number(n) if n.is_finite() => *n, _ => return Err(HostError::Type(format!("{what} must be a finite number"))), }; - if !(n > 0.0 && n <= 1000.0) { - return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000"))); + // A percentage: the DXF writer's `scale` is `n / 100`, and its smallest scale (1e-6) is + // 0.0001%. + if !(0.0001..=1000.0).contains(&n) { + return Err(HostError::Range(format!("{what} must be at least 0.0001 and at most 1000"))); } - p.insert("scale".into(), json!(n)); + p.insert("scale".into(), json!((n / 100.0).max(*vectorcraft_cad::SCALE_RANGE.start()))); } "version" => { let version = match pick("AutoCADCompatibility")? { @@ -878,6 +881,24 @@ pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Result) -> r } +/// Writes each warning in a command's answer `result` to the console after `method`'s name. +pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) { + if let Data::Object(items) = result { + for (key, value) in items { + let warnings: &[Data] = match (key.as_str(), value) { + ("warning", Data::String(_)) => std::slice::from_ref(value), + ("warnings", Data::Array(warnings)) => warnings, + _ => continue, + }; + for warning in warnings { + if let Data::String(warning) = warning { + super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + } + } + } +} + /// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s /// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or /// a linked image an open could not read. → the command's answer. @@ -1006,7 +1027,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`. + // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100. if !matches!(kind.format, "svg" | "dxf") { p.insert("scale".into(), json!(hs / 100.0)); } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 3c4acac317..b14b065c84 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1,12 +1,16 @@ -//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its //! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , //! , -//! and +//! , +//! and //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: +//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`, +//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden +//! or locked layer or group throws. //! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so //! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves //! out to the whole character. One item of `characters` is one code point. @@ -33,6 +37,8 @@ //! value; set on an empty range it changes nothing. A paragraph attribute reads the first //! paragraph the range touches and sets every one of them. A text range has the members of //! both its `characterAttributes` and its `paragraphAttributes`. +//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes +//! the paint away. `strokeWeight` is 0 to 1000 points. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; @@ -40,13 +46,14 @@ use std::rc::Rc; use std::sync::{Arc, Weak}; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref}; use super::{ - Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, - editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, - returns, text, typed, typename_of, whole, with_doc, + Answer, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, + doc_ref, edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, + page_items, point, property, returns, text, typed, typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -59,6 +66,10 @@ pub const STALE_RANGE: &str = "Stale text range"; /// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit /// is stale. const MAX_EDITS: usize = 100_000; +/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of +/// the other frames are given up; their text, generations and edits stay, and each frame's tables +/// are made again when it is next read. +const INDEX_BUDGET: usize = 64 << 20; /// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. pub(super) struct Index { @@ -102,6 +113,22 @@ impl Index { Self { text, chars, bytes, words, paras } } + /// The text alone, without its offset tables, for a frame whose tables were given up under + /// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read. + fn bare(text: String) -> Self { + Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() } + } + + fn is_bare(&self) -> bool { + self.chars.is_empty() + } + + /// The bytes the offset tables hold. + fn table_bytes(&self) -> usize { + let pairs = self.words.capacity() + self.paras.capacity(); + (self.chars.capacity() + self.bytes.capacity()) * size_of::() + pairs * size_of::<(usize, usize)>() + } + fn len(&self) -> usize { self.chars.last().copied().unwrap_or(0) } @@ -202,10 +229,32 @@ pub(in crate::script) struct TextState { made: Cell, /// The span of each range object, by its number, whose `length` the script set. resized: RefCell>, + /// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]). + table_bytes: Cell, /// The styles the run's style objects name. styles: styles::StyleState, } +/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within +/// [`INDEX_BUDGET`], giving up the tables of other frames first. +fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) { + let mut total = state.table_bytes.get() + index.table_bytes(); + if let Some(l) = frames.get_mut(&key) { + total -= l.index.table_bytes(); + l.index = Rc::new(index); + } + for (k, l) in frames.iter_mut() { + if total <= INDEX_BUDGET { + break; + } + if *k != key && !l.index.is_bare() { + total -= l.index.table_bytes(); + l.index = Rc::new(Index::bare(l.index.text.clone())); + } + } + state.table_bytes.set(total); +} + fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { match &st.doc.node(id)?.kind { NodeKind::Text(t) => Some(t), @@ -231,29 +280,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc {} + let fresh = match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None, Some(l) => { - if l.reverts != st.reverts || !same_text(t, &l.index.text) { + let changed = l.reverts != st.reverts || !same_text(t, &l.index.text); + if changed { l.stamp += 1; l.floor = l.stamp; l.edits.clear(); - l.index = Rc::new(Index::new(t.plain_text())); } l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + changed.then(|| t.plain_text()) } None => { let l = Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, - index: Rc::new(Index::new(t.plain_text())), + index: Rc::new(Index::bare(String::new())), stamp: 0, floor: 0, edits: VecDeque::new(), }; frames.insert(key, l); + Some(t.plain_text()) } + }; + // Tables given up under the budget are made again from the text the log keeps. + let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone())); + if let Some(text) = fresh { + set_index(&h.dom.text, &mut frames, key, Index::new(text)); } let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; Ok((l.index.clone(), l.stamp)) @@ -303,6 +359,27 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u }) } +/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing +/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a +/// locked artboard. +fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + refuse_protected(h, item, "TextFrame")?; + edit_item(h, item, id, params) +} + +/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is +/// hidden or locked, or it is on a locked artboard. +fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> { + let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id))); + if !ok { + return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0))); + } + Ok(()) +} + /// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. /// When the text is not what that edit gives, every earlier range goes stale. fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { @@ -323,9 +400,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser l.floor = l.stamp; l.edits.clear(); } - l.index = Rc::new(Index::new(now)); l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now)); Ok(()) }) } @@ -453,7 +530,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { return Ok(Data::Undefined); } let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; record(h, r.item, &index, s, e - s, &insert)?; Ok(Data::Undefined) } @@ -547,6 +624,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { /// `null` when the type has nothing to outline and the command removed it. fn frame_outline(h: &Host, a: &[Data]) -> Answer { let item = this_frame(h, a)?; + refuse_protected(h, item, "TextFrame")?; let (_, r) = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; super::command_value(h, "type.createOutlines", &json!({})) @@ -568,6 +646,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), Some(true) => {} } + refuse_protected(h, item, "TextFrame")?; let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; new_ref(h, item.doc, result_id(&r).or(Some(item.id))) @@ -730,35 +809,44 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let (r, part) = this_part(h, a)?; let contents = contents_of(arg(a, 1))?; let (index, s, e, _) = resolve(h, r)?; - let at = if before || matches!(arg(a, 2), Data::Undefined) { + // The place, and whether it is the end of a range, which rounds up to a character boundary. + let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) { let (items, spans) = part_spans(&index, part, s, e); let span = |k: usize| match spans { None => index.char_span(k), Some(list) => list.get(k).copied(), }; if before { - items.clone().next().and_then(span).map_or(s, |(x, _)| x) + (items.clone().next().and_then(span).map_or(s, |(x, _)| x), false) } else { - items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + (items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true) } } else { let rel = arg(a, 2); let target = if handle_of(rel, "TextFrame").is_some() { whole_span(h, item_of(h, rel)?)?.1 + } else if handle_of(rel, "TextRange").is_some() { + span_of(h, rel, &["TextRange"])? } else { - span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + // A range of a removed frame keeps its own error. + span_of(h, rel, &["TextRange"]).map_err(|e| match e { + HostError::Error(m) if m == STALE_RANGE => HostError::Error(m), + _ => HostError::Type("relativeObject must be a TextRange or a TextFrame".into()), + })? }; if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); } let (_, ts, te, _) = resolve(h, target)?; - if text_placement(arg(a, 3))? { te } else { ts } + if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) } }; + // A place inside a character (between the two halves of a surrogate pair) moves to its edge. + let b = index.byte(at, after); + let at = index.text[..b].encode_utf16().count(); if contents.is_empty() { let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); } - let b = index.byte(at, false); let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); let (lead, trail) = match part { Part::Characters => ("", ""), @@ -774,7 +862,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { ), }; let insert = format!("{lead}{contents}{trail}"); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; record(h, r.item, &index, at, 0, &insert)?; let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; let start = at + lead.encode_utf16().count(); @@ -804,9 +892,12 @@ enum Attr { Underline, StrikeThrough, TextFont, + FillColor, + StrokeColor, + StrokeWeight, } -const ATTRS: [(&str, Attr); 11] = [ +const ATTRS: [(&str, Attr); 14] = [ ("size", Attr::Size), ("leading", Attr::Leading), ("autoLeading", Attr::AutoLeading), @@ -818,6 +909,9 @@ const ATTRS: [(&str, Attr); 11] = [ ("underline", Attr::Underline), ("strikeThrough", Attr::StrikeThrough), ("textFont", Attr::TextFont), + ("fillColor", Attr::FillColor), + ("strokeColor", Attr::StrokeColor), + ("strokeWeight", Attr::StrokeWeight), ]; /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with @@ -920,9 +1014,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) Attr::Underline => Data::Bool(s.underline), Attr::StrikeThrough => Data::Bool(s.strikethrough), Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + Attr::FillColor => colors::of_paint(&s.fill), + Attr::StrokeColor => colors::of_paint(&s.stroke), + Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)), } } +/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a +/// `strokeWidth` it is given. +fn stroke_scale(t: &TextObject) -> f64 { + vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0) +} + /// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { let finite = || number(v, name); @@ -991,6 +1094,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, & let (family, style) = font_of(h, v)?; (json!({"font": family, "style": style}), font_ref(h, &family, &style)) } + Attr::FillColor | Attr::StrokeColor => { + let color = colors::assigned(v, name)?; + let paint = color.map_or(Paint::None, Paint::solid); + let given = color.map_or_else(|| json!("none"), |c| colors::param(&c)); + let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" }; + (json!({ key: given }), colors::of_paint(&paint)) + } + Attr::StrokeWeight => { + let n = finite()?; + if !(0.0..=1000.0).contains(&n) { + return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into())); + } + (json!({"strokeWidth": n}), num(n)) + } }) } @@ -1024,7 +1141,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; // A leading set on characters with auto leading fixes it even where auto gives that value. let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); - let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); + // An empty range changes nothing, also one inside a character that `ba..bb` widens to it. + let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p)); let fixed = match (attr, &wants) { (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), _ => None, @@ -1042,7 +1160,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { super::atomically(h, |h| { for (start, end, leading) in &spans { let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); - edit_item(h, r.item, "text.setRangeStyle", &p)?; + edit_text(h, r.item, "text.setRangeStyle", &p)?; } Ok(()) })?; @@ -1054,7 +1172,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?; if let Attr::TextFont = attr { let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; @@ -1216,7 +1334,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - edit_item(h, r.item, id, &p)?; + edit_text(h, r.item, id, &p)?; Ok(Data::Undefined) } @@ -1250,32 +1368,46 @@ fn frame_ids(h: &Host, st: &DocState) -> std::result::Result>, Ho Ok(ids) } +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + super::layers::text_scope(h, arg(a, 0)) +} + fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "TextFrames") + Ok(frames_scope(h, a)?.0) +} + +/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those +/// directly in a layer or group, topmost first. +fn listed(h: &Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { + match container { + None => frame_ids(h, st), + Some(c) => super::layers::text_list(h, st, c), + } } fn frames_length(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64))) + let (doc, c) = frames_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64))) } fn frames_parent(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(doc_ref(h, doc.uid)) + let (doc, c) = frames_scope(h, a)?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } fn frames_at(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; - with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn frames_by_name(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st)?; + let ids = listed(h, st, c)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -1303,29 +1435,40 @@ fn vertical_of(d: &Data) -> std::result::Result { } } -/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. -fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on +/// top of the contents of `container` when there is one. +fn point_text(h: &Host, (doc, container): (Doc, Option), anchor: Option<[f64; 2]>, vertical: bool) -> Answer { let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; - let (_, r) = - on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical}); + if let Some(c) = container { + check_open(h, doc, c)?; + if let Some(o) = params.as_object_mut() { + o.insert("parent".into(), json!(c.0)); + } + } + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", ¶ms))?; new_ref(h, doc, result_id(&r)) } +/// The error for a layer or group that takes no new type. +const SHUT_CONTAINER: &str = "the layer or group is hidden or locked"; + /// `add()`: empty point type at the origin. fn frames_add(h: &Host, a: &[Data]) -> Answer { - point_text(h, frames_doc(h, a)?, None, false) + point_text(h, frames_scope(h, a)?, None, false) } /// `pointText(anchor, orientation?)`. fn frames_point_text(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let scope = frames_scope(h, a)?; let anchor = point(arg(a, 1), "anchor")?; - point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) + point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?) } -/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves +/// it on top of the contents of the collection's layer or group when there is one. fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, container) = frames_scope(h, a)?; if handle_of(arg(a, 1), "PathItem").is_none() { return Err(HostError::Type("textPath must be a PathItem".into())); } @@ -1336,6 +1479,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { return Err(HostError::Error("TextFrames: path positions are not available yet".into())); } + refuse_protected(h, path, "PathItem")?; let (orientation, base) = if on_path { (4, 5) } else { (2, 3) }; let vertical = vertical_of(arg(a, orientation))?; let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?; @@ -1344,12 +1488,35 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { } let mode = if on_path { "onPath" } else { "area" }; let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); - let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; - let id = result_id(&r); - if let (Some((base, postfix)), Some(id)) = (base, id) { - threads::thread_new(h, base, id, postfix)?; + // Makes the type, threaded after or before the base frame when there is one. + let make = |h: &Host| -> std::result::Result, HostError> { + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + let id = result_id(&r); + if let (Some((base, postfix)), Some(id)) = (base, id) { + threads::thread_new(h, base, id, postfix)?; + } + Ok(id) + }; + let Some(c) = container else { + return new_ref(h, doc, make(h)?); + }; + check_open(h, doc, c)?; + // The path is moved as well as converted, so it must be one that `move` takes. + if !with_doc(h, doc, |_, st| editable(&st.doc, path.id)) { + return Err(HostError::Error(format!("Cannot move PathItem {}: it is hidden or locked", path.id.0))); } - new_ref(h, doc, id) + super::refuse_protected_edit(h, path)?; + let id = super::atomically(h, |h| { + let id = make(h)?.ok_or_else(|| HostError::Error("the command made no object".into()))?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?; + new_ref(h, doc, Some(id)) +} + +/// Refuses a hidden or locked layer or group as the place for new type. +fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> { + if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) } } /// `areaText(textPath, orientation?, baseFrame?, postFix?)`. @@ -1362,17 +1529,22 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a -/// locked artboard, stops it first, as `PageItems.removeAll()` does. +/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or +/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st)?; + let (doc, c) = frames_scope(h, a)?; + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { + let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + // Type that clips a group or layer releases its mask, so the object above it is not made + // the clipping path. + let released = super::masks_cleared_by(&st.doc, &ids); + // So would deleting the type above an image in an ordinary group named as a tracing. + let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, released, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1380,10 +1552,15 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { } if !on_locked.is_empty() { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); - return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + // A clip group named as a tracing, released with an image left first, would become one. + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>()}); + super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms)))?; } Ok(Data::Undefined) } @@ -1557,6 +1734,7 @@ fn attr_type(attr: Attr) -> &'static str { match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", + Attr::FillColor | Attr::StrokeColor => "Color", _ => "number", } } @@ -1738,8 +1916,8 @@ pub(super) fn classes(l: &Link) -> Vec { named(vec![ ("typename", get(l, frames_typename), typed("string")), ("length", get(l, frames_length), typed("number")), - ("parent", get(l, frames_parent), typed("Document")), - ("index", method(l, frames_index), returns("number", &[("itemKey", "*")])), + ("parent", get(l, frames_parent), typed("*")), + ("index", method(l, frames_index), returns("TextFrame", &[("itemKey", "*")])), ("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])), ("add", method(l, frames_add), returns("TextFrame", &[])), ("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])), diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 8317e1ae04..45d1a428f3 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result { span_of(h, d, &TEXT) } -/// `applyTo(textItem, clearingOverrides?)`. +/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the +/// text frame is protected as for any other text edit. fn style_apply_to(h: &Host, a: &[Data]) -> Answer { let style = this_style(h, a)?; let target = target_span(h, arg(a, 1))?; @@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the text is in another document than the style".into())); } let (index, s, e, _) = resolve(h, target)?; + super::refuse_protected(h, target.item, "TextFrame")?; h.charge_call(16 + (e - s) as u64)?; let (start, end) = if style.para { let (_, ba, bb) = para_range(&index, s, e); @@ -429,6 +431,8 @@ fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")), None => Data::Undefined, }, + // A style's colors and stroke weight are not available yet (`char_members`). + Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight => Data::Undefined, } } @@ -538,6 +542,9 @@ fn char_members(link: &Link) -> Vec { ATTRS .iter() .map(|&(name, attr)| { + if matches!(attr, Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight) { + return super::super::later(link, "CharacterAttributes", name); + } let data_type = match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index a37a062849..22a1e36f1d 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -128,6 +128,10 @@ pub(super) struct State { prev: RefCell>, sources: RefCell>, descendants: RefCell>>, + /// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`]) + /// and the lowest id the run could allocate after the first note or the latest revert + /// ([`note_document`]). + marks: RefCell>, retraces: Cell, } @@ -208,6 +212,37 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { }); } +/// Before each command a script runs: notes the active document ([`note_document`]). +pub(super) fn before_command(h: &Host) { + let s = h.session.borrow(); + if let Some(st) = s.active() { + note_document(h, st); + } +} + +/// Records the next object id when the run first notes the document `st`. A revert resets +/// the mark to the reloaded document's next object id and keeps the descendant snapshots. +/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it. +fn note_document(h: &Host, st: &crate::DocState) { + let mut marks = h.dom.tracing.marks.borrow_mut(); + match marks.get_mut(&st.uid) { + Some((reverts, _)) if *reverts == st.reverts => {} + Some((reverts, mark)) => { + *reverts = st.reverts; + *mark = st.doc.peek_next_id(); + } + None => { + marks.insert(st.uid, (st.reverts, st.doc.peek_next_id())); + } + } +} + +/// Returns the lowest id the run could allocate in document `uid` after its first note or latest +/// revert ([`note_document`]). +fn mark(h: &Host, uid: u64) -> Option { + h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark) +} + pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied(); source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) @@ -325,15 +360,22 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< /// and "Cannot edit page item" when it holds a locked object other than its source image, which /// the replacement would discard. The objects looked at are charged to the run either way. fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { - let (visited, result) = read_group(h, item, |_, group| { + let (visited, result) = read_group(h, item, |st, group| { + note_document(h, st); remember_source(h, item.doc.uid, group); - // The objects the trace made, as the tracing records them; a tracing saved without that - // record is checked against the objects it held when this run first saw it. + // A tracing with a record is checked against the objects its trace made. A tracing without + // a record is checked against its first descendant snapshot, which survives reverts. + // If the group id is below the document's mark, members at or above the mark are also added. + // A revert resets the mark to the reloaded document's next object id. let made = group.trace_made(); let descendants = h.dom.tracing.descendants.borrow(); let ids = match made { Some(_) => None, - None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?), + None => descendants.get(&(item.doc.uid, item.id.0)), + }; + let newer = match made { + Some(_) => None, + None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m), }; let source = group.children().and_then(|c| c.first()).map(|n| n.id); let mut visited = 0u64; @@ -345,7 +387,7 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { (Some(m), _) => !m.contains(n.id), (None, Some(ids)) => !ids.contains(&n.id), (None, None) => false, - }; + } || newer.is_some_and(|m| n.id.0 >= m); // Added artwork is reported before a locked object, whichever comes first. if added { return Ok((visited, Err(HostError::Error(refusal.into())))); diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 6c07a070e1..3bf88a577c 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -20,11 +20,16 @@ //! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own //! scale in percent, the square root of the area it scales by (stroke weights and effects scale //! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to -//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any -//! other value, and a scale of strokes and effects with positions left as they are, throws an -//! error that says so. +//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points. +//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight +//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale +//! of strokes and effects with positions left as they are, throws an error that says so. +//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN` +//! still uses the first artboard's bottom-left corner; other named points use the origin. +//! Its linked opacity mask, strokes, effects and patterns transform with the same options. //! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a -//! locked object, and an object on a locked artboard are refused with nothing changed, and so are +//! locked object, an object on a locked artboard and a guide while guides are locked are refused +//! with nothing changed, and so are //! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object //! past the canvas. @@ -36,13 +41,16 @@ use super::matrix::{self, Matrix}; use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc}; /// The error for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; /// The error for a locked object. -const LOCKED: &str = "cannot transform locked objects"; +pub(super) const LOCKED: &str = "cannot transform locked objects"; + +/// The error for a guide while guides are locked. +const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked"; /// The error for a hidden object. -const HIDDEN: &str = "cannot transform hidden objects"; +pub(super) const HIDDEN: &str = "cannot transform hidden objects"; /// The identity matrix. const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; @@ -132,8 +140,17 @@ fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> { } /// The point of `r` (document coordinates, Y down) that the `Transformation` member `name` -/// ([`anchor_name`]) names. -fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result { +/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`. +fn anchor(h: &Host, item: Item, r: Option, name: &str) -> std::result::Result { + if r.is_none() && !paths::is_path(h, item) { + return Err(HostError::Error("the object has no bounds".into())); + } + if name == "DOCUMENTORIGIN" { + return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0]))); + } + let Some(r) = r else { + return Ok(Point::ORIGIN); + }; let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); Ok(match name { "TOPLEFT" => Point::new(r.x0, r.y0), @@ -144,7 +161,6 @@ fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result Point::new(r.x0, r.y1), "BOTTOM" => Point::new(cx, r.y1), "BOTTOMRIGHT" => Point::new(r.x1, r.y1), - "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?, _ => Point::new(cx, cy), }) } @@ -215,12 +231,13 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } - // The identity acts the same about every point, so an object without bounds (an empty path) - // takes it too. + if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) { + return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0))); + } + // The identity acts the same about every point for any object. let o = match (about, bounds) { _ if m == IDENTITY => Point::ORIGIN, - (Some(name), Some(r)) => anchor(h, item, r, name)?, - (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), + (Some(name), r) => anchor(h, item, r, name)?, (None, _) => Point::ORIGIN, }; let xf = on_page(m, o); @@ -242,6 +259,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, } let c = xf.as_coeffs(); let identity = xf == Affine::IDENTITY; + // Every stroke layer's weight is checked with the factor `object.transform` applies. + let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None }; + if let Some(k) = factor + && paths::is_path(h, item) + && (!k.is_finite() || { + let width = paths::largest_stroke_weight(h, item)? * k; + !width.is_finite() || width > paths::MAX_STROKE_WIDTH + }) + { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; // The transformation and the stroke weight change together or not at all. atomically(h, |h| { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0890a75fcd..cd966a5605 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -858,6 +858,9 @@ struct Host { args: RefCell<(Data, u64)>, /// The run's state of the script object model (`app`). dom: dom::State, + /// While a slice runs: the documents the interface has open ([`World::docs`] of the run's + /// job), which a capture must not write over either. Empty between slices. + interface_docs: RefCell>, /// The actions `app.doScript` can play. actions: Vec, /// The index of each open document's active artboard as the run starts, by document uid. The @@ -1374,7 +1377,10 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value // the open documents; it also reads the files the documents open when the run began link to, as the // person left them. A document a script's command opened gives it no file. let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); - let gate = host.disk.borrow().gate(documents, host.linked()); + // The linked files are fixed at the run's first step, also when that step is an exact open that gets none. + let linked = host.linked(); + let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { linked }; + let gate = host.disk.borrow().gate(documents, linked); let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // What the command opened, changed or gave another file is not as the person left it. @@ -2432,6 +2438,7 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::new(self.documents(), heap_bytes), + interface_docs: RefCell::new(Vec::new()), actions: request.actions, active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), artboard_picks, @@ -2988,6 +2995,8 @@ fn failure_frame(report: &Value) -> (String, String) { fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { let depth = std::mem::replace(&mut s.depth, 0); job.world.swap(s); + // The interface's documents are the host's to read during the slice, and the job's again after. + std::mem::swap(&mut job.world.docs, &mut *job.host.interface_docs.borrow_mut()); // The run's front document draws and converts through its own profiles, and the interface's // again after the slice. s.sync_front_profiles(); @@ -3021,6 +3030,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result Vec<(u64, String, String)> { + std::mem::take(&mut self.swatch_renames) + } + /// Run `f` on a mutable copy of the active document. Outside an interaction this records one /// undo step labelled `label`; inside one it just mutates (the interaction commits later). pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result) -> Result { @@ -394,32 +400,34 @@ impl Session { // A change the command made to the new-art paints stays when the next preview or a cancel // puts back the paints the interaction began with (the Live Paint Bucket's colors); the // parts it left alone keep the interaction's. The pattern lists every field, so a field - // added to `PaintDefaults` does not compile until it is handled here. + // added to `PaintDefaults` does not compile until it is handled here. The paints a preview + // took its new-art paints over from take the change as well. let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint; - let start = &mut it.paint; - if *fill != paint.fill { - start.fill.clone_from(fill); - } - if *stroke != paint.stroke { - start.stroke.clone_from(stroke); - } - if *stroke_width != paint.stroke_width { - start.stroke_width = *stroke_width; - } - if *appearance != paint.appearance { - start.appearance.clone_from(appearance); - } - if *opacity != paint.opacity { - start.opacity = *opacity; - } - if *blend != paint.blend { - start.blend = *blend; - } - if *style != paint.style { - start.style.clone_from(style); - } - if *inherited != paint.inherited { - start.inherited = *inherited; + for start in std::iter::once(&mut it.paint).chain(it.inherited_preview_paint.as_mut()) { + if *fill != paint.fill { + start.fill.clone_from(fill); + } + if *stroke != paint.stroke { + start.stroke.clone_from(stroke); + } + if *stroke_width != paint.stroke_width { + start.stroke_width = *stroke_width; + } + if *appearance != paint.appearance { + start.appearance.clone_from(appearance); + } + if *opacity != paint.opacity { + start.opacity = *opacity; + } + if *blend != paint.blend { + start.blend = *blend; + } + if *style != paint.style { + start.style.clone_from(style); + } + if *inherited != paint.inherited { + start.inherited = *inherited; + } } let active = self.active().is_some_and(|d| d.uid == uid); let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return }; @@ -549,8 +557,13 @@ impl Session { revision: st.revision, preview: None, tool: false, + tool_joined: false, paint, used_defaults_only: false, + preserve_paint_on_cancel: false, + inherited_preview_paint: None, + inherited_preview_paint_used: false, + last_preview_paint: None, preview_paint: None, color_mode_paints: None, tool_paints: false, @@ -581,7 +594,8 @@ impl Session { // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); - let (paint, restore_paint) = { + let new_art_basic = self.prefs.new_art_basic; + let (paint, restore_paint, inherited, last_preview_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -596,13 +610,19 @@ impl Session { // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); + it.preserve_paint_on_cancel |= cmd == "addon.document.floodFillArtboards"; it.tool_paints |= tool_paints; let restore_paint = it.tool_paints || cmd == "command.batch" || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) - || it.color_mode_paints.is_some(); + || it.color_mode_paints.is_some() + || (!new_art_basic && it.selection.is_empty() && it.preview.is_some() && cmd.starts_with("paint.")); let paint = it.paint.clone(); + let last_preview_paint = it.last_preview_paint.take().filter(|_| it.preview.is_some()); + // A preview that took the new-art paints from the art it drew puts back the paints it + // started from, which an earlier paint preview may have set. + let inherited = it.inherited_preview_paint.take(); it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -619,11 +639,25 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint) + (paint, restore_paint, inherited, last_preview_paint) + }; + // The paints before the previews that build on each other: a preview that starts from the + // interaction's paints (or from the inherited ones) starts a new run of them. A field that + // no longer holds what the last preview left was changed outside the previews. + let base = if restore_paint || inherited.is_some() { + None + } else { + last_preview_paint.map(|(mut base, left)| { + take_changed_paints(&mut base, &left, &self.paint); + base + }) }; if restore_paint { self.paint = paint.clone(); + } else if let Some(before) = &inherited { + self.paint.clone_from(before); } + let base = base.unwrap_or_else(|| self.paint.clone()); self.pending_paint = None; // The previous preview's Assign Profile is undone with it. self.sync_front_profiles(); @@ -642,6 +676,13 @@ impl Session { } let params = self.noted(params); let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); + // A failed preview leaves the document at the snapshot, so the new-art paints that earlier + // previews changed (a `paint.*` preview with nothing selected) go back to the paints from + // before them as well. A change made outside the previews stays. + if r.is_err() { + self.paint.clone_from(&base); + } + let after_paint = r.is_ok().then(|| (base, self.paint.clone())); let after_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { @@ -651,6 +692,14 @@ impl Session { // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); + it.last_preview_paint = after_paint; + // After a failed preview a cancel still puts back the paints the interaction began with. + if r.is_err() && !restore_paint && it.inherited_preview_paint.is_none() { + it.inherited_preview_paint.clone_from(&inherited); + } + if r.is_ok() && !restore_paint && inherited.is_some() { + it.inherited_preview_paint_used = true; + } if it.color_mode_paints.is_some() { it.preview_paint = batch_paint.clone(); } @@ -684,6 +733,15 @@ impl Session { if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { self.paint = paint; } + // A failed last preview leaves nothing to commit, so the paints an earlier preview set go too. + if let Some(paint) = self + .active() + .and_then(|st| st.interaction.as_ref()) + .filter(|it| it.preview.is_none() && (it.inherited_preview_paint.is_some() || it.inherited_preview_paint_used)) + .map(|it| it.paint.clone()) + { + self.paint = paint; + } self.remember_pending_paint(); cmd::colormgmt::commit_new_art_colors(self)?; let paint = self.paint.clone(); @@ -790,6 +848,10 @@ impl Session { // it does a color previewed with `defaultsOnly: true`. let tool_paints = self.tool_paints(false) || self.tool_paints(true); let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); + let preserve_paint = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.preserve_paint_on_cancel); + // With New Art Has Basic Appearance off, a preview that selected new art from an empty + // selection gave that art's appearance to the new-art paints; after the undo nothing is + // selected to take them from, so the cancel puts back the paints the interaction began with. if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) @@ -797,8 +859,12 @@ impl Session { tool_paints || it.tool_paints || it.used_defaults_only + || it.preserve_paint_on_cancel || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() + || it.inherited_preview_paint.is_some() + || it.inherited_preview_paint_used + || (!self.prefs.new_art_basic && it.preview.is_some() && it.selection.is_empty()) }) .map(|it| it.paint.clone()) { @@ -814,7 +880,7 @@ impl Session { // With New Art Has Basic Appearance off, new art takes the appearance of the selection as // the document has it again, not as a preview left it. An interaction that changed only the // defaults (`defaultsOnly: true`) leaves the defaults it began with. - if !used_defaults_only { + if !used_defaults_only && !preserve_paint { self.inherit_new_art(); } if open { @@ -828,6 +894,40 @@ impl Session { } } +/// Copy into `target` each field of `now` that differs from `left`. The pattern lists every field, +/// so a field added to `PaintDefaults` does not compile until it is handled here. +fn take_changed_paints( + target: &mut vectorcraft_tools::PaintDefaults, + left: &vectorcraft_tools::PaintDefaults, + now: &vectorcraft_tools::PaintDefaults, +) { + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = now; + if left.fill != *fill { + target.fill.clone_from(fill); + } + if left.stroke != *stroke { + target.stroke.clone_from(stroke); + } + if left.stroke_width != *stroke_width { + target.stroke_width = *stroke_width; + } + if left.appearance != *appearance { + target.appearance.clone_from(appearance); + } + if left.opacity != *opacity { + target.opacity = *opacity; + } + if left.blend != *blend { + target.blend = *blend; + } + if left.style != *style { + target.style.clone_from(style); + } + if left.inherited != *inherited { + target.inherited = *inherited; + } +} + /// The selection a drag began with, without the objects that a command run during it removed, /// hid or locked in `doc`. fn drag_selection(began: &Selection, doc: &Document) -> Selection { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6aa26f2edc..e880f436f6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -196,6 +196,7 @@ mod script_include; mod script_io; mod script_modules; mod script_print; +mod script_raster_capture; mod script_run; mod script_save_open; mod script_scriptui; @@ -5188,6 +5189,39 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() { assert!(!s.doc().unwrap().selection.contains(b)); } +/// The selection commands and Curvature edits refuse a mode or op they do not know, and leave the +/// selection, the document and the undo history as they were. +#[test] +fn an_unknown_selection_mode_or_curvature_op_is_refused_without_changes() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 30.0, 20.0); + let b = rect(&mut s, 50.0, 10.0, 30.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let objects = s.doc().unwrap().selection.objects.clone(); + let anchors = s.doc().unwrap().selection.anchors.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let mut wrong = vec![]; + for (cmd, p, says) in [ + ("select.segments", json!({"id": a.0, "segments": [[0, 0]], "mode": "bogus"}), "unknown mode"), + ("select.anchorsMany", json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "bogus"}), "unknown mode"), + ("select.magicWand", json!({"id": a.0, "mode": "bogus"}), "unknown mode"), + ("path.curvatureEdit", json!({"id": a.0, "op": "bogus", "anchor": 0, "x": 0, "y": 0}), "unknown op"), + ] { + match s.execute(cmd, &p) { + Err(e) if e.to_string().contains(says) => {} + other => wrong.push(format!("{cmd}: {other:?}")), + } + let st = s.doc().unwrap(); + let changed = st.selection.objects != objects || st.selection.anchors != anchors || st.doc != doc || st.history.undo.len() != undo; + if changed { + wrong.push(format!("{cmd} changed the selection, the document or the undo history")); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + /// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With /// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that /// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 38bb94a6f3..c640c08e26 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -225,6 +225,7 @@ fn a_linked_handle_makes_the_anchor_smooth() { json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}), + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "symmetric": true}), json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}), diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 7f7c7fffa4..88a5c7b4b1 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -456,6 +456,7 @@ fn a_linked_spine_handle_makes_the_point_smooth() { for bad in [ json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}), json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}), + json!({"anchor": 1, "handle": "out", "x": 60, "y": 40, "link": true, "symmetric": true}), json!({"anchor": 1, "x": 75, "y": 25, "link": true}), ] { assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}"); diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 7b72a06089..c9126f5f52 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -1870,6 +1870,51 @@ fn front_and_back_beside_a_compound_paths_member_go_beside_the_compound_path() { assert_eq!(members(&s), [before[0], path[0], before[1]]); } +/// The ids of `n`, its members and its opacity-mask art, in depth. +fn ids_in(n: &Node, out: &mut Vec) { + out.push(n.id); + n.children().into_iter().flatten().for_each(|c| ids_in(c, out)); + if let Some(m) = n.extras().mask.as_deref() { + ids_in(&m.art, out); + } +} + +#[test] +fn a_copied_member_of_a_compound_path_pastes_with_its_transparency_and_opacity_mask() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let b = rect(&mut s, 10.0, 0.0, 40.0, 40.0); + sel(&mut s, &[a, b]); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let art = rect(&mut s, 5.0, 5.0, 20.0, 20.0); + sel(&mut s, &[c, art]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.setOpacityMask", &json!({"ids": [c.0], "invert": true})).unwrap(); + let set = json!({"ids": [c.0], "opacity": 30, "blend": "screen", "isolate": true, "knockout": "on"}); + s.execute("object.setProps", &set).unwrap(); + let member = node(&s, c).children().unwrap()[0].id; + copy(&mut s, &[member]); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.clone(); + assert_eq!(pasted.len(), 1); + let p = node(&s, pasted[0]); + assert!(matches!(p.kind, NodeKind::Path { .. }), "the member pastes as a path"); + assert!((p.opacity - 0.3).abs() < 1e-6, "opacity {}", p.opacity); + assert_eq!(p.blend, vectorcraft_color::BlendMode::Screen); + assert!(p.isolate, "Isolate Blending"); + assert_eq!(p.knockout, vectorcraft_doc::Knockout::On, "Knockout Group"); + let m = p.extras().mask.as_deref().expect("the pasted path has the compound path's opacity mask"); + assert!(m.invert, "Invert Mask comes along"); + assert_ne!(m.art.id, art, "the pasted mask art has an id of its own"); + // Every id in the document, mask art included, is used once. + let mut ids = vec![]; + doc(&s).layers.iter().for_each(|l| ids_in(l, &mut ids)); + let count = ids.len(); + ids.sort_by_key(|i| i.0); + ids.dedup(); + assert_eq!(ids.len(), count, "ids are unique"); +} + #[test] fn paste_in_back_of_a_clipping_path_keeps_it_the_clipping_path() { let mut s = session(); diff --git a/crates/engine/src/tests/compoundpaint.rs b/crates/engine/src/tests/compoundpaint.rs index 4e22e31d3f..ffcc542e8a 100644 --- a/crates/engine/src/tests/compoundpaint.rs +++ b/crates/engine/src/tests/compoundpaint.rs @@ -2,7 +2,8 @@ //! compound holds the paint, so a member's own appearance is never drawn. use serde_json::{Value, json}; -use vectorcraft_color::Paint; +use vectorcraft_color::{BlendMode, Paint}; +use vectorcraft_doc::Knockout; use crate::*; @@ -87,3 +88,126 @@ fn a_group_with_a_compound_still_paints_the_compound_once() { assert_eq!(paint(&s, compound, false), solid("#ff0000")); assert_eq!(paint(&s, loose, false), solid("#ff0000")); } + +/// The opacity, blend mode, Isolate Blending, Knockout Group and Knockout Shape of `id`. +fn transparency(s: &Session, id: NodeId) -> (f32, BlendMode, bool, Knockout, bool) { + let n = s.doc().unwrap().doc.node(id).unwrap(); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) +} + +/// The id and the clip and invert settings of `id`'s opacity mask, `None` when it has none. +fn mask(s: &Session, id: NodeId) -> Option<(NodeId, bool, bool)> { + let n = s.doc().unwrap().doc.node(id).unwrap(); + n.extras().mask.as_deref().map(|m| (m.art.id, m.clip, m.invert)) +} + +/// An opacity mask made from a new rectangle for `id`, with Invert Mask on → the mask art's id. +fn give_mask(s: &mut Session, id: NodeId) -> NodeId { + let art = rect(s, 5.0); + run(s, "select.set", json!({"ids": [id.0, art.0]})); + run(s, "transparency.makeOpacityMask", json!({})); + run(s, "transparency.setOpacityMask", json!({"ids": [id.0], "invert": true})); + art +} + +#[test] +fn release_gives_each_path_the_compound_paths_transparency() { + let (mut s, compound, members, _) = compound(); + let set = json!({"ids": [compound.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "knockoutShape": true}); + run(&mut s, "object.setProps", set); + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "object.compoundPath.release", json!({})); + let released = s.doc().unwrap().selection.objects.clone(); + assert_eq!(released, members); + for id in released { + assert_eq!(transparency(&s, id), (0.5, BlendMode::Multiply, true, Knockout::On, true), "path {id:?}"); + assert_eq!(paint(&s, id, true), solid("#000000")); + } +} + +#[test] +fn release_gives_each_path_the_compound_paths_opacity_mask() { + let (mut s, compound, members, _) = compound(); + let art = give_mask(&mut s, compound); + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "object.compoundPath.release", json!({})); + // The mask art is in document coordinates, so each path masked by it draws as its part of the + // masked compound path did. The first path keeps the art; the others get copies with ids of + // their own, since stored art is in the document once. + let masks: Vec<_> = members.iter().map(|id| mask(&s, *id)).collect(); + assert_eq!(masks[0], Some((art, true, true))); + let (copy, clip, invert) = masks[1].unwrap(); + assert!((clip, invert) == (true, true) && copy != art, "{masks:?}"); + let geometry = |id: NodeId, art: NodeId| { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let m = n.extras().mask.as_deref().unwrap(); + assert_eq!(m.art.id, art); + m.art.geometric_bounds() + }; + assert_eq!(geometry(members[0], art), geometry(members[1], copy)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(mask(&s, compound), Some((art, true, true)), "one undo step gives the compound path its mask back"); +} + +#[test] +fn make_takes_the_backmost_objects_transparency_and_release_gives_it_back() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + run(&mut s, "object.setProps", json!({"ids": [back.0], "opacity": 50, "blend": "screen", "knockout": "off"})); + run(&mut s, "object.setProps", json!({"ids": [front.0], "opacity": 80})); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + assert_eq!(transparency(&s, compound), (0.5, BlendMode::Screen, false, Knockout::Off, false)); + run(&mut s, "object.compoundPath.release", json!({})); + for id in [back, front] { + assert_eq!(transparency(&s, id), (0.5, BlendMode::Screen, false, Knockout::Off, false), "path {id:?}"); + } +} + +#[test] +fn make_takes_the_backmost_objects_opacity_mask() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + let art = give_mask(&mut s, back); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + assert_eq!(mask(&s, compound), Some((art, true, true))); + // The backmost path gives its mask to the compound path rather than keeping a second one. + assert_eq!(mask(&s, back), None); + run(&mut s, "edit.undo", json!({})); + assert_eq!(mask(&s, back), Some((art, true, true)), "one undo step gives the path its mask back"); +} + +#[test] +fn make_from_a_group_takes_the_groups_transparency() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + run(&mut s, "object.setProps", json!({"ids": [back.0], "opacity": 80})); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.setProps", json!({"ids": [group.0], "opacity": 50, "blend": "multiply"})); + let art = give_mask(&mut s, group); + run(&mut s, "select.set", json!({"ids": [group.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + // The group's 50% applied to the backmost path's 80%. + assert_eq!(transparency(&s, compound), (0.4, BlendMode::Multiply, false, Knockout::Neutral, false)); + assert_eq!(mask(&s, compound), Some((art, true, true))); +} + +#[test] +fn release_of_an_unmasked_compound_path_keeps_a_front_paths_own_mask() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 100})); + let (back, front) = (rect(&mut s, 0.0), rect(&mut s, 10.0)); + let art = give_mask(&mut s, front); + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + assert_eq!(mask(&s, compound), None); + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "object.compoundPath.release", json!({})); + assert_eq!(mask(&s, front), Some((art, true, true))); + assert_eq!(mask(&s, back), None); +} diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 39fb6a5bc2..982bf51d24 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -43,6 +43,34 @@ fn a_rounded_rectangle_gives_background_border_and_radius() { assert!(s.execute("css.selection", &json!({"units": "furlong"})).is_err(), "unknown units are refused"); } +#[test] +fn round_dots_are_a_dotted_border_without_a_note() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 120, "height": 60})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + run(&mut s, "stroke.set", json!({"cap": "round", "dash": [0, 4]})); + let r = run(&mut s, "css.selection", json!({})); + assert!(css(&r).contains("border: 1px dotted #000000;"), "{}", css(&r)); + assert!(r["rules"][0].get("unsupported").is_none(), "{r}"); + // Squares, dots fitted to corners, dots mixed with dashes and unevenly spaced dots are not what + // `dotted` draws. + let others = [json!({"cap": "projecting"}), json!({"alignDashes": true}), json!({"dash": [0, 4, 6, 4]}), json!({"dash": [0, 4, 0, 40]})]; + for p in others { + run(&mut s, "stroke.set", json!({"cap": "round", "dash": [0, 4], "alignDashes": false})); + run(&mut s, "stroke.set", p.clone()); + let r = run(&mut s, "css.selection", json!({})); + assert!(r["rules"][0].get("unsupported").is_some(), "{p}: {r}"); + } + // A gradient border image draws the border whole, without its dots or dashes. + run(&mut s, "paint.setStroke", json!({"gradient": {"kind": "linear"}})); + for dash in [json!([0, 4]), json!([4, 2])] { + run(&mut s, "stroke.set", json!({"cap": "round", "dash": dash, "alignDashes": false})); + let r = run(&mut s, "css.selection", json!({})); + assert!(css(&r).contains("border-image: linear-gradient("), "{}", css(&r)); + assert_eq!(r["rules"][0]["unsupported"], json!("dashes or dots on a gradient border"), "{dash}"); + } +} + #[test] fn type_gives_font_properties_and_gradients_css_gradients() { let mut s = session(); @@ -79,6 +107,48 @@ fn gradients_mixed_around_the_hue_wheel_give_css_the_stops_on_their_way() { } } +/// A round-capped dash that starts with a 0 length is a dotted border, any other dash a dashed +/// one, and a gradient stroke a border with a `border-image`. +#[test] +fn dashed_dotted_and_gradient_strokes_give_border_styles() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 120, "height": 60})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + let border = |s: &mut Session| { + let text = css(&run(s, "css.selection", json!({}))).to_string(); + let line = text.lines().find(|l| l.trim_start().starts_with("border:")).unwrap_or_else(|| panic!("a border in {text}")).trim().to_string(); + (line, text) + }; + run(&mut s, "stroke.set", json!({"weight": 1, "cap": "round", "dash": [0, 4]})); + let (line, text) = border(&mut s); + assert_eq!(line, "border: 1px dotted #000000;", "{text}"); + run(&mut s, "stroke.set", json!({"cap": "butt", "dash": [6, 3]})); + assert_eq!(border(&mut s).0, "border: 1px dashed #000000;"); + run(&mut s, "stroke.set", json!({"dash": null})); + run(&mut s, "paint.setStroke", json!({"gradient": {"kind": "linear"}})); + let (line, text) = border(&mut s); + assert_eq!(line, "border: 1px solid;", "{text}"); + let image = text.lines().find(|l| l.trim_start().starts_with("border-image:")).unwrap_or_else(|| panic!("a border-image in {text}")); + assert!(image.contains("linear-gradient(") && image.trim_end().ends_with(" 1;"), "{image}"); +} + +/// A pen-drawn upright rectangle is written as a rectangle: a background with square corners. The +/// same path turned is not, and gets the note for a shape CSS cannot draw. +#[test] +fn a_drawn_upright_rectangle_is_a_rectangle_and_a_turned_one_is_not() { + let mut s = session(); + let id = run(&mut s, "path.create", json!({"d": "M10 20 H130 V80 H10 Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#3366cc"})); + let r = run(&mut s, "css.selection", json!({"ids": [id]})); + let text = css(&r); + assert!(text.contains("background-color: #3366cc;"), "{text}"); + assert!(!text.contains("border-radius"), "{text}"); + assert!(r["rules"][0].get("unsupported").is_none(), "{r}"); + run(&mut s, "object.rotate", json!({"angle": 30})); + let r = run(&mut s, "css.selection", json!({"ids": [id]})); + assert_eq!(r["rules"][0]["unsupported"], json!("a shape other than a rectangle or an ellipse"), "{r}"); +} + #[test] fn generate_covers_the_document_and_an_empty_selection_has_none() { let mut s = session(); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 516e4fb3b0..3be402bb94 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -6802,6 +6802,80 @@ fn join_two_subpaths_of_same_path_node() { assert_eq!(pd.subpaths[0].anchors[3].p, Point::new(250.0, 0.0)); } +/// A path with one open two-anchor subpath per pair of points. +fn path_of_lines(s: &mut Session, lines: &[[Point; 2]]) -> NodeId { + let p = line(s, lines[0][0].x, lines[0][0].y, lines[0][1].x, lines[0][1].y); + let rest: Vec<_> = lines[1..].iter().map(|l| vectorcraft_geom::SubPath::polyline(l, false)).collect(); + s.edit("Add Subpaths", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(p).unwrap().kind { + path.subpaths.extend(rest); + } + Ok(()) + }) + .unwrap(); + p +} + +fn subpath_points(s: &Session, id: NodeId) -> Vec> { + path(s, id).subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p).collect()).collect() +} + +/// `path.join` with the same id twice and `subpaths` joins two subpaths of one path. Here the later +/// subpath comes first, so the earlier one is removed and the joined subpath takes the later one's +/// place, the coincident junction anchors become one, and the subpath between them stays as it was. +/// One undo step brings back all three subpaths. +#[test] +fn join_of_one_path_by_ids_and_subpaths_merges_the_junction_and_keeps_the_other_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(100.0, 0.0), pt(110.0, 0.0)], [pt(500.0, 0.0), pt(510.0, 0.0)], [pt(0.0, 0.0), pt(100.0, 0.0)]]); + let before = subpath_points(&s, p); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("path.join", &json!({"ids": [p.0, p.0], "subpaths": [2, 0], "ends": ["last", "first"]})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(500.0, 0.0), pt(510.0, 0.0)], vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(110.0, 0.0)]]); + assert!(path(&s, p).subpaths.iter().all(|sp| !sp.closed)); + assert_eq!(s.doc().unwrap().selection.objects, vec![p]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(subpath_points(&s, p), before); +} + +/// With both ends of one open subpath direct-selected, Join closes that subpath and leaves the +/// other open subpath of the same path as it is, instead of joining the two. +#[test] +fn join_with_both_ends_of_one_subpath_selected_closes_that_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(0.0, 0.0), pt(100.0, 0.0)], [pt(0.0, 50.0), pt(100.0, 50.0)]]); + s.execute("select.anchors", &json!({"id": p.0, "anchors": [[1, 0], [1, 1]], "mode": "set"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(0.0, 0.0), pt(100.0, 0.0)], vec![pt(0.0, 50.0), pt(100.0, 50.0)]]); + let pd = path(&s, p); + assert!(!pd.subpaths[0].closed, "the other subpath stays open"); + assert!(pd.subpaths[1].closed, "the subpath with both ends selected is closed"); +} + +/// With both ends of one line selected and only the first end of another, Join takes the nearest +/// pair of selected ends: the second line's unselected end is nearer but is not joined. +#[test] +fn join_with_both_ends_of_one_line_selected_takes_the_nearest_selected_pair() { + let mut s = session(); + let pt = Point::new; + let a = line(&mut s, 0.0, 0.0, 100.0, 0.0); + let b = line(&mut s, 300.0, 0.0, 105.0, 0.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + let joined = paths(&s); + assert_eq!(joined.len(), 1, "{joined:?}"); + let pts: Vec = joined[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(300.0, 0.0), pt(105.0, 0.0)]); +} + /// Direct-selecting 2 open endpoints in a complex compound path with multiple open segments joins only those 2. #[test] fn join_complex_compound_path_direct_endpoints() { diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index a42f2c4ca7..1539ece240 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -70,6 +70,21 @@ fn balance_previews_and_commits_one_step() { assert_eq!(fill_of(&s, a).to_hex(), "#808080"); } +/// An `objectOnly` paint during an open interaction keeps the remembered colors: the paint it would +/// leave waiting for the commit is not added to Recent Colors when the interaction commits. +#[test] +fn object_only_paint_in_an_interaction_keeps_recent_colors() { + let mut s = session(); + let a = rect(&mut s, json!("#808080")); + s.recent_colors.clear(); + let recent = (s.recent_colors.clone(), s.last_solid); + s.begin_interaction("Adjust Colors").unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000", "objectOnly": true})).unwrap(); + assert_eq!(fill_of(&s, a).to_hex(), "#ff0000"); + s.commit_interaction().unwrap(); + assert_eq!((s.recent_colors.clone(), s.last_solid), recent, "the recent colors are as they were"); +} + /// Saturate needs its intensity: a call without one, or with one that is not a number, is an error /// that changes nothing and records no undo step. A number outside −100..100 counts as its nearest end. #[test] diff --git a/crates/engine/src/tests/halftone.rs b/crates/engine/src/tests/halftone.rs index d836502baa..c7ec58549c 100644 --- a/crates/engine/src/tests/halftone.rs +++ b/crates/engine/src/tests/halftone.rs @@ -66,6 +66,65 @@ fn halftone_options() { } } +/// The dot path Vector Halftone makes from a gray square with `params`. +fn dots_of(params: serde_json::Value) -> vectorcraft_geom::PathData { + let mut s = session(); + red_rect(&mut s); + s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap(); + let r = s.execute("object.vectorHalftone", ¶ms).unwrap(); + let g = node(&s, NodeId(r["id"].as_u64().unwrap())); + g.children().unwrap()[0].path_data().unwrap().clone() +} + +#[test] +fn halftone_styles_set_the_shape_and_angle_unless_given() { + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots"})), dots_of(json!({"frequency": 18, "shape": "circle", "angle": 0}))); + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridAngle"})), dots_of(json!({"frequency": 18, "shape": "euclidean", "angle": 45}))); + assert_ne!(dots_of(json!({"frequency": 18, "style": "grid"})), dots_of(json!({"frequency": 18}))); + // A given shape or angle wins over the style's. + assert_eq!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "angle": 0}))); + assert_ne!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "style": "grid"}))); + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots", "angle": 45})), dots_of(json!({"frequency": 18, "style": "gridDotsAngle"}))); + // An unknown style is refused and leaves the document as it was. + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("object.vectorHalftone", &json!({"style": "checker"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); +} + +#[test] +fn halftone_refuses_null_and_non_string_styles() { + for style in [json!(null), json!(42), json!(true), json!([]), json!({})] { + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let result = s.execute("object.vectorHalftone", &json!({"style": style})); + assert!(matches!(result, Err(EngineError::BadParams { .. })), "{style}: {result:?}"); + assert_eq!(s.doc().unwrap().doc, before, "{style}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{style}"); + } + assert_eq!(dots_of(json!({"style": "custom"})), dots_of(json!({}))); +} + +/// The live effect refuses an unknown style when applied or edited, and leaves the document as it +/// was; a known style in another letter case is taken. +#[test] +fn halftone_effect_refuses_an_unknown_style() { + const HALFTONE: &str = "addon.color.halftone"; + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "gridDot"}})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "GRIDDOTS"}})).unwrap(); + let applied = s.doc().unwrap().doc.clone(); + assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "gridDot"}})).is_err()); + assert_eq!(s.doc().unwrap().doc, applied); + s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "custom"}})).unwrap(); +} + #[test] fn halftone_refuses_a_param_of_the_wrong_type() { for bad in [ diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index d0d12cce94..00588ecf0c 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -808,6 +808,25 @@ fn a_fill_chosen_during_a_bucket_drag_stays() { } } +/// With New Art Has Basic Appearance off, a fill chosen during a rectangle drag from an empty +/// selection is the fill the drag's next preview and its release draw with. +#[test] +fn a_fill_chosen_during_a_rectangle_drag_draws_the_rectangle() { + for real_time in [true, false] { + let at = format!("real time {real_time}"); + let (mut s, _) = session(real_time); + s.prefs.new_art_basic = false; + pointer(&mut s, PointerKind::Down, 100.0, 100.0); + pointer(&mut s, PointerKind::Drag, 150.0, 150.0); + s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": []})).unwrap(); + let blue = s.paint.fill.clone(); + pointer(&mut s, PointerKind::Drag, 200.0, 180.0); + pointer(&mut s, PointerKind::Up, 200.0, 180.0); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_eq!(s.doc().unwrap().doc.node(drawn).unwrap().appearance.fill_paint(), blue, "{at}"); + } +} + /// A command run during a Quick Pen press still runs inside the press, so it records no undo /// step of its own while the press is held. #[test] diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 0b35b2f772..35f86fa582 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -966,6 +966,45 @@ fn canceling_an_undo_group_keeps_a_batchs_steps_in_other_documents() { assert_eq!(r.active_index(), s.active_index()); } +/// A batch step in the canceled group that leaves another document in front (switching to the +/// grouped document measures its type again in its own composite font) is dropped from the batch's +/// journal entry and replaced by that switch, so the edit made after the group replays in the +/// document it was made in. +#[test] +fn canceling_an_undo_group_keeps_the_switch_of_a_dropped_batch_step() { + let mut s = Session::new(); + let fonts = |size: i32| { + let parts = json!({"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono", "size": size}}); + json!({"fonts": [{"name": "CF Undo Group", "parts": parts}]}) + }; + s.execute("file.new", &json!({"created": null})).unwrap(); + s.execute("type.compositeFonts.set", &fonts(50)).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "CF Undo Group"})).unwrap(); + s.execute("file.new", &json!({"created": null})).unwrap(); + s.execute("type.compositeFonts.set", &fonts(75)).unwrap(); + let objects = |s: &Session| s.documents().iter().map(|d| d.doc.node_count()).collect::>(); + let before = objects(&s); + let activate = |index: usize| json!({"command": "document.activate", "params": {"index": index}}); + let steps = json!([rect_step(10), activate(0)]); + for (id, p) in [ + ("document.activate", json!({"index": 0})), + ("edit.undoGroup.begin", json!({})), + ("shape.rectangle", rect_step(50)["params"].clone()), + ("document.activate", json!({"index": 1})), + ("command.batch", json!({ "commands": steps })), + ("edit.undoGroup.end", json!({"cancel": true})), + ("shape.rectangle", rect_step(30)["params"].clone()), + ] { + s.execute(id, &p).unwrap(); + } + assert_eq!(objects(&s), vec![before[0] + 1, before[1] + 1]); + let (_, batch) = s.journal.iter().find(|(id, _)| id == "command.batch").unwrap(); + assert_eq!(batch["commands"], json!([steps[0], activate(0)])); + let r = replayed(&s); + assert_eq!(documents(&r), documents(&s)); + assert_eq!(r.active_index(), s.active_index()); +} + /// The edits made in an undo group (a scrubbed numeric field, #400) are one undo step, journaled /// one by one; a cancelled group undoes them and leaves the journal as it was. #[test] @@ -1074,6 +1113,25 @@ fn an_undo_group_begun_by_command_opens_in_each_document_created_before_its_end( assert!(s.doc().unwrap().undo_group.is_none()); } +/// Between `edit.undoGroup.begin` and `edit.undoGroup.end`, a document added outside a command (a +/// template the app opens itself) opens an undo group with the begun group's name too: its edits are +/// one undo step there. +#[test] +fn an_undo_group_begun_by_command_opens_in_a_document_added_outside_a_command() { + let mut s = Session::new(); + let rect = json!({"x": 10, "y": 10, "width": 100, "height": 50}); + let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>(); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + s.execute("edit.undoGroup.begin", &json!({"label": "Job"})).unwrap(); + s.add_document(vectorcraft_doc::Document::new(400.0, 300.0), None); + s.execute("shape.rectangle", &rect).unwrap(); + s.execute("shape.ellipse", &rect).unwrap(); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + assert_eq!(labels(&s), ["Job"]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s), 0, "one undo takes back both edits"); +} + /// Between `edit.undoGroup.begin` and `edit.undoGroup.end`, a command that creates a document and /// edits it (a `command.batch`) keeps its edits as an undo step of its own in that document, and the /// edits after it are the group's step. A cancel undoes only those, keeps the document and the diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index e2ea567acd..b105a3fd90 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -1020,6 +1020,31 @@ fn moves_are_validated() { assert_eq!(parent(&s, sub), None); } +/// `node.move` keeps a clip group's clipping path at its bottom: the path does not leave the group +/// or move up in it, and a row moved to index 0 goes directly above it. +#[test] +fn node_move_keeps_a_clip_groups_clipping_path_at_the_bottom() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 30.0), rect(&mut s, 60.0)); + let layer = parent(&s, a).unwrap(); + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + let g = id(&run(&mut s, "object.clippingMask.make", json!({}))); + let before = children(&s, g); + let mask = before[0]; + for p in [json!({"id": mask.0, "parent": layer.0, "index": 0}), json!({"id": mask.0, "parent": g.0, "index": 2})] { + let err = s.execute("node.move", &p).unwrap_err().to_string(); + assert!(err.contains("clipping path stays at the bottom"), "{p}: {err}"); + assert_eq!(children(&s, g), before, "{p}"); + } + run(&mut s, "node.move", json!({"id": mask.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g), before, "the clipping path stays where it is"); + let d = rect(&mut s, 90.0); + run(&mut s, "node.move", json!({"id": d.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, d], "the row goes directly above the clipping path"); + run(&mut s, "node.move", json!({"id": before[2].0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, before[2]]); +} + /// The Layers panel's commands refuse a switch given as text or as another value that is not true /// or false, and leave the document, the selection, the highlighted rows and the undo history as /// they were; true, false and null still work. diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index ebc2b5d1c6..f9ebd99b85 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -100,6 +100,20 @@ fn places_named_from_a_share_are_not_followed_after_a_save_elsewhere() { assert_eq!(follow_from(link, on_share, Some(r"C:\b\poster.vectorcraft"), resolve), None); } +#[test] +fn capture_sources_exclude_paths_the_document_cannot_follow() { + let dir = Folder::new("capture-paths"); + let mut paths = far(&dir); + paths.push(dir.file("local.png")); + let path = save_linked(&dir, &paths); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let st = s.active().unwrap(); + let places = crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st)); + assert_eq!(far_reads(&places), Vec::<&String>::new(), "{places:?}"); + assert!(places.contains(&dir.file("local.png")), "local links remain capture sources: {places:?}"); +} + /// The final path Windows gives a folder of the drive `Z:` mapped to `\\server\share`. The /// share's root folder has no trailing separator (`\\?\UNC\server\share`). fn on_share(folder: &str) -> Option { diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index a0f001afe6..e04296d26d 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -133,6 +133,18 @@ fn spot_gradients_export_as_separation_shadings() { assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "an Ink → paper gradient is a Separation shading"); // Its function runs over the tints: 80 % (204 / 255) to 0 %. assert!(pdf.contains("/C0[0.8]/C1[0]"), "the shading's tints"); + // An off-center midpoint adds a stop there at the mean tint, still in the one spot ink. + run( + &mut s, + "paint.editGradient", + json!({"stops": [{"offset": 0, "swatch": "Ink", "tint": 80, "midpoint": 0.3}, {"offset": 1, "color": "#ffffff"}]}), + ); + let (pdf, _) = pdf_of(&s); + assert!(pdf.contains("/Separation/Ink/DeviceCMYK") && !pdf.contains("/DeviceN"), "still one spot ink"); + let functions: Vec<_> = pdf.match_indices("/C0[").filter_map(|(i, _)| pdf.get(i..i + 24)).collect(); + assert!(pdf.contains("/C0[0.8]/C1[0.4]") && pdf.contains("/C0[0.4]/C1[0]"), "the tints through the midpoint: {functions:?}"); + let bounds: Vec<_> = pdf.match_indices("/Bounds").filter_map(|(i, _)| pdf.get(i..i + 16)).collect(); + assert!(pdf.contains("/Bounds[0.3]"), "the midpoint stop sits at 30 %: {bounds:?}"); // Mixing the spot ink with an RGB color writes the gradient without the spot ink, with a warning. run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]})); let (pdf, warnings) = pdf_of(&s); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 6e1623c00e..21cc4af602 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -137,6 +137,45 @@ fn a_preset_starts_the_document_and_params_change_it() { assert_eq!(s.doc().unwrap().doc.units, Unit::Pixels); } +#[test] +fn a_bad_preset_or_preset_category_is_an_error() { + let s = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + assert!((s.doc().unwrap().doc.artboards[0].rect.height() - 841.89).abs() < 0.01); + for p in [ + json!({"preset": "A4", "presetCategory": "Napkins"}), + json!({"preset": "A4", "presetCategory": 5}), + json!({"preset": "A4", "presetCategory": ""}), + json!({"preset": "A4", "presetCategory": " Print "}), + json!({"presetCategory": "Print"}), + json!({"presetCategory": "Napkins"}), + json!({"preset": 5}), + json!({"preset": true, "presetCategory": "Print"}), + ] { + assert!(Session::new().execute("file.new", &p).is_err(), "file.new {p}"); + let mut save = p.clone(); + save["name"] = json!("Mine"); + assert!(Session::new().execute("file.newPresets.save", &save).is_err(), "file.newPresets.save {save}"); + } + let e = Session::new().execute("file.new", &json!({"preset": "A4", "presetCategory": "Napkins"})).unwrap_err().to_string(); + assert!(e.contains("unknown category `Napkins`"), "{e}"); + // Null leaves a param out. + Session::new().execute("file.new", &json!({"preset": null, "presetCategory": null})).unwrap(); + // A step this version took replays, and one an earlier version took still plays as it did then. + let recorded = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + let mut recorded = new_doc(json!({})); + recorded.journal.last_mut().unwrap().1["presetCategory"] = json!("Print"); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); +} + #[test] fn ppi_overprint_preview_and_bad_params() { // Overprint Preview is process-wide. @@ -219,6 +258,8 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { ("rows", 2.4, 2), ("rows", 0.6, 1), ("rows", 1000.4, 1000), + ("rows", 1000.6, 1000), + ("rows", 5000.0, 1000), ] { let mut p = json!({"width": 10, "height": 10, "artboards": 4, "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); @@ -236,8 +277,11 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { p["artboardLayout"][key] = json!(expected); } assert_eq!(boards(&s), boards(&new_doc(p))); + if key == "rows" { + assert_eq!(presets(&mut s, "Recent")[0]["artboardLayout"]["rows"], json!(expected), "{value}"); + } } - for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4})] { let mut p = json!({"artboardLayout": layout}); p["artboardLayout"]["layout"] = json!("gridByColumn"); let mut s = Session::new(); @@ -345,6 +389,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { assert_eq!(boards(&s).iter().map(|r| r.x0).collect::>(), [0.0, 100.0, 200.0], "side by side, not overlapping"); } +/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that +/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows. +#[test] +fn a_saved_preset_with_too_many_rows_reads_in_range() { + let mut s = Session::new(); + let prefs = json!({ + "newDocPresets": [ + {"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001}, + {"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0}, + ], + }); + s.apply_prefs(serde_json::from_value(prefs).unwrap()); + let saved = presets(&mut s, "Saved"); + assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]); + assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]); + s.execute("file.new", &saved[0]).unwrap(); + assert_eq!(boards(&s).len(), 4); +} + /// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest /// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names /// the limit in points and, when the document's units aren't points, in those units too. diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 802748e407..a5a082058e 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -123,6 +123,54 @@ fn intersect_disjoint_is_error_and_no_change() { assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); } +/// Pathfinder refuses a selection that holds no paths (an image alone) and paths with an anchor +/// that is not a finite number, and leaves the document and the undo history as they were. +#[test] +fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() { + let mut s = session(); + let image = s + .edit("Place", |d, sel| { + d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![0; 8])); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 2, + height: 2, + xf: Default::default(), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select paths"), "{e}"); + assert!(s.doc().unwrap().doc == before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); + + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 5.0, 0.0, 10.0, 10.0); + s.edit("Break", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(a).unwrap().kind { + path.subpaths[0].anchors[1].p.x = f64::NAN; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("invalid coordinates"), "{e}"); + assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some()); + assert!(s.doc().unwrap().doc.node(image).is_some()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); +} + #[test] fn exclude_makes_compound() { let mut s = session(); diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index a655002a4d..301ae6622e 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -479,6 +479,25 @@ fn paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned() { assert!(halves(&pts), "slice: {pts:?}"); } +/// A path that `node.move` puts into a pixel-aligned compound path snaps with it, though neither +/// the path nor where it came from was pixel-aligned. +#[test] +fn a_path_node_move_puts_into_an_aligned_compound_path_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0); + let b = path(&mut s, "M200 100 L210 100 L210 110 L200 110 Z", 1.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap(); + let loose = path(&mut s, "M300.25 100 L310 100 L310 110 L300.25 110 Z", 1.0); + assert!(!aligned(&s, loose)); + s.execute("node.move", &json!({"id": loose, "parent": c, "index": 99})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(loose)), Some(NodeId(c))); + let pts = compound_points(&s, c); + assert_eq!(pts.len(), 12); + assert!(halves(&pts), "{pts:?}"); +} + /// Art moved by Artboard Options with Move Artwork with Artboard, and the art copies of an /// artboard copied with its art, stay on the pixel grid. #[test] @@ -578,23 +597,29 @@ fn the_art_of_a_linked_opacity_mask_keeps_it_aligned() { let m = path(&mut s, "M12 23 L39 23 L39 28 L12 28 Z", 2.0); s.execute("object.setPixelAligned", &json!({"ids": [m]})).unwrap(); s.execute("transparency.makeOpacityMask", &json!({"ids": [o, m]})).unwrap(); - let mask_points = |s: &Session| { - let n = s.doc().unwrap().doc.node(NodeId(o)).unwrap().clone(); + let mask_points = |s: &Session, id: u64| { + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone(); let mask = n.extras().mask.clone().expect("an opacity mask"); assert!(mask.art.extras().pixel_aligned); mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::>() }; s.execute("select.set", &json!({"ids": [o]})).unwrap(); s.execute("object.move", &json!({"dx": 0.3, "dy": 0.4})).unwrap(); - assert_eq!(mask_points(&s), [(12.0, 23.0), (39.0, 23.0), (39.0, 28.0), (12.0, 28.0)]); - // The masked path inside a pixel-aligned compound path. + assert_eq!(mask_points(&s, o), [(12.0, 23.0), (39.0, 23.0), (39.0, 28.0), (12.0, 28.0)]); + // A pixel-aligned compound path made with the masked path at the back takes its mask. + // The masked path in front keeps its own mask inside it. let other = path(&mut s, "M110 21 L141 21 L141 30 L110 30 Z", 2.0); + let om = path(&mut s, "M112 23 L139 23 L139 28 L112 28 Z", 2.0); + s.execute("object.setPixelAligned", &json!({"ids": [om]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [other, om]})).unwrap(); s.execute("select.set", &json!({"ids": [o, other]})).unwrap(); let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); s.execute("object.move", &json!({"dx": 0.3, "dy": 0.4})).unwrap(); - assert!(whole(&mask_points(&s)), "{:?}", mask_points(&s)); + assert!(s.doc().unwrap().doc.node(NodeId(o)).unwrap().extras().mask.is_none()); + assert!(whole(&mask_points(&s, c)), "{:?}", mask_points(&s, c)); + assert!(whole(&mask_points(&s, other)), "{:?}", mask_points(&s, other)); } /// The start point of path object `id`'s placed gradient fill. diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 01493efda5..1e7dd7e9d1 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -3105,3 +3105,28 @@ fn pixel_snapping_options_read_set_and_reset() { s.execute("prefs.reset", &json!({})).unwrap(); assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all); } + +/// User Interface › Tool Icons is Classic by default and in preferences saved before it existed. Current, +/// once set, is saved and read back by a new session; a value that is neither is refused and changes nothing. +#[test] +fn tool_icons_default_to_classic_and_current_survives_a_restart() { + assert_eq!(Prefs::default().ui_tool_icons, "classic"); + let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap(); + assert_eq!(older.ui_tool_icons, "classic"); + + let mut first = Session::new(); + assert_eq!(first.execute("prefs.get", &json!({"key": "uiToolIcons"})).unwrap(), json!("classic")); + for bad in [json!("modern"), json!(""), json!(true), json!(1)] { + assert!(first.execute("prefs.set", &json!({"key": "uiToolIcons", "value": bad})).is_err(), "{bad}"); + assert_eq!(first.prefs.ui_tool_icons, "classic", "{bad} left the preference as it was"); + } + first.execute("prefs.set", &json!({"key": "uiToolIcons", "value": "current"})).unwrap(); + let saved = first.prefs.to_json(); + assert_eq!(saved["uiToolIcons"], "current"); + + let mut restarted = Session::new(); + restarted.apply_prefs(serde_json::from_value(saved).unwrap()); + assert_eq!(restarted.execute("prefs.get", &json!({"key": "uiToolIcons"})).unwrap(), json!("current")); + restarted.execute("prefs.reset", &json!({"category": "User Interface"})).unwrap(); + assert_eq!(restarted.prefs.ui_tool_icons, "classic"); +} diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 278e7e0f3d..cd7d763b8c 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -858,6 +858,263 @@ fn a_rows_tint_tints_the_spot_color_the_art_links_to() { assert!(e.to_string().contains("`tint` must be a number"), "{e}"); } +/// A row's `swatch` (the swatch its new color was picked from) links its art to that swatch without +/// Limit to Library: a spot or global swatch gives linked tints, and a process swatch, a swatch +/// whose color is not the row's new color and a swatch that is not there link nothing. A `swatch` +/// that is not `{name, library?}` is refused. Randomize moves the swatch with its color. +#[test] +fn a_rows_swatch_links_its_art_without_limit_to_library() { + for (options, linked) in [(json!({"spot": true}), true), (json!({"global": true}), true), (json!({}), false)] { + let mut s = session(); + let mut w = json!({"name": "Ink", "color": "cmyk 0 100 0 0"}); + w.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + run(&mut s, "swatch.new", w); + let dark = rect(&mut s, json!("gray 80")); + let light = rect(&mut s, json!("gray 40")); + select_all(&mut s); + let row = |swatch: Value| json!([{"from": ["gray 80", "gray 40"], "to": "cmyk 0 100 0 0", "swatch": swatch}]); + run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints"})); + let d = &s.doc().unwrap().doc; + let paint = |id: NodeId| match d.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, tint } => (color, swatch, tint), + p => panic!("{p:?}"), + }; + let ((c1, l1, t1), (c2, l2, t2)) = (paint(dark), paint(light)); + assert_eq!(l1.is_some() && l2.is_some(), linked, "{options}: {l1:?} {l2:?}"); + // A process swatch's row keeps the art's gray model (see the next test). + if linked { + assert!(t1 > t2 && t2 > 0.0, "{options}: the lighter gray is a lighter tint: {t1} {t2}"); + assert!(close(c1, Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: {c1:?}"); + } + assert!(!close(c2, c1), "{options}: {c1:?} {c2:?}"); + // Without the swatch the same row gives tints with no link. + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + run(&mut s, "recolor.apply", json!({"map": row(Value::Null), "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: no swatch, no link"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // A swatch of another color than the row's new color links nothing. + let other = json!([{"from": ["gray 80", "gray 40"], "to": "#00ff00", "swatch": {"name": "Ink", "library": "document"}}]); + run(&mut s, "recolor.apply", json!({"map": other, "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: another color"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // With a Global Adjust the art takes the adjusted colors, not the swatch. + let adjust = json!({"saturation": -40}); + run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints", "globalAdjust": adjust})); + assert_eq!(paint_link(&s, dark), None, "{options}: adjusted"); + assert!(!close(fill(&s, dark), Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: the adjustment applies"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // A swatch or library that is not there (deleted since the pick) links nothing, and the result + // names it. + for gone in [json!({"name": "Missing"}), json!({"name": "Ink", "library": "nowhere"})] { + let r = run(&mut s, "recolor.apply", json!({"map": row(gone.clone()), "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: {gone}"); + assert_eq!(r["swatchesNotFound"], json!([gone["name"]]), "{options}: {r}"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + } + for bad in [json!("Ink"), json!({"name": ""}), json!({"name": "Ink", "library": 3})] { + let e = s.execute("recolor.apply", &json!({"map": row(bad.clone())})).unwrap_err(); + assert!(e.to_string().contains("`swatch` must be"), "{bad}: {e}"); + } + let two = json!([ + {"from": ["gray 80"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink"}}, + {"from": ["gray 40"], "to": "#00ff00"}, + ]); + let r = run(&mut s, "recolor.randomize", json!({"map": two, "seed": 3})); + let rows = r["map"].as_array().unwrap(); + let ink = rows.iter().find(|r| r["to"] == "cmyk 0 100 0 0").unwrap(); + let green = rows.iter().find(|r| r["to"] == "rgb 0 255 0").unwrap(); + assert_eq!(ink["swatch"], json!({"name": "Ink", "library": "document"}), "{r}"); + assert!(green.get("swatch").is_none(), "{r}"); + let r = run(&mut s, "recolor.randomize", json!({"map": two, "order": false, "saturationBrightness": true, "seed": 3})); + let rows = r["map"].as_array().unwrap(); + assert_eq!(rows.len(), 2, "{r}"); + assert!(rows.iter().all(|r| r.get("swatch").is_none()), "a changed color drops its swatch: {r}"); + } +} + +/// A swatch whose components are finer than a color key's hundredths still links the art of the row +/// whose new color is its key. +#[test] +fn a_rows_swatch_with_a_finer_color_than_its_key_still_links() { + let mut s = session(); + let ink = Color::cmyk(0.123_456, 0.876_543, 0.0, 0.0); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0.123_456, "m": 0.876_543, "y": 0.0, "k": 0.0}, "spot": true})); + let id = rect(&mut s, json!("gray 50")); + select_all(&mut s); + let to = vectorcraft_color::recolor::ColorKey::of(&ink).to_string(); + run(&mut s, "recolor.apply", json!({"map": [{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink"}}], "method": "scaleTints"})); + assert_eq!(paint_link(&s, id).as_deref(), Some("Ink")); + assert!(close(fill(&s, id), ink), "the swatch's own color: {:?}", fill(&s, id)); +} + +/// A row's `swatch` that is a global swatch of the group being rewritten with another color links +/// nothing: the row's art takes the row's new color as with no swatch, in its own model and without +/// the row's tint of the swatch. A swatch of the group that keeps its color still links the art. +#[test] +fn a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Red Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Blue Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "G", "swatches": ["Red Ink", "Blue Ink"]})); + let red = rect(&mut s, json!("#ff0000")); + let blue = rect(&mut s, json!("#0000ff")); + select_all(&mut s); + let map = |first: &str| { + json!([ + {"from": ["#ff0000"], "to": first}, + {"from": ["#0000ff"], "to": "#ff0000", "swatch": {"name": "Red Ink"}}, + ]) + }; + run(&mut s, "recolor.apply", json!({"map": map("#00ff00"), "group": "G"})); + let ink = |s: &Session| s.doc().unwrap().doc.swatch("Red Ink").unwrap().paint.color().unwrap().to_hex(); + assert_eq!(ink(&s), "#00ff00", "the group is rewritten"); + assert_eq!(fill(&s, red).to_hex(), "#00ff00"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000", "the blue art keeps its row's new color"); + assert_eq!(paint_link(&s, blue), None); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // Also at a row tint of 0, where Red Ink's old and new colors both show white. + let mut zero = map("#00ff00"); + zero[1]["tint"] = json!(0); + run(&mut s, "recolor.apply", json!({"map": zero, "group": "G"})); + assert_eq!(paint_link(&s, blue), None, "at a tint of 0"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000", "the row's new color, as with no swatch"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // Red Ink is rewritten with its own color, so the blue art links to it. + run(&mut s, "recolor.apply", json!({"map": map("#ff0000"), "group": "G"})); + assert_eq!(ink(&s), "#ff0000"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000"); + assert_eq!(paint_link(&s, blue).as_deref(), Some("Red Ink")); + run(&mut s, "edit.undo", json!({})); + // A CMYK swatch of a group rewritten with another color: the RGB art takes the row's new color + // as the row without the swatch gives it, in the art's own model. + run(&mut s, "swatch.new", json!({"name": "Cyan Ink", "color": "cmyk 100 0 0 0", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "C", "swatches": ["Cyan Ink"]})); + let result = |s: &mut Session, swatch: Value| { + select_all(s); + let map = json!([{"from": ["#0000ff"], "to": "cmyk 100 0 0 0", "swatch": swatch}]); + let r = run(s, "recolor.apply", json!({"map": map, "group": "C", "groupColors": ["#00ff00"]})); + let out = (fill(s, blue), paint_link(s, blue), r.get("note").cloned()); + run(s, "edit.undo", json!({})); + out + }; + let alone = result(&mut s, Value::Null); + assert!(alone.2.is_some(), "the RGB art keeps its model: {alone:?}"); + assert_eq!(result(&mut s, json!({"name": "Cyan Ink"})), alone); +} + +/// A row's `swatch` from a loaded library links the art to it and adds it to the document's +/// swatches; of two library swatches with the same name, the one with the row's new color is used, +/// and rows that pick the same one link to one added swatch; of a process and a spot swatch with +/// one name and color, the first is used; and a process swatch recolors as the row's new color +/// alone does, in the color model `model` gives. +#[test] +fn a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Twin", "color": "cmyk 100 0 0 0", "spot": true})); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink", "Twin"], "name": "Inks"}))["data"].as_str().unwrap().to_string(); + // Both of the library's swatches are named Ink. + let data = data.replace("\"Twin\"", "\"Ink\""); + let lib = run(&mut s, "swatch.library.load", json!({"data": data, "name": "inks.vcswatches"}))["library"].as_str().unwrap().to_string(); + run(&mut s, "swatch.delete", json!({"names": ["Ink", "Twin"]})); + let id = rect(&mut s, json!("gray 50")); + select_all(&mut s); + let row = |to: &str| json!([{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink", "library": lib}}]); + let r = run(&mut s, "recolor.apply", json!({"map": row("cmyk 100 0 0 0"), "method": "scaleTints"})); + assert_eq!(r["swatches"], json!(["Ink"]), "{r}"); + let d = &s.doc().unwrap().doc; + let w = d.swatch("Ink").unwrap(); + assert!(w.spot && close(w.paint.color().unwrap(), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "the swatch of the row's color joined: {w:?}"); + assert_eq!(paint_link(&s, id).as_deref(), Some("Ink")); + assert!(close(fill(&s, id), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "{:?}", fill(&s, id)); + run(&mut s, "edit.undo", json!({})); + + // Three rows that pick the magenta, the cyan and again the cyan Ink: the two cyan rows link to + // one swatch added to the document. + let more = [rect(&mut s, json!("gray 20")), rect(&mut s, json!("gray 80"))]; + select_all(&mut s); + let three = json!([ + {"from": ["gray 50"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink", "library": lib}}, + {"from": ["gray 20"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}}, + {"from": ["gray 80"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}}, + ]); + let r = run(&mut s, "recolor.apply", json!({"map": three, "method": "scaleTints"})); + assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}"); + let (a, b, c) = (paint_link(&s, id), paint_link(&s, more[0]), paint_link(&s, more[1])); + assert!(a.is_some() && b.is_some() && a != b && b == c, "{a:?} {b:?} {c:?}"); + run(&mut s, "edit.undo", json!({})); + + // Of a process and a spot swatch with one name and color, the first, the process one, is used. + run(&mut s, "swatch.new", json!({"name": "Pair", "color": "cmyk 0 0 100 0"})); + run(&mut s, "swatch.new", json!({"name": "Pear", "color": "cmyk 0 0 100 0", "spot": true})); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Pair", "Pear"], "name": "Pairs"}))["data"] + .as_str() + .unwrap() + .replace("\"Pear\"", "\"Pair\""); + let pairs = run(&mut s, "swatch.library.load", json!({"data": data, "name": "pairs.vcswatches"}))["library"].as_str().unwrap().to_string(); + run(&mut s, "swatch.delete", json!({"names": ["Pair", "Pear"]})); + select_all(&mut s); + let map = json!([{"from": ["gray 50"], "to": "cmyk 0 0 100 0", "swatch": {"name": "Pair", "library": pairs}}]); + run(&mut s, "recolor.apply", json!({"map": map, "method": "scaleTints"})); + assert_eq!(paint_link(&s, id), None, "the process swatch"); + run(&mut s, "edit.undo", json!({})); + + // A global process Ink and a spot Ink of one color, from two libraries, while the document's Ink + // is another color: each row links to its own added swatch. + let mut libraries = vec![]; + for (file, kind) in [("global.vcswatches", json!({"global": true})), ("spot.vcswatches", json!({"spot": true}))] { + let mut w = json!({"name": "Ink", "color": "cmyk 0 0 0 100"}); + w.as_object_mut().unwrap().extend(kind.as_object().unwrap().clone()); + run(&mut s, "swatch.new", w); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink"], "name": file}))["data"].as_str().unwrap().to_string(); + libraries.push(run(&mut s, "swatch.library.load", json!({"data": data, "name": file}))["library"].as_str().unwrap().to_string()); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + } + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00"})); + select_all(&mut s); + let two = json!([ + {"from": ["gray 50"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[0]}}, + {"from": ["gray 20"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[1]}}, + ]); + let r = run(&mut s, "recolor.apply", json!({"map": two, "method": "scaleTints"})); + assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}"); + let (global, spot) = (paint_link(&s, id).unwrap(), paint_link(&s, more[0]).unwrap()); + let d = &s.doc().unwrap().doc; + assert!(global != spot && !d.swatch(&global).unwrap().spot && d.swatch(&spot).unwrap().spot, "{global} {spot}"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + select_all(&mut s); + + run(&mut s, "swatch.new", json!({"name": "Leaf", "color": "cmyk 60 0 100 10"})); + select_all(&mut s); + let fills = |s: &mut Session, swatch: Value, model: &str| { + let map = json!([{"from": ["gray 50"], "to": "cmyk 60 0 100 10", "swatch": swatch}]); + let r = run(s, "recolor.apply", json!({"map": map, "method": "scaleTints", "model": model})); + let paint = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + run(s, "edit.undo", json!({})); + select_all(s); + (paint, r.get("note").cloned()) + }; + for model in ["keep", "new", "document"] { + let alone = fills(&mut s, Value::Null, model); + assert_eq!(fills(&mut s, json!({"name": "Leaf"}), model), alone, "{model}: a process swatch is its color"); + } +} + +fn paint_link(s: &Session, id: NodeId) -> Option { + match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { swatch, .. } => swatch, + p => panic!("{p:?}"), + } +} + /// Randomize order moves a row's tint with its new color; changing saturation and brightness /// drops the tint of every color it changes. #[test] diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index ea399d2fd2..cdb3275607 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -458,6 +458,18 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // Once the script makes an artboard active, the selection from the start of the run no longer holds. + let (mut s, was, _) = setup(); + let before = objects(&s); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 1, "one copy, on the artboard the script made active"); + let pasted = s.active().unwrap().selection.objects.clone(); + let copy = s.active().unwrap().doc.bounds_of(&pasted, false).unwrap(); + assert!(copy.x0 >= was[1].x0 && copy.x1 <= was[1].x1, "the copy is on artboard 1: {copy:?}"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(2); app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [was[0], was[1], art[2]], "only the artboard the script made active fits its art"); // A kept artboard past the last one is left out; with fewer than two left, the active one applies. let (mut s, ..) = setup(); s.reset_tool(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 73e44c2af7..8f71d64e62 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -134,6 +134,65 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the direction handles of a curve, which reach past its visible bounds. +#[test] +fn control_bounds_take_in_the_direction_handles() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!(top(&out[0]) < 180.0, "{out:?}"); + assert_eq!(top(&out[1]), 200.0, "{out:?}"); + assert_eq!(out[1][2].as_f64().unwrap(), out[0][2].as_f64().unwrap(), "{out:?}"); +} + +/// The `controlBounds` of a group leave out the handles of a hidden curve in it. +#[test] +fn control_bounds_leave_out_hidden_paths() { + let (mut s, a, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, id]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"id": id, "visible": false})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.selection[0].parent; vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[1], out[0], "{out:?}"); +} + +/// Each anchor `controlBounds` visits counts toward the data a run passes, so reading the bounds of +/// a large path again and again ends the run where reading its geometric bounds does not. +#[test] +fn control_bounds_count_the_anchors_they_visit() { + let (mut s, _, _) = doc(); + let d: String = (0..2000u32).map(|i| format!(" L{} {}", i % 300, (i * 7) % 200)).collect(); + let id = s.execute("path.create", &json!({"d": format!("M0 0{d}")})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // 100 reads of 2001 anchors are about 200 KB of steps, over a 64 KiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let read = |s: &mut Session, what: &str| run(s, &format!("var i = app.activeDocument.selection[0]; for (var n = 0; n < 100; n++) i.{what};")); + let geometric = read(&mut s, "geometricBounds"); + let control = read(&mut s, "controlBounds"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + geometric.unwrap(); + let e = control.unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); +} + +/// The `controlBounds` of a clip group leave out the handles of the clipped art past the clipping +/// path. +#[test] +fn control_bounds_of_a_clip_group_come_from_its_clipping_path() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + let mask = rect(&mut s, 100.0, 150.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[0], json!(true), "{out:?}"); + assert_eq!(out[2], out[1], "{out:?}"); +} + /// `controlBounds` takes in the Bézier handles of a path, which can reach past what it draws. #[test] fn page_item_control_bounds_take_in_the_handles() { @@ -543,6 +602,36 @@ fn app_undo_and_redo_step_through_the_runs_edits() { assert!(failure(&mut s, "app.redo();").contains("No active document")); } +/// A layer, page item or artboard read before `app.undo()` took it away is stale, even when an +/// object added afterwards takes its id; one that `app.redo()` brings back, and one that was there +/// before the undone step, still work. +#[test] +fn a_handle_from_before_an_undo_does_not_name_a_later_object() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, kept = d.layers[0], m;\ + var a = d.layers.add(); app.undo(); var b = d.layers.add(); b.name = 'b';\ + m = ''; try { a.name = 'x'; } catch (e) { m = e.message; } vc.log([m, b.name]);\ + m = ''; try { a.groupItems.length; } catch (e) { m = e.message; } vc.log(m);\ + var p = d.groupItems.add(); app.undo(); var q = d.groupItems.add(); q.name = 'q';\ + m = ''; try { p.name = 'y'; } catch (e) { m = e.message; } vc.log([m, q.name]);\ + var r = d.artboards.add([500, 300, 700, 100]); app.undo(); var t = d.artboards.add([800, 300, 1000, 100]); t.name = 't';\ + m = ''; try { r.name = 'z'; } catch (e) { m = e.message; } vc.log([m, t.name]);\ + var c = d.layers.add(); app.undo(); app.redo(); c.name = 'c'; kept.name = 'kept'; vc.log([c.name, kept.name]);", + ); + assert_eq!( + out, + vec![ + json!(["Stale layer", "b"]), + json!("Stale layer"), + json!(["Stale page item", "q"]), + json!(["Stale artboard", "t"]), + json!(["c", "kept"]), + ] + ); +} + /// An opacity a graph mark already has still replaces the opacity another mark of its series left on /// the graph, as `object.setProps` does. #[test] @@ -727,6 +816,28 @@ fn blending_mode_reads_and_sets_the_objects_blend_mode() { } } +/// An opacity near the one an item has, but not the one it reports, is set. +#[test] +fn an_opacity_close_to_the_current_one_is_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.opacity = 50.00009; vc.log(i.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); +} + +/// A layer opacity near the one the layer has, but not the one it reports, is set. +#[test] +fn a_layer_opacity_close_to_the_current_one_is_set() { + let (mut s, _, _) = doc(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = 50; l.opacity = 50.00009; vc.log(l.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); + // The same number again stores as the opacity the layer has, and runs no command. + let sets = |s: &Session| s.journal.iter().filter(|(id, _)| id == "object.setProps").count(); + let before = sets(&s); + log(&mut s, "app.activeDocument.layers[0].opacity = 50.00009;"); + assert_eq!(sets(&s), before); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -734,6 +845,18 @@ fn selection_assignment_is_atomic_across_invalid_items() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); assert!(e.contains("Cannot select PathItem"), "{e}"); assert!(s.active().unwrap().selection.objects.is_empty()); + // In either order, the refused assignment leaves nothing selected while the script runs. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + function pick(list) { var m = ''; try { d.selection = list; } catch (e) { m = e.message; } vc.log([m, d.selection.length === 0]); }\ + pick([p[0], p[1]]); pick([p[1], p[0]]);", + ); + assert_eq!(out.len(), 2); + for o in &out { + assert!(o[0].as_str().is_some_and(|m| m.contains("Cannot select PathItem")), "{o}"); + assert_eq!(o[1], json!(true), "{o}"); + } // With the valid item first and the error caught, the run sees the selection unchanged. let out = log( &mut s, @@ -953,6 +1076,45 @@ fn move_and_duplicate_place_by_element_placement() { assert!(e.contains("hidden or locked"), "{e}"); } +/// An object cannot go behind a clip group's clipping path; one put at the end of the group goes +/// directly above the clipping path. +#[test] +fn an_object_cannot_go_behind_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let before = kids(&s); + s.execute("object.setProps", &json!({"id": before[0].0, "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"id": before[1].0, "name": "art"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('art').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);"); + assert!(e.contains("an object cannot go below a clipping mask"), "{e}"); + assert_eq!(kids(&s), before); + // The clipping path moved directly below the object above it stays where it is. + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art'), ElementPlacement.PLACEAFTER);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); + // The clipping path put at the end of its own clip group stays where it is; put on top of the + // group's contents, it is refused. + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); + for place in ["INSIDE", "PLACEATBEGINNING"] { + let e = failure( + &mut s, + &format!("var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.{place});"), + ); + assert!(e.contains("the clipping path stays at the bottom of its clip group"), "{place}: {e}"); + assert_eq!(kids(&s), before, "{place}"); + } + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), [before[0], c, before[1]]); +} + #[test] fn a_copy_goes_beside_its_source() { let (mut s, a, b) = doc(); @@ -976,6 +1138,34 @@ fn a_copy_goes_beside_its_source() { assert!(e.contains("into itself"), "{e}"); } +/// A clipping group's clipping path stays at the bottom of the group, so an object cannot go +/// below it; above it is the bottom of the clipped art. +#[test] +fn nothing_goes_below_a_clipping_path() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "loose"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let children = |s: &Session| -> Vec { s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect() }; + assert_eq!(children(&s)[0], b, "the clipping path is the group's first child"); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for source in [ + "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + "var p = app.activeDocument.pageItems; p.getByName('loose').duplicate(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("an object cannot go below a clipping mask"), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "a refused move changes nothing"); + assert_eq!(undo_steps(&s), steps); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEBEFORE);"); + assert_eq!(children(&s), [b, c, a]); +} + #[test] fn a_copy_that_cannot_be_placed_is_deleted() { let mut s = Session::new(); @@ -1321,6 +1511,24 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn file_new_replays_legacy_fractional_and_large_rows() { + for (rows, rounded) in [(3.6, 4), (1000.4, 1000), (1000.5, 1000), (5000.0, 1000)] { + let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); + let mut s = Session::new(); + // A direct call refuses a fraction or a count over 1000; a replay rounds it and keeps it to at most 1000. + let direct = Session::new().execute("file.new", ¶ms); + assert!(direct.is_err(), "{rows}: {direct:?}"); + s.replay("file.new", ¶ms).unwrap(); + let mut expected = Session::new(); + let mut params = params; + params["artboardLayout"]["rows"] = json!(rounded); + expected.execute("file.new", ¶ms).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|b| b.rect).collect::>(); + assert_eq!(boards(&s), boards(&expected)); + } +} + #[test] fn a_listed_preset_keeps_more_rows_than_artboards() { use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; @@ -1371,6 +1579,30 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +/// A path saved with selected segments and no anchor entry gets its segments back, and only the +/// anchors at their ends, which `select.segments` selects with them. +#[test] +fn an_edit_gives_a_path_with_only_segments_no_other_anchors() { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "set"})).unwrap(); + let ends = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert_eq!(ends.as_ref().map(|e| e.len()), Some(2)); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + s.active_mut().unwrap().selection.anchors.remove(&a); + let before = s.active().unwrap().selection.clone(); + assert!(before.segments.contains_key(&a) && !before.anchors.contains_key(&a)); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.anchors.get(&a), ends.as_ref()); + assert_eq!(sel.segments.get(&a), before.segments.get(&a)); + let mut objects = sel.objects.clone(); + objects.sort(); + let mut was = before.objects.clone(); + was.sort(); + assert_eq!(objects, was, "the same objects are selected"); +} + #[test] fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { let (mut s, a, b) = doc(); @@ -2000,6 +2232,63 @@ fn add_document_takes_only_a_document_preset() { assert_eq!(out, vec![json!(500)]); } +#[test] +fn document_preset_settings_are_limited_in_bytes() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var presets = [];\ + for (var k = 0; k < 1000; k++) { var p = new DocumentPreset(); p.title = 'old'; presets.push(p); }\ + var message = '';\ + try { for (var k = 0; k < presets.length; k++) presets[k].title = title; }\ + catch (e) { message = e.name + ': ' + e.message; }\ + vc.log(message); vc.log(k > 0 && k < presets.length); vc.log(presets[k].title);\ + presets[0].title = 'x'; presets[k].title = title;\ + vc.log(presets[0].title); vc.log(presets[k].title === title);", + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!( + out, + vec![ + json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)), + json!(true), + json!("old"), + json!("x"), + json!(true), + ] + ); +} + +#[test] +fn a_new_document_preset_is_refused_past_the_byte_limit() { + use crate::script::TEST_ENGINE_HEAP; + let preset_bytes = 6 * std::mem::size_of::() + "DocumentArtboardLayout.GridByRow".len(); + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + &format!( + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var first = new DocumentPreset(); first.title = title;\ + try {{ for (var k = 0; k < 2000; k++) {{ var p = new DocumentPreset(); p.title = title; }} }} catch (e) {{}}\ + var message = '';\ + try {{ for (var k = 0; k < 10000; k++) new DocumentPreset(); }}\ + catch (e) {{ message = e.name + ': ' + e.message; }}\ + vc.log(message); vc.log(k < 10000);\ + first.title = title.substring({preset_bytes});\ + vc.log((new DocumentPreset()).width);\ + var again = ''; try {{ new DocumentPreset(); }} catch (e) {{ again = e.name + ': ' + e.message; }}\ + vc.log(again);" + ), + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + let message = json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)); + assert_eq!(out, vec![message.clone(), json!(true), json!(612), message]); +} + #[test] fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let root = vectorcraft_testkit::TempDir::new("script-add-document-profile"); @@ -2206,6 +2495,47 @@ fn wrappers_go_stale_after_revert() { } } +/// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does. +#[test] +fn a_layers_page_items_read_names_as_the_documents_do() { + let (mut s, _, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "Logo"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.layers[0].pageItems;\ + vc.log([p['Logo'].name, 'Logo' in p, 'none' in p, p[-1] === undefined, p.index(0).name, String(p)]);\ + var m = ''; try { p['none']; } catch (e) { m = e.message; } vc.log(m);\ + var n = ''; try { p.index(1.5); } catch (e) { n = e.message; } vc.log(n);", + ); + assert_eq!(out, vec![json!(["Logo", true, false, true, "Logo", "[PageItems]"]), json!("Not found"), json!("Not found")]); +} + +/// A layer's `textFrames.areaText` refuses a path in a locked layer and leaves it as it was. +#[test] +fn area_text_into_a_layer_refuses_a_locked_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "var d = app.activeDocument, p = d.pathItems[d.pathItems.length - 1], l = d.layers.add(); l.textFrames.areaText(p);"); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert!(s.active().unwrap().doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))); +} + +/// `clipped` on a group on a locked artboard throws `Cannot edit` and keeps the group as it was. +#[test] +fn clipping_a_group_on_a_locked_artboard_is_refused() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); + assert!(e.contains("Cannot edit"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert!(!s.active().unwrap().doc.layers[0].children().unwrap().iter().any(|n| n.clips())); +} + /// A layer's or group's collection and an artboard read before File › Revert are stale after it, /// while the document's own collections follow the loaded document. #[test] @@ -2319,7 +2649,8 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { fn scoped_remove_all_refuses_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); - s.execute("object.group", &json!({})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": g, "name": "locked"})).unwrap(); let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); @@ -2332,20 +2663,32 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { .unwrap(); }; lock(&mut s, true); + // A path and a group on a second, unlocked artboard, made last so each lists first in its + // scope, are not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let u = rect(&mut s, 1300.0, 100.0, 20.0, 20.0); + let v = rect(&mut s, 1100.0, 100.0, 20.0, 20.0); + let w = rect(&mut s, 1150.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [v.0, w.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); let before = format!("{:?}", s.active().unwrap().doc.layers); let steps = undo_steps(&s); for scope in [ "app.activeDocument.layers[0].pageItems", "app.activeDocument.layers[0].groupItems", "app.activeDocument.groupItems", - "app.activeDocument.groupItems[0].pageItems", + "app.activeDocument.groupItems.getByName('locked').pageItems", "app.activeDocument.layers[0].compoundPathItems", "app.activeDocument.compoundPathItems", ] { - let err = failure(&mut s, &format!("{scope}.removeAll();")); - assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + // The error is caught, so the run keeps whatever `removeAll()` did before it threw. + let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);")); + assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}"); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); assert_eq!(undo_steps(&s), steps, "{scope}"); + let doc = &s.active().unwrap().doc; + assert!([u, v, w].iter().all(|i| doc.node(*i).is_some()), "{scope}"); } lock(&mut s, false); let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); @@ -3263,6 +3606,35 @@ fn clipped_setter_refuses_locked_artboards_layers_and_groups() { } } +#[test] +fn clipped_setter_refuses_a_hidden_or_locked_topmost_object() { + for hidden in [false, true] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Protect", |d, _| { + let n = d.node_mut(b).unwrap(); + if hidden { + n.visible = false; + } else { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.node(b).unwrap().appearance); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; try { g.clipped = true; vc.log('changed'); } catch (e) { vc.log(e.message); } vc.log(g.clipped);", + ); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "hidden {hidden}: {out:?}"); + assert_eq!(out[1], json!(false)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b).unwrap().appearance), before); + assert_eq!(undo_steps(&s), steps); + } +} + #[test] fn scoped_collections_convert_to_strings() { let (mut s, ..) = doc(); @@ -3386,7 +3758,7 @@ fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() { } #[test] -fn a_compound_paths_path_items_are_path_items() { +fn a_compound_paths_path_items_are_page_items() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); @@ -3452,6 +3824,9 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { let b = run(&mut s, in_order).unwrap(); assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); + // A list built again for each lookup would add a host call to both. Building the document's + // page items for `groupItems` counts one call. + assert_eq!(a["hostCalls"], json!(51), "{a}"); } /// A loop over `layers.length` and `layers[i]` lists the layers once while the document is @@ -3471,6 +3846,39 @@ fn a_loop_over_layers_lists_them_once() { assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); } +/// Reading `zOrderPosition` for every layer lists the layers once while the document is unchanged. +#[test] +fn z_order_position_of_each_layer_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log( + &mut s, + "var L = app.activeDocument.layers, k = L.length, z = []; for (var i = 0; i < k; i++) { z.push(L[i].zOrderPosition); } vc.log(z[0]); vc.log(z[k - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + +/// `groupItems.createFromFile` on a collection whose group is gone reports the stale object before +/// the member that is not available yet. +#[test] +fn create_from_file_on_a_stale_group_collection_reports_it_stale() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var g = app.activeDocument.groupItems[0], c = g.groupItems; g.remove(); c.createFromFile(new File('x.svg'));"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.groupItems[0].groupItems.createFromFile(new File('x.svg'));"); + assert!(e.contains("GroupItems.createFromFile is not available yet"), "{e}"); +} + /// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the /// document's `pageItems`, also when the list was already built. #[test] @@ -3679,6 +4087,82 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +/// A stale container's `pageItems.index(n)` and `groupItems.index(n)` throw the stale error for +/// every number, a negative one included. +#[test] +fn a_stale_containers_list_throws_its_stale_error_for_any_index() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-stale-index"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for list in ["pageItems", "groupItems"] { + let source = + format!("var d = app.activeDocument, p = d.layers[0].{list}; d.pageItems[0].name = 'changed'; vc.run('file.revert'); p.index(-1);"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{list}: {e}"); + } +} + +/// `removeAll()` on a clip group releases its mask, so an object added to the group afterwards is +/// not its clipping path; the run's one undo step puts everything back. +#[test] +fn remove_all_on_a_clip_group_releases_its_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); g.groupItems.add(); vc.log(g.clipped);"); + assert_eq!(out, [json!(false), json!(false)]); + assert!(!s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert!(st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // `groupItems.removeAll()` leaves the clipping path, and the group keeps its mask. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; g.groupItems.add(); g.groupItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);", + ); + assert_eq!(out, [json!(true), json!(2)]); +} + +/// `remove()` on a clip group's clipping path while other art stays in the group releases the +/// mask, so the art above it is not made the clipping path, and so does emptying a clipping layer +/// with the document's `pageItems.removeAll()`. +#[test] +fn deleting_a_clipping_path_releases_its_mask() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let mask = kids(&s)[0]; + assert!(matches!(s.active().unwrap().doc.node(mask).unwrap().kind, NodeKind::Compound { .. })); + s.execute("object.setProps", &json!({"id": mask.0, "name": "mask"})).unwrap(); + let clips = |s: &Session| s.active().unwrap().doc.node(g).unwrap().clips(); + assert!(clips(&s)); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.getByName('mask').remove(); vc.log([g.clipped, g.pageItems.length]);"); + assert_eq!(out, [json!([false, 2])]); + assert!(!clips(&s)); + assert_eq!(kids(&s), [a, b]); + // A clipping layer emptied by `pageItems.removeAll()` releases its mask too. + let (mut s, _, _) = doc(); + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.active().unwrap().doc.layers[0].clips()); + log(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(!s.active().unwrap().doc.layers[0].clips()); +} + /// Choosing the artboard that is active only by default keeps that artboard: one inserted before it /// moves it to the next index, and the report gives that index. #[test] @@ -3792,6 +4276,62 @@ fn has_selected_artwork_charges_the_walk_when_nothing_is_added() { assert!(error.contains("passed more data"), "{error}"); } +/// Reading `hasSelectedArtwork` is charged for every selected object it looks at. +#[test] +fn has_selected_artwork_charges_the_selection_it_reads() { + let repeated = |n: usize| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + r + }; + repeated(1).unwrap(); + let error = repeated(200).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +/// While a group is isolated, `hasSelectedArtwork = true` selects the art inside the group, as +/// Select All does. +#[test] +fn has_selected_artwork_selects_inside_an_isolated_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": g})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true; vc.log(l.hasSelectedArtwork);"); + assert_eq!(out, [json!(true)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b), "{sel:?}"); +} + +/// While Lock Guides is on, a path made into a guide is not counted as art to add, so a selection +/// at the limit does not refuse a layer that holds only such a path. +#[test] +fn has_selected_artwork_skips_locked_guide_paths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0); + s.active_mut().unwrap().selection.objects = vec![other; 10_000]; + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_000); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); @@ -3891,6 +4431,41 @@ fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() { assert!(e.contains("at most 10000"), "{e}"); } +#[test] +fn has_selected_artwork_on_an_empty_layer_passes_a_full_selection() { + let (mut s, a, _) = doc(); + let n = crate::script::dom::MAX_LISTED; + // Each Duplicate of everything doubles the objects. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..n.ilog2() { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + assert!(s.active().unwrap().selection.objects.len() > n); + // The empty layer adds nothing, so the selection's size does not matter. + run(&mut s, "app.activeDocument.layers.add().hasSelectedArtwork = true;").unwrap(); + // A layer with an unselected object would take the selection past the limit. + s.execute("select.toggle", &json!({"ids": [a.0]})).unwrap(); + assert!(s.active().unwrap().selection.objects.len() > n); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").contains("at most")); + assert!(!s.active().unwrap().selection.objects.contains(&a)); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn artboards_insert_gives_undefined_and_index_reflects_an_artboard() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(typeof A.insert([500, 300, 700, 100], 0));\ + function info(o, n) { var m = o.reflect.methods; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType + ':' + m[i].arguments[0].dataType; }\ + function prop(o, n) { var m = o.reflect.properties; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType; }\ + vc.log(info(A, 'index')); vc.log(prop(app.activeDocument.pageItems, 'parent'));", + ); + assert_eq!(out, [json!("undefined"), json!("Artboard:*"), json!("*")]); +} + #[test] fn artboards_stop_at_one_hundred() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index ac1e9ca782..8fc2876981 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -287,6 +287,45 @@ fn a_file_that_is_not_an_image_is_refused_before_placing() { let _ = std::fs::remove_dir_all(base); } +/// How many times the engine read the file at `path` on this thread since the last call. +#[cfg(not(target_arch = "wasm32"))] +fn reads_of(path: &Path) -> usize { + let path = path.to_string_lossy(); + crate::cmd::fileio::FILES_READ.with(|r| r.take().iter().filter(|p| plain_path(p) == path).count()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn placing_or_relinking_from_a_script_reads_the_file_once() { + let base = folder("read-once"); + let (a, b) = (base.join("main/a.png"), base.join("main/b.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + let mut s = session(); + reads_of(&a); + log(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = new File('{}');", js_path(&a))); + assert_eq!(reads_of(&a), 1, "placing reads the file once"); + log(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&b))); + assert_eq!(reads_of(&b), 1, "relinking reads the file once"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn relinking_to_a_file_that_is_not_an_image_keeps_the_link() { + let base = folder("relink-text"); + let (a, notes) = (base.join("main/a.png"), base.join("main/notes.txt")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(¬es, "hello").unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let before = undo_steps(&s); + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(¬es))); + assert!(e.contains("The file is not an image") && !e.contains("notes.txt"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn placed_items_add_is_bounded() { let base = folder("pending"); @@ -497,6 +536,41 @@ fn a_stale_placed_item_is_not_a_relative_object() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn image_matrix_refuses_locked_hidden_and_locked_artboard_images() { + let base = folder("matrix-locks"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, true); + // A moved matrix and the matrix the image already has are refused alike. + let sets = [ + "var p = app.activeDocument.placedItems[0], m = p.matrix; m.mValueTX = m.mValueTX + 5; p.matrix = m;", + "var p = app.activeDocument.placedItems[0]; p.matrix = p.matrix;", + ]; + let refused = |s: &mut Session, message: &str| { + for set in sets { + let (was, before) = (s.active().unwrap().doc.clone(), undo_steps(s)); + let e = failure(s, &base, set); + assert!(e.contains(message), "{set}: {e}"); + assert_eq!(*s.active().unwrap().doc, *was, "{set}"); + assert_eq!(undo_steps(s), before, "{set}"); + } + }; + for (field, set_to, message) in [("locked", true, "cannot transform locked objects"), ("visible", false, "cannot transform hidden objects")] { + s.execute("object.setProps", &json!({"ids": [id.0], field: set_to})).unwrap(); + refused(&mut s, message); + s.execute("object.setProps", &json!({"ids": [id.0], field: !set_to})).unwrap(); + } + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + refused(&mut s, "cannot transform objects on a locked artboard"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn image_matrix_refuses_bad_values_without_changing_the_image() { let base = folder("matrix-bad"); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 3155d1e34f..1e4a123d09 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -50,6 +50,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node { s.active().unwrap().doc.node(id).unwrap().clone() } +#[test] +fn path_creation_replays_on_top_of_the_active_layer() { + for mode in ["behind", "inside", "isolation"] { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let setup = || { + let (mut s, a, b) = doc(); + if mode == "isolation" { + let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "{mode}: {create}"); + assert_eq!(replay.draw_mode, s.draw_mode); + assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation); + } + } +} + +#[test] +fn path_paint_edits_replay_without_changing_new_art() { + let (mut s, a, _) = doc(); + let start = s.journal.len(); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\ + app.activeDocument.pathItems.rectangle(100, 200, 20, 30);", + ); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(node(&replay, a).appearance, node(&s, a).appearance); + assert_eq!(art(&replay), art(&s)); + assert_eq!(replay.paint, s.paint); + assert_eq!(replay.fill_active, s.fill_active); + assert_eq!(replay.recent_colors, s.recent_colors); +} + +#[test] +fn mixed_anchor_and_segment_picks_keep_independent_anchors() { + for selected in ["ANCHORPOINT", "NOSELECTION"] { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\ + vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\ + p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);", + if selected == "ANCHORPOINT" { 1 } else { 3 } + ), + ); + assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]); + assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 })); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] })); + } +} + +#[test] +fn an_empty_path_keeps_closed_before_points_are_added() { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);", "p.setEntirePath([]);"] { + let (mut s, _, _) = doc(); + let start = s.journal.len(); + let out = log( + &mut s, + &format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"), + ); + assert_eq!(out, [json!(true), json!(true)]); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s)); + } +} + +#[test] +fn enabling_path_paint_preserves_the_new_art_color_model() { + for fill in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; + s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want); + } +} + /// Each number of `v` rounded to 3 decimals, in place. fn rounded(v: &Value) -> Value { match v { @@ -114,6 +222,23 @@ fn path_items_read_with_a_name_give_the_named_path() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); } +#[test] +fn path_items_read_non_index_numbers_as_names() { + for name in ["-1", "1.5", "4294967295"] { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap(); + let out = log( + &mut s, + &format!( + "var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\ + vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\ + vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');" + ), + ); + assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]); + } +} + /// `pathItems` read with a name that is the text of a number but not an array index, such as `-1` /// or `1.5`, gives the path of that name, and `undefined` when no path has it; `index` still takes /// a number as a position, as in `pageItems`. @@ -332,6 +457,354 @@ fn path_point_wrapper_goes_stale_after_remove() { ); } +#[test] +fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\ + var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\ + vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\ + vc.log(p.pathPoints[0].selected);", + ); + assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); + assert!(s.active().unwrap().selection.contains(b)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(s.active().unwrap().selection.contains(b)); + + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::>(), vec![(0, 1)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); +} + +#[test] +fn removing_a_point_replays_selection_before_moving_anchors() { + for segments in [false, true] { + let setup = || { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap(); + if segments { + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap(); + } else { + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + let a = s.active().unwrap().selection.objects[0]; + // The removed anchor's segments take their other ends with them unless a selected segment + // still ends there, so with segments the anchor after the removed one leaves the selection. + assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] })); + s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap(); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "segments: {segments}"); + assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}"); + } +} + +#[test] +fn removing_the_last_selected_point_of_a_path_keeps_the_current_layer() { + let (mut s, _, b) = doc(); + s.execute("layer.new", &json!({"name": "Top"})).unwrap(); + let c = rect(&mut s, 200.0, 50.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 1]], "mode": "add"})).unwrap(); + let (layer, rows) = { + let st = s.active().unwrap(); + (st.active_layer, st.highlighted_rows()) + }; + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();"); + let st = s.active().unwrap(); + assert!(!st.selection.contains(c) && st.selection.contains(b)); + assert_eq!(st.active_layer, layer); + assert_eq!(st.highlighted_rows(), rows); +} + +#[test] +fn emptying_an_unselected_path_keeps_the_targeted_layer() { + let (mut s, a, _) = doc(); + let layer = NodeId(s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert!(!s.active().unwrap().selection.contains(a)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints.removeAll();"); + assert_eq!(s.active().unwrap().selection.target, Some(layer)); +} + +#[test] +fn point_selection_reads_flush_removed_closing_segments() { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\ + p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\ + vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);", + ); + assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]); + assert_eq!(out[4], json!("PathPointSelection.NOSELECTION")); + } +} + +#[test] +fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { + for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let anchors = selected_anchors(&s, a); + let steps = undo_steps(&s); + let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}")); + assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] }); + assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed); + let selection = &s.active().unwrap().selection; + assert!(selection.contains(b)); + assert_eq!(selected_anchors(&s, a), anchors); + let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect(); + assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] }); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, a).path_data().unwrap().subpaths[0].closed); + } + } +} + +#[test] +fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = node(&s, a); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\ + p.name = 'changed'; vc.run('file.revert');\ + try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\ + var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\ + fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);" + ), + ); + assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}"); + assert_ne!(node(&s, a).path_data(), before.path_data()); + s.execute("file.revert", &json!({})).unwrap(); + } +} + +#[test] +fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { + let (mut s, a, _) = doc(); + s.execute( + "path.setAnchors", + &json!({"id": a.0, "subpaths": [ + {"anchors": [{"x": 0, "y": 0}]}, + {"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]} + ]}), + ) + .unwrap(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); + assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2)))); +} + +#[test] +fn locked_guides_refuse_path_edits_and_bulk_removal() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.pathPoints[0].anchor = [0, 0]", + "p.pathPoints[0].remove()", + "p.pathPoints.removeAll()", + "p.setEntirePath([[0, 0], [1, 1]])", + "p.closed = false", + "p.translate(1, 0)", + "p.filled = false", + "p.strokeWidth = 12", + "app.activeDocument.pathItems.removeAll()", + ] { + let out = + log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}"); + } + assert!(is_guide(&s, a)); + s.set_guides_locked(false); + log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);"); + assert_ne!(art(&s), before); +} + +#[test] +fn document_path_creators_use_the_active_layer_during_isolation() { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let (mut s, a, b) = doc(); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": group.0})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap(); + let before = node(&s, group); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let st = s.active().unwrap(); + let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap(); + assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}"); + assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}"); + assert_eq!(node(&s, group), before, "{create}"); + assert_eq!(st.isolation, Some(group), "{create}"); + assert_eq!(st.selection, selection, "{create}"); + assert_eq!(undo_steps(&s), steps + 1, "{create}"); + } +} + +#[test] +fn paint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + for unpainted in [false, true] { + let (mut s, a, _) = doc(); + if unpainted { + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); + } + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({ + "type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4" + }), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + let path = paths[0]; + s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.fillColor = c", + "p.strokeColor = c", + "p.filled = !p.filled", + "p.stroked = !p.stroked", + "p.strokeWidth = 12", + "p.strokeCap = StrokeCap.ROUNDENDCAP", + "p.strokeJoin = StrokeJoin.BEVELENDJOIN", + "p.strokeMiterLimit = 22", + "p.strokeDashes = [3, 4]", + ] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\ + try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}" + ), + ); + assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}"); + } + } + } +} + +#[test] +fn overprint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut s, a, _) = doc(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap(); + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap(); + let before = (art(&s), undo_steps(&s)); + for property in ["fillOverprint", "strokeOverprint"] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\ + try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);" + ), + ); + assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}"); + assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}"); + assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}"); + } + } +} + +#[test] +fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { + let (mut s, a, b) = doc(); + for i in 0..100 { + rect(&mut s, f64::from(i), 10.0, 2.0, 2.0); + } + let out = log( + &mut s, + &format!( + "var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\ + for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\ + for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\ + var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\ + vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\ + try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\ + paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\ + vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\ + try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}", + a = a.0, + b = b.0 + ), + ); + assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]); +} + #[test] fn points_read_before_a_removal_or_replacement_go_stale() { let (mut s, _, _) = doc(); @@ -1250,6 +1723,78 @@ fn locked_paths_and_wrong_objects_are_refused() { assert!(e.contains("not a PathPoint"), "{e}"); } +/// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing. +#[test] +fn point_edits_of_a_path_on_a_locked_artboard_are_refused() { + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = art(&s); + let steps = undo_steps(&s); + for source in [ + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", + "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];", + "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}"); + } + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +/// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a +/// later member call does not lose an assignment that returned. +#[test] +fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { + let (mut s, a, _) = doc(); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let far = crate::MAX_COORD * 1.5; + for source in [ + format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"), + format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"), + format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"), + ] { + let e = failure(&mut s, &source); + assert!(e.contains("outside the canvas"), "{source}: {e}"); + } + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\ + q.anchor = [45, 285];\ + try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\ + vc.log(q.anchor); vc.log(p.closed);" + ), + ); + assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]); + let after = node(&s, a).path_data().unwrap().subpaths.clone(); + assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays"); + assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); +} + +#[test] +fn transforms_refuse_moving_gradients_without_the_path() { + for transform in + ["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"] + { + let (mut s, a, b) = doc(); + s.execute( + "paint.setFill", + &json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)); + let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}"); + assert!( + out[1].as_str().unwrap().contains("Gradients different from") && out[1].as_str().unwrap().contains("not available yet"), + "{transform}: {out:?}" + ); + assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}"); + } +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); @@ -1676,3 +2221,25 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } + +/// A point change made before a call that fails and is put back, here a new document whose +/// profile cannot be read, is kept. +#[test] +fn a_point_change_before_a_failed_new_document_is_kept() { + let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let (mut s, a, _) = doc(); + s.attach_new_doc_profiles(dir.clone()); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let out = log( + &mut s, + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\ + try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }", + ); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(out, vec![json!("refused")]); + assert_eq!(s.documents().len(), 1); + assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept"); +} diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..ede881af0d 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -506,6 +506,57 @@ fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn a_tracing_saved_without_its_record_counts_artwork_added_through_its_paths() { + let base = folder("retrace-legacy-paths"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let held = members(&s, group); + // The script reaches the tracing's paths before the tracing itself. + let add = "var d = app.activeDocument, p = d.pathItems[0], r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.name = 'added'; r.move(p, ElementPlacement.PLACEBEFORE);"; + let out = log(&mut s, &base, &format!("{add} {}", retrace_item(0))); + assert_eq!(out, [json!(ADDED_ARTWORK)]); + assert_eq!(members(&s, group).len(), held.len() + 1, "the added path stays in the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_again_after_a_revert() { + let base = folder("retrace-legacy-revert"); + let path = base.join("main/legacy.vectorcraft"); + for seen_first in [false, true] { + for added in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = members(&s, group); + s.execute("edit.clear", &json!({"ids": [held[held.len() - 1].0]})).unwrap(); + let seen = if seen_first { "var p = app.activeDocument.pageItems[0];" } else { "app.activeDocument.pathItems[0].name = 'x';" }; + let add = if added { + format!( + "var d = app.activeDocument, r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.move(d.pageItems[1], ElementPlacement.PLACEATEND); vc.run('file.saveAs', {{path: {}}}); r.name = 'after';", + json!(path.to_string_lossy()) + ) + } else { + String::new() + }; + let out = log(&mut s, &base, &format!("{seen} {add} vc.run('file.revert'); {}", retrace_item(0))); + // A revert keeps the snapshot taken before it. + let message = if added || seen_first { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "seen first: {seen_first}, added: {added}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn engine_trace_can_be_retraced_by_a_script() { let base = folder("retrace-engine-artwork"); @@ -1197,6 +1248,102 @@ fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// Deleting the clipping path of a clip group named as a tracing releases its mask, so `remove()` and +/// `textFrames.removeAll()` refuse it when an image would be left first in the released group. +#[test] +fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("release-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.rasterItems[0], d.pathItems.rectangle(10, 10, 20, 20)];\ + vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { d.pathItems[0].remove(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.clipped);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, t = d.textFrames.add(); t.contents = 'Clip';\ + d.selection = [d.rasterItems[0], t]; vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { g.textFrames.removeAll(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.textFrames.length);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(1)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// `textFrames.removeAll()` and `groupItems.removeAll()` on an ordinary group named as a tracing +/// refuse to leave an image first in it, before the document changes, and delete when another +/// object stays first. +#[test] +fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("remove-all-trace-name"); + let refused = json!("Only Image Trace can make a tracing"); + for (under, call) in [ + ("var u = d.textFrames.add(); u.contents = 'Under';", "g.textFrames.removeAll();"), + ("d.selection = [d.pathItems.rectangle(50, 50, 5, 5)]; vc.run('object.group'); var u = d.pageItems[0];", "g.groupItems.removeAll();"), + ] { + let (mut s, _) = session(&base, false); + // The group holds the type or group at the bottom and the image above it. + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; var p = d.pathItems.rectangle(10, 10, 20, 20); d.selection = [p]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; {under} u.move(g, ElementPlacement.PLACEATEND);\ + d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING); p.remove();" + ), + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, g = d.pageItems[0], m = ''; try {{ {call} m = 'done'; }} catch (e) {{ m = e.message; }} vc.log(m); vc.log(g.typename);" + ), + ); + assert_eq!(out, [refused.clone(), json!("GroupItem")], "{call}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{call}"); + assert_eq!(undo_steps(&s), steps, "{call}"); + assert!(traces(&s).is_empty()); + } + // With a rectangle left first, the type goes and the group stays an ordinary group. + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; var t = d.textFrames.add(); t.contents = 'Over';\ + t.move(g, ElementPlacement.PLACEATBEGINNING); d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);\ + g.textFrames.removeAll(); vc.log(g.textFrames.length); vc.log(g.pageItems.length); vc.log(g.typename);", + ); + assert_eq!(out, [json!(0), json!(2), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object /// its trace did not make, before the document changes. #[test] @@ -1271,6 +1418,22 @@ fn unimplemented_tracing_members_are_not_reported() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn new_group_at_the_bottom_of_a_tracing_is_refused() { + let base = folder("new-group-bottom"); + let (mut s, id) = session(&base, false); + let tid = NodeId(s.execute("imageTrace.make", &json!({"id": id.0})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let e = s.execute("object.newGroup", &json!({"parent": tid.0, "index": 0})).unwrap_err().to_string(); + assert!(e.contains("source image"), "{e}"); + assert_eq!(traces(&s), [tid]); + assert_eq!(undo_steps(&s), steps); + let g = NodeId(s.execute("object.newGroup", &json!({"parent": tid.0, "index": 1})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(traces(&s), [tid]); + assert_eq!(s.active().unwrap().doc.children(Some(tid)).unwrap()[1].id, g); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn retrace_keeps_the_tracing_opacity_and_blend_mode() { let base = folder("retrace-appearance"); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index d57d4570d5..f3aa67c361 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -130,6 +130,69 @@ fn resize_scales_about_the_center_and_line_widths_follow_their_argument() { assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}"); } +#[test] +fn a_line_width_of_the_scale_itself_keeps_a_path_stroke_within_1000_points() { + let (mut s, _, _) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 600;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["resize(200, 200, true, true, true, true, 200)", "transform(app.getScaleMatrix(200), true, true, true, true, 200)"] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains("more than 1000 points"), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A scale that keeps the weight within the limit still scales it. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.resize(150, 150, true, true, true, true, 150); vc.log(i.strokeWidth);"); + assert!(close(&numbers(&out[0]), &[900.0]), "{out:?}"); + + // The lower stroke must stay within the limit too. + let (mut s, a, _) = doc(); + s.execute("stroke.set", &json!({"id": a.0, "weight": 600})).unwrap(); + s.execute("appearance.addStroke", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 1;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(200, 200, true, true, true, true, 200);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + + // A nonfinite scale must not turn a zero-width stroke into NaN. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.strokeWidth = 0;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(1e202, 1e202, true, true, true, true, 1e202);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); +} + +#[test] +fn an_empty_path_takes_any_transformation_about_any_point() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.add();"); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.rotate(30); n.rotate(30, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(50, 200); n.resize(50, 50, true, true, true, true, 100, Transformation.BOTTOM);\ + n.transform(app.getRotationMatrix(45)); n.rotate(30, true, true, true, true, Transformation.DOCUMENTORIGIN);\ + vc.log(n.pathPoints.length);", + ); + assert_eq!(out, vec![json!(0)]); + // Its stroke weight still scales with the transformation. + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.strokeWidth = 10; n.resize(200, 200, true, true, true, true, 200); vc.log(n.strokeWidth);", + ); + assert!(close(&numbers(&out[0]), &[20.0]), "{out:?}"); + let e = failure(&mut s, "app.activeDocument.pathItems[0].rotate(30, true, true, true, true, 'x');"); + assert!(e.contains("Transformation value"), "{e}"); +} + #[test] fn transform_applies_a_matrix_record_about_the_center() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs new file mode 100644 index 0000000000..9e0d53c696 --- /dev/null +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -0,0 +1,1069 @@ +//! Rasterizing and capturing art from a script: `Document.rasterize`, `Document.imageCapture`, +//! `RasterizeOptions`, `ImageCaptureOptions` and `object.rasterize` with `ids` and `clipBounds`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// Fills the objects `ids` with `color` and takes their strokes off. +fn paint(s: &mut Session, ids: &[NodeId], color: &str) { + let ids: Vec = ids.iter().map(|i| i.0).collect(); + s.execute("paint.setFill", &json!({"ids": ids, "color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": ids, "none": true})).unwrap(); +} + +/// A 400 × 300 pt document with two rectangles without strokes: `a` at (10, 20) 30 × 40 pt, `b` at +/// (100, 100) 50 × 50 pt. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + paint(&mut s, &[a, b], "#ff0000"); + s.execute("select.none", &json!({})).unwrap(); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The size of each embedded image of the active document, in pixels. +fn images(s: &Session) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(i) = &n.kind { + out.push((i.width, i.height)); + } + }); + out +} + +/// A script that selects `b` and rasterizes `a` (the second and first page items: the list starts +/// with the topmost object). +const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[1], b = d.pageItems[0]; b.name = 'b'; d.selection = [b];"; + +#[test] +fn script_rasterize_explicit_sources_preserves_selection() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); vc.log(d.selection.length); vc.log(d.selection[0].name === 'b');\ + try {{ a.name; }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);" + ), + ); + assert_eq!(out, [json!("RasterItem"), json!(1), json!(true), json!("Stale page item"), json!(2)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + assert_eq!(st.selection.objects, vec![b], "the selection stays as it was"); + assert_eq!(undo_steps(&s), undo + 1, "one undo step"); +} + +#[test] +fn script_rasterize_defaults_override_document_raster_settings() { + let (mut s, ..) = doc(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72, "background": "transparent"})).unwrap(); + log(&mut s, &format!("{RASTERIZE_A} d.rasterize(a);")); + // 30 × 40 pt at 300 ppi, snapped out to whole pixels (at 72 ppi it would be about 30 × 40). + let [(w, h)] = images(&s)[..] else { panic!("one image: {:?}", images(&s)) }; + assert!((125..=126).contains(&w) && (167..=168).contains(&h), "300 ppi, the help page's default, not the document's 72: {w} × {h}"); + let (mut s, ..) = doc(); + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 144; o.padding = 5; d.rasterize(a, undefined, o);")); + assert_eq!(images(&s), vec![(80, 100)], "40 × 50 pt with the padding, at 144 ppi"); +} + +#[test] +fn script_rasterize_options_have_the_help_page_defaults() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var o = new RasterizeOptions(); vc.log([o.typename, o.antiAliasingMethod, o.backgroundBlack, o.clippingMask, o.colorModel, \ + o.convertSpotColors, o.convertTextToOutlines, o.includeLayers, o.padding, o.resolution, o.transparency]);\ + var c = new ImageCaptureOptions(); vc.log([c.typename, c.antiAliasing, c.matte, c.matteColor.red, c.matteColor.green, \ + c.matteColor.blue, c.resolution, c.transparency]); vc.log([AntiAliasingMethod.TYPEOPTIMIZED, RasterizationColorModel.BITMAP]);", + ); + let rasterize = json!([ + "RasterizeOptions", + "AntiAliasingMethod.ARTOPTIMIZED", + false, + false, + "RasterizationColorModel.DEFAULTCOLORMODEL", + false, + false, + false, + 0, + 300, + false + ]); + assert_eq!(out[0], rasterize); + assert_eq!(out[1], json!(["ImageCaptureOptions", false, false, 255, 255, 255, 150, false])); + assert_eq!(out[2], json!(["AntiAliasingMethod.TYPEOPTIMIZED", "RasterizationColorModel.BITMAP"])); +} + +#[test] +fn script_rasterize_clip_mask_returns_image_child() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.clippingMask = true; var r = d.rasterize([a], null, o); vc.log([r.typename, r.parent.typename]);" + ), + ); + assert_eq!(out, [json!(["RasterItem", "GroupItem"])]); +} + +#[test] +fn script_rasterize_clip_bounds_cut_the_image() { + let (mut s, ..) = doc(); + // The left half of `a`: x 10 to 25, and its whole height (y 280 to 240, Y up). + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; d.rasterize(a, [10, 280, 25, 240], o);")); + assert_eq!(images(&s), vec![(15, 40)]); +} + +/// A clip rectangle that ends partway through a pixel keeps partial coverage in the image's last +/// column and row. +#[test] +fn script_rasterize_fractional_clip_bounds_stay_inside_the_rectangle() { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; o.transparency = true; d.rasterize(a, [10, 280, 25.5, 240.5], o);" + ), + ); + assert_eq!(images(&s), vec![(16, 40)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + assert_eq!(pixels.get_pixel(14, 20)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(15, 20)[3]), "the last column keeps only its in-bounds coverage"); + assert_eq!(pixels.get_pixel(7, 38)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(7, 39)[3]), "the last row keeps only its in-bounds coverage"); +} + +/// A clip rectangle from a fractional origin that spans whole pixels keeps every one of them, +/// though the subtraction of its edges is not exact. +#[test] +fn script_rasterize_clip_bounds_from_a_fractional_origin_keep_whole_pixels() { + for (left, right, width, partial) in [(10.4, 10.7, 3, false), (10.1, 10.4, 3, false), (10.4, 10.75, 4, true)] { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [{left}, 280, {right}, 240], o);" + ), + ); + assert_eq!(images(&s), vec![(width, 400)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let alpha = pixels.get_pixel(width - 1, 200)[3]; + if partial { + assert!((1..255).contains(&alpha), "the last column keeps only its in-bounds coverage"); + } else { + assert_eq!(alpha, 255, "the whole boundary pixel stays opaque"); + } + } +} + +#[test] +fn script_rasterize_rejects_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The clipping path is `b`, the topmost of the two. + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [b.0]})).unwrap_err().to_string(); + assert!(e.contains("is a clipping path"), "{e}"); + assert_eq!(undo_steps(&s), undo, "a refused clipping path adds no undo step"); + s.execute("object.rasterize", &json!({"ids": [a.0]})).unwrap(); +} + +/// The new `RasterItem` is bound to the image's exact id, also for an id above 2^53, which a +/// script number does not hold exactly. +#[test] +fn script_rasterize_binds_an_image_id_above_two_to_the_53() { + let (mut s, a, _) = doc(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log(&mut s, &format!("{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); r.name = 'img';")); + assert_eq!(out, [json!("RasterItem")]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + let mut named = Vec::new(); + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + named.push((n.id, n.name.clone())); + } + }); + assert_eq!(named.len(), 1, "{named:?}"); + assert!(named[0].0.0 > 1u64 << 53, "{named:?}"); + assert_eq!(named[0].1.as_deref(), Some("img"), "the item names the image itself"); +} + +/// The image takes the place of the last object, so objects in different clipping contexts are +/// refused before anything changes. +#[test] +fn script_rasterize_rejects_sources_clipped_differently() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 20.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [c.0, a.0]})).unwrap_err().to_string(); + assert!(e.contains("is clipped differently"), "{e}"); + assert!(*before == *s.active().unwrap().doc, "a refused call leaves the document as it was"); + assert_eq!(undo_steps(&s), undo); + assert!(s.active().unwrap().doc.node(c).is_some(), "the unclipped object stays"); +} + +#[test] +fn script_rasterize_disposes_several_sources_in_one_step() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log(&mut s, "var d = app.activeDocument; var r = d.rasterize([d.pageItems[1], d.pageItems[0]]); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(1)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none() && st.doc.node(b).is_none()); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// Each bad call throws and leaves the document as it was, with no undo step. +fn refused(s: &mut Session, source: &str, message: &str) { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(s); + let e = failure(s, source); + assert!(e.contains(message), "{source}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc) || *before == *s.active().unwrap().doc, "{source} changed the document"); + assert_eq!(undo_steps(s), undo, "{source} added an undo step"); +} + +#[test] +fn script_rasterize_rejects_other_documents_art() { + let (mut s, ..) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 10.0, 10.0); + refused(&mut s, "app.documents[0].rasterize(app.documents[1].pageItems[0]);", "The source art must be in this document"); +} + +#[test] +fn script_rasterize_rejects_listed_twice() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[0]]);", "listed twice"); +} + +#[test] +fn script_rasterize_rejects_locked_art() { + let (mut s, ..) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].locked = true;"); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); +} + +#[test] +fn script_rasterize_rejects_groups_with_locked_descendants() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [inner, c.0]})).unwrap(); + let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "locked": true})).unwrap(); + for id in [inner, outer] { + let before = s.active().unwrap().doc.clone(); + let selection = s.active().unwrap().selection.objects.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(s.active().unwrap().selection.objects, selection); + assert_eq!(undo_steps(&s), undo); + } + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); + s.execute("object.setProps", &json!({"id": a.0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap(); +} + +#[test] +fn rasterize_rejects_explicit_hidden_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"id": group, "visible": false})).unwrap(); + for id in [a.0, b.0] { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("hidden"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + } + s.execute("object.setProps", &json!({"id": a.0, "visible": true})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72})).unwrap(); +} + +#[test] +fn rasterize_rejects_explicit_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap_err().to_string(); + assert!(e.contains("locked artboard"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked artboard"); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap(); +} + +#[test] +fn script_rasterize_logs_a_missing_image_warning() { + let (mut s, ..) = doc(); + let id = super::menucmds::place_undecodable_png(&mut s); + let out = run(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);").unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("rasterize: ") && s.contains("couldn't be decoded")), "{out}"); + assert_eq!(out["log"], json!(["RasterItem"])); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn image_capture_logs_a_missing_image_warning() { + let base = folder("warning"); + let (mut s, dir) = capture_doc(&base); + let id = super::menucmds::place_undecodable_png(&mut s); + let before = s.active().unwrap().doc.clone(); + let out = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("capture.png")))).unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("imageCapture: ") && s.contains("couldn't be decoded")), "{out}"); + assert!(dir.join("capture.png").is_file()); + assert!(s.active().unwrap().doc.node(id).is_some()); + assert_eq!(*s.active().unwrap().doc, *before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_rasterize_rejects_art_inside_listed_art() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[1]]);", "which is listed too"); +} + +#[test] +fn script_rasterize_rejects_a_compound_path_member() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The page items are the compound path, then its two paths. + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[1]);", "part of a compound path"); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);"); + assert_eq!(out, [json!("RasterItem")], "the compound path itself is rasterized"); +} + +#[test] +fn script_rasterize_rejects_stale_and_missing_sources() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument, a = d.pageItems[0]; a.remove(); d.rasterize(a);", "Stale page item"); + refused(&mut s, "app.activeDocument.rasterize([]);", "at least one page item"); + refused(&mut s, "app.activeDocument.rasterize();", "needs the source art"); + refused(&mut s, "app.activeDocument.rasterize(5);", "not a page item"); + let many = "var d = app.activeDocument, l = []; for (var i = 0; i < 10001; i++) l.push(d.pageItems[0]); d.rasterize(l);"; + refused(&mut s, many, "at most 10000 objects"); +} + +#[test] +fn script_rasterize_rejects_bad_options() { + let (mut s, ..) = doc(); + let cases = [ + ("var o = new RasterizeOptions(); o.resolution = 71;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = 2401;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = NaN;", "finite number"), + ("var o = new RasterizeOptions(); o.resolution = Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.padding = 1001;", "from 0 to 1000"), + ("var o = new RasterizeOptions(); o.padding = -Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.antiAliasingMethod = 'smooth';", "AntiAliasingMethod value"), + ("var o = new RasterizeOptions(); o.colorModel = AntiAliasingMethod.None;", "RasterizationColorModel value"), + ("var o = new RasterizeOptions(); o.clippingMask = 1;", "true or false"), + ("var o = new RasterizeOptions(); o.convertTextToOutlines = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.includeLayers = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.convertSpotColors = true;", "not available yet"), + ("var o = new ImageCaptureOptions();", "RasterizeOptions object"), + ("var o = {resolution: 300};", "RasterizeOptions object"), + ]; + for (options, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; {options} d.rasterize(d.pageItems[0], undefined, o);"), message); + } +} + +#[test] +fn script_rasterize_rejects_bad_clip_bounds() { + let (mut s, ..) = doc(); + let cases = [ + ("[25, 280, 10, 240]", "right edge right of its left edge"), + ("[10, 240, 25, 280]", "bottom edge below its top edge"), + ("[10, 280, 25]", "four numbers"), + ("[10, 280, 25, NaN]", "finite number"), + ("[10, 280, 25, 1e300]", "outside the canvas"), + ("[300, 20, 350, 10]", "does not overlap the art"), + ("'all'", "four numbers"), + ]; + for (bounds, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[1], {bounds});"), message); + } + // `a` spans x 10 to 40: a rectangle at x 42 to 48 reaches only the 10 pt padding around it. + refused( + &mut s, + "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[1], [42, 280, 48, 240], o);", + "does not overlap the art", + ); +} + +#[test] +fn object_rasterize_refuses_clip_bounds_between_the_sources() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + // The rectangle lies inside the box around `a` and `b` but reaches neither of them. + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [55, 45, 65, 55]})).unwrap_err().to_string(); + assert!(e.contains("does not overlap the art"), "{e}"); + assert_eq!(undo_steps(&s), undo, "no edit"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); + // A rectangle that reaches only `a` is still accepted. + s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [30, 30, 65, 55]})).unwrap(); + assert_eq!(images(&s).len(), 1); +} + +#[test] +fn script_rasterize_rejects_an_image_past_the_size_limit() { + let (mut s, ..) = doc(); + let source = "var d = app.activeDocument, b = d.pageItems[0]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; + let e = failure(&mut s, source); + assert!(e.contains("too large"), "{e}"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); +} + +#[test] +fn object_rasterize_with_ids_keeps_the_selection_and_names_the_image() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let r = s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72, "clippingMask": true})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.selection.objects, vec![b]); + let (id, image) = (NodeId(r["id"].as_u64().unwrap()), NodeId(r["imageId"].as_u64().unwrap())); + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. })); + assert!(matches!(st.doc.node(image).unwrap().kind, NodeKind::Image(_))); + assert_eq!(st.doc.parent_of(image), Some(id)); + let r = s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + assert_eq!(r["id"], r["imageId"], "without a clip group the image is the new object"); + assert_eq!(s.active().unwrap().selection.objects, vec![NodeId(r["id"].as_u64().unwrap())], "the selection is rasterized as before"); +} + +// ---- imageCapture ---- + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-capture-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// [`doc`] in a session whose scripts keep their data folders in `base`, and the data folder, where +/// scripts may write. +fn capture_doc(base: &Path) -> (Session, PathBuf) { + let (mut s, ..) = doc(); + s.attach_script_data(base.join("settings/Script Data")); + let dir = PathBuf::from(script(&mut s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()); + (s, dir) +} + +/// Runs `main/main.jsx` in `base` with the text `text`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + // Reading `Folder.userData` makes the data folder, where the script may write. + std::fs::write(&main, format!("Folder.userData; {text}").as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn script(s: &mut Session, base: &Path, text: &str) -> Vec { + run_file(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].as_array().cloned().unwrap_or_default() +} + +fn file_failure(s: &mut Session, base: &Path, text: &str) -> String { + run_file(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +/// The PNG at `path`, decoded by the `image` crate, as RGBA. +fn png(path: &Path) -> image::RgbaImage { + let bytes = std::fs::read(path).unwrap(); + assert!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG signature"); + image::load_from_memory_with_format(&bytes, image::ImageFormat::Png).unwrap().to_rgba8() +} + +#[test] +fn image_capture_whole_artwork_including_pasteboard() { + let base = folder("whole"); + let (mut s, dir) = capture_doc(&base); + // A third rectangle off the artboard, left of it: the art spans x -90 to 150 and y 20 to 150. + let c = rect(&mut s, -90.0, 30.0, 20.0, 20.0); + paint(&mut s, &[c], "#0000ff"); + // The capture's own 150 ppi applies, not the document's raster effects resolution. + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let undo = undo_steps(&s); + let out = script( + &mut s, + &base, + &format!("var r = app.activeDocument.imageCapture(new File({})); vc.log(r === undefined);", quoted(&dir.join("all.png"))), + ); + assert_eq!(out, [json!(true)]); + let img = png(&dir.join("all.png")); + assert_eq!((img.width(), img.height()), (500, 271), "240 × 130 pt at 150 ppi"); + assert_eq!(img.get_pixel(5, 30).0, [0, 0, 255, 255], "the art off the artboard is there"); + assert_eq!(img.get_pixel(499, 0).0, [255, 255, 255, 255], "white where there is no art"); + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_capture_exact_clip_bounds_and_matte() { + let base = folder("clip"); + let (mut s, dir) = capture_doc(&base); + // x 0 to 50 and y 300 to 250 (Y up): the top-left corner of the artboard, with `a` in it. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.matte = true; o.matteColor = {{red: 0, green: 128, blue: 0}}; d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.transparency = true; d.imageCapture(new File({}), [0, 300, 50, 250], o);", + f("white.png"), + f("matte.png"), + f("clear.png") + ); + script(&mut s, &base, &source); + for (name, blank) in [("white.png", [255, 255, 255, 255]), ("matte.png", [0, 128, 0, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.get_pixel(2, 2).0, blank, "{name}: the area without art"); + assert_eq!(img.get_pixel(20, 30).0, [255, 0, 0, 255], "{name}: the art"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// `imageCapture` rounds fractional clip dimensions to the nearest whole pixel, as +/// `document.export` does, where `rasterize` rounds them up. +#[test] +fn image_capture_rounds_fractional_clip_dimensions_to_the_nearest_pixel() { + let base = folder("nearest"); + let (mut s, dir) = capture_doc(&base); + let source = format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 300, 10.25, 289.75], o);", + quoted(&dir.join("n.png")) + ); + script(&mut s, &base, &source); + let img = png(&dir.join("n.png")); + assert_eq!((img.width(), img.height()), (10, 10), "10.25 pt at 72 ppi"); + let _ = std::fs::remove_dir_all(base); +} + +/// Bounds that miss every object still give an image of that area, blank or transparent. +#[test] +fn image_capture_of_bounds_without_art_is_blank() { + let base = folder("empty"); + let (mut s, dir) = capture_doc(&base); + // x 300 to 350 and y 100 to 50 (Y up): below and right of both rectangles. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [300, 100, 350, 50], o);\ + o.transparency = true; d.imageCapture(new File({}), [300, 100, 350, 50], o);", + f("blank.png"), + f("clear.png") + ); + let undo = undo_steps(&s); + script(&mut s, &base, &source); + for (name, blank) in [("blank.png", [255, 255, 255, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.pixels().len(), 2500, "{name}"); + assert!(img.pixels().all(|p| p.0 == blank), "{name}: every pixel is {blank:?}"); + } + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_64mp_and_side_limit_before_render() { + let base = folder("huge"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("huge.png"); + // 4000 × 4000 pt at 2400 ppi is far past 64 megapixels; 40,000 × 1 pt at 72 ppi is past 32,768 a side. + let cases = [ + format!( + "var o = new ImageCaptureOptions(); o.resolution = 2400; app.activeDocument.imageCapture(new File({}), [0, 4000, 4000, 0], o);", + quoted(&target) + ), + format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 1, 40000, 0], o);", + quoted(&target) + ), + ]; + for case in &cases { + let e = file_failure(&mut s, &base, case); + assert!(e.contains("64 megapixels"), "{case}: {e}"); + } + assert!(!target.exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_bad_options_and_names() { + let base = folder("bad"); + let (mut s, dir) = capture_doc(&base); + let png = quoted(&dir.join("x.png")); + let cases = [ + ( + format!("var o = new ImageCaptureOptions(); o.resolution = 50; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "from 72 to 2400", + ), + ( + format!("var o = new ImageCaptureOptions(); o.resolution = Infinity; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "finite number", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: NaN, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "finite number", + ), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 300, Infinity, 250]);"), "finite number"), + ( + format!("var o = new ImageCaptureOptions(); o.matte = 'yes'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "true or false", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: 300, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "from 0 to 255", + ), + ( + format!("var o = new ImageCaptureOptions(); o.matteColor = 'red'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "RGBColor", + ), + (format!("app.activeDocument.imageCapture(new File({png}), undefined, new RasterizeOptions());"), "ImageCaptureOptions object"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("x.tif"))), "ends with .png"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join(".png"))), "ends with .png"), + ("app.activeDocument.imageCapture('x.png');".to_string(), "needs a File"), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 0, 0, 0]);"), "right edge right of its left edge"), + (format!("app.activeDocument.windowCapture(new File({}), [100, 100]);", quoted(&dir.join("w.tif"))), "not available yet"), + ]; + for (case, message) in &cases { + let e = file_failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(message), "{case}: {e}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.path().extension().is_some())).count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +/// A second hard link to an open document's file names the same file, so a capture to it is refused. +#[test] +fn capture_refuses_a_hard_link_to_an_open_document() { + let base = folder("hard-link"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + let alias = dir.join("alias.png"); + if std::fs::hard_link(&source, &alias).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&alias).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a capture never writes over a file with other hard links, which an in-place write would +/// change under every name. +#[cfg(unix)] +#[test] +fn capture_refuses_a_file_with_other_hard_links() { + let base = folder("other-links"); + let (mut s, dir) = capture_doc(&base); + let other = dir.join("other.bin"); + std::fs::write(&other, b"kept").unwrap(); + let alias = dir.join("alias.png"); + std::fs::hard_link(&other, &alias).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("other hard links"), "{e}"); + assert_eq!(std::fs::read(&other).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// A destination that becomes a second name of an open document's file after the capture's checks, +/// while the art renders, is refused as the export commits its file. +#[test] +fn capture_refuses_a_destination_linked_to_an_open_document_during_the_export() { + let base = folder("rebind"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let target = dir.join("late.png"); + let probe = dir.join("probe-link"); + if std::fs::hard_link(&source, &probe).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + std::fs::remove_file(&probe).unwrap(); + let (from, to) = (source.clone(), target.clone()); + crate::script::dom::BEFORE_CAPTURE_EXPORT.with(|f| *f.borrow_mut() = Some(Box::new(move || std::fs::hard_link(&from, &to).unwrap()))); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept", "the late link is left as it was"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a destination whose real path is not valid UTF-8 is refused before anything is written, +/// rather than written under a name with its bytes replaced. +#[cfg(unix)] +#[test] +fn capture_refuses_a_destination_that_is_not_utf8() { + use std::os::unix::ffi::OsStrExt; + let base = folder("non-utf8"); + let (mut s, dir) = capture_doc(&base); + let odd = dir.join(std::ffi::OsStr::from_bytes(b"odd\xff")); + if std::fs::create_dir(&odd).is_err() { + // The volume refuses names that are not UTF-8. + let _ = std::fs::remove_dir_all(base); + return; + } + // A link with a UTF-8 name that leads into the folder whose name is not. + let link = dir.join("plain"); + std::os::unix::fs::symlink(&odd, &link).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&link.join("x.png")))); + assert!(e.contains("not valid UTF-8"), "{e}"); + assert_eq!(std::fs::read_dir(&odd).unwrap().count(), 0, "nothing written"); + assert!(!dir.join("odd\u{fffd}").exists(), "nothing written under the replaced name"); + let _ = std::fs::remove_dir_all(base); +} + +/// On macOS, whose volumes look names up in either Unicode normalization form, a missing linked +/// file's name in the other form is the linked file. +#[cfg(target_os = "macos")] +#[test] +fn capture_to_a_missing_links_name_in_the_other_normalization_form_writes_nothing() { + let base = folder("missing-nfd"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // The link's name is composed (NFC); the capture names it decomposed (NFD). + place_linked( + &mut s, + "cafe", + vectorcraft_doc::LinkInfo { path: "caf\u{e9}.png".into(), relative: Some("caf\u{e9}.png".into()), ..Default::default() }, + ); + let nfd = dir.join("cafe\u{301}.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&nfd))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!nfd.exists() && !dir.join("caf\u{e9}.png").exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_denied_or_source_path_writes_nothing() { + let base = folder("denied"); + let (mut s, dir) = capture_doc(&base); + let outside = base.join("outside/x.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&outside))); + assert!(e.contains(DENIED), "{e}"); + assert!(!outside.exists()); + // An open document whose file is named .png in the folder the script may write: its source. + let source = dir.join("source.png"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&source))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + // An image linked by a path relative to the document's folder, not to the working directory. + let linked = dir.join("linked.png"); + std::fs::write(&linked, b"kept").unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "linked.png".into(), relative: Some("linked.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&linked))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&linked).unwrap(), b"kept"); + // An image linked only from a symbol's art, outside the layers. + let in_symbol = dir.join("in-symbol.png"); + std::fs::write(&in_symbol, b"kept").unwrap(); + s.edit("Symbol", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: in_symbol.to_string_lossy().into_owned(), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "symbol-pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + let art = vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))); + d.symbols.push(vectorcraft_doc::Symbol { name: "Mark".into(), art: std::sync::Arc::new(art), dynamic: false }); + Ok(()) + }) + .unwrap(); + let e = file_failure( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&in_symbol)), + ); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&in_symbol).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_to_a_missing_links_path_writes_nothing() { + let base = folder("missing-link"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // An image linked by a path next to the document whose file is not there. + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "gone.png".into(), relative: Some("gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let gone = dir.join("gone.png"); + assert!(!gone.exists()); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&gone))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!gone.exists(), "nothing written"); + // The same name in other letter case is the linked file only where the volume ignores case. + std::fs::write(dir.join("probe.txt"), b"x").unwrap(); + let volume_ignores_case = dir.join("PROBE.TXT").exists(); + let upper = dir.join("GONE.png"); + let text = format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&upper)); + if volume_ignores_case { + assert!(file_failure(&mut s, &base, &text).contains("cannot write over an open document")); + assert!(!gone.exists(), "nothing written"); + } else { + script(&mut s, &base, &text); + assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); + // Two names for one file that differ only in case show that the folder keeps case. + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(sub.join("probe.txt"), b"x").unwrap(); + std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "sub-gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let sub_upper = sub.join("GONE.png"); + script(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&sub_upper))); + assert!(sub_upper.exists() && !sub.join("gone.png").exists()); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Places a linked image of the key `key` with `link` on the active document's default layer. +fn place_linked(s: &mut Session, key: &str, link: vectorcraft_doc::LinkInfo) { + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: key.into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); +} + +/// An untitled document opened from a template finds a link by its relative path from the +/// template's folder, so a capture there is refused, also when the file is missing. +#[test] +fn capture_to_a_templates_relative_link_writes_nothing() { + let base = folder("template-link"); + let (mut s, dir) = capture_doc(&base); + let st = s.active_mut().unwrap(); + st.path = None; + st.links_from = Some(dir.join("t.vctemplate").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale, relative: Some("pic.png".into()), ..Default::default() }); + let target = dir.join("pic.png"); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!target.exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +/// Two images that share a stale path and a content but keep different relative paths are each +/// looked for at their own relative path, so a capture over either one's file is refused. +#[test] +fn capture_over_either_relative_path_of_one_linked_content_writes_nothing() { + let base = folder("two-relatives"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + for relative in ["a.png", "b.png"] { + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale.clone(), relative: Some(relative.into()), ..Default::default() }); + } + for name in ["a.png", "b.png"] { + let target = dir.join(name); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{name}: {e}"); + assert!(!target.exists(), "{name}: nothing written"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A DCS image whose stored path is stale reads its plate files beside the main file its relative +/// path finds, so a capture over one of those is refused. +#[test] +fn capture_over_a_plate_beside_a_found_dcs_file_writes_nothing() { + use vectorcraft_doc::separated::{InkPlate, PlateFile, Separated}; + let base = folder("dcs-plate"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + std::fs::write(dir.join("main.eps"), b"main").unwrap(); + let plate = dir.join("cyan.png"); + std::fs::write(&plate, b"kept").unwrap(); + let separated = Separated::new(1, 1, vec![InkPlate { name: "Cyan".into(), cmyk: [1.0, 0.0, 0.0, 0.0], data: vec![255] }]).unwrap(); + let files = [PlateFile { name: "cyan.png".into(), size: 4, modified: 0 }]; + let blob = vectorcraft_doc::ImageBlob::separated_tiff(&separated, None, &files).unwrap(); + s.edit("Blob", |d, _| { + d.images.insert("dcs".into(), blob); + Ok(()) + }) + .unwrap(); + let stale = base.join("outside/gone/main.eps").to_string_lossy().into_owned(); + place_linked(&mut s, "dcs", vectorcraft_doc::LinkInfo { path: stale, relative: Some("main.eps".into()), ..Default::default() }); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&plate))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&plate).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// A document the interface opens while the run is paused is open too: a capture over its file is +/// refused. +#[test] +fn capture_over_a_document_opened_while_paused_writes_nothing() { + let base = folder("paused-open"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("opened.png"); + let main = base.join("main/main.jsx"); + let text = format!( + "Folder.userData; for (var i = 0; i < 2000000; i++) {{}}\ + try {{ app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]); vc.log('written'); }} catch (e) {{ vc.log(e.message); }}", + quoted(&target) + ); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + let svg = br#""#; + crate::cmd::fileio::open_bytes(&mut s, "opened.svg", svg, Some(target.to_string_lossy().into_owned())).unwrap(); + std::fs::write(&target, b"kept").unwrap(); + let r = loop { + if let Some(r) = s.script_pump() { + break r.unwrap(); + } + }; + s.script_frames = false; + let out = r["log"].as_array().cloned().unwrap_or_default(); + assert!(out.len() == 1 && out[0].as_str().is_some_and(|m| m.contains("cannot write over an open document")), "{out:?}"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_written_before_a_failure_is_reported() { + let base = folder("report"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("kept.png"); + let r = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({})); throw new Error('later');", quoted(&target))); + let e = r.unwrap_err().to_string(); + assert!(e.contains("later") && e.contains("kept.png"), "the failure names the file it wrote: {e}"); + assert!(target.is_file()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 11bcd74225..3952955779 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,6 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), + // Names the app's own reference errors give a hint for: a script's own text keeps none. ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("throw new ReferenceError('BridgeTalk is not defined');", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 52fc48cf73..5a58964284 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -10,6 +10,54 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[cfg(unix)] +#[test] +fn save_as_uses_the_scripts_extension_before_following_a_link() { + let base = folder("save-link-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let target = dir.join("target.vectorcraft"); + let alias = dir.join("alias.svg"); + std::fs::write(&target, b"keep").unwrap(); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias))); + assert!(std::fs::read_to_string(&target).unwrap().contains(""), + ) + .unwrap(); + let capture = dir.join("existing.png"); + logged( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({})); app.open(new File({}));", quoted(&capture), quoted(&page)), + ); + let pixels = image::open(&capture).unwrap().to_rgb8(); + assert!(pixels.pixels().any(|p| p.0 == [255, 0, 0]), "existing art can still read its linked image"); + let mut images = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + images.push((im.width, im.height, im.link.as_ref().is_some_and(|l| l.hash.is_some()))); + } + }); + assert_eq!(images, [(64, 64, false)], "the new document cannot read the inherited link"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn export_file_logs_encoder_warnings() { let base = folder("export-warnings"); @@ -578,9 +678,9 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ - o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ + o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ - o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\ var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" @@ -594,7 +694,8 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format"); assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each"); - assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); + // The DXF writes six decimals. + assert!((dxf_widest(&a) - dxf_widest(&b) * 10.0).abs() < 1e-4, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); for name in ["c.dxf", "u.dxf"] { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); @@ -606,6 +707,34 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { let _ = std::fs::remove_dir_all(base); } +/// `unitScaleRatio` is a percentage: 100 writes the drawing at the size an option left out gives, +/// and 200 writes it twice as wide. +#[test] +fn an_autocad_unit_scale_ratio_is_a_percentage() { + let base = folder("autocad-ratio"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF;\n\ + d.exportFile(new File(dir + '/n'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/h'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 200; d.exportFile(new File(dir + '/t'), ExportType.AutoCAD, o);\n\ + vc.log(1);" + ), + ); + let width = |name: &str| dxf_widest(&std::fs::read_to_string(dir.join(name)).unwrap()); + let (n, h, t) = (width("n.dxf"), width("h.dxf"), width("t.dxf")); + assert!((h - n).abs() < 1e-6, "100 is full size: {h} and {n}"); + assert!((t - 2.0 * n).abs() < 1e-5, "200 is twice the size: {t} and {n}"); + let _ = std::fs::remove_dir_all(base); +} + /// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and /// an option the script changes applies over the preset. #[test] @@ -1071,6 +1200,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "at most 1000", ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 0.00001; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD.unitScaleRatio must be at least 0.0001", + ), ( format!( "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 2794e929b2..7b7bb91078 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -46,6 +46,17 @@ fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { } } +#[test] +fn character_color_attributes_reflect_as_color() { + let (mut s, _) = doc_with("color"); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\ + vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);", + ); + assert_eq!(out, [json!("Color"), json!("Color")]); +} + #[test] fn text_frames_add_point_area_and_path_type() { let mut s = Session::new(); @@ -252,6 +263,131 @@ fn setting_the_value_a_range_has_records_no_undo_step() { assert_eq!(undo_steps(&s), before); } +fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn character_attributes_paint_only_their_own_characters() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\ + var red = new RGBColor(); red.red = 255; b.fillColor = red;\ + var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\ + vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\ + vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);", + ); + let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}"); + assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given"); + assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill"); + assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke"); + let runs = paints(&s, id); + let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own"); + assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!(b.3 > 1.0); + assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}"); + assert!(undo_steps(&s) > before); + + let steps = undo_steps(&s); + log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step"); + log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();"); + assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away"); +} + +#[test] +fn stroke_weight_reads_back_in_document_points_on_scaled_type() { + let (mut s, id) = doc_with("abc"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);"); + assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}"); + let stored = paints(&s, id)[0].3; + assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}"); + let steps = undo_steps(&s); + log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has"); +} + +#[test] +fn bad_text_paint_is_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let runs = paints(&s, id); + for (src, want) in [ + ("r.fillColor = 'red';", "fillColor must be a color object"), + ("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"), + ("r.fillColor = new GradientColor();", "not available yet"), + ("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"), + ("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight must be a finite number"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(paints(&s, id), runs); +} + +#[test] +fn hidden_or_locked_type_is_not_edited() { + let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify), + _ => panic!("not text"), + }; + for hide in ["t.locked = true;", "t.hidden = true;"] { + for edit in [ + "r.characters[1].fillColor = red;", + "r.size = 30;", + "r.contents = 'xyz';", + "r.characters.add('!');", + "r.justification = Justification.CENTER;", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(r);", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(t);", + "var c = app.activeDocument.paragraphStyles.add('C'); c.paragraphAttributes.justification = Justification.CENTER; c.applyTo(r);", + ] { + // Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden. + let (mut s, id) = doc_with("abc"); + let before = state(&s, id); + let e = failure( + &mut s, + &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), + ); + assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + assert_eq!(state(&s, id), before, "{hide} {edit}"); + } + } +} + +#[test] +fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() { + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\ + var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", + ); + assert_eq!(plain(&s, id), "\u{1F600}!X"); + // Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's + // end joins the range. + assert_eq!(out, vec![json!(["!", "\u{1F600}!"])]); + // An empty range there sits after the character too, and styling it changes nothing. + let runs = paints(&s, id); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\ + var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);", + ); + assert_eq!(out, vec![json!(0)]); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); @@ -331,8 +467,13 @@ fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); let db = vectorcraft_text::FontDb::global(); - let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); - if !covers(from) || covers(to) { + // Both faces ship in assets/fonts: with the bundled fonts the test fails when either one is + // missing, and without them it is skipped. A lookup that falls back to another face counts + // as missing. + let regular = |family: &str| db.face(family, "Regular").filter(|f| f.family == family && f.style == "Regular"); + let faces = regular(from).zip(regular(to)); + assert!(faces.is_some() || !cfg!(feature = "bundled-fonts"), "{from} Regular or {to} Regular is not available"); + if !faces.is_some_and(|(source, dest)| source.covers(c) && !dest.covers(c)) { return; // Installed fonts of these names cover other characters. } let mut s = Session::new(); @@ -465,7 +606,7 @@ fn text_fonts_list_and_assign_fonts_by_name() { &format!( "var f = app.textFonts, m = '';\ try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ - try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" @@ -547,7 +688,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() { } // Empty contents add nothing; bad arguments throw before anything changes. let (mut s, id) = doc_with("ab"); - s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().unwrap()); let before = undo_steps(&s); // `textFrames` lists the topmost first, so the newer "other" is [0]. let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); @@ -558,12 +699,86 @@ fn collections_of_text_add_words_characters_and_paragraphs() { ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + // A range of a frame that is gone stays stale rather than of the wrong type. + ( + "var o = app.activeDocument.textFrames[1].characters[0]; app.activeDocument.textFrames[1].remove(); t.words.add('x', o)", + "Stale text range", + ), ] { let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, other), "other"); assert_eq!(plain(&s, id), "ab"); + // A range of a frame that was removed is stale, not of the wrong class. + let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);"); + assert!(e.contains("Stale text range"), "{e}"); + assert_eq!(plain(&s, id), "ab"); +} + +/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are +/// not changed. +#[test] +fn protected_type_and_paths_are_not_converted_or_edited() { + let (mut s, id) = doc_with("abc"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}")); + assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}"); + } + assert_eq!(plain(&s, id), "abc"); + assert_eq!(undo_steps(&s), steps); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] { + let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};")); + assert!(e.contains("Cannot edit PathItem"), "{call}: {e}"); + assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]); + } +} + +/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as +/// `pathItems.removeAll()` does. +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("ab"); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}"); + assert_eq!(plain(&s, id), "ab"); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]); +} + +/// Text added after a range that ends inside a character goes after the whole character, and the +/// range returned holds the added text. +#[test] +fn text_added_after_half_a_character_goes_after_it() { + let (mut s, id) = doc_with("a\u{1F600}b"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.characters[0]; r.length = 2;\ + var x = t.characters.add('X', r, ElementPlacement.PLACEAFTER); vc.log([x.start, x.contents]);", + ); + assert_eq!(out, vec![json!([3, "X"])]); + assert_eq!(plain(&s, id), "a\u{1F600}Xb"); } #[test] @@ -640,6 +855,120 @@ fn type_made_with_a_large_id_is_the_new_type() { assert_eq!(plain(&s, NodeId(big)), ""); } +/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a +/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type +/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current. +const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\ + function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\ + put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\ + var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\ + var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\ + var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\ + function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }"; + +#[test] +fn a_layers_and_a_groups_text_frames_list_only_their_own_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + &format!( + "{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\ + vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\ + vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\ + vc.log(d.textFrames.length);" + ), + ); + assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"])); + assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"])); + assert_eq!(out[2], json!(["front", "back", true])); + assert_eq!(out[3], json!(6)); + // Type inside the layer's group or sublayer is not the layer's own. + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');")); + assert!(e.contains("Not found"), "{e}"); +} + +#[test] +fn text_frames_of_a_layer_or_group_put_new_type_in_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap(); + let before = undo_steps(&s); + // The rectangle is in the first layer, which becomes `base`; `other` is current while the + // collections of `base` and `g` add type. + let out = log( + &mut s, + &format!( + "var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\ + var t = L0.textFrames.add(); t.name = 'added';\ + vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\ + var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\ + var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\ + g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);" + ), + ); + assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"])); + assert_eq!(out[1], json!(["g", "g-added"])); + assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"])); + // removeAll takes the group's own type and leaves the type inside its group. + assert_eq!(out[3], json!(["gg", "added,front,back"])); + assert_eq!(undo_steps(&s), before + 1); + // A locked layer and a hidden group take no new type, and the run changes nothing. + let before = undo_steps(&s); + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();")); + assert!(e.contains("hidden or locked"), "{e}"); + let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);")); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), before); +} + +/// `textFrames.removeAll()` on type that clips a group releases the mask, so the object above the +/// type stays an ordinary member and is not made the clipping path. +#[test] +fn text_frames_remove_all_releases_a_mask_the_type_clips() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let t = s.execute("text.create", &json!({"x": 20, "y": 100, "text": "clip", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b, t]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let first = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().first().map(|c| c.id); + assert_eq!(first(&s), Some(NodeId(t)), "the type is the clipping path"); + let steps = undo_steps(&s); + let out = log(&mut s, "app.activeDocument.textFrames.removeAll(); vc.log(app.activeDocument.groupItems[0].clipped);"); + assert_eq!(out, [json!(false)]); + let st = s.active().unwrap(); + assert!(!st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // The run is one undo step, and undoing it puts back both the type and its mask. + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(first(&s), Some(NodeId(t))); +} + +#[test] +fn text_create_puts_type_in_the_layer_or_group_it_names() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // A new layer is current, and a locked one takes no type. + let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap(); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let before = undo_steps(&s); + for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] { + assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before); + let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group))); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index 20144d4411..ab379c2f6c 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -989,6 +989,64 @@ fn linked(hex: &str, name: &str) -> Paint { Paint::Solid { color: Color::from_hex(hex).unwrap(), swatch: Some(name.into()), tint: 1.0 } } +#[test] +fn swatch_edits_record_only_renames_and_taking_empties_the_record() { + let mut s = session(); + let uid = s.active().unwrap().uid; + run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"})); + run(&mut s, "swatch.edit", json!({"name": "Teal", "color": "#009090"})); + assert!(s.take_swatch_renames().is_empty()); + run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Renamed teal"})); + assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Renamed teal".to_owned())]); + assert!(s.take_swatch_renames().is_empty()); +} + +#[test] +fn failed_batches_restore_pending_swatch_renames_after_eviction() { + let mut s = session(); + let uid = s.active().unwrap().uid; + run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"})); + run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Ink 0 letter"})); + let mut commands = Vec::new(); + for i in 0..=MAX_SWATCH_RENAMES { + commands.push(json!({"command": "swatch.edit", "params": {"name": format!("Ink {i} letter"), "newName": format!("Ink {} letter", i + 1)}})); + } + commands.push(json!({"command": "command.batch", "params": {"commands": []}})); + assert!(s.execute("command.batch", &json!({"commands": commands})).is_err()); + assert!(doc(&s).swatch("Ink 0 letter").is_some()); + assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Ink 0 letter".to_owned())]); + commands.pop(); + run(&mut s, "command.batch", json!({"commands": commands})); + let renames = s.take_swatch_renames(); + let expected: Vec<_> = (1..=MAX_SWATCH_RENAMES).map(|i| (uid, format!("Ink {i} letter"), format!("Ink {} letter", i + 1))).collect(); + assert_eq!(renames, expected, "only the newest renames remain, in order"); +} + +#[test] +fn swatch_rename_previews_leave_no_record_and_confirmation_records_once() { + let mut s = session(); + let uid = s.active().unwrap().uid; + run(&mut s, "swatch.new", json!({"name": "Teal", "color": "#008080"})); + s.begin_interaction("Swatch Options").unwrap(); + for name in ["Preview teal", "Replacement teal"] { + s.preview("swatch.edit", &json!({"name": "Teal", "newName": name})).unwrap(); + assert!(doc(&s).swatch(name).is_some()); + assert!(s.take_swatch_renames().is_empty()); + } + s.cancel_interaction().unwrap(); + assert!(doc(&s).swatch("Teal").is_some()); + assert!(s.take_swatch_renames().is_empty()); + + // Swatch Options cancels its preview and runs the confirmed edit again. + s.begin_interaction("Swatch Options").unwrap(); + s.preview("swatch.edit", &json!({"name": "Teal", "newName": "Renamed teal"})).unwrap(); + assert!(s.take_swatch_renames().is_empty()); + s.cancel_interaction().unwrap(); + run(&mut s, "swatch.edit", json!({"name": "Teal", "newName": "Renamed teal"})); + assert_eq!(s.take_swatch_renames(), vec![(uid, "Teal".to_owned(), "Renamed teal".to_owned())]); + assert!(s.take_swatch_renames().is_empty()); +} + #[test] fn editing_a_global_swatch_recolours_linked_art_in_one_step() { let mut s = session(); diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index 891e7a6ba0..7af09c95e8 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -489,6 +489,9 @@ fn malformed_docx_fails_cleanly() { let store = |files: &[(&str, &[u8])]| cmd::fileio::zip::store(files).unwrap(); let document = |body: &str| format!(r#"{body}"#); assert!(place(&mut s, "a.docx", b"Plain words, not a package").is_err(), "a .docx file that isn't a ZIP archive"); + // A .docx file that starts with a local file header and has no end record. + let e = place(&mut s, "a.docx", b"PK\x03\x04 and nothing after the first header").unwrap_err(); + assert!(e.contains("isn't a ZIP package"), "{e}"); let e = place(&mut s, "a.docx", &store(&[("readme.txt", b"x")])).unwrap_err(); assert!(e.contains("no main document part"), "{e}"); let e = place(&mut s, "a.zip", &store(&[("readme.txt", b"x")])).unwrap_err(); @@ -531,6 +534,29 @@ fn malformed_docx_fails_cleanly() { longer[central + 20..central + 24].copy_from_slice(&packed.to_le_bytes()); let e = place(&mut s, "a.docx", &longer).unwrap_err(); assert!(e.contains("damaged"), "{e}"); + // A file whose directory record sets the encryption flag (bit 0) or names a compression method other than stored + // or deflated, and an end record with the values that mean a ZIP64 record holds the real ones. + let words = || store(&[("word/document.xml", document("words").as_bytes())]); + let record = |zip: &[u8]| zip.windows(4).position(|w| w == 0x0201_4b50u32.to_le_bytes()).unwrap(); + let mut encrypted = words(); + let at = record(&encrypted); + encrypted[at + 8] |= 1; + let e = place(&mut s, "a.docx", &encrypted).unwrap_err(); + assert!(e.contains("`word/document.xml` in the Word document is encrypted"), "{e}"); + let mut method = words(); + let at = record(&method); + method[at + 10..at + 12].copy_from_slice(&99u16.to_le_bytes()); + let e = place(&mut s, "a.docx", &method).unwrap_err(); + assert!(e.contains("uses compression method 99"), "{e}"); + let mut zip64 = words(); + let end = zip64.len() - 22; + zip64[end + 10..end + 12].copy_from_slice(&0xFFFFu16.to_le_bytes()); + let e = place(&mut s, "a.docx", &zip64).unwrap_err(); + assert!(e.contains("uses ZIP64 records"), "{e}"); + // One paragraph more than placed type takes: a paragraph is written when the next one starts, so 100,002 + // paragraphs write 100,001. + let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document(&"".repeat(100_002)).as_bytes())])).unwrap_err(); + assert!(e.contains("too much text or formatting"), "{e}"); // Containers nested past the depth read are skipped, and a part nested deeper still is refused. let nested = |n: usize| { let deep = format!("{}deep{}", "".repeat(n), "".repeat(n)); @@ -549,6 +575,60 @@ fn malformed_docx_fails_cleanly() { assert_eq!(s.doc().unwrap().history.undo.len(), 2, "failed places leave no undo step"); } +#[test] +fn docx_parts_in_utf16_with_a_byte_order_mark_place_their_text() { + let mut s = session(); + let xml = format!(r#"Grüße 東京"#); + for (bom, le) in [([0xFF, 0xFE], true), ([0xFE, 0xFF], false)] { + let part = [&bom[..], &utf16(&xml, le)].concat(); + let zip = cmd::fileio::zip::store(&[("word/document.xml", &part[..])]).unwrap(); + let r = s.execute("file.place", &json!({"name": "a.docx", "dataBase64": vectorcraft_format::base64_encode(&zip)})).unwrap(); + assert_eq!(placed(&s, &r).0, "Grüße 東京", "little-endian: {le}"); + } +} + +/// A style's `w:basedOn` chain stops at a style already in it, and takes in at most 32 styles. +#[test] +fn docx_based_on_chains_stop_at_a_cycle_and_after_32_styles() { + let mut styles = String::from(concat!( + r#""#, + r#""#, + )); + // S0 is based on S1, S1 on S2, and so on to S32, the only one that sets a size. + for i in 0..32 { + styles += &format!(r#""#, i + 1); + } + styles += r#""#; + let para = |style: &str, text: &str| format!(r#"{text}"#); + let body = [para("A", "cycle"), para("S1", "thirty-two"), para("S0", "thirty-three"), "plain".into()].concat(); + let mut s = session(); + let r = s.execute("file.place", &json!({"name": "styles.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, &styles))})).unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("not type") }; + let size = |word: &str| t.runs.iter().find(|r| r.text.contains(word)).map(|r| r.style.size); + assert_eq!(t.paragraph_styles()[0].justify, vectorcraft_doc::Justify::Center, "A takes its own alignment"); + assert_eq!(size("cycle"), Some(20.0), "A takes the size of B, which is based on A"); + assert_eq!(size("thirty-two"), Some(20.0), "a chain of 32 styles takes in the last one"); + assert_ne!(size("thirty-three"), Some(20.0), "a chain of 33 styles leaves the last one out"); + assert_eq!(size("thirty-three"), size("plain")); +} + +/// Run containers and table rows nested more than 64 deep are left out; ones nested 60 deep are placed. +#[test] +fn docx_run_containers_and_table_rows_nested_past_the_depth_read_are_left_out() { + let wrap = |n: usize, open: &str, close: &str, inner: &str| format!("{}{inner}{}", open.repeat(n), close.repeat(n)); + let run = |text: &str| format!("{text}"); + let tagged = |n: usize, text: &str| wrap(n, "", "", &run(text)); + let row = |n: usize, text: &str| { + let tr = format!("{}", run(text)); + format!("{}", wrap(n, "", "", &tr)) + }; + let body = format!("{}{}{}{}{}", tagged(70, "deep "), tagged(60, "kept "), run("shallow"), row(70, "deep row"), row(60, "kept row")); + let mut s = session(); + let r = s.execute("file.place", &json!({"name": "nested.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, ""))})).unwrap(); + assert_eq!(placed(&s, &r).0, "kept shallow\nkept row"); +} + /// The bytes of the Prls `prls`: each sprm and its operand. fn prls(prls: &[(u16, &[u8])]) -> Vec { prls.iter().flat_map(|(sprm, op)| sprm.to_le_bytes().into_iter().chain(op.iter().copied())).collect() @@ -927,6 +1007,14 @@ fn malformed_doc_fails_cleanly() { assert!(e.contains("compound file structure is damaged"), "{e}"); let e = place(&mut s, "a.doc", &compound_file(&[("WordDocument", &[0; 900])])).unwrap_err(); assert!(e.contains("doesn't start with a file information block"), "{e}"); + // A WordDocument stream whose directory entry gives one byte more than 64 MB is refused from that length, before + // any of it is read. The stream length is at byte 120 of the entry, which starts with the stream's name. + let mut large = compound_file(&[("WordDocument", &[0; 4096])]); + let name = utf16("WordDocument", true); + let entry = large.windows(name.len()).position(|w| w == name).unwrap(); + large[entry + 120..entry + 128].copy_from_slice(&((64u64 << 20) + 1).to_le_bytes()); + let e = place(&mut s, "a.doc", &large).unwrap_err(); + assert!(e.contains("too large to place (its WordDocument stream holds more than 64 MB)"), "{e}"); let e = place(&mut s, "a.doc", &Word97 { nfib: 0x0065, ..words() }.build()).unwrap_err(); assert!(e.contains("Word 6.0 or Word 95"), "{e}"); let e = place(&mut s, "a.doc", &Word97 { flags: 0x0100, ..words() }.build()).unwrap_err(); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 656a5689f8..746537db05 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -356,6 +356,13 @@ fn slices_give_one_image_each_and_a_page() { assert_eq!(f.len(), n); let html = String::from_utf8(f[0].1.clone()).unwrap(); assert!(html.contains("Hi") && html.contains("background: #ffffff;") && html.contains("justify-content: center")); + // Over the matte, at the bottom right. + run(&mut s, "object.slice.options", json!({"background": "matte", "hAlign": "right", "vAlign": "bottom"})); + let f = files(&run(&mut s, "document.exportForWeb", json!({"output": "html", "matte": "#ffff00"}))); + let html = String::from_utf8(f[0].1.clone()).unwrap(); + let cell = html.lines().find(|l| l.contains("Hi")).unwrap_or_else(|| panic!("the No Image cell in {html}")); + assert!(cell.contains("background: #ffff00;"), "{cell}"); + assert!(cell.contains("justify-content: flex-end;") && cell.contains("align-items: flex-end;"), "{cell}"); // Selected slices only. run(&mut s, "object.slice.select", json!({"slices": [a]})); let f = files(&run(&mut s, "document.exportForWeb", json!({"slices": "selected"}))); @@ -367,6 +374,14 @@ fn slices_give_one_image_each_and_a_page() { assert_eq!(run(&mut s, "document.exportForWeb.preview", json!({}))["slices"], n - 1); let one_slice = run(&mut s, "document.exportForWeb.preview", json!({"slice": layout[0]["number"]})); assert_eq!((one_slice["width"].as_f64(), one_slice["height"].as_f64()), (layout[0]["width"].as_f64(), layout[0]["height"].as_f64())); + // An HTML Text slice: the type's text, escaped, with its lines joined by
. + let t = run(&mut s, "text.create", json!({"x": 20, "y": 150, "text": "A&B\nC"}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.make", json!({"ids": [t]})); + run(&mut s, "select.set", json!({"ids": [t]})); + run(&mut s, "object.slice.options", json!({"kind": "htmlText"})); + let f = files(&run(&mut s, "document.exportForWeb", json!({"output": "html"}))); + let html = String::from_utf8(f[0].1.clone()).unwrap(); + assert!(html.contains(">A&B
C"), "{html}"); } /// Save for Web writes the image of a slice named after a Windows device (`aux`, `NUL`, `COM1`…) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f0b519a664..05dde4c156 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1360,6 +1360,11 @@ impl Session { self.tool.busy() } + /// Whether a tool began or joined the active document's interaction. + pub fn interaction_joined_by_tool(&self) -> bool { + self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.tool_joined) + } + /// Is the pointer button held: was the last pointer event a press or a drag, not a release or a /// move? A tool that is busy while the button is not held is waiting between its clicks (the /// Dimension tool after its first point). @@ -1865,10 +1870,11 @@ impl Session { // The snapshot of the interaction open before, which the tool's drag then joins. let open = self.active().and_then(|st| st.interaction.as_ref()).map(|it| std::sync::Arc::as_ptr(&it.doc)); self.begin_interaction(&label)?; - if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) - && open != Some(std::sync::Arc::as_ptr(&it.doc)) - { - it.tool = true; + if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut()) { + it.tool_joined = true; + if open != Some(std::sync::Arc::as_ptr(&it.doc)) { + it.tool = true; + } } } Action::Preview(cmd, p) => { diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index bcc712e844..646e586400 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1072,6 +1072,9 @@ fn structured_junk() { ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), + ("addon.document.floodFillArtboards", json!({"artboards": [1e308, -1, null, u64::MAX], "color": [1e308]})), + ("addon.document.floodFillArtboards", json!({"all": true, "artboards": "x", "layer": {"name": 3}})), + ("addon.document.floodFillArtboards", json!({"color": {"c": f64::MAX, "m": -1e308, "y": 0, "k": 0}, "layer": "\u{0}"})), // Packaging Tools add-on. ("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})), ("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})), diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 9a6b736535..b833c5d07f 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -47,6 +47,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"), ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; @@ -150,7 +151,7 @@ const INSIDE: &[(&str, &str)] = &[ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ - textFrames= toString typename visible visible= zOrder zOrderPosition", + toString typename visible visible= zOrder zOrderPosition", ), ("Layers.", "prototype"), ("Layers.prototype.", "add constructor getByName index length parent removeAll toString typename"), @@ -158,7 +159,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "GroupItem.prototype.", "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ - rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", + rasterItems rasterItems= symbolItems symbolItems= textFrames", ), ("GroupItems.", "prototype"), ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll toString typename"), @@ -332,6 +333,11 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of rasterizing and the document's rasterize and window capture methods. + ("", "AntiAliasingMethod RasterizationColorModel"), + ("Document.prototype.", "rasterize windowCapture windowCapture="), + ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), + ("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"), // The enumerations of placed and raster items. ("", "ImageColorSpace RasterLinkState"), ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), @@ -450,12 +456,14 @@ const INSIDE: &[(&str, &str)] = &[ "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \ - duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + duplicate duplicate= end end= fillColor fillColor= firstLineIndent firstLineIndent= getLocalCharOverridesJSON \ + getLocalCharOverridesJSON= \ getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \ paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ - spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \ + spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= strokeColor strokeColor= \ + strokeWeight strokeWeight= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ verticalScale= words", ), @@ -468,9 +476,9 @@ const INSIDE: &[(&str, &str)] = &[ ("CharacterAttributes.", "prototype"), ( "CharacterAttributes.prototype.", - "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ - rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ - underline= verticalScale verticalScale=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphAttributes.", "prototype"), ( @@ -485,9 +493,9 @@ const INSIDE: &[(&str, &str)] = &[ ("CharacterStyleAttributes.", "prototype"), ( "CharacterStyleAttributes.prototype.", - "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ - rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ - underline= verticalScale verticalScale=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphStyles.", "prototype"), ("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"), @@ -523,12 +531,12 @@ const INSIDE: &[(&str, &str)] = &[ "StoryRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \ characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \ - contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \ + contents contents= deSelect deSelect= duplicate duplicate= end end= fillColor fillColor= getLocalCharOverridesJSON \ getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \ getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \ length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \ paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \ - strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ + strikeThrough= strokeColor strokeColor= strokeWeight strokeWeight= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ underline underline= verticalScale verticalScale= words", ), ("StoryCharacters.", "prototype"), @@ -557,10 +565,12 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// that have no members of their own, the color classes, and the save and export option classes. +/// that have no members of their own, the color classes, and the save, export, rasterize and image +/// capture option classes. const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \ MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \ - EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions \ + ImageCaptureOptions RasterizeOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 8c3b4ad12d..aaeb97ccf4 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -16261,6 +16261,281 @@ fn dynamic_symbols_and_their_instance_changes_survive_a_round_trip() { assert!(got[2].is_empty()); } +/// A document with one instance of dynamic symbol "Leaf", whose art is `art`, with changes `overrides`. +fn dynamic_instance_doc(art: impl FnOnce(&mut Document) -> Node, overrides: Vec) -> Document { + let mut doc = Document::new(200.0, 100.0); + let art = art(&mut doc); + doc.symbols.push(Symbol { dynamic: true, name: "Leaf".into(), art: Arc::new(art) }); + let layer = doc.layers[0].id; + let mut i = instance(&mut doc, "Leaf", Affine::translate((10.0, 10.0))); + i.extras_mut().symbol_overrides = overrides; + doc.insert(Some(layer), usize::MAX, i).unwrap(); + doc +} + +/// Exports `doc`, checks that its one instance is written as its art with [`writer::SYMBOL_ART`], and +/// returns the fills of the paths it reads back as and the opacities of all its objects. +fn dynamic_instance_as_art(doc: &Document) -> (Vec, Vec) { + let out = export_ai_editing(doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::SYMBOL_CHANGES), "{:?}", out.warnings); + let back = read_back(doc); + let kids = back.layers[0].children().unwrap(); + assert!(!kids.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "the instance stays live"); + let (mut fills, mut opacities) = (vec![], vec![]); + for k in kids { + vectorcraft_doc::swatches::walk_with_masks(k, &mut |n| { + opacities.push(n.opacity); + if matches!(n.kind, NodeKind::Path { .. }) { + fills.extend(n.appearance.items.iter().filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f.paint.clone()), + _ => None, + })); + } + }); + } + (fills, opacities) +} + +#[test] +fn a_dynamic_instance_whose_changed_part_follows_an_empty_path_is_written_as_its_art() { + let red = Color::rgb(1.0, 0.0, 0.0); + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + Node::group(doc.alloc_id(), vec![Arc::new(empty), Arc::new(sq)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![1], fill: Some(solid(red)), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn a_dynamic_instance_whose_art_loses_an_empty_path_after_the_changed_part_is_written_as_its_art() { + let red = Color::rgb(1.0, 0.0, 0.0); + let doc = dynamic_instance_doc( + |doc| { + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + Node::group(doc.alloc_id(), vec![Arc::new(sq), Arc::new(empty)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(red)), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn a_dynamic_instance_stays_live_when_an_empty_path_after_its_changed_part_moves_nothing() { + let red = Color::rgb(1.0, 0.0, 0.0); + let doc = dynamic_instance_doc( + |doc| { + let a = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let b = square(doc, Rect::new(20.0, 0.0, 30.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + Node::group(doc.alloc_id(), vec![Arc::new(a), Arc::new(b), Arc::new(empty)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(red)), ..Default::default() }], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + assert!(matches!(kids[0].kind, NodeKind::SymbolInstance { .. })); + assert_eq!(kids[0].extras().symbol_overrides, doc.layers[0].children().unwrap()[0].extras().symbol_overrides); +} + +#[test] +fn a_dynamic_instance_with_a_named_or_transparent_root_and_one_kept_child_is_written_as_its_art() { + for named in [true, false] { + let doc = dynamic_instance_doc( + |doc| { + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + let mut root = Node::group(doc.alloc_id(), vec![Arc::new(sq), Arc::new(empty)]); + if named { + root.name = Some("Branch".into()); + } else { + root.opacity = 0.5; + } + root + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let (fills, opacities) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); + if !named { + assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-3), "{opacities:?}"); + } + } +} + +#[test] +fn a_dynamic_instance_with_a_root_override_and_one_kept_child_is_written_as_its_art() { + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + let mut sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + sq.opacity = 0.5; + Node::group(doc.alloc_id(), vec![Arc::new(empty), Arc::new(sq)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() }], + ); + dynamic_instance_as_art(&doc); + let back = read_back(&doc); + fn path_opacities(n: &Node, parent: f32, out: &mut Vec) { + let opacity = parent * n.opacity; + if matches!(n.kind, NodeKind::Path { .. }) { + out.push(opacity); + } + for child in n.children().into_iter().flatten() { + path_opacities(child, opacity, out); + } + } + let mut opacities = vec![]; + for child in back.layers[0].children().unwrap() { + path_opacities(child, 1.0, &mut opacities); + } + assert_eq!(opacities.len(), 1, "{opacities:?}"); + assert!((opacities[0] - 0.25).abs() < 1e-3, "{opacities:?}"); +} + +#[test] +fn a_dynamic_instance_whose_override_targets_an_omitted_child_is_written_as_its_art() { + for nested in [false, true] { + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + let a = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let b = square(doc, Rect::new(20.0, 0.0, 30.0, 10.0), LEAF); + let root = Node::group(doc.alloc_id(), vec![Arc::new(empty), Arc::new(a), Arc::new(b)]); + if nested { Node::group(doc.alloc_id(), vec![Arc::new(root)]) } else { root } + }, + vec![vectorcraft_doc::SymbolOverride { + path: if nested { vec![0, 0] } else { vec![0] }, + fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), + ..Default::default() + }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 2, "{fills:?}"); + assert!(fills.iter().all(|f| *f == solid(LEAF)), "the squares keep their original fills: {fills:?}"); + } +} + +#[test] +fn a_dynamic_instance_with_a_root_note_and_one_kept_child_is_written_as_its_art() { + let doc = dynamic_instance_doc( + |doc| { + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + let mut root = Node::group(doc.alloc_id(), vec![Arc::new(sq), Arc::new(empty)]); + root.extras_mut().attrs = Some(Box::new(vectorcraft_doc::ObjectAttributes { note: "Branch note".into(), ..Default::default() })); + root + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn dynamic_instances_on_a_large_canvas_or_in_clipped_art_do_not_serialize_overrides() { + for clipped in [false, true] { + let o = vectorcraft_doc::SymbolOverride { fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }; + let mut doc = dynamic_instance_doc(|doc| square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), vec![o; 40_000]); + if clipped { + let layer = doc.layers[0].id; + let id = doc.layers[0].children().unwrap()[0].id; + let art = doc.remove(id).unwrap(); + let outline = square(&mut doc, Rect::new(0.0, 0.0, 15.0, 15.0), LEAF); + let clip = group(&mut doc, vec![outline], false); + let g = group(&mut doc, vec![clip, (*art).clone()], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + } else { + doc = on_large_canvas(doc); + } + writer::OVERRIDE_SERIALIZATIONS.with(|count| count.set(0)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + writer::OVERRIDE_SERIALIZATIONS.with(|count| assert_eq!(count.get(), 0)); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::SYMBOL_CHANGES), "{:?}", out.warnings); + } +} + +#[test] +fn a_live_dynamic_instance_serializes_its_overrides_once() { + let doc = dynamic_instance_doc( + |doc| square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), + vec![vectorcraft_doc::SymbolOverride { opacity: Some(0.5), ..Default::default() }], + ); + writer::OVERRIDE_SERIALIZATIONS.with(|count| count.set(0)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + writer::OVERRIDE_SERIALIZATIONS.with(|count| assert_eq!(count.get(), 1)); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + let got = &back.layers[0].children().unwrap()[0]; + assert!(matches!(got.kind, NodeKind::SymbolInstance { .. })); + assert_eq!(got.extras().symbol_overrides, doc.layers[0].children().unwrap()[0].extras().symbol_overrides); +} + +#[test] +fn a_dynamic_instance_stays_live_with_an_out_of_range_override_after_an_empty_path() { + let doc = dynamic_instance_doc( + |doc| { + let a = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let b = square(doc, Rect::new(20.0, 0.0, 30.0, 10.0), LEAF); + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + Node::group(doc.alloc_id(), vec![Arc::new(a), Arc::new(b), Arc::new(empty)]) + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![5], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + let got = &back.layers[0].children().unwrap()[0]; + assert!(matches!(got.kind, NodeKind::SymbolInstance { .. })); + assert_eq!(got.extras().symbol_overrides, doc.layers[0].children().unwrap()[0].extras().symbol_overrides); + assert!(vectorcraft_doc::symbol_overrides::part(&doc.symbols[0].art, &[5]).is_none()); + assert!(vectorcraft_doc::symbol_overrides::part(&back.symbols[0].art, &[5]).is_none()); +} + +#[test] +fn a_dynamic_instance_whose_changed_part_follows_an_empty_compound_path_is_written_as_its_art() { + let doc = dynamic_instance_doc( + |doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(LEAF), Paint::None, 1.0)); + let compound = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(empty)], rule: FillRule::EvenOdd }); + let sq = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let mut root = Node::group(doc.alloc_id(), vec![Arc::new(compound), Arc::new(sq)]); + root.name = Some("Branch".into()); + root + }, + vec![vectorcraft_doc::SymbolOverride { path: vec![1], fill: Some(solid(Color::rgb(1.0, 0.0, 0.0))), ..Default::default() }], + ); + let (fills, _) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); +} + +#[test] +fn a_dynamic_instance_whose_changes_pass_the_size_limit_is_written_as_its_art() { + let red = Color::rgb(1.0, 0.0, 0.0); + let o = vectorcraft_doc::SymbolOverride { fill: Some(solid(red)), opacity: Some(0.5), ..Default::default() }; + let doc = dynamic_instance_doc(|doc| square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), vec![o; 40_000]); + assert!(serde_json::to_vec(&doc.layers[0].children().unwrap()[0].extras().symbol_overrides).unwrap().len() > 1 << 20); + let (fills, opacities) = dynamic_instance_as_art(&doc); + assert_eq!(fills.len(), 1, "{fills:?}"); + assert_ne!(fills[0], solid(LEAF), "the square keeps its changed fill"); + assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-3), "{opacities:?}"); +} + #[test] fn static_symbols_write_no_dynamic_entries() { let mut doc = dynamic_doc(); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index b8ea88a1fd..020b7bd901 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -50,7 +50,7 @@ pub(super) use paints::{ }; pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; #[cfg(test)] -pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; +pub(super) use symbols::{MISSING_SYMBOL, OVERRIDE_SERIALIZATIONS, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] @@ -269,6 +269,7 @@ pub(super) struct Writer<'a> { /// Whether each symbol's art paints with a pattern, nested symbols included /// ([`Self::symbol_paints_pattern`]). patterned_symbols: HashMap, + symbol_omissions: HashMap<*const Node, symbols::OmissionFacts>, /// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over /// for each symbol's art). wrote_pattern: bool, @@ -289,6 +290,7 @@ pub(super) struct Writer<'a> { symbol_scales: HashMap, /// The entries a symbol's dictionary adds to its art's dictionary, and the art's id. root_entries: Option<(vectorcraft_doc::NodeId, String)>, + /// The override dictionary entries prepared by [`Self::live_instance`], and the instance's id. instance_entries: Option<(vectorcraft_doc::NodeId, String)>, /// The objects that may be written with an art style, as they were before baking, by id /// ([`styles::styled_objects`]). @@ -402,6 +404,7 @@ impl<'a> Writer<'a> { defining_symbols: vec![], pattern_symbols: HashMap::new(), patterned_symbols: HashMap::new(), + symbol_omissions: HashMap::new(), wrote_pattern: false, pattern_written: HashSet::new(), wrote_fixed: false, diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 72966faf81..c3249ed756 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -497,3 +497,60 @@ impl Writer<'_> { s.push_str("/End X!\n"); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A closed outline through `points`, each side a straight segment. + fn outline(points: &[(f64, f64)]) -> PathData { + let mut bp = kurbo::BezPath::new(); + for (i, &(x, y)) in points.iter().enumerate() { + if i == 0 { + bp.move_to((x, y)); + } else { + bp.line_to((x, y)); + } + } + bp.close_path(); + PathData::from_bezpath(&bp) + } + + fn assert_near(got: Option, want: (f64, f64)) { + let Some(got) = got else { panic!("no grid point") }; + assert!(got.distance(Point::new(want.0, want.1)) < 1e-9, "{got:?} is not {want:?}"); + } + + /// A top object with two segments on each side is written as a 2 × 2 grid whose middle point + /// blends the four sides' middles less the four corners. + #[test] + fn a_top_object_with_two_segments_a_side_gets_its_middle_point_from_the_sides() { + let path = outline(&[(30.0, 10.0), (100.0, 0.0), (170.0, 10.0), (180.0, 50.0), (170.0, 90.0), (100.0, 90.0), (30.0, 90.0), (30.0, 50.0)]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 2, 4, 6])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 2)); + // (100, 0) and (100, 90) halved, (30, 50) and (180, 50) halved, less the corners' mean. + assert_near(pts.get(4).map(|q| q.0), (105.0, 45.0)); + } + + /// Three segments across and two down: each middle point is weighted by its column across and + /// its row down, not the other way around. + #[test] + fn a_top_object_wider_than_it_is_tall_blends_by_column_across_and_row_down() { + let path = outline(&[ + (0.0, 0.0), + (40.0, -6.0), + (80.0, 4.0), + (120.0, 0.0), + (126.0, 40.0), + (120.0, 80.0), + (80.0, 86.0), + (40.0, 84.0), + (0.0, 80.0), + (-4.0, 40.0), + ]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 3, 5, 8])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 3)); + assert_near(pts.get(5).map(|q| q.0), (39.0 + 1.0 / 3.0, 39.0)); + assert_near(pts.get(6).map(|q| q.0), (82.0 + 2.0 / 3.0, 45.0)); + } +} diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index a616d748d1..41f9f0e7e2 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -1,7 +1,7 @@ //! Symbols: their definitions, the symbol list and their instances (see [`crate::ai_editing`] for //! the form). -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::fmt::Write; use vectorcraft_color::Paint; @@ -21,6 +21,11 @@ pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol"; pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides"; const MAX_OVERRIDES_BYTES: usize = 1 << 20; +#[cfg(test)] +thread_local! { + pub(in crate::ai_editing) static OVERRIDE_SERIALIZATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + pub(crate) fn hex_decode(s: &str) -> Option> { if !s.len().is_multiple_of(2) || s.len() / 2 > MAX_OVERRIDES_BYTES { return None; @@ -64,10 +69,73 @@ pub(super) fn redrawn(n: &Node) -> bool { } } +/// What leaving out a group's paths and compound paths without anchors ([`Writer::shape`]) does to +/// it in the editing data, worked out once for each group of a symbol's art. +pub(super) struct OmissionFacts { + /// The first omitted child's index. Overrides targeting this child or later children are unsafe. + first: Option, + /// A symbol root group with an omitted child and one kept child is treated as collapsing, + /// regardless of its state. + root_collapses: bool, +} + +impl OmissionFacts { + fn of(n: &Node) -> Self { + fn omitted(c: &Node) -> bool { + match &c.kind { + NodeKind::Path { path, .. } => path.is_empty(), + NodeKind::Compound { .. } => c.children().is_none_or(|k| k.iter().filter_map(|m| m.path_data()).all(|p| p.is_empty())), + _ => false, + } + } + let mut first = None; + let mut kept_count = 0; + for (i, c) in n.children().into_iter().flatten().enumerate() { + if omitted(c) { + first.get_or_insert(i); + } else { + kept_count += 1; + } + } + let root_collapses = first.is_some() && kept_count == 1 && matches!(n.kind, NodeKind::Group { .. }); + Self { first, root_collapses } + } +} + +/// Returns serialized changes within the reader's limit when their targets remain safe after import. +fn changes_kept(art: &Node, overrides: &[vectorcraft_doc::SymbolOverride], omissions: &mut HashMap<*const Node, OmissionFacts>) -> Option> { + fn group_kids(n: &Node) -> Option<&Vec>> { + n.children().filter(|_| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) + } + #[cfg(test)] + OVERRIDE_SERIALIZATIONS.with(|count| count.set(count.get() + 1)); + let json = serde_json::to_vec(overrides).ok()?; + if json.len() > MAX_OVERRIDES_BYTES { + return None; + } + for o in overrides { + if omissions.entry(std::ptr::from_ref(art)).or_insert_with(|| OmissionFacts::of(art)).root_collapses { + return None; + } + let mut n = art; + for &i in o.path.iter().take(vectorcraft_doc::symbol_overrides::MAX_PATH_DEPTH) { + let Some(kids) = group_kids(n) else { break }; + let Some(c) = kids.get(i as usize) else { break }; + let facts = omissions.entry(std::ptr::from_ref(n)).or_insert_with(|| OmissionFacts::of(n)); + if facts.first.is_some_and(|f| f <= i as usize) { + return None; + } + n = c; + } + } + Some(json) +} + impl Writer<'_> { /// Whether instance `n` of symbol `symbol`, placed by `xf`, is written as an instance: not on the /// layers of a large canvas, in a pattern's tile or in art cut to a clipping object, without a - /// fill or appearance changes of its own (which stain or change the art it draws) and without + /// fill or appearance changes of its own (which stain or change the art it draws; a dynamic + /// symbol's instance keeps its changes only when [`changes_kept`] returns their bytes) and without /// isolation, knockout or knockout shape of its own (which an instance's transparency doesn't /// hold), of a symbol without 9-slice guides and without pattern paint in its art (the canvas /// keeps an instance's pattern tiles where the document puts them, and a definition's art moves @@ -75,8 +143,11 @@ impl Writer<'_> { /// that keeps the art's area as it is written and scales it as the definition allows /// ([`Self::keeps_scale`]). pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool { - let dynamic = self.symbol_doc.symbols.iter().any(|s| s.name == symbol && s.dynamic); - let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !n.extras().symbol_overrides.is_empty()); + let doc = self.symbol_doc; + let sym = doc.symbols.iter().find(|s| s.name == symbol); + let dynamic = sym.is_some_and(|s| s.dynamic); + let overrides = &n.extras().symbol_overrides; + let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !overrides.is_empty()); let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape; // The matrix as written (to ten decimals) must still keep the art's area. let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10)); @@ -91,6 +162,13 @@ impl Writer<'_> { && self.define_symbol(symbol) && !self.symbol_paints_pattern(symbol) && self.keeps_scale(symbol, xf) + && (overrides.is_empty() + || sym.is_some_and(|s| { + let Some(json) = changes_kept(&s.art, overrides, &mut self.symbol_omissions) else { return false }; + let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes())); + self.instance_entries = Some((n.id, e)); + true + })) } /// Whether instance matrix `xf` places symbol `symbol`'s definition as the canvas draws the @@ -175,13 +253,7 @@ impl Writer<'_> { /// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd` /// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two. pub(super) fn symbol_instance(&mut self, n: &Node, symbol: &str, xf: Affine, xy: Xy) { - let o = &n.extras().symbol_overrides; - if !o.is_empty() - && let Ok(json) = serde_json::to_vec(o) - && json.len() <= MAX_OVERRIDES_BYTES - { - let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes())); - self.instance_entries = Some((n.id, e)); + if self.instance_entries.as_ref().is_some_and(|(id, _)| *id == n.id) { self.warn(SYMBOL_CHANGES); } let m = self.instance_space * xf; diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 8e2a46c852..1fcdc67266 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -785,6 +785,17 @@ mod tests { } } + /// A row of patches with as many columns as a mesh keeps is stitched into one mesh; one more + /// column is not. + #[test] + fn a_mesh_with_more_lines_than_are_kept_is_not_stitched() { + for (n, kept) in [(MAX_LINES, true), (MAX_LINES + 1, false)] { + let r = Grid::new(n, 1).read([n as f64, 1.0]); + let at: Vec<(usize, usize)> = (0..n).map(|i| (0, i)).collect(); + assert_eq!(stitch(&r.cells, &at, 1, n).is_some(), kept, "{n} columns"); + } + } + /// A 2 × 2 mesh comes in as one mesh of 9 shared points, each where the patches put it, with /// the colours the separate patches had at every place. #[test] diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index fe425346d2..57c7e21442 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2799,6 +2799,43 @@ fn ai_variable_library_without_the_layers() { assert_eq!(variables(stream(&square).as_bytes()), read::VariableRead::default()); } +/// A library whose `variableSets` node writes its children and attributes before its name is +/// still found on its own when reading stops before it. +#[test] +fn a_variable_library_named_after_its_children_is_read_when_reading_stops_early() { + use vectorcraft_doc::DataValue; + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_text}; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let value = xml_element("Team", &[], &[xml_element("p", &[], &[xml_text(XmlValue::Unicode("Home Team"))])]); + let set = xml_element( + "variableSet", + &[("locked", "none"), ("varSetName", "binding1")], + &[ + xml_element("variables", &[], &[xml_element("variable", &[("trait", "textcontent"), ("varName", "Team")], &[])]), + xml_element( + "v:sampleDataSets", + &[("xmlns", "&ns_custom;"), ("xmlns:v", "&ns_vars;")], + &[xml_element("v:sampleDataSet", &[("dataSetName", "Home")], &[value])], + ), + ], + ); + let named_first = xml_element("variableSets", &[("xmlns", "&ns_vars;")], &[set]); + // Move the name line from the top of the node to just before the line that closes it. + let name = "%_(variableSets) /String (xmlnode-nodename) ,\n"; + let body = named_first.strip_prefix(&format!("%_/XMLNode :\n{name}")).and_then(|b| b.strip_suffix("%_;\n")).unwrap_or_default(); + assert!(!body.is_empty(), "{named_first}"); + let named_last = format!("%_/XMLNode :\n{body}{name}%_;\n"); + let early = stream(&format!("LB\n{}{square}", variable_library_data(&named_last))); + assert!(read(early.as_bytes()).is_err()); + let found = variables(early.as_bytes(), &mut Names::default()); + assert!(found.present); + let names: Vec<&str> = found.variables.variables.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["Team"]); + assert_eq!(found.variables.datasets.len(), 1); + assert_eq!(found.variables.datasets[0].name, "Home"); + assert_eq!(found.variables.datasets[0].values.get("Team"), Some(&DataValue::Text("Home Team".into()))); +} + #[test] fn a_drawn_look_stands_for_its_object() { // The look (a group, with a part on `%_` lines for newer readers), then the object on `%_` diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 3fb4393b19..43cb3b35d2 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -2361,6 +2361,12 @@ mod tests { } let deep = format!("/0 {}", "[".repeat(200)); assert!(read(deep.as_bytes()).is_none()); + // Balanced nesting: 65 levels are read, and a 66th ends the parse. + let nest = |open: &str, close: &str, n: usize| format!("/0 {}1{}", open.repeat(n), close.repeat(n)); + for (open, close) in [("<< /0 ", " >>"), ("[ ", " ]")] { + assert!(read(nest(open, close, MAX_DEPTH + 1).as_bytes()).is_some(), "{open}nested {} levels", MAX_DEPTH + 1); + assert!(read(nest(open, close, MAX_DEPTH + 2).as_bytes()).is_none(), "{open}nested {} levels", MAX_DEPTH + 2); + } } /// A text document's frame on a path of `segments` (each `x0 y0 x1 y1 x2 y2 x3 y3`) with the diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index e43f2a1227..7a0685d80a 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -722,6 +722,21 @@ fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_place assert_eq!(text.lines().filter(|l| l.ends_with(" XI")).count(), 1, "the one image"); } +/// A distorted image on a layer, which the format has no form for, is written as the pieces it is +/// drawn as, with a warning. +#[test] +fn a_distorted_image_on_a_layer_is_written_as_its_pieces() { + let mut doc = Document::new(200.0, 100.0); + let mut art = picture(&mut doc, Rect::new(10.0, 10.0, 90.0, 90.0)); + art.set_image_corners([(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap(); + doc.insert(doc.default_layer(), usize::MAX, art).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == LIVE), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == DEEP_DISTORTED), "{:?}", out.warnings); + let text = String::from_utf8(out.bytes).unwrap(); + assert!(text.lines().filter(|l| l.ends_with(" XI")).count() > 1, "the pieces, not one image"); +} + /// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group /// holding an image and an image; a layer `Above` holding an orange square. Without `images`, /// `Below` is empty. diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index dc40025954..aa14fcde37 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -426,6 +426,61 @@ fn strokes_keep_their_caps_joins_and_dashes() { assert!(page.contains("0 0 0 rg\n20 20 m\n80 20 l\n80 80 l\n20 80 l\n20 20 l\nh\nS\n"), "{page}"); } +/// The page for a square stroked 4 pt with `paint`, aligned `align`. +fn aligned_stroke_page(align: vectorcraft_doc::StrokeAlign, paint: impl FnOnce(&mut Document) -> Paint) -> String { + let d = doc_with(|d| { + let paint = paint(d); + let mut n = path(d, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Paint::None, paint, 4.0); + for i in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = i { + s.align = align; + } + } + vec![n] + }); + page_of(&d, &opts(&d)) +} + +/// Where the first line of `page` that `matches` is. +fn line_at(page: &str, matches: impl Fn(&str) -> bool) -> Option { + page.lines().position(matches) +} + +/// A stroke inside or outside a closed path is drawn at twice its width, clipped first: inside to +/// the path, outside to everything but the path (even-odd), so only its own half shows. +#[test] +fn inside_and_outside_strokes_are_clipped_to_their_side_and_drawn_twice_as_wide() { + use vectorcraft_doc::StrokeAlign; + let black = |_: &mut Document| Paint::solid(Color::BLACK); + for (align, clip) in [(StrokeAlign::Inside, "W"), (StrokeAlign::Outside, "W*")] { + let page = aligned_stroke_page(align, black); + let clip_at = line_at(&page, |l| l == clip); + let width_at = line_at(&page, |l| l.starts_with("8 w ")); + let stroke_at = line_at(&page, |l| l == "S"); + assert!(clip_at.is_some() && clip_at < width_at && width_at < stroke_at, "{align:?}: {page}"); + let other = if clip == "W" { "W*" } else { "W" }; + assert_eq!(line_at(&page, |l| l == other), None, "{align:?}: {page}"); + } + // Centered: the width as set, with no clip. + let page = aligned_stroke_page(StrokeAlign::Center, black); + assert!(line_at(&page, |l| l.starts_with("4 w ")).is_some(), "{page}"); + assert_eq!(line_at(&page, |l| l == "W" || l == "W*"), None, "{page}"); +} + +/// A stroke painted with a pattern is written as the area it covers, filled with the pattern's +/// tiles, not as a stroke. +#[test] +fn a_pattern_stroke_is_written_as_its_filled_outline() { + let pattern = |d: &mut Document| { + let square = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![Arc::new(square)])); + Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY } + }; + let page = aligned_stroke_page(vectorcraft_doc::StrokeAlign::Center, pattern); + assert!(page.contains("0 0 1 rg"), "the tile is painted: {page}"); + assert_eq!(line_at(&page, |l| l == "S" || l.contains("strokepath") || l.contains(" w ")), None, "{page}"); +} + #[test] fn transparency_is_written_opaque_with_a_warning() { let d = doc_with(|d| { diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index dd0cd4cc6c..1e353f309f 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -265,15 +265,19 @@ pub fn write_atomic_checked( } } -/// See the Unix version. +/// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is +/// filled, right before it is put in place; a refusal then removes the temporary file and leaves +/// `path` unchanged. #[cfg(not(unix))] pub fn write_atomic_checked( path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>, - allowed: impl FnOnce(&Path) -> io::Result<()>, + allowed: impl Fn(&Path) -> io::Result<()>, ) -> io::Result<()> { allowed(path)?; - write_atomic_with(path, fill) + let replacing = path.exists(); + let create = |tmp: &Path| if replacing { create_private(tmp) } else { create_new(tmp) }; + write_atomic_staged(path, fill, create, || allowed(path), |tmp, target| std::fs::rename(tmp, target)) } /// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links @@ -404,6 +408,18 @@ fn write_atomic_stepping( fill: impl FnOnce(&mut File) -> io::Result<()>, create: impl FnOnce(&Path) -> io::Result, rename: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> io::Result<()> { + write_atomic_staged(path, fill, create, || Ok(()), rename) +} + +/// [`write_atomic_stepping`], with `check` run after the temporary file is filled and right before +/// it is put in place. An error from `check` removes the temporary file and leaves `path` unchanged. +fn write_atomic_staged( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + create: impl FnOnce(&Path) -> io::Result, + check: impl Fn() -> io::Result<()>, + rename: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> io::Result<()> { let target = resolve_link(path)?; let beside = temp_path(&target)?; @@ -420,7 +436,7 @@ fn write_atomic_stepping( }; let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); - if let Err(e) = filled { + if let Err(e) = filled.and_then(|()| check()) { // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); return Err(e); @@ -435,7 +451,7 @@ fn write_atomic_stepping( e } }; - write_over(&tmp, &target, refused) + write_over(&tmp, &target, refused, &check) } /// The content of `tmp`, which is whole and flushed, copied into `target` itself, and `tmp` @@ -443,8 +459,8 @@ fn write_atomic_stepping( /// writing it is untouched: `tmp` is removed and `refused` returned. When what it holds can't be /// copied aside first ([`keep_old`]) it is untouched too: `tmp` stays and the error names it. When /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the -/// error says where they are. -fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { +/// error says where they are. `check` runs again right before `target` is overwritten. +fn write_over(tmp: &Path, target: &Path, refused: io::Error, check: &dyn Fn() -> io::Result<()>) -> io::Result<()> { let old = tmp.with_extension("old"); let over = Over { tmp: &|| tmp.to_path_buf(), @@ -457,11 +473,20 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { remove_tmp: &|| { let _ = std::fs::remove_file(tmp); }, - open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, - #[cfg(unix)] + // A missing target is created by `create_target`, after the last check. An existing one is + // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. + open_target: &|write| { + if !write { + return File::open(target); + } + if matches!(std::fs::symlink_metadata(target), Err(e) if e.kind() == io::ErrorKind::NotFound) { + return Err(io::ErrorKind::NotFound.into()); + } + OpenOptions::new().write(true).create(true).truncate(false).open(target) + }, create_target: &|| create_new(target), synced: &|| sync_written_parent(target), - still_allowed: &|| Ok(()), + still_allowed: check, }; write_over_in(&over, refused) } @@ -481,10 +506,9 @@ struct Over<'a> { /// Best effort. remove_tmp: &'a dyn Fn(), /// Opens the target without truncating it for writing when `true`, or for reading when `false`. - /// Checked Unix writes defer creation of a missing target to `create_target`. + /// It never creates a missing target: `create_target` does that, after the final check. open_target: &'a dyn Fn(bool) -> io::Result, /// Creates a missing target after the final check and fails if its name is taken. - #[cfg(unix)] create_target: &'a dyn Fn() -> io::Result, /// The target's folder flushed, after the target is written. synced: &'a dyn Fn() -> io::Result<()>, @@ -494,7 +518,7 @@ struct Over<'a> { /// [`write_over`] through `over`. fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { - // Checked Unix writes create a missing target only after the final check. + // A missing target is created only after the final check. if let Err(e) = (over.still_allowed)() { (over.remove_tmp)(); return Err(e); @@ -502,7 +526,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { let opened = (over.open_tmp)().and_then(|from| { let to = match (over.open_target)(true) { Ok(to) => Some(to), - #[cfg(unix)] Err(e) if e.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e), }; @@ -547,7 +570,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { } let mut to = match to { Some(to) => to, - #[cfg(unix)] None => match (over.create_target)() { Ok(to) => to, // A file put at the name meanwhile is left alone, and reported as there. @@ -560,11 +582,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { return Err(refused); } }, - #[cfg(not(unix))] - None => { - (over.remove_tmp)(); - return Err(refused); - } }; let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); @@ -1100,6 +1117,26 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A refused rename onto a missing file that is no longer allowed at the final check does not + /// create the file. + #[test] + fn a_refused_rename_does_not_create_a_missing_file_once_no_longer_allowed() { + let d = dir("no-rename-missing-disallowed"); + let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let check = || { + checks.set(checks.get() + 1); + if checks.get() == 1 { Ok(()) } else { Err(io::Error::other("moved outside")) } + }; + let e = write_over(&tmp, &path, denied::<()>().unwrap_err(), &check).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!path.exists(), "the refused write created {}", path.display()); + assert!(!tmp.exists()); + let _ = std::fs::remove_dir_all(d); + } + /// A refused rename whose folder is no longer allowed by the time the file would be overwritten /// leaves the file as it was, and neither copy stays behind. #[test] @@ -1121,7 +1158,6 @@ mod tests { let _ = std::fs::remove_file(&tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, - #[cfg(unix)] create_target: &|| create_new(&path), synced: &|| Ok(()), still_allowed: &|| { @@ -1413,6 +1449,156 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A checked write whose fill fails puts nothing in place: the error is returned, the file + /// keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_keeps_the_original_when_its_fill_fails() { + let (d, root, _) = checked_folders("checked-fill-fails"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let r = write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + assert_eq!(r.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked write canceled while it fills puts nothing in place: the error is the + /// cancellation, the file keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_canceled_while_it_fills_keeps_the_original() { + use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope}; + let (d, root, _) = checked_folders("checked-cancel"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let token = CancelToken::new(); + let r = scope(&token, None, || { + write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"new")?; + token.cancel(); + Ok(()) + }, + under(&root), + ) + }); + assert!(r.as_ref().is_err_and(|e| e.get_ref().is_some_and(|e| e.is::())), "{r:?}"); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// Makes `folder` refuse new files (mode 0o555). `false`, with the folder writable again, when + /// a new file can still be created there (root ignores the mode). + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn refuse_new_files(folder: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o555)).unwrap(); + let probe = folder.join("probe"); + if std::fs::write(&probe, b"").is_ok() { + let _ = std::fs::remove_file(&probe); + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + return false; + } + true + } + + /// Files in the system's temporary folder whose names start with the temporary names a write + /// to a file named `name` uses. + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn system_temp_files(name: &str) -> Vec { + let prefix = format!(".{name}.{}-", std::process::id()); + std::fs::read_dir(std::env::temp_dir()) + .unwrap() + .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().to_string())) + .filter(|n| n.starts_with(&prefix)) + .collect() + } + + /// A checked write over a file whose folder refuses the rename and then any new file: the copy + /// of the file as it was goes to the system's temporary folder, the new content is copied into + /// the file, and that copy is removed afterwards. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_keeps_the_old_copy_outside_a_folder_that_takes_no_new_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-old-elsewhere.txt"; + let (d, root, _) = checked_folders("checked-old-elsewhere"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + let refused = std::cell::Cell::new(true); + let r = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"new")?; + RENAME_REFUSED.with(|c| c.set(true)); + refused.set(refuse_new_files(&folder)); + Ok(()) + }, + under(&root), + ); + RENAME_REFUSED.with(|c| c.set(false)); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + if !refused.get() { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + r.unwrap(); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(!leftovers(&folder, name).iter().any(|n| n.ends_with(".old")), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that refuses the temporary file of a checked write but lets the file itself be + /// written: the content is written in the system's temporary folder and copied in, and nothing + /// is left behind. A failed fill there leaves the file as it was. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_saves_through_the_system_folder_when_its_folder_takes_no_temporary_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-no-temp.txt"; + let (d, root, _) = checked_folders("checked-no-temp"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + if !refuse_new_files(&folder) { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + let saved = write_atomic_checked(&folder.join(name), |f| f.write_all(b"new"), under(&root)); + let saved_content = std::fs::read(folder.join(name)).unwrap(); + let saved_temp = system_temp_files(name); + let failed = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + saved.unwrap(); + assert_eq!(saved_content, b"new"); + assert!(saved_temp.is_empty(), "{saved_temp:?}"); + assert_eq!(failed.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(leftovers(&folder, name).is_empty(), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() @@ -1753,6 +1939,64 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A check that refuses after the file is filled keeps the old file, removes the temporary file + /// and tries no rename, whether the folder takes the temporary file or not. + #[test] + fn a_check_refused_after_the_fill_keeps_the_file() { + let d = dir("staged-check"); + let path = d.join("staged-check.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let renamed = std::cell::Cell::new(false); + let rename = |_: &Path, _: &Path| { + renamed.set(true); + Ok(()) + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), |_| denied(), || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(!renamed.get() && leftovers(&d, "staged-check.vectorcraft").is_empty()); + // A folder that refuses the rename: the check runs again before the file is written over. + let calls = std::cell::Cell::new(0); + let check = || { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("moved away")) } else { Ok(()) } + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, check, |_, _| denied()); + assert!(r.is_err_and(|e| e.to_string().contains("moved away"))); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "staged-check.vectorcraft").is_empty()); + let staged = format!(".staged-check.vectorcraft.{}-", std::process::id()); + let in_system = std::fs::read_dir(std::env::temp_dir()).unwrap().filter_map(Result::ok); + assert!(!in_system.into_iter().any(|e| e.file_name().to_string_lossy().starts_with(&staged)), "the system's folder keeps no staging file"); + let _ = std::fs::remove_dir_all(&d); + } + + /// Off Unix the check runs again after the file is filled: a refusal at that point keeps the + /// old file and leaves no temporary file. + #[cfg(not(unix))] + #[test] + fn a_checked_write_checks_again_before_the_file_is_put_in_place() { + let d = dir("checked-twice"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let calls = std::cell::Cell::new(0); + let r = write_atomic_checked( + &path, + |f| f.write_all(b"new"), + |_| { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("no longer allowed")) } else { Ok(()) } + }, + ); + assert_eq!(r.unwrap_err().to_string(), "no longer allowed"); + assert_eq!(calls.get(), 2); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "doc.vectorcraft").is_empty()); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn write_new_never_replaces_what_is_there() { let d = dir("new"); diff --git a/crates/format/src/unpack.rs b/crates/format/src/unpack.rs index ec9623118c..e636aadf74 100644 --- a/crates/format/src/unpack.rs +++ b/crates/format/src/unpack.rs @@ -374,6 +374,36 @@ mod tests { assert!(matches!(Unpacked::within(&gz, json.len() as u64 - 1), Err(FormatError::TooBig))); } + /// A compressed file with data after its JSON is refused past its budget on both paths: the + /// JSON before the marker where the writer puts it, and the whole file when the marker is + /// elsewhere and the file is unpacked whole. + #[test] + fn a_compressed_file_with_data_is_capped_on_both_paths() { + let with_data = |json: &[u8]| { + let mut file = json.to_vec(); + file.extend(crate::BLOB_MAGIC); + file.extend([1u8; 64]); + file + }; + let mut json = br#"{"pad":""#.to_vec(); + json.extend(std::iter::repeat_n(b'x', 4096)); + json.extend(br#""}"#); + let streamed = gzip(&with_data(&json)); + let max_json = json.len() as u64; + let opened = Unpacked::within(&streamed, max_json).unwrap(); + assert!(matches!(opened.tail, Tail::Stream { .. }), "read as a stream"); + assert_eq!(opened.json(), json.as_slice()); + assert!(matches!(Unpacked::within(&streamed, max_json - 1), Err(FormatError::TooBig))); + // No `}` before the marker: unpacked whole, within the whole-file cap and not one byte past it. + let plain = with_data(b"1"); + let whole = gzip(&plain); + let max_whole = plain.len() as u64; + let opened = Unpacked::within_capped(&whole, 64, max_whole, MAX_BLOBS).unwrap(); + assert!(matches!(opened.tail, Tail::Whole(_)), "unpacked whole"); + assert_eq!(opened.json(), b"1"); + assert!(matches!(Unpacked::within_capped(&whole, 64, max_whole - 1, MAX_BLOBS), Err(FormatError::TooBig))); + } + #[test] fn entries_sharing_bytes_obey_the_limits_in_memory_too() { // Each entry within MAX_BLOB, together past MAX_BLOBS: many references to the same bytes. diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 2d23c4c3bc..3a3cc606c5 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -1697,4 +1697,99 @@ mod tests { let b3d = box3d(r, 30.0, 35.0, 0.0, true, true, true); assert!(!b3d.subpaths.is_empty() && b3d.subpaths.iter().all(|s| s.closed && s.anchors.len() == 4)); } + + /// Rounded with no Randomize still builds the rounded contour, for stars and polygons alike. + #[test] + fn rounded_shapes_without_randomize_have_handles_on_every_anchor() { + let star = star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.5, 0.0); + assert_eq!(star.anchor_count(), 10); + assert!(star.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out()), "star: {star:?}"); + let poly = polygon_configured(Point::ZERO, 50.0, 6, 0.0, 0.5, 0.0); + assert_eq!(poly.anchor_count(), 6); + assert!(poly.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out()), "polygon: {poly:?}"); + } + + /// A rounded square's handles run along the unit tangent at each corner: 0.4 × Rounded of the + /// side long, at right angles to the radius. + #[test] + fn rounding_handles_are_their_share_of_the_side_along_the_tangent() { + let radius = 50.0; + let path = polygon_configured(Point::ZERO, radius, 4, 0.0, 1.0, 0.0); + let side = radius * 2.0_f64.sqrt(); + let want = 0.4 * side; + assert_eq!(path.anchor_count(), 4); + for a in &path.subpaths[0].anchors { + let (h_out, h_in, out_from_center) = (a.h_out - a.p, a.p - a.h_in, a.p.to_vec2()); + assert!((h_out.hypot() - want).abs() < 1e-9, "out handle {} long, want {want}", h_out.hypot()); + assert!((h_in.hypot() - want).abs() < 1e-9, "in handle {} long, want {want}", h_in.hypot()); + assert!(h_out.dot(out_from_center).abs() < 1e-9, "out handle {h_out:?} is not at right angles to {out_from_center:?}"); + assert!(h_in.dot(out_from_center).abs() < 1e-9, "in handle {h_in:?} is not at right angles to {out_from_center:?}"); + } + } + + /// A spiral starts at its center (inner radius 0) and ends a radius away, at the angle its turns + /// reach: an eighth past three whole turns, clockwise on screen, is down and to the right. + #[test] + fn a_spiral_runs_from_its_center_to_the_radius_at_its_last_angle() { + let (center, radius) = (Point::new(50.0, 60.0), 100.0); + let sp = spiral_configured(center, radius, 3.125, 1.0, 0.0, true); + let anchors = &sp.subpaths[0].anchors; + let (first, last) = (anchors[0].p, anchors[anchors.len() - 1].p); + assert!(first.distance(center) < 1e-9, "first anchor {first:?}, center {center:?}"); + let diagonal = radius / 2.0_f64.sqrt(); + let want = Point::new(center.x + diagonal, center.y + diagonal); + assert!(last.distance(want) < 1e-9, "last anchor {last:?}, want {want:?}"); + assert!((last.distance(center) - radius).abs() < 1e-9); + } + + /// Randomize moves each vertex out or in by at most 45% of its radius per unit of Randomize, + /// and does move some. + #[test] + fn randomize_keeps_vertex_radii_within_their_range() { + let distances = |p: &PathData| p.subpaths[0].anchors.iter().map(|a| a.p.distance(Point::ZERO)).collect::>(); + let within = |d: f64, base: f64| d >= base * 0.55 - 1e-9 && d <= base * 1.45 + 1e-9; + + let poly = distances(&polygon_configured(Point::ZERO, 50.0, 8, 0.0, 0.0, 1.0)); + assert_eq!(poly.len(), 8); + assert!(poly.iter().all(|&d| within(d, 50.0)), "polygon radii {poly:?}"); + assert!(poly.iter().any(|&d| (d - 50.0).abs() > 1e-6), "Randomize moved no vertex: {poly:?}"); + + let star = distances(&star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.0, 1.0)); + assert_eq!(star.len(), 10); + let (tips, inner): (Vec<_>, Vec<_>) = star.iter().enumerate().partition(|(i, _)| i % 2 == 0); + assert!(tips.iter().all(|&(_, &d)| within(d, 50.0)), "star tips {tips:?}"); + assert!(inner.iter().all(|&(_, &d)| within(d, 25.0)), "star inner points {inner:?}"); + assert!(star.iter().zip([50.0, 25.0].iter().cycle()).any(|(d, base)| (d - base).abs() > 1e-6), "{star:?}"); + } + + /// Every face of a box drawn without perspective is a parallelogram with four distinct + /// corners, seen from each side of the box. + #[test] + fn a_parallel_box_draws_its_faces_as_parallelograms() { + let r = Rect::new(0.0, 0.0, 100.0, 80.0); + for (ax, ay) in [(30.0, 35.0), (-30.0, 35.0), (30.0, -35.0), (-30.0, -35.0), (150.0, 215.0)] { + let b = box3d(r, ax, ay, 0.0, true, true, true); + assert!(!b.subpaths.is_empty()); + for sp in &b.subpaths { + let p: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert_eq!(p.len(), 4); + let gap = (p[0].to_vec2() + p[2].to_vec2() - p[1].to_vec2() - p[3].to_vec2()).hypot(); + assert!(gap < 1e-6, "angles ({ax}, {ay}): face {p:?} is not a parallelogram"); + for i in 0..4 { + for j in i + 1..4 { + assert!(p[i].distance(p[j]) > 1e-6, "angles ({ax}, {ay}): face {p:?} repeats a corner"); + } + } + } + } + } + + /// An end angle a hair short of a full turn opens the whole shape for Arc instead of cutting it. + #[test] + fn a_span_within_rounding_of_a_full_turn_opens_the_whole_shape() { + let r = Rect::new(0.0, 0.0, 100.0, 60.0); + let mut opened = ellipse(r); + opened.subpaths[0].closed = false; + assert_eq!(apply_shape_arc(ellipse(r), r.center(), 0.0, -1e-10, EllipseMode::Arc), opened); + } } diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 6438392335..909b191571 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -194,6 +194,23 @@ fn async_function_prototype_has_its_to_string_tag() { assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]"); } +#[test] +fn a_class_extends_async_function_and_its_instances_inherit_from_the_class() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2017 section + // 19.2.1.1.1). + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + class X extends AF { tag() { return 'x'; } }\n\ + var f = new X('a', 'return a + 1');\n\ + log.push(Object.getPrototypeOf(f) === X.prototype, f instanceof AF, f.tag(), Object.prototype.toString.call(f));\n\ + f(1).then(function (v) { log.push(v); });"; + assert_eq!(log(src), "true true x [object AsyncFunction] 2"); + // The source is parsed before `new.target.prototype` is read. + let order = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + var NT = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') log.push('read'); return t[k]; } });\n\ + try { Reflect.construct(AF, ['(('], NT); } catch (e) { log.push(e instanceof SyntaxError); }"; + assert_eq!(log(order), "true"); +} + #[test] fn an_await_stays_within_the_heap_limit() { // The activation, its two reactions, the derived promise and the suspended frame's bytes all diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 4314aa60f8..87c1c744c8 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -172,7 +172,15 @@ impl Interp { let i = &self.intrinsics; Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto] .contains(&p) - || i.error_protos.contains(&p)) + || i.error_protos.contains(&p) + || self.dynamic_function_proto(p)) + } + + /// Is `p` the prototype of the functions that `GeneratorFunction` or `AsyncFunction` makes? + /// Both constructors take a subclass's prototype from `new.target` (ECMA-262 2017 sections + /// 25.2.1.1 and 25.5.1.1, through CreateDynamicFunction in section 19.2.1.1.1). + fn dynamic_function_proto(&self, p: ObjId) -> bool { + self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) || self.promises.async_function_proto == Some(p) } /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). @@ -367,13 +375,13 @@ impl Interp { return Err(self.type_error("the Promise executor is not a function")); } // `Number`, `String` and `Date` convert arguments before reading `prototype` - // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function` and `GeneratorFunction` - // convert and parse source first (sections 19.2.1.1.1 and 25.2.1.1). + // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function`, `GeneratorFunction` and + // `AsyncFunction` convert and parse source first (sections 19.2.1.1.1, 25.2.1.1 + // and 25.5.1.1). let converts_first = { let i = &self.intrinsics; intrinsic.is_some_and(|p| { - [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) - || self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) + [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) || self.dynamic_function_proto(p) }) }; let fallback = intrinsic.unwrap_or(self.intrinsics.object_proto); diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 1a076c43c1..ec43bfe327 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -203,6 +203,17 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); } +#[test] +fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() { + // A parameter between the eval code and its variable environment has the name, so the block + // function gets no variable (Annex B.3.2.3) and the parameter keeps its value. + truth("function f(a = eval('{ function a() {} }'), b = a) { return typeof b; } f() === 'undefined'"); + truth("function f(a = 1, b = eval('{ function a() {} }'), c = a) { return c + typeof a; } f() === '1number'"); + truth("function f(a = 2, b = eval('{ function a() {} }')) { return a; } f() === 2"); + // A name that no parameter has still gets the variable. + truth("function f(x = eval('{ function a() { return 3; } }'), b = a) { return b(); } f() === 3"); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index 551fb4e5e6..19eb0c1edf 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -253,6 +253,23 @@ fn bad_generators_are_syntax_errors() { truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); } +#[test] +fn a_class_extends_generator_function_and_function() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2015 section + // 19.2.1.1.1). + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor;\n\ + class G extends GF { tag() { return 'g'; } }\n\ + var g = new G('yield 7');\n\ + Object.getPrototypeOf(g) === G.prototype && g instanceof GF && g.tag() === 'g' && g().next().value === 7", + ); + truth( + "class F extends Function { tag() { return 'f'; } }\n\ + var f = new F('a', 'return a * 2');\n\ + Object.getPrototypeOf(f) === F.prototype && f.tag() === 'f' && f(3) === 6", + ); +} + #[test] fn realms_without_es2015_have_no_generators() { let es5 = Options::default(); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0639d52d25..3784b3a515 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4813,7 +4813,8 @@ impl Interp { /// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and /// B.3.3.3, ): no /// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch` - /// parameter does not count, and on the global object the name is its own property or the + /// parameter does not count, no parameter has the name when the code is in a default + /// parameter's value (B.3.2.3), and on the global object the name is its own property or the /// object is extensible. Each environment passed takes a unit of fuel. fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult { let mut cur = Some(env).filter(|&e| e != var_env); @@ -4832,7 +4833,14 @@ impl Interp { .filter(|&o| o != var_env); } if var_env != self.global_env { - return Ok(true); + // Eval code in a default parameter's value declares into the parameters' environment, + // where the parameters are lexical bindings. + self.use_fuel()?; + return match self.heap.env(var_env) { + Some(Env::Decl { bindings, .. }) => Ok(!bindings.get(name).is_some_and(|b| b.lexical)), + Some(Env::Obj { .. }) => Ok(true), + None => internal("environment out of range"), + }; } let global = self.global; Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible) diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index 850846abe1..0cfb20cce2 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -266,7 +266,10 @@ impl Parser<'_> { self.bump()?; return self.export_default(info, span).map(Some); } - let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some(); + let exportable = self.at_keyword(Keyword::Var) + || self.at_keyword(Keyword::Function) + || self.at_async_function() + || self.at_lexical_declaration().is_some(); if !exportable { return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok)))); } @@ -287,7 +290,7 @@ impl Parser<'_> { if self.at_keyword(Keyword::Class) { return Err(self.error_at_token(&self.tok, "classes are not supported")); } - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.default_function(); self.leave(); @@ -305,19 +308,22 @@ impl Parser<'_> { Ok(stmt) } - /// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of - /// `name`, or of [`DEFAULT_BINDING`] for a function without one. + /// `function name(…) {…}` or `function (…) {…}` after `export default`, either one optionally + /// `async`: a declaration of `name`, or of [`DEFAULT_BINDING`] for a function without one. fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> { + let is_async = self.at_async(); + let async_start = if is_async { Some(self.bump()?.span) } else { None }; let keyword = self.expect_keyword(Keyword::Function)?; - let start = keyword.span; - let generator = self.es2015 && self.eat(Punct::Star)?; + let start = async_start.unwrap_or(keyword.span); + // Async generators (ECMAScript 2018) stay syntax errors, as in a plain declaration. + let generator = !is_async && self.es2015 && self.eat(Punct::Star)?; let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name()? } else { (Name { name: DEFAULT_BINDING.into(), span: start }, keyword) }; let local = name.0.name.clone(); - let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, false)?; + let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?; let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start)); Ok((stmt, fid, local)) } @@ -410,6 +416,36 @@ mod tests { assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into()))); } + #[test] + fn async_function_declarations_are_exported() { + let options = Options { es2015: true, es2017: true, ..Options::default() }; + let cases = [ + ("export async function f() {}", "f", "f"), + ("export default async function f() {}", "default", "f"), + ("export default async function () {}", "default", crate::ast::DEFAULT_BINDING), + ]; + for (source, export, binding) in cases { + let (program, info) = match parse_module(source, &options) { + Ok(parsed) => parsed, + Err(error) => panic!("{source}: {error:?}"), + }; + assert!( + matches!(info.exports.as_slice(), [crate::ExportEntry::Local { export_name, local, .. }] if export_name == export && local == binding), + "{source}: {:?}", + info.exports + ); + let declared = program.body.iter().any(|&stmt| match program.ast.stmt(stmt) { + Some(crate::ast::Stmt::FunctionDecl(fid)) => program.ast.function(*fid).is_some_and(|f| f.is_async), + _ => false, + }); + assert!(declared, "{source}: an async function declaration"); + } + // A line break after `async` ends the declaration; the export is then an expression. + assert!(parse_module("export async\nfunction f() {}", &options).is_err()); + // Without ES2017, `async` is an identifier and cannot start an exported declaration. + assert!(parse_module("export async function f() {}", &Options { es2015: true, ..Options::default() }).is_err()); + } + #[test] fn module_specifiers_reject_legacy_octal_escapes() { for source in diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index acbbb5d151..345e1ff995 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1018,7 +1018,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", @@ -1543,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", @@ -1768,7 +1768,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.placementOptionsDialog", "Placement Options…", "", - "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions", + "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)", ), ( "ui.relinkDialog", diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index ef20585154..fc9f306ffe 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -331,6 +331,56 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(masked(&r.document)[0].1.is_none()); } +/// A masked CMYK image drawn twice, at two sizes, carries its opacity mask both times: the same +/// mask image, fitted to each drawing. Drawn twice with a mask that hides nothing, it has no mask +/// either time. +#[test] +fn a_masked_cmyk_image_drawn_twice_keeps_its_mask_both_times() { + let z = |data: &[u8]| crate::output::deflate(data).unwrap(); + let file = |mask: &[u8]| { + let content = "q 50 0 0 50 10 10 cm /Im0 Do Q q 30 0 0 20 100 40 cm /Im0 Do Q"; + pdf_of(&[ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>".to_vec(), + stream("", content.as_bytes()), + stream( + &format!("/Type /XObject /Subtype /Image {}", cmyk_dict(2, 2, "/SMask 6 0 R /Filter /FlateDecode")), + &z(&flat([0, 102, 255, 0], 4)), + ), + stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", mask), + ]) + }; + let images = |d: &Document| { + let NodeKind::Layer { children, .. } = &d.layers[0].kind else { panic!() }; + children.iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).cloned().collect::>() + }; + let r = import_with_report(&file(&[255, 128, 255, 128]), &ImportOptions::default()).unwrap(); + let drawn = images(&r.document); + assert_eq!(drawn.len(), 2); + let mut keys = vec![]; + for n in &drawn { + let mask = n.extras().mask.as_ref().expect("an opacity mask on each drawing"); + let NodeKind::Image(a) = &mask.art.kind else { panic!("mask art is an image: {:?}", mask.art.kind) }; + assert_eq!((a.width, a.height), (2, 2)); + assert!(near(n.geometric_bounds(), mask.art.geometric_bounds()), "{:?} {:?}", n.geometric_bounds(), mask.art.geometric_bounds()); + keys.push(a.key.clone()); + } + assert_eq!(keys[0], keys[1], "one mask image"); + assert!(drawn[0].geometric_bounds() != drawn[1].geometric_bounds(), "two sizes"); + let r = import_with_report(&file(&[255; 4]), &ImportOptions::default()).unwrap(); + let drawn = images(&r.document); + assert_eq!(drawn.len(), 2); + assert!(drawn.iter().all(|n| n.extras().mask.is_none()), "a mask that hides nothing adds none, either time"); +} + +fn near(a: Option, b: Option) -> bool { + match (a, b) { + (Some(a), Some(b)) => [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6), + _ => false, + } +} + /// Every image blob a document's art uses (mask art included). fn all_images(d: &Document) -> Vec<&ImageBlob> { let mut keys = vec![]; diff --git a/crates/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index 086b711aec..a7e83e56f3 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -560,3 +560,63 @@ fn rgb_numbers_stand_in_editor_documents_only() { assert!(near(color(true), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(true)); assert!(!near(color(false), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(false)); } + +/// The space the scan of a page holding colour spaces `spaces` finds for a Gold Separation (tint +/// transform [`GOLD_TINT`]). +fn gold_space(spaces: &str) -> Space { + use craft::pdf::interpret::Function; + use craft::pdf::syntax::object::{FromBytes, Object}; + let key = format!("{:?}", Function::new(&Object::from_bytes(GOLD_TINT.as_bytes()).unwrap()).unwrap()); + let pdf = craft::pdf::syntax::Pdf::new(pdf(&[page_with(spaces, &[])], None)).unwrap(); + Colors::new(&pdf, vec![]).space_of(&format!("ColorSpace(Separation(Separation {{ tint_transform: {key} }}))"), 1, None) +} + +const GOLD_TINT: &str = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + +/// The scan for ink spaces looks 32 levels into an object and no deeper. +#[test] +fn ink_spaces_nested_past_the_scan_depth_are_not_found() { + let gold = format!("[/Separation /Gold /DeviceCMYK {GOLD_TINT}]"); + let nested = |levels: usize| format!("/A {}{gold}{}", "[".repeat(levels), "]".repeat(levels)); + assert_eq!(gold_space(&nested(20)), Space::Inks(0)); + assert_eq!(gold_space(&nested(40)), Space::Other); +} + +/// The scan keeps 4,096 ink spaces: a space after that many others is not found. +#[test] +fn ink_spaces_past_the_scan_count_are_not_found() { + let filler = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>"; + let spaces = |n: usize| -> String { + let fillers: String = (0..n).map(|i| format!("[/Separation /Ink{i} /DeviceCMYK {filler}]")).collect(); + format!("/A [{fillers}[/Separation /Gold /DeviceCMYK {GOLD_TINT}]]") + }; + assert_eq!(gold_space(&spaces(4095)), Space::Inks(4095)); + assert_eq!(gold_space(&spaces(4096)), Space::Other); +} + +/// A one-ink image of more pixels than a CMYK image may have is refused before its samples are +/// decoded; the same samples read at a smaller size are not. +#[test] +fn one_ink_images_past_the_pixel_cap_are_refused() { + use std::io::Write; + let side = 8193u32; + let row = (side as usize).div_ceil(8); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + z.write_all(&vec![0u8; row * side as usize]).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02x}")).collect(); + let image = format!( + "<< /Type /XObject /Subtype /Image /Width {side} /Height {side} /BitsPerComponent 1 /ColorSpace [/Separation /Gold /DeviceCMYK {GOLD_TINT}] /Filter [/ASCIIHexDecode /FlateDecode] /Length {} >>\nstream\n{hex}>\nendstream", + hex.len() + 1 + ); + let file = craft::pdf::syntax::Pdf::new(pdf_with(&[PdfPage::new(10.0, 10.0, "")], &[&image], None)).unwrap(); + let st = file + .objects() + .into_iter() + .find_map(|o| match o { + craft::pdf::syntax::object::Object::Stream(s) if s.dict().contains_key(b"Width") => Some(s), + _ => None, + }) + .unwrap(); + assert_eq!(crate::import_image::tint_gray(&st, side, side).map(|g| g.len()), Err(crate::import_image::UNREAD_TINTS)); + assert_eq!(crate::import_image::tint_gray(&st, 16, 2), Ok(vec![255; 32])); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 731f18ff06..ea74b0dc2d 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -370,6 +370,53 @@ fn tiling_patterns_become_pattern_swatches() { assert_eq!(colors, vec![Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]); } +/// Links in the chains of nested patterns and soft masks below: more than are read. +const CHAIN: usize = 12; + +/// The warnings of opening a page drawing `content` with `resources`, plus `objects`. +fn warnings_of(objects: &[String], resources: &str, content: &str) -> Vec { + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + open_with(&one_page(content, resources, &extra), |_| {}).warnings +} + +/// Tiling patterns whose cells fill with the next pattern are read only so many levels deep: a +/// chain of them opens, with a warning. +#[test] +fn patterns_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let cells: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = if i + 1 < CHAIN { + (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f") + } else { + (String::new(), "1 0 0 rg 0 0 5 5 re f") + }; + let cell = "/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10"; + stream(&format!("{cell} /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("tiling patterns nested too deeply")), "{w:?}"); +} + +/// Soft masks whose groups draw through the next mask are read only so many levels deep: a chain +/// of them opens, with a warning. +#[test] +fn soft_masks_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let mask = |i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); + let groups: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = + if i + 1 < CHAIN { (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f") } else { (String::new(), "1 1 1 rg 0 0 100 100 re f") }; + let group = "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >>"; + stream(&format!("{group} /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("soft masks nested too deeply")), "{w:?}"); +} + // ---------- text ---------- const HELVETICA: &str = @@ -712,6 +759,85 @@ fn a_mesh_shading_of_thousands_of_patches_becomes_gradient_meshes() { assert_eq!(all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Mesh(_))).count(), 5000); } +/// The gradient meshes a page drawing shading `sh` (`/Sh0 sh`) comes in as, with the import's +/// warnings. +fn meshes_of(sh: &str) -> (Vec, Vec) { + let s = first_extra(1); + let r = open_with(&one_page("/Sh0 sh", &format!("/Shading << /Sh0 {s} 0 R >>"), &[sh]), |_| {}); + let meshes = all(&r.document).into_iter().filter_map(|n| if let NodeKind::Mesh(m) = n.kind { Some(m) } else { None }).collect(); + (meshes, r.warnings) +} + +/// A tensor-product patch mesh shading's dictionary for [`tensor_patch`] data. +const TENSOR_MESH: &str = "/ShadingType 7 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode"; + +/// One tensor patch over the same boundary as [`coons_patch`], with its four inner points far +/// outside it at (250, 250). +fn tensor_patch() -> Vec { + let mut data = coons_patch(); + let colors = data.split_off(1 + 24); + data.extend([250; 8]); + data.extend(colors); + data +} + +/// A triangle mesh shading's dictionary (types 4 and 5 share their vertex layout). +const TRIANGLE_MESH: &str = "/ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode"; + +/// One triangle: red at (10, 10), green at (90, 10), blue at (50, 90), each vertex with flag 0. +fn triangle() -> Vec { + [[0, 10, 10, 255, 0, 0], [0, 90, 10, 0, 255, 0], [0, 50, 90, 0, 0, 255]].concat() +} + +/// A tensor-product patch mesh (type 7) comes in as the gradient mesh of its boundary, the same +/// mesh a Coons patch over that boundary gives: its inner points do not move it. +#[test] +fn a_tensor_patch_mesh_becomes_the_gradient_mesh_of_its_boundary() { + let (tensor, warnings) = meshes_of(&stream(TENSOR_MESH, &hex(&tensor_patch()))); + let [m] = tensor.as_slice() else { panic!("one mesh: {tensor:?} {warnings:?}") }; + assert_eq!((m.rows, m.cols), (1, 1)); + let at = |r, c| &m.points[m.idx(r, c)]; + assert!((at(0, 0).p - kurbo::Point::new(10.0, 90.0)).hypot() < 0.01, "{:?}", at(0, 0).p); + assert!((at(1, 1).p - kurbo::Point::new(90.0, 10.0)).hypot() < 0.01, "{:?}", at(1, 1).p); + assert_eq!(at(0, 0).color.to_rgb(), [1.0, 0.0, 0.0]); + assert_eq!(at(1, 0).color.to_rgb(), [0.0, 1.0, 0.0]); + assert_eq!(at(1, 1).color.to_rgb(), [0.0, 0.0, 1.0]); + assert_eq!(at(0, 1).color.to_rgb(), [1.0, 1.0, 1.0]); + let (coons, _) = meshes_of(&stream(COONS_MESH, &hex(&coons_patch()))); + assert_eq!(Some(m), coons.first(), "the mesh of a Coons patch over the same boundary"); +} + +/// A triangle mesh (types 4 and 5) comes in as one gradient mesh per triangle, a patch whose last +/// two corners are the triangle's third vertex, each corner in its vertex's color. +#[test] +fn a_triangle_mesh_becomes_a_gradient_mesh() { + let (meshes, warnings) = meshes_of(&stream(TRIANGLE_MESH, &hex(&triangle()))); + let [m] = meshes.as_slice() else { panic!("one mesh: {meshes:?} {warnings:?}") }; + assert_eq!((m.rows, m.cols), (1, 1)); + let at = |r, c| &m.points[m.idx(r, c)]; + // PDF y 10 is page y 90. + let want = [((0, 0), (10.0, 90.0), [1.0, 0.0, 0.0]), ((1, 0), (90.0, 90.0), [0.0, 1.0, 0.0]), ((1, 1), (50.0, 10.0), [0.0, 0.0, 1.0])]; + for ((r, c), (x, y), color) in want { + assert!((at(r, c).p - kurbo::Point::new(x, y)).hypot() < 0.01, "({r}, {c}): {:?}", at(r, c).p); + assert_eq!(at(r, c).color.to_rgb(), color, "({r}, {c})"); + } + assert_eq!(at(0, 1).p, at(1, 1).p, "the third vertex closes the patch"); +} + +/// A tensor patch or triangle mesh of more patches than the importer reads is not a gradient mesh: +/// it comes in as a flat gray, with a warning. +#[test] +fn a_tensor_or_triangle_mesh_over_the_patch_limit_is_a_flat_gray() { + let over = 16_385; + let tensor: Vec = std::iter::repeat_n(tensor_patch(), over).flatten().collect(); + let triangles: Vec = std::iter::repeat_n(triangle(), over).flatten().collect(); + for (name, sh) in [("tensor", stream(TENSOR_MESH, &hex(&tensor))), ("triangle", stream(TRIANGLE_MESH, &hex(&triangles)))] { + let (meshes, warnings) = meshes_of(&sh); + assert!(meshes.is_empty(), "{name}: {} meshes", meshes.len()); + assert!(warnings.iter().any(|w| w.contains("flat grey")), "{name}: {warnings:?}"); + } +} + /// A stroke painted with a mesh shading (how Illustrator writes a freeform gradient on a stroke) /// is the mesh clipped to the area the stroke paints, dashes included, not a flat grey. #[test] diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 33ada6d549..3badde2181 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -506,3 +506,50 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } + +/// Art marked with a membership dictionary is skipped by its policy over its groups, by the page's +/// walk as by the interpreter, so each shown path keeps the ink the walk found it painted in: with +/// "Shapes" on and "Hidden" off, AllOn and AllOff over both are hidden, AnyOff and the default +/// AnyOn show. Groups named by a single reference, not an array, count the same: AllOff over +/// "Hidden" alone shows and AllOff over "Shapes" alone is hidden. +#[test] +fn membership_dictionaries_show_art_by_their_policy() { + let (objs, catalog, [a, b]) = groups(1, "/OFF [{B}]"); + let both = format!("[{a} 0 R {b} 0 R]"); + let runs = [ + ("AllOn", format!("{both} /P /AllOn")), + ("AnyOff", format!("{both} /P /AnyOff")), + ("AllOff", format!("{both} /P /AllOff")), + ("AnyOn", both.clone()), + ("OffAlone", format!("{b} 0 R /P /AllOff")), + ("OnAlone", format!("{a} 0 R /P /AllOff")), + ]; + let memberships: Vec = runs.iter().map(|(_, m)| format!("<< /Type /OCMD /OCGs {m} >>")).collect(); + let first = first_extra(1) + 2; + // Every ink has the same tint transform: only the walk tells the interpreter's paths apart. + let tint = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + let mut content = String::new(); + let (mut props, mut spaces) = (String::new(), String::new()); + for (i, (ink, _)) in runs.iter().enumerate() { + content += &format!("/OC /M{i} BDC /CS{i} cs 1 scn {} 10 5 5 re f EMC ", 10 * i); + props += &format!("/M{i} {} 0 R ", first + i); + spaces += &format!("/CS{i} [/Separation /{ink} /DeviceCMYK {tint}] "); + } + let page = PdfPage { resources: format!("/Properties << {props}>> /ColorSpace << {spaces}>>"), ..PdfPage::new(100.0, 100.0, &content) }; + let mut extra: Vec<&str> = vec![&objs[0], &objs[1]]; + extra.extend(memberships.iter().map(String::as_str)); + let options = ImportOptions { layers: false, ..Default::default() }; + let r = import_with_report(&pdf_with_catalog(&[page], &extra, &catalog, None), &options).unwrap(); + assert_eq!(names(&r.document), ["Page 1"]); + let inks: Vec> = r.document.layers[0] + .children() + .unwrap() + .iter() + .map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(vectorcraft_color::Paint::Solid { swatch, .. }) => swatch.clone(), + _ => None, + }) + .collect(); + let shown = ["AnyOff", "AnyOn", "OffAlone"].map(|s| Some(s.to_string())); + assert_eq!(inks, shown, "{:?}", r.warnings); +} diff --git a/crates/pdf/src/tests/textstroke.rs b/crates/pdf/src/tests/textstroke.rs index 109685c9c7..01b4035be5 100644 --- a/crates/pdf/src/tests/textstroke.rs +++ b/crates/pdf/src/tests/textstroke.rs @@ -556,6 +556,25 @@ fn a_glyph_stroked_again_where_it_was_drawn_stays_one_type_object() { } } +/// The last glyph of a run stroked again where it was drawn, in another stroke color, splits off +/// into its own run with that stroke; the glyphs before it keep theirs. +#[test] +fn the_last_glyph_stroked_again_in_another_color_splits_off_with_that_stroke() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + // Helvetica's A is 667 units wide, so in 48-point type B stands at 20 + 32.016. + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 48 Tf 1 0 0 1 20 80 Tm 2 Tr (AB) Tj 1 0 0 RG 1 Tr 1 0 0 1 52.016 80 Tm (B) Tj 0 Tr ET"; + let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>"; + let d = import(&pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, content) }], None)).unwrap(); + let mut types = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + types.push(t.runs.iter().map(|r| (r.text.clone(), !r.style.fill.is_none(), r.style.stroke.color())).collect::>()); + } + }); + let want = [vec![("A".to_string(), true, Some(Color::BLACK)), ("B".to_string(), true, Some(Color::rgb(1.0, 0.0, 0.0)))]]; + assert_eq!(types, want); +} + /// A stroke pass longer than the importer holds at once ([`MAX_HELD`] strokes) goes over its own /// operator's glyphs, filled right before it, also when an operator before it filled the same /// glyphs at the same places: `A` and 4,095 `B`s filled, then `A` and 4,096 `B`s filled and diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 99ee9a5f0c..9ee678965c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1730,6 +1730,33 @@ fn a_kept_decoded_image_is_drawn_without_decoding_it() { assert!(!image_cached(&cmyk)); } +/// Pixels [`keep_decoded_image`] refuses (here, pixels past the decode allowance) are not +/// kept anywhere: the first render that draws the image decodes it, as for any image. +#[test] +fn a_refused_decoded_image_is_decoded_when_first_drawn() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + // Pixels no other test uses, since every test shares the store. + let img = image::RgbaImage::from_fn(29, 17, |x, y| image::Rgba([(x * 5) as u8, (y * 13) as u8, 41, 255])); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png.clone()); + paint::TEST_ALLOWANCE.with(|c| c.set(Some(64))); + let kept = keep_decoded_image(&blob, image::load_from_memory(&png).unwrap()); + paint::TEST_ALLOWANCE.with(|c| c.set(None)); + assert!(!kept, "past the allowance: the pixels are refused"); + assert!(!image_cached(&blob)); + let mut d = Document::new(29.0, 17.0); + d.images.insert("refused".into(), blob); + let id = d.alloc_id(); + let im = + ImageObject { key: "refused".into(), width: 29, height: 17, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + let decodes = image_decodes(); + let r = Renderer::new().render(&d, 29, 17, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(image_decodes(), decodes + 1, "the first draw decodes the image"); + assert!(r.pixel(14, 8)[3] > 0, "the image is drawn"); +} + /// A CMYK image's inks and the pixels shown from them are admitted against the decode allowance /// before either is made: past it, the image is read as other images are (reduced), not whole. #[test] diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 9fdf4d73ce..6a40857796 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -77,7 +77,7 @@ pub(crate) const REFLECT: &str = "reflect"; pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ -pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "saveAs"]; +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs"]; // Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_FILE_READS: &[&str] = &["open"]; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 05b8077967..9aee330bd4 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -550,6 +550,21 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `imageCapture` writes the file it is given, with or without bounds and options, and +/// called by its name in brackets; `rasterize` stays inside the document. +#[test] +fn image_capture_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument.imageCapture(f);\n", + "var d = app.activeDocument; d.imageCapture(f, [0, 0, 10, 10], new ImageCaptureOptions());\n", + "d['imageCapture'](f);\n", + "d.rasterize(d.pageItems[0]);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 4][..])]); +} + /// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. #[test] fn export_variables_writes_a_file() { diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 76069d802a..d37715f9b9 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -539,8 +539,11 @@ impl Rules<'_> { /// A stroke as a border: weight, style (dashed; dotted for round dots) and colour. fn border(&mut self, s: &StrokeLayer, bounds: Rect, art: &mut Art) { - // Aligned strokes still draw as borders; arrowheads, profiles, brushes and fitted dashes don't. - if !vectorcraft_effects::stroke::is_plain(&StrokeLayer { align: StrokeAlign::Center, ..s.clone() }) { + // Aligned strokes still draw as borders, and evenly spaced round dots as `dotted`; + // arrowheads, profiles, brushes and fitted dashes don't. + let dots = s.dash.as_ref().is_some_and(|d| d.is_dashed() && s.cap == LineCap::Round && !d.align_corners && even_dots(&d.pattern)); + let dash = if dots { None } else { s.dash.clone() }; + if !vectorcraft_effects::stroke::is_plain(&StrokeLayer { align: StrokeAlign::Center, dash, ..s.clone() }) { art.unsupported("arrowheads, width profiles, brushes or dashes fitted to corners"); } let style = match &s.dash { @@ -553,6 +556,11 @@ impl Rules<'_> { Paint::Solid { color, .. } => art.props.push(("border", format!("{width} {style} {}", color_css(color, s.opacity)))), Paint::Gradient(g) => match self.gradient(g, s.paint_bounds(bounds), s.opacity) { Some(css) => { + // A border image takes the place of the border's style + // (https://www.w3.org/TR/css-backgrounds-3/#border-images). + if style != "solid" { + art.unsupported("dashes or dots on a gradient border"); + } art.props.push(("border", format!("{width} {style}"))); art.props.push(("border-image", format!("{css} 1"))); } @@ -803,6 +811,13 @@ fn corners(path: &PathData, live: Option<&LiveShape>) -> Option { } } +/// Whether `pattern` (dash, gap, dash, gap…) draws evenly spaced dots: every dash has zero length +/// and every gap is the same. An odd-length pattern repeats with dashes and gaps swapped, so its +/// dashes can't all be zero unless the whole pattern is. +fn even_dots(pattern: &[f64]) -> bool { + pattern.len().is_multiple_of(2) && pattern.chunks(2).all(|c| c.first() == Some(&0.0) && c.get(1) == pattern.get(1)) +} + /// One closed subpath of four straight sides along the axes. fn is_upright_rectangle(path: &PathData) -> bool { let ([sp], Some(b)) = (path.subpaths.as_slice(), path.bounds()) else { return false }; diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e8c84530d5..140b94e183 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -85,9 +85,8 @@ fn physical_num(v: f64) -> String { return "0".into(); } let leading_zeros = (-v.log10().floor() as i32).max(0); - let decimals = (leading_zeros + 3).clamp(3, 14) as u8; - let s = fmt_num(v, decimals); - if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s } + let decimals = (leading_zeros + 3).max(3); + if decimals > 14 { format!("{v:e}") } else { fmt_num(v, decimals as u8) } } /// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated @@ -186,7 +185,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: .join(nl); svg.doctype_internal("svg", &entities, nl); } - let (ww, hh) = (w.num(rect.width()), w.num(rect.height())); + // A positive pixel size that the chosen decimals round to 0 is written with enough digits to stay positive. + let nonzero = |v: f64, s: String| if v > 0.0 && s == "0" { physical_num(v) } else { s }; + let (ww, hh) = (nonzero(rect.width(), w.num(rect.width())), nonzero(rect.height(), w.num(rect.height()))); let mut root = svg.root().attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); for (ns, prefix) in &w.foreign_ns { root = root.attr(&format!("xmlns:{prefix}"), ns); @@ -197,7 +198,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: if !opts.responsive { // Explicit SVG Options override the document unit; absence keeps its native save behavior. if let Some(unit) = opts.units { - let (width, height) = (unit.length(rect.width(), opts.decimals), unit.length(rect.height(), opts.decimals)); + // Pixels are written bare at one per point. + let (width, height) = + (nonzero(rect.width(), unit.length(rect.width(), opts.decimals)), nonzero(rect.height(), unit.length(rect.height(), opts.decimals))); root = root.attr("width", &width).attr("height", &height); } else if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) { let w_val = physical_num(unit.from_pt(rect.width())); @@ -207,9 +210,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("width", &ww).attr("height", &hh); } } - let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() }; - let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() }; - root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open(); + root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); let mut out = svg.as_str().to_string(); out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 9c1cac5890..4a9e0050e2 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -1126,6 +1126,25 @@ fn weights_spacing_and_decoration() { assert_eq!(style('a').kerning, None); } +/// Font-size keywords scale `medium` (12), `larger` and `smaller` scale the parent's size by 1.2, +/// and `bolder` and `lighter` step from the parent's weight as CSS's relative-weight table says. +#[test] +fn font_size_keywords_and_relative_weights_follow_the_parent() { + let d = open( + r#"abcdefghijklm"#, + ); + let t = only_text(&d); + let style = |c: char| t.runs.iter().find(|r| r.text.contains(c)).unwrap().style.clone(); + let size = |c: char| style(c).size; + assert!(close(size('b'), 18.0, 1e-9), "x-large is 3/2 of medium: {}", size('b')); + assert!(close(size('d'), 12.0, 1e-9), "larger than 10: {}", size('d')); + assert!(close(size('e'), 10.0 / 1.2, 1e-9), "smaller than 10: {}", size('e')); + assert_eq!(style('g').font_style, "Bold", "bolder than 500 is 700"); + assert_eq!(style('i').font_style, "Black", "bolder than 600 is 900"); + assert_eq!(style('k').font_style, "Regular", "lighter than 700 is 400"); + assert_eq!(style('m').font_style, "Bold", "lighter than 900 is 700"); +} + /// `font-variation-settings` becomes the characters' Variable Font settings, inherited as CSS /// inherits it; `normal` and `initial` set none, and `unset` and a value CSS ignores leave the /// inherited settings. diff --git a/crates/svg/tests/it/import_units.rs b/crates/svg/tests/it/import_units.rs index 91138d8a93..1c17c156fe 100644 --- a/crates/svg/tests/it/import_units.rs +++ b/crates/svg/tests/it/import_units.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Document, Node, NodeKind, Unit}; use vectorcraft_geom::Rect; -use vectorcraft_svg::{ExportOptions, export, import}; +use vectorcraft_svg::{ExportOptions, SizeUnit, export, import}; fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); @@ -191,6 +191,28 @@ fn export_physical_units_writes_unit_suffixes() { // Re-importing preserved physical units let back = import(&s).unwrap(); assert_eq!(back.units, Unit::Millimeters); + + // A small positive size in pixels keeps a nonzero width and height, with the document unit + // and with Pixels chosen in the SVG options + for (w, h) in [(0.0004, 0.0002), (1e-17, 2e-17), (5.1e-17, 1e-17), (5.1e-15, 4.9e-15)] { + let mut d = Document::new(w, h); + d.units = Unit::Pixels; + for opts in [ExportOptions::default(), ExportOptions { units: Some(SizeUnit::Px), ..Default::default() }] { + let s = export(&d, &opts); + let num = |name: &str| -> f64 { root_attr(&s, name).and_then(|v| v.parse().ok()).unwrap_or_else(|| panic!("{name}: {s}")) }; + let view: Vec = root_attr(&s, "viewBox").unwrap_or_default().split(' ').filter_map(|v| v.parse().ok()).collect(); + for (got, want) in [(num("width"), w), (num("height"), h), (view[2], w), (view[3], h)] { + assert!((got - want).abs() <= want * 1e-3, "{got} for {want}: {s}"); + } + } + } +} + +/// The value of attribute `name` on `svg`'s root element. +fn root_attr<'a>(svg: &'a str, name: &str) -> Option<&'a str> { + let start = svg.find("').next()?; + tag.split(&format!(" {name}=\"")).nth(1)?.split('"').next() } /// The `width` of `svg`'s root as a length in points, read by the SVG and CSS absolute units diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index f2a7e4835e..78ff31af5f 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -190,6 +190,40 @@ mod alias_tests { assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss"); } + /// The file search for a character no loaded font covers skips font files over 40 MiB + /// without reading them, and loads the same font at its own length. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_file_search_skips_font_files_over_40_mib() { + use crate::{FileFontInfo, FileGlyph, build_file_font}; + use kurbo::Shape; + let pua = '\u{E123}'; + let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() }; + let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; + let font = build_file_font(&info, &[glyph]).unwrap(); + // Removes the folder when dropped, so a panic part way through does not leave the 41 MiB file behind. + struct TempDir(std::path::PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let search = |name: &str, bytes: &[u8]| { + let dir = TempDir(std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir(&dir.0).unwrap(); + std::fs::write(dir.0.join("Pua.ttf"), bytes).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.0.clone()]); + let found = db.system_fallback(pua); + std::fs::remove_dir_all(&dir.0).unwrap(); + found + }; + assert!(search("small", &font), "a font at its own length is loaded"); + let mut padded = font.clone(); + padded.resize(41 << 20, 0); + assert!(!search("padded", &padded), "the same font padded to 41 MiB is skipped"); + } + #[test] fn a_collection_lists_at_most_max_faces() { let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]); diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 54e4125e88..2fd95fd6b2 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -793,7 +793,77 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, #[cfg(test)] mod tests { - use super::longest_start_tried; + use super::{Affine, ArcPath, BezPath, GlyphBend, PathEl, Point, bend_outline, longest_start_tried}; + use vectorcraft_geom::{Rect, shapes}; + + /// A glyph-sized rectangle in pen space, `w` wide and `h` tall, standing on the baseline. + fn block(w: f64, h: f64) -> BezPath { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((w, 0.0)); + p.line_to((w, h)); + p.line_to((0.0, h)); + p.close_path(); + p + } + + fn end_points(path: &BezPath) -> Vec { + path.elements() + .iter() + .filter_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), + PathEl::ClosePath => None, + }) + .collect() + } + + /// Bent along a circle, a rectangle's baseline edge follows the circle and its other edge + /// follows a circle `h` farther along the path's normal; its corners stay at the ends of its + /// step along the path. Moving it off the path (`rise`) moves both edges by the same amount. + #[test] + fn an_outline_bent_along_a_circle_follows_it() { + let (center, r) = (Point::new(100.0, 100.0), 100.0); + let ap = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + let (w, h, s) = (40.0, 20.0, 30.0); + let (p0, d0) = ap.at(s); + let (p1, _) = ap.at(s + w); + // Which way the path's normal points: away from the center (+1) or towards it (-1). + let side = (kurbo::Vec2::new(-d0.y, d0.x).dot(p0 - center)).signum(); + let at_radius = |p: Point, radius: f64| center + (p - center) * (radius / r); + for rise in [0.0, 5.0] { + let bend = GlyphBend { s, step: w, advance: w, rise }; + let bent = bend_outline(&block(w, h), Affine::IDENTITY, &ap, &bend).expect("a turning path bends the outline"); + let points = end_points(&bent); + let (base, top) = (r + side * rise, r + side * (rise + h)); + let corners = [at_radius(p0, base), at_radius(p1, base), at_radius(p1, top), at_radius(p0, top)]; + for c in corners { + assert!(points.iter().any(|p| p.distance(c) < 0.1), "rise {rise}: no point near the corner {c:?} in {points:?}"); + } + // The edges are cut into pieces that stay between the two circles; a straight chord + // between the corners would pass inside the inner one. + assert!(points.len() > 8, "rise {rise}: {} points", points.len()); + let (inner, outer) = (base.min(top), base.max(top)); + for p in &points { + let d = p.distance(center); + assert!(d > inner - 0.1 && d < outer + 0.1, "rise {rise}: {p:?} lies {d} from the center, outside {inner}..{outer}"); + } + let on_base = points.iter().filter(|p| (p.distance(center) - base).abs() < 0.1).count(); + assert!(on_base > 2, "rise {rise}: only {on_base} points on the baseline circle"); + } + } + + /// A path that does not turn under the glyph, and a glyph with no advance, leave the outline + /// as it is. + #[test] + fn an_outline_on_a_straight_path_is_not_bent() { + let line = ArcPath::new(&shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0))); + let bend = GlyphBend { s: 30.0, step: 40.0, advance: 40.0, rise: 0.0 }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &line, &bend).is_none()); + let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &bend).is_some()); + let no_advance = GlyphBend { advance: 0.0, ..bend }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &no_advance).is_none()); + } /// The longest start that fits is found among the ones tried; past the tries, a binary search /// finds one that fits, with as many more tries as halvings of the rest. diff --git a/crates/three-d/Cargo.toml b/crates/three-d/Cargo.toml index 48d2bfbf05..b5153163ce 100644 --- a/crates/three-d/Cargo.toml +++ b/crates/three-d/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-pathops = { workspace = true } +craft-pbr = { workspace = true } [dev-dependencies] proptest = { workspace = true } diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 891ff4fcbc..f561c0b7c6 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -21,6 +21,8 @@ mod shading; pub use shading::{ClassicShading, ClassicSurface, LightGradient, RgbGradient, ShadeGradient}; mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; +mod material; +pub use material::{Highlight, Material}; mod caps; mod mesh; pub use mesh::{ @@ -106,6 +108,9 @@ pub struct Revolve { /// Ambient Light, 0 to 2. pub ambient: f64, pub shade: bool, + /// The surface's Roughness and Metallic. [`Material::DEFAULT`] shades as before they existed; + /// any other material adds its specular light ([`Highlight`]). + pub material: Material, /// Interpolate profile normals using vector gradients. Enabled by default. pub smooth_shading: bool, /// Close circular endpoint rings of open profiles (sectors on a partial sweep), and the two @@ -149,6 +154,7 @@ impl Default for Revolve { lights: None, ambient: 0.25, shade: true, + material: Material::DEFAULT, smooth_shading: true, cap_ends: true, fill_rule: FillRule::NonZero, @@ -377,6 +383,9 @@ pub struct Face { pub illumination: [f64; 3], pub light_gradient: Option, pub rgb_gradient: Option, + /// The light a material other than [`Material::DEFAULT`] reflects over the paint; `None` for + /// the default material and when the face is not shaded. + pub highlight: Option, /// Curved vector boundary; points remain a bounded visibility approximation. pub outline: Option, /// A single endpoint disk or sector, with its axis centre first in points. @@ -695,6 +704,29 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi if area.abs() < 1e-10 { return Ok(None); } + if material::shades(&o) { + let seen = |n: &V3| if n.dot(normal) < 0.0 { V3(-n.0, -n.1, -n.2) } else { *n }; + let corners: Vec = normals + .map(|normals| normals.iter().zip(vertices).map(|(n, v)| material::lit(&o, seen(n), material::to_eye(eye, *v), light)).collect()) + .unwrap_or_default(); + let shading = Shading::of(&points, &corners, material::lit(&o, normal, material::to_eye(eye, centre), light)); + return Ok(Some(Face { + points, + depth: vertices.iter().map(|v| v.2).sum::() / vertices.len() as f64, + normal: [normal.0, normal.1, normal.2], + brightness: shading.brightness, + gradient: shading.gradient, + illumination: shading.illumination, + light_gradient: shading.light_gradient, + rgb_gradient: shading.rgb_gradient, + highlight: Some(shading.highlight), + outline: None, + cap: false, + visibility_pieces: None, + surface: None, + plane, + })); + } let (brightness, gradient) = if let Some(normals) = normals { let values: Vec<_> = normals .iter() @@ -741,6 +773,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi illumination, light_gradient, rgb_gradient, + highlight: None, outline: None, cap: false, visibility_pieces: None, @@ -749,6 +782,63 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi })) } +/// A face's lighting under a material other than [`Material::DEFAULT`]. +pub(crate) struct Shading { + pub(crate) brightness: f64, + pub(crate) gradient: Option, + pub(crate) illumination: [f64; 3], + /// The tone ramp with the face's mean hue for mapped graphics. Proportional, unclipped RGB + /// channels share this ramp exactly; independent channel placements retain only their mean hue. + pub(crate) light_gradient: Option, + pub(crate) rgb_gradient: Option, + pub(crate) highlight: Highlight, +} + +impl Shading { + /// The lighting of a face drawn at `points` whose corners are lit as `corners` (none for a + /// flatly shaded face) and whose own normal is lit as `flat`. A face with corner values takes + /// their mean; three corners also give the smooth ramps. + pub(crate) fn of(points: &[Point], corners: &[material::Lit], flat: material::Lit) -> Self { + let mean = |pick: fn(&material::Lit) -> [f64; 3]| -> [f64; 3] { + if corners.is_empty() { + return pick(&flat); + } + let mut sum = [0.0; 3]; + for c in corners { + for (s, v) in sum.iter_mut().zip(pick(c)) { + *s += v; + } + } + sum.map(|s| s / corners.len() as f64) + }; + let illumination = mean(|l| l.paint).map(|v| v.clamp(0.0, 1.0)); + let average = |rgb: [f64; 3]| (rgb[0] + rgb[1] + rgb[2]) / 3.0; + let paints: Vec<[f64; 3]> = corners.iter().map(|c| c.paint).collect(); + let overs: Vec<[f64; 3]> = corners.iter().map(|c| c.over).collect(); + let tones: Vec = paints.iter().map(|p| average(p.map(|v| v.clamp(0.0, 1.0)))).collect(); + let brightness = average(illumination); + let gradient = ShadeGradient::triangle(points, &tones); + let rgb_gradient = RgbGradient::triangle(points, &paints); + let light_gradient = rgb_gradient.map(|rgb| LightGradient { + diffuse: gradient.unwrap_or(ShadeGradient { + start: rgb.channels[0].start, + end: rgb.channels[0].start, + brightness: [tones.iter().sum::() / tones.len() as f64; 2], + }), + ambient: 0.0, + color: if brightness == 0.0 || illumination == [illumination[0]; 3] { [1.0; 3] } else { illumination.map(|v| v / brightness) }, + }); + Self { + brightness, + gradient, + illumination, + light_gradient, + rgb_gradient, + highlight: Highlight { flat: mean(|l| l.over), ramp: RgbGradient::triangle(points, &overs) }, + } + } +} + /// 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> { diff --git a/crates/three-d/src/material.rs b/crates/three-d/src/material.rs new file mode 100644 index 0000000000..fef547d017 --- /dev/null +++ b/crates/three-d/src/material.rs @@ -0,0 +1,395 @@ +//! A surface's Roughness and Metallic, and the light they reflect. +//! +//! The specular light of each light and of the environment is craft-pbr's metallic-roughness BRDF: +//! glTF 2.0's Appendix B form with B.3.2's separable Smith visibility (B.3.5, +//! ) for a +//! directional light, and the split sum of Karis 2013 over craft-pbr's default studio environment. +//! Schlick's Fresnel (B.3.4) is linear in the reflectance at normal incidence `f0`, and +//! `f0 = 0.04 (1 − metallic) + base × metallic`, so the specular light of a paint `base` is +//! `base × A + B` for two values that do not depend on the paint. [`Lit::paint`] holds the diffuse +//! light plus `A`, which scales the paint as the lighting does today, and [`Lit::over`] holds `B`, +//! which is screened over the shaded paint. The diffuse light is the softened Lambert term of the +//! lights, scaled by `(1 − F) (1 − metallic)` with the Fresnel term `F` of the 0.04 dielectric +//! reflectance, and Ambient Light scaled by `1 − metallic`. +//! +//! The effects draw `paint` as a color layer that multiplies the paint, so each channel of `paint` is +//! clamped to 0..1 where it is drawn (`Shading::of`). Where a bright light or a low Roughness +//! makes `paint` greater than 1, the drawn face stops at that limit. The highlight `h` is also +//! drawn with Screen, so the drawn color is `p + h − p × h` for the shaded paint `p`, not `p + h`. + +use std::sync::OnceLock; + +use craft_pbr::{EnvImage, Limits, Material as Brdf, PrefilterOptions}; + +use crate::{Revolve, V3}; + +/// The reflectance at normal incidence of a dielectric, as glTF 2.0 gives it. +const DIELECTRIC: f64 = 0.04; + +/// A surface's Roughness and Metallic, each from 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Material { + roughness: f64, + metallic: f64, +} + +impl Default for Material { + fn default() -> Self { + Self::DEFAULT + } +} + +impl Material { + /// Roughness 1 and Metallic 0: the surface the 3D effects draw without a material, shaded + /// exactly as before Roughness and Metallic existed. + pub const DEFAULT: Self = Self { roughness: 1.0, metallic: 0.0 }; + + /// A material, or `None` unless `roughness` and `metallic` are both numbers from 0 to 1. + pub fn new(roughness: f64, metallic: f64) -> Option { + let unit = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v); + (unit(roughness) && unit(metallic)).then_some(Self { roughness, metallic }) + } + + pub fn roughness(self) -> f64 { + self.roughness + } + + pub fn metallic(self) -> f64 { + self.metallic + } + + /// Is this [`Material::DEFAULT`]? + pub fn is_default(self) -> bool { + self == Self::DEFAULT + } +} + +/// The light a surface with a material other than [`Material::DEFAULT`] reflects over its paint: +/// the RGB values screened over the shaded paint at the face's normal (`flat`), and on a smoothly +/// shaded triangle, those values interpolated from its corners (`ramp`), before each channel is +/// clipped to 0..1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Highlight { + pub flat: [f64; 3], + pub ramp: Option, +} + +/// The light at one point of a surface ([`lit`]): what scales the paint, per RGB channel, and +/// what is screened over it. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Lit { + pub(crate) paint: [f64; 3], + pub(crate) over: [f64; 3], +} + +/// Does `o` shade with its material ([`lit`]) rather than as before materials existed? Only when +/// it is shaded and its material is not [`Material::DEFAULT`]. +pub(crate) fn shades(o: &Revolve) -> bool { + o.shade && !o.material.is_default() +} + +/// The unit direction from view-space point `at` to the eye at `eye` in front of the center, or +/// straight toward the viewer without perspective (`None`) or when `at` is at the eye. +pub(crate) fn to_eye(eye: Option, at: V3) -> V3 { + let v = eye.map_or(V3(0.0, 0.0, 1.0), |e| V3(0.0, 0.0, e).sub(at).unit()); + if v.dot(v) < 0.5 { V3(0.0, 0.0, 1.0) } else { v } +} + +#[cfg(test)] +thread_local! { + /// How many times this thread has evaluated craft-pbr's direct BRDF, for the tests. + pub(crate) static DIRECT_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The specular light of one light from direction `l` on a surface with normal `n` seen from `v`, +/// per unit of the light's color and intensity, for `f0` 0 and for `f0` 1 (craft-pbr's +/// [`Brdf::try_direct`] with a metal whose base color holds both). 0 for directions that are not +/// finite. +fn specular(n: V3, v: V3, l: V3, roughness: f64) -> [f64; 2] { + #[cfg(test)] + DIRECT_CALLS.with(|c| c.set(c.get() + 1)); + let f = |p: V3| [p.0 as f32, p.1 as f32, p.2 as f32]; + let Ok(metal) = Brdf::try_new([0.0, 1.0, 0.0], 1.0, roughness as f32) else { return [0.0; 2] }; + let metal = metal.with_visibility(craft_pbr::Visibility::SmithSeparable); + match metal.try_direct(f(n), f(v), f(l)) { + Ok([zero, one, _]) if zero.is_finite() && one.is_finite() => [f64::from(zero).max(0.0), f64::from(one).max(f64::from(zero))], + _ => [0.0; 2], + } +} + +/// craft-pbr's default studio environment, GGX-prefiltered once per process into its six +/// roughness levels; `None` when it could not be built. +fn environment() -> Option<&'static [EnvImage]> { + static CHAIN: OnceLock>> = OnceLock::new(); + CHAIN + .get_or_init(|| { + let env = craft_pbr::default_environment().ok()?; + craft_pbr::try_prefilter(&env, &PrefilterOptions::default(), &Limits::default()).ok() + }) + .as_deref() +} + +/// The environment's prefiltered radiance in view-space direction `d` (x right, y down, z toward +/// the viewer) for `roughness`, between the two levels nearest it. The environment's up is the +/// page's up, and its +X the page's right. 0 when it is unavailable. +fn environment_light(d: V3, roughness: f64) -> [f64; 3] { + let Some(chain) = environment().filter(|c| !c.is_empty()) else { return [0.0; 3] }; + let dir = [d.0 as f32, -d.1 as f32, d.2 as f32]; + let at = roughness.clamp(0.0, 1.0) * (chain.len() - 1) as f64; + let (lo, t) = (at.floor() as usize, at - at.floor()); + let sample = |k: usize| chain.get(k.min(chain.len() - 1)).and_then(|level| level.sample(dir).ok()).map(|c| c.map(f64::from)); + match (sample(lo), sample(lo + 1)) { + (Some(a), Some(b)) => std::array::from_fn(|c| a[c] + (b[c] - a[c]) * t), + (Some(a), None) => a, + _ => [0.0; 3], + } +} + +/// The light at a point with unit normal `n` (turned to the side the viewer sees) seen from unit +/// direction `v`, under `o`'s lights (or its single light from `legacy`) and environment, for +/// `o`'s material ([`Lit`]). +pub(crate) fn lit(o: &Revolve, n: V3, v: V3, legacy: V3) -> Lit { + let (roughness, metallic) = (o.material.roughness, o.material.metallic); + let mut out = Lit { paint: [o.ambient * (1.0 - metallic); 3], over: [0.0; 3] }; + let mut add = |l: V3, color: [f64; 3], intensity: f64, softness: f64| { + let diffuse = intensity * ((n.dot(l) + softness) / (1.0 + softness)).max(0.0); + let h = V3(v.0 + l.0, v.1 + l.1, v.2 + l.2).unit(); + let k = if h.dot(h) < 0.5 { 0.0 } else { (1.0 - v.dot(h).max(0.0)).clamp(0.0, 1.0).powi(5) }; + let fresnel = DIELECTRIC + (1.0 - DIELECTRIC) * k; + let [zero, one] = if n.dot(l) > 0.0 { specular(n, v, l, roughness) } else { [0.0; 2] }; + let lobe = one - zero; + for c in 0..3 { + out.paint[c] += color[c] * (diffuse * (1.0 - fresnel) * (1.0 - metallic) + intensity * metallic * lobe); + out.over[c] += color[c] * intensity * (DIELECTRIC * (1.0 - metallic) * lobe + zero); + } + }; + match o.lights { + Some(lights) => { + for light in lights.iter() { + let [x, y, z] = light.direction(); + add(V3(x, y, z), light.color, light.intensity, light.softness); + } + } + None => add(legacy, o.light_color, o.light_intensity, o.light_softness), + } + let n_v = n.dot(v); + let reflected = V3(2.0 * n_v * n.0 - v.0, 2.0 * n_v * n.1 - v.1, 2.0 * n_v * n.2 - v.2).unit(); + if let (Ok([scale, bias]), true) = (craft_pbr::try_environment_brdf(n_v as f32, roughness as f32), reflected.dot(reflected) > 0.5) { + let (scale, bias) = (f64::from(scale), f64::from(bias)); + let radiance = environment_light(reflected, roughness); + for c in 0..3 { + let e = radiance[c] * o.ambient; + out.paint[c] += e * metallic * scale; + out.over[c] += e * (DIELECTRIC * (1.0 - metallic) * scale + bias); + } + } + let finite = |v: [f64; 3]| v.map(|c| if c.is_finite() { c.max(0.0) } else { 0.0 }); + Lit { paint: finite(out.paint), over: finite(out.over) } +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_geom::{Rect, Shape}; + + /// One white light of intensity 1 from `l`, no softness and no ambient (so no environment), in + /// `material`. + fn one_light(material: Material) -> Revolve { + Revolve { ambient: 0.0, light_intensity: 1.0, light_softness: 0.0, light_color: [1.0; 3], lights: None, material, ..Revolve::default() } + } + + #[test] + fn a_material_takes_numbers_from_0_to_1_only() { + for (r, m) in [(0.0, 0.0), (1.0, 1.0), (0.5, 0.25)] { + assert!(Material::new(r, m).is_some(), "{r} {m}"); + } + for (r, m) in [(f64::NAN, 0.0), (0.5, f64::INFINITY), (f64::NEG_INFINITY, 0.0), (-0.01, 0.0), (1.01, 0.0), (0.0, -0.5), (0.0, 1.5)] { + assert_eq!(Material::new(r, m), None, "{r} {m}"); + } + assert!(Material::DEFAULT.is_default() && Material::default().is_default()); + assert!(!Material::new(0.99, 0.0).is_some_and(Material::is_default)); + } + + /// The paint scale and the screened light split craft-pbr's direct BRDF exactly: for any base + /// color, `base × paint + over` is craft-pbr's whole result for a dielectric and for a metal. + #[test] + fn the_paint_and_its_highlight_add_up_to_the_brdf() { + let (n, v) = (V3(0.0, 0.0, 1.0), V3(0.3, -0.2, 0.93).unit()); + let l = V3(-0.4, -0.5, 0.77).unit(); + for (roughness, metallic) in [(0.2, 0.0), (0.6, 0.0), (0.2, 1.0), (0.7, 1.0), (1.0, 1.0)] { + let Some(material) = Material::new(roughness, metallic) else { panic!("{roughness} {metallic}") }; + let lit = lit(&one_light(material), n, v, l); + for base in [[0.8f32, 0.2, 0.1], [0.1, 0.5, 0.9], [1.0, 1.0, 1.0]] { + let Ok(brdf) = Brdf::try_new(base, metallic as f32, roughness as f32) else { panic!("material") }; + let brdf = brdf.with_visibility(craft_pbr::Visibility::SmithSeparable); + let f = |p: V3| [p.0 as f32, p.1 as f32, p.2 as f32]; + let Ok(want) = brdf.try_direct(f(n), f(v), f(l)) else { panic!("brdf") }; + for c in 0..3 { + let got = f64::from(base[c]) * lit.paint[c] + lit.over[c]; + assert!((got - f64::from(want[c])).abs() < 1e-4, "{roughness} {metallic} {base:?} channel {c}: {got} vs {}", want[c]); + } + } + } + } + + /// Compares the full Appendix B result for metallic 0 and 1. At metallic 0.5 only the specular + /// term is compared: the diffuse uses dielectric Fresnel regardless of metallic, while the + /// specular term uses the base-dependent f0 of B.3.4. Softness and ambient are zero, so these + /// comparisons are exact, including the Fresnel-weighted Lambert term at metallic 0. + #[test] + fn specular_matches_the_gltf_formula() { + let directions = [ + (V3(0.0, 0.0, 1.0), V3(0.3, -0.2, 0.93), V3(-0.4, -0.5, 0.77)), + (V3(0.2, 0.1, 1.0), V3(-0.2, 0.4, 1.0), V3(0.6, -0.1, 0.8)), + (V3(-0.1, 0.3, 1.0), V3(0.4, 0.2, 1.0), V3(-0.5, 0.4, 1.0)), + ]; + let pi = std::f64::consts::PI; + for roughness in [0.1_f64, 0.5, 0.9] { + for metallic in [0.0, 0.5, 1.0] { + for (n, v, l) in directions { + let (n, v, l) = (n.unit(), v.unit(), l.unit()); + let h = V3(v.0 + l.0, v.1 + l.1, v.2 + l.2).unit(); + let (nl, nv, nh, vh) = (n.dot(l), n.dot(v), n.dot(h), v.dot(h)); + assert!(nl > 0.3 && nv > 0.3); + let a = roughness * roughness; + let a2 = a * a; + let root = |x: f64| (a2 + (1.0 - a2) * x * x).sqrt(); + let visibility = 1.0 / ((nl + root(nl)) * (nv + root(nv))); + let distribution = a2 / (pi * (nh * nh * (a2 - 1.0) + 1.0).powi(2)); + let k = (1.0 - vh).powi(5); + let material = Material::new(roughness, metallic).unwrap_or_else(|| panic!("material")); + let got = lit(&one_light(material), n, v, l); + for base in [[0.8, 0.2, 0.1], [0.1, 0.5, 0.9]] { + for c in 0..3 { + let f0 = 0.04 * (1.0 - metallic) + base[c] * metallic; + let fresnel = f0 + (1.0 - f0) * k; + let specular = fresnel * distribution * visibility * nl * pi; + let diffuse = (1.0 - fresnel) * (1.0 - metallic) * base[c] * nl; + let (actual, expected) = if metallic == 0.5 { + // Remove the softened Lambert term to isolate base * metallic * lobe + over. + let dielectric_f = 0.04 + 0.96 * k; + (base[c] * (got.paint[c] - nl * (1.0 - dielectric_f) * (1.0 - metallic)) + got.over[c], specular) + } else { + (base[c] * got.paint[c] + got.over[c], diffuse + specular) + }; + assert!((actual - expected).abs() < 1e-4, "{roughness} {metallic} {n:?} {v:?} {l:?} channel {c}: {actual} vs {expected}"); + } + } + } + } + } + } + + /// glTF 2.0's BRDF at normal incidence: with n = v = l, h = n, so the GGX D is 1 / (π α²) for + /// α = roughness², Fresnel is f0, and a metal reflects its base color while a dielectric + /// reflects 0.04 of the light over a diffuse 0.96 × (1 − metallic). + #[test] + fn at_normal_incidence_a_dielectric_reflects_four_percent_over_its_diffuse_light() { + let n = V3(0.0, 0.0, 1.0); + let Some(material) = Material::new(0.5, 0.0) else { panic!("material") }; + let dielectric = lit(&one_light(material), n, n, n); + let Some(metal) = Material::new(0.5, 1.0) else { panic!("material") }; + let metal = lit(&one_light(metal), n, n, n); + // The lobe of a white metal is the dielectric's highlight over 0.04. + let lobe = metal.paint[0]; + assert!(lobe > 0.0, "{metal:?}"); + for c in 0..3 { + assert!((dielectric.paint[c] - 0.96).abs() < 1e-6, "diffuse {:?}", dielectric.paint); + assert!((dielectric.over[c] - 0.04 * lobe).abs() < 1e-6, "{dielectric:?} {metal:?}"); + assert!(metal.over[c].abs() < 1e-6, "a metal's highlight is its paint: {metal:?}"); + } + // D V π at α = 0.25, with V from craft-pbr's visibility, falls as roughness rises. + let Some(rough) = Material::new(0.9, 1.0) else { panic!("material") }; + assert!(lit(&one_light(rough), n, n, n).paint[0] < lobe); + } + + #[test] + fn light_from_behind_the_surface_reflects_no_highlight() { + let Some(material) = Material::new(0.1, 0.5) else { panic!("material") }; + let lit = lit(&one_light(material), V3(0.0, 0.0, 1.0), V3(0.0, 0.0, 1.0), V3(0.0, 0.0, -1.0)); + assert_eq!(lit.over, [0.0; 3]); + assert_eq!(lit.paint, [0.0; 3]); + } + + /// The environment adds light only through Ambient Light: with it, a smooth metal facing the + /// viewer is lit even with its lights turned away. + #[test] + fn ambient_light_reflects_the_studio_environment() { + let Some(material) = Material::new(0.1, 1.0) else { panic!("material") }; + let o = Revolve { ambient: 1.0, light_intensity: 0.0, material, ..Revolve::default() }; + let n = V3(0.0, 0.0, 1.0); + let lit = lit(&o, n, n, V3(0.0, 0.0, -1.0)); + assert!(lit.paint.iter().all(|c| *c > 0.0 && c.is_finite()), "{lit:?}"); + } + + fn square() -> vectorcraft_geom::PathData { + vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, 40.0, 80.0).to_path(0.1)) + } + + /// Revolve's faces with the default material are those of the shading without materials: no + /// highlight, and craft-pbr is not called. + #[test] + fn the_default_material_shades_as_before_and_calls_no_brdf() { + DIRECT_CALLS.with(|c| c.set(0)); + let faces = crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), Revolve::default()).unwrap_or_default(); + assert!(!faces.is_empty()); + assert!(faces.iter().all(|f| f.highlight.is_none())); + assert_eq!(DIRECT_CALLS.with(std::cell::Cell::get), 0); + let Some(material) = Material::new(0.4, 0.3) else { panic!("material") }; + let shaded = crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), Revolve { material, ..Revolve::default() }).unwrap_or_default(); + assert_eq!(shaded.len(), faces.len()); + assert!(shaded.iter().all(|f| f.highlight.is_some())); + // One evaluation per lit point of each face: its normal and its smooth corners. + let calls = DIRECT_CALLS.with(std::cell::Cell::get); + assert!(calls > 0 && calls <= faces.len() * 5, "{calls} for {} faces", faces.len()); + let unshaded = + crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), Revolve { material, shade: false, ..Revolve::default() }).unwrap_or_default(); + assert!(unshaded.iter().all(|f| f.highlight.is_none())); + } + + /// Mapped graphics follow each smooth material face's RGB lighting under a white light, + /// including triangles whose lighting is constant. + #[test] + fn a_materials_graphic_light_matches_its_rgb_ramp_under_white_light() { + let Some(material) = Material::new(0.4, 0.0) else { panic!("material") }; + let faces = crate::revolve(&square(), Rect::new(0.0, 0.0, 40.0, 80.0), one_light(material)).unwrap_or_default(); + let color = [0.2, 0.5, 0.8]; + let mut smooth_faces = 0; + let mut varying_faces = 0; + for face in &faces { + let Some(rgb) = face.rgb_gradient else { continue }; + smooth_faces += 1; + varying_faces += usize::from(face.gradient.is_some()); + let Some(light) = face.light_gradient else { panic!("a material RGB face must also shade its graphics smoothly") }; + for &point in &face.points { + let want = rgb.at(point); + let got = light.at(point); + let scale = (0..3).map(|c| color[c] * want[c]).fold(0.0, f64::max); + for c in 0..3 { + let error = (color[c] * got[c] - color[c] * want[c]).abs(); + assert!(error <= 1e-6 * scale, "at {point:?}, channel {c}: {got:?} vs {want:?}"); + } + } + } + assert!(smooth_faces > 0, "the revolved square must have smooth RGB faces"); + assert!(varying_faces > 0, "the graphic lighting must be checked across a varying ramp"); + } + + /// The step from the default material to the nearest others, measured on Revolve's faces: the + /// largest change of a face's brightness and of its highlight. + #[test] + fn the_nearest_materials_to_the_default_change_the_shading_by_a_measured_step() { + let b = Rect::new(0.0, 0.0, 40.0, 80.0); + let faces = |material| crate::revolve(&square(), b, Revolve { material, ..Revolve::default() }).unwrap_or_default(); + let base = faces(Material::DEFAULT); + for (r, m) in [(0.99, 0.0), (1.0, 0.01)] { + let Some(material) = Material::new(r, m) else { panic!("material") }; + let near = faces(material); + assert_eq!(near.len(), base.len()); + let brightness = base.iter().zip(&near).map(|(a, b)| (a.brightness - b.brightness).abs()).fold(0.0, f64::max); + let highlight = near.iter().filter_map(|f| f.highlight).map(|h| h.flat.iter().copied().fold(0.0, f64::max)).fold(0.0, f64::max); + println!("roughness {r} metallic {m}: brightness changes by at most {brightness:.4}, highlight at most {highlight:.4}"); + assert!(brightness < 0.1 && highlight < 0.1, "{r} {m}: {brightness} {highlight}"); + } + } +} diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 49e42e6732..deeaab4dde 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -4,7 +4,7 @@ //! z-axis, about the centre of its bounds, at the art's own position and size. Planar faces (caps //! and the rotated plane) are drawn whole, holes included, so no triangulation is needed; curved //! faces are cut into small facets. Colored Inflate interpolates shared membrane normals; -//! bevels and side walls retain their planar lighting. +//! bevel bands interpolate shared normals for non-default materials, and side walls retain planar lighting. //! //! Visibility is a painter's algorithm, as for Revolve: faces of a closed solid that face away //! from the viewer are left out, the rest are drawn back to front. @@ -60,6 +60,8 @@ pub struct View { pub lights: Option, pub ambient: f64, pub shade: bool, + /// The surface's Roughness and Metallic, as Revolve's. + pub material: crate::Material, } impl Default for View { @@ -79,6 +81,7 @@ impl Default for View { lights: r.lights, ambient: r.ambient, shade: r.shade, + material: r.material, } } } @@ -90,6 +93,12 @@ impl View { view.lights.map_or(view.light_color != [1.0; 3], |lights| lights.iter().any(|light| light.color != [1.0; 3])) } + /// Whether the view shades with a material other than [`crate::Material::DEFAULT`], which also + /// needs RGB shading: its highlight ([`Facet::highlight`]) and a metal's tint. + pub fn shades_material(self) -> bool { + crate::material::shades(&self.revolve()) + } + /// The same rotation, projection and lighting maths as Revolve's. fn revolve(self) -> Revolve { Revolve { @@ -106,6 +115,7 @@ impl View { lights: self.lights, ambient: self.ambient, shade: self.shade, + material: self.material, ..Revolve::default() } .sanitized() @@ -402,8 +412,12 @@ pub struct Facet { /// The face's unit normal in view space (x right, y down, z toward the viewer), turned to the /// side the viewer sees. pub normal: [f64; 3], - /// Smooth lighting on an inflated triangle, before clipping individual RGB channels. + /// Smooth lighting on an inflated triangle or a bevel-band triangle, before clipping + /// individual RGB channels. pub rgb_gradient: Option, + /// The light a material other than [`crate::Material::DEFAULT`] reflects over the paint; + /// `None` for the default material and when the facet is not shaded. + pub highlight: Option, /// The facet's outline with the profile's curves kept as cubics, for [`Facet::path`]. The /// contours stay the polygon that visibility and depth use. pub outline: Option, @@ -518,6 +532,7 @@ impl Facet { illumination: face.illumination, normal: face.normal, rgb_gradient: None, + highlight: face.highlight, outline: face.outline, side: !face.cap, // A revolved cap is not one of the planar faces graphics map onto. diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 63a6e76e68..8d74f3135f 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -201,6 +201,8 @@ pub(super) struct Builder<'a> { /// A closed solid keeps the faces turned away from the viewer too, with their outward normals, /// drawn behind the others. pub(super) hidden: bool, + /// Whether doubling every band face fits within the solid's face limit. + pub(super) split_bands: bool, pub(super) facets: Vec, /// With `Some`, every face goes here as it is, none hidden or projected, for a mesh. pub(super) mesh: Option>, @@ -244,6 +246,7 @@ impl<'a> Builder<'a> { camera, closed, hidden, + split_bands: false, facets: vec![], mesh: (keep != Keep::Facets).then(Vec::new), draw: keep != Keep::Faces, @@ -342,13 +345,21 @@ impl<'a> Builder<'a> { } else { centre.2 }; + let (brightness, illumination, highlight) = if crate::material::shades(&self.camera.view) { + let flat = crate::material::lit(&self.camera.view, n, crate::material::to_eye(self.camera.eye, centre), self.camera.light); + let shading = crate::Shading::of(&[], &[], flat); + (shading.brightness, shading.illumination, Some(shading.highlight)) + } else { + (self.camera.brightness(n), crate::illumination(&self.camera.view, n, self.camera.light), None) + }; self.facets.push(Facet { contours, depth, - brightness: self.camera.brightness(n), - illumination: crate::illumination(&self.camera.view, n, self.camera.light), + brightness, + illumination, normal: [n.0, n.1, n.2], rgb_gradient: None, + highlight, outline: None, side: false, away: behind, @@ -387,6 +398,29 @@ impl<'a> Builder<'a> { if self.facets.len() == before || !self.camera.view.shade { return Ok(()); } + if crate::material::shades(&self.camera.view) { + let view = &self.camera.view; + let corners: Vec = normals + .into_iter() + .zip(vertices) + .map(|(n, v)| { + crate::material::lit( + view, + if flip { V3(-n.0, -n.1, -n.2) } else { n }, + crate::material::to_eye(self.camera.eye, v), + self.camera.light, + ) + }) + .collect(); + if let Some(face) = self.facets.last_mut() { + let points = face.contours.first().map(Vec::as_slice).unwrap_or_default(); + let flat = crate::material::Lit { paint: face.illumination, over: face.highlight.map_or([0.0; 3], |h| h.flat) }; + let shading = crate::Shading::of(points, &corners, flat); + face.rgb_gradient = shading.rgb_gradient; + face.highlight = Some(shading.highlight); + } + return Ok(()); + } let values: Vec<_> = normals .into_iter() .map(|n| crate::unclipped_illumination(&self.camera.view, if flip { V3(-n.0, -n.1, -n.2) } else { n }, self.camera.light)) @@ -405,7 +439,10 @@ impl<'a> Builder<'a> { /// `curves`, the pieces of curve the rings' edges follow and the outlines at `a` and `b`, each /// quad keeps its edges along the profile curved. An edge cut into pieces is cut at points of /// its curve, each piece taking an equal share of the edge's piece of curve. With `side`, each - /// quad carries where its corners lie on the side unrolled flat ([`Facet::surface`]). + /// quad carries where its corners lie on the side unrolled flat ([`Facet::surface`]). Smoothed + /// bands shaded with a non-default material draw as two triangles when doubling every band + /// face fits within the solid's face limit; otherwise each band keeps one facet. Each triangle + /// has its own corner lighting and side coordinates. The mesh keeps the quad and its corner normals. pub(super) fn curved_band( &mut self, [a, b]: [&[V3]; 2], @@ -440,13 +477,15 @@ impl<'a> Builder<'a> { normal = V3(-normal.0, -normal.1, -normal.2); } let before = self.facets.len(); + let vertices = [quad[0], quad[1], quad[2], quad[3]]; + let na = mesh.normals.and_then(|(na, _)| na.get(i)?.get(k).copied().flatten()); + let nb = mesh.normals.and_then(|(_, nb)| nb.get(i)?.get(k).copied().flatten()); + let smooth = crate::material::shades(&self.camera.view) && (na.is_some() || nb.is_some()); let attrs = |_: &[Vec]| { let (u0, u1) = (mesh.u.get(i).copied().unwrap_or(0.5), mesh.u.get(i + 1).copied().unwrap_or(0.5)); let (ua, ub) = (u0 + (u1 - u0) * s0, u0 + (u1 - u0) * s1); let [va, vb] = mesh.v; // Each piece of a cut edge takes the normals smoothed for that piece. - let na = mesh.normals.and_then(|(na, _)| na.get(i)?.get(k).copied().flatten()); - let nb = mesh.normals.and_then(|(_, nb)| nb.get(i)?.get(k).copied().flatten()); Attrs::Corners(vec![vec![([ua, va], na), ([ub, va], na), ([ub, vb], nb), ([ua, vb], nb)]]) }; self.face(vec![quad], normal, order, mesh.part, attrs)?; @@ -476,14 +515,72 @@ impl<'a> Builder<'a> { }); } } - if let Some(w) = curves.as_mut() + // A band is split only when it is one facet with four corners on the page and on its surfaces. + let four = |page: &[Point], uv: &[Point]| page.len() == 4 && uv.len() == 4; + let split = self.split_bands + && smooth + && self.facets.len() == before + 1 + && self.facets.last().is_some_and(|b| { + b.contours.len() == 1 + && b.contours[0].len() == 4 + && b.cell.as_ref().is_none_or(|c| four(&c.page, &c.uv)) + && b.surface.as_ref().is_none_or(|c| four(&c.page, &c.uv)) + }); + if split && let Some(band) = self.facets.pop() { + // Both triangles keep the band's culling, normal, plane and paint order. + let normal = V3(band.normal[0], band.normal[1], band.normal[2]); + let points = vertices.map(|v| self.camera.project(v)); + let corners = [na, na, nb, nb].map(|n| n.unwrap_or(normal)); + let corners = std::array::from_fn::<_, 4, _>(|j| { + let n = corners[j]; + let n = if n.dot(normal) < 0.0 { V3(-n.0, -n.1, -n.2) } else { n }; + crate::material::lit(&self.camera.view, n, crate::material::to_eye(self.camera.eye, vertices[j]), self.camera.light) + }); + let flat = crate::material::Lit { paint: band.illumination, over: band.highlight.map_or([0.0; 3], |h| h.flat) }; + for (mut f, indices) in [band.clone(), band].into_iter().zip([[0, 1, 2], [0, 2, 3]]) { + let select = |points: &[Point]| indices.map(|j| points[j]).to_vec(); + f.contours = vec![select(&f.contours[0])]; + if let Some(cell) = f.cell.as_mut() { + cell.page = select(&cell.page); + cell.uv = select(&cell.uv); + } + if let Some(cell) = f.surface.as_mut() { + cell.page = select(&cell.page); + cell.uv = select(&cell.uv); + } + #[cfg(test)] + { + f.view = vec![indices.map(|j| vertices[j]).to_vec()]; + } + let shading = crate::Shading::of(&indices.map(|j| points[j]), &indices.map(|j| corners[j]), flat); + f.brightness = shading.brightness; + f.illumination = shading.illumination; + f.rgb_gradient = shading.rgb_gradient; + f.highlight = Some(shading.highlight); + self.facets.push(f); + } + if self.facets.len() > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); + } + } + if self.draw + && let Some(w) = curves.as_mut() && let Some(span) = span { // An edge cut on its chord, with no place on the curve for its cut corners, // stays straight. let near = w.near.filter(|_| pieces == 1 || w.places[0].is_some()); let far = w.far.filter(|_| pieces == 1 || w.places[1].is_some()); - self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), ends, quad, near, far, w.budget))); + if split { + let quad = vertices.map(|v| self.camera.project(v)); + for (half, f) in self.facets[before..].iter_mut().enumerate() { + f.outline = outline::wall(&span, (t(s0), t(s1)), ends, &quad, near, far, Some(half), w.budget); + } + } else { + self.outline(before, |c| { + c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), ends, quad, near, far, None, w.budget)) + }); + } } } } @@ -859,10 +956,10 @@ fn step_coordinates(steps: &[Step], depth: f64) -> Vec { } /// The largest angle, in degrees, between two neighboring bands of one bevel whose shared corners -/// are smoothed for a mesh. A sharper turn (a Step profile's) stays a hard edge. +/// are smoothed. A sharper turn (a Step profile's) stays a hard edge. pub(crate) const BEVEL_CREASE: f64 = 60.0; -/// For a mesh, the normal of each corner of each piece of each edge of `ring` at each step (one +/// The normal of each corner of each piece of each edge of `ring` at each step for meshes and material ramps (one /// list per step, one list per edge, one entry per piece: `cuts[i]` pieces along edge `i`, as /// [`Builder::curved_band`] cuts it, or one) where the bands on either side are smoothed: two /// bands of the same bevel, front or back, that turn by less than [`BEVEL_CREASE`], neither of @@ -996,6 +1093,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio } let camera = Camera::new(view, bounds, o.depth); let mut b = Builder::new(&camera, o.cap, o.hidden, keep); + b.split_bands = edges.saturating_mul(bands).saturating_mul(2).saturating_add(caps) <= MAX_SOLID_FACES; let z = |t: f64| o.depth / 2.0 - o.depth * t; let ring_at = |ring: &[Point], s: &Step| -> Vec { section(&inset(ring, s.inset), bounds, &o, s.t).iter().map(|p| camera.place(*p, z(s.t))).collect() }; @@ -1065,7 +1163,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r); let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); let u = along_ring(ring); - let rows = if b.keeps_mesh() { + let rows = if b.keeps_mesh() || crate::material::shades(&camera.view) { let at: Vec<&Place> = places.iter().map(|p| p as &Place).collect(); smoothed_rows(&camera, ring, &steps, &placed, pieces, &traced.spans, &at) } else { diff --git a/crates/three-d/src/solid/outline.rs b/crates/three-d/src/solid/outline.rs index b2491896d7..1345945a46 100644 --- a/crates/three-d/src/solid/outline.rs +++ b/crates/three-d/src/solid/outline.rs @@ -212,7 +212,8 @@ pub(super) fn face(rings: &[&Ring], points: &[Vec], step: &Along, budget: /// takes). `ends` are the corners of the whole edges at `near` and at `far` (projected, where each /// starts and ends on all of `span`), so that a piece follows the curve the whole edge does, as the /// cap's edge it meets. An edge without its outline stays straight. `None` when neither edge is -/// curved. +/// curved. With `triangle`, return only half 0 (`a`, `a'`, `b'`) or half 1 (`a`, `b'`, `b`), +/// keeping that half's profile curve and a straight shared diagonal from `a` to `b'`. #[allow(clippy::too_many_arguments)] pub(super) fn wall( span: &Span, @@ -221,6 +222,7 @@ pub(super) fn wall( quad: &[Point], near: Option<&Along>, far: Option<&Along>, + triangle: Option, budget: &mut Budget, ) -> Option { let [a, a2, b2, b] = <[Point; 4]>::try_from(quad).ok()?; @@ -231,21 +233,25 @@ pub(super) fn wall( finite.then_some(Whole { t: (span.t0, span.t1), d }) }; let [near_ends, far_ends] = ends; - let front = near.and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, whole(near, near_ends), budget)); - let back = far.and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, whole(far, far_ends), budget)); + let front = near.filter(|_| triangle != Some(1)).and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, whole(near, near_ends), budget)); + let back = far.filter(|_| triangle != Some(0)).and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, whole(far, far_ends), budget)); if front.is_none() && back.is_none() { return None; } let mut path = BezPath::new(); path.move_to(a); - match front { - Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), - None => path.line_to(a2), + if triangle != Some(1) { + match front { + Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), + None => path.line_to(a2), + } } path.line_to(b2); - match back { - Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), - None => path.line_to(b), + if triangle != Some(0) { + match back { + Some(curves) => curves.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)), + None => path.line_to(b), + } } path.close_path(); Some(PathData::from_bezpath(&path)) diff --git a/crates/three-d/src/solid/tests_limits.rs b/crates/three-d/src/solid/tests_limits.rs index bd70096232..9ff4392389 100644 --- a/crates/three-d/src/solid/tests_limits.rs +++ b/crates/three-d/src/solid/tests_limits.rs @@ -91,6 +91,43 @@ fn faces_at_the_limit_are_taken_and_one_past_it_is_refused_before_sampling() { assert_eq!(extrude(&path, FillRule::NonZero, path.bounds().unwrap(), rounded, turned()), Err(SURFACE.to_string())); } +#[test] +fn a_material_keeps_a_rounded_bevel_within_the_face_limit() { + let rounded = Extrude { bevel: Some(Bevel { shape: BevelShape::Rounded, ..Bevel::default() }), ..Extrude::default() }; + // Eight rounded bevel bands and one wall band, with two caps. + let bevel_bands = BevelShape::Rounded.samples().len() - 1; + let bands = bevel_bands + 1; + let caps = 2; + assert_eq!(bands, 9); + let edges = (MAX_SOLID_FACES - caps) / bands; + let faces = edges * bands + caps; + assert!(faces <= MAX_SOLID_FACES && MAX_SOLID_FACES - faces < bands); + assert!(edges * bands * 2 + caps > MAX_SOLID_FACES); + let path = polygon(edges, 20_000.0); + let bounds = path.bounds().unwrap(); + let view = View { shade: true, ..turned() }; + let material_view = View { material: crate::Material::new(0.4, 0.0).unwrap(), ..view }; + let plain = extrude(&path, FillRule::NonZero, bounds, rounded, view); + let material = extrude(&path, FillRule::NonZero, bounds, rounded, material_view); + assert!(plain.is_ok(), "{plain:?}"); + assert!(material.is_ok(), "{material:?}"); + assert!(built(&plain.unwrap())); + assert!(built(&material.unwrap())); +} + +#[test] +fn a_material_splits_rounded_bevel_bands_with_room_below_the_face_limit() { + let path = polygon(256, 20_000.0); + let bounds = path.bounds().unwrap(); + let rounded = Extrude { bevel: Some(Bevel { shape: BevelShape::Rounded, ..Bevel::default() }), ..Extrude::default() }; + let view = View { shade: true, ..turned() }; + let material_view = View { material: crate::Material::new(0.4, 0.0).unwrap(), ..view }; + let plain = extrude(&path, FillRule::NonZero, bounds, rounded, view).unwrap(); + let material = extrude(&path, FillRule::NonZero, bounds, rounded, material_view).unwrap(); + assert!(built(&plain) && built(&material)); + assert!(material.len() > plain.len(), "the material splits smoothed bands into triangles"); +} + #[test] fn curves_over_the_budget_take_fewer_pieces_down_to_four() { let path = petals(2000, 500.0, 20.0); diff --git a/crates/three-d/src/visibility.rs b/crates/three-d/src/visibility.rs index 71c5af62c3..f98d19d668 100644 --- a/crates/three-d/src/visibility.rs +++ b/crates/three-d/src/visibility.rs @@ -26,6 +26,7 @@ pub struct VisibleFace { pub illumination: [f64; 3], pub light_gradient: Option, pub rgb_gradient: Option, + pub highlight: Option, } struct Polygon { @@ -273,6 +274,7 @@ pub fn visible_faces(faces: &[Face]) -> Result, String> { illumination: face.illumination, light_gradient: face.light_gradient, rgb_gradient: face.rgb_gradient, + highlight: face.highlight, }); // A completely covered face need not occupy the grid. Its coverage already belongs // to nearer faces; this keeps repeated overlapping surfaces bounded in practice. @@ -302,6 +304,7 @@ mod tests { illumination: [brightness; 3], light_gradient: None, rgb_gradient: None, + highlight: None, outline: None, cap: false, visibility_pieces: None, diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs index 8ce1aa6812..1b012b66f7 100644 --- a/crates/ui-egui/src/addons/cleanup.rs +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -8,10 +8,11 @@ use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::keymap::Mods; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::sections::Section; use egui::Ui; use serde_json::{Value, json}; @@ -136,6 +137,8 @@ pub(crate) struct Results { rows: Vec<(String, String, u64)>, /// The rows picked in the list, by position in `rows`. picked: Selection, + /// The clicked finding and the kinds to fix, captured when its menu opens. + menu: Option<(String, Vec)>, /// What the last fix did. status: String, } @@ -320,14 +323,41 @@ fn text_tools(ui: &mut Ui, selected: bool, editing: bool, action: &mut Option) { let source = Positional { rows: &r.rows, label: |row| row.1.as_str() }; - List::::new(tl!("Issues").to_string()).empty(tl!("No issues found.").to_string()).selection(Bind::bound(&mut r.picked)).show_items( - ui, - &source, - &mut |key, _| match r.rows.get(*key) { - Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()), + let mut selection = r.picked.clone(); + let out = List::::new(tl!("Issues")) + .id(ui.scope_id().with(("cleanup-issues", r.doc))) + .select(SelectMode::Multi) + .row_menu() + .empty(tl!("No issues found.").to_string()) + .selection(Bind::bound(&mut selection)) + .show_items(ui, &source, &mut |key, item| match r.rows.get(*key) { + Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()).state(item.row.clone()), None => ListRow::spacer(), - }, - ); + }); + if let Some(key) = out.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => Some(request.key), + _ => None, + }) { + if !r.picked.items.contains(&key) { + r.picked = Selection::single(key); + } + r.menu = r.rows.get(key).map(|row| (row.0.clone(), r.picked_kinds())); + } else { + r.picked = selection; + } + if let Some((kind, kinds)) = &r.menu { + let menu = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Show Affected Artwork")).show(ui).ran { + *action = Some(Action::Show(kind.clone())); + } + if MenuItem::new(tl!("Fix Selected")).show(ui).ran { + *action = Some(Action::Fix(kinds.clone())); + } + }); + if menu.output.closed.is_some() || action.is_some() { + r.menu = None; + } + } if !r.status.is_empty() { Text::new(r.status.clone()).show(ui); } diff --git a/crates/ui-egui/src/addons/cleanup/tests.rs b/crates/ui-egui/src/addons/cleanup/tests.rs index 1b414177fb..072eb5e8fc 100644 --- a/crates/ui-egui/src/addons/cleanup/tests.rs +++ b/crates/ui-egui/src/addons/cleanup/tests.rs @@ -3,6 +3,7 @@ use vectorcraft_engine::Session; use super::{check, current, fix}; use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; /// An app with a rectangle and a stray point (a path of one anchor), nothing selected. fn app() -> VectorcraftApp { @@ -46,3 +47,52 @@ fn a_fix_with_no_results_does_nothing() { assert!(app.addon_panels.cleanup.is_none()); assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "nothing was fixed without a check"); } + +#[test] +fn a_selected_rows_menu_shows_its_own_artwork_and_fixes_the_whole_selection() { + let mut app = app(); + let outside = app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + check(&mut app, None); + let mut panel = Panel::new(app, super::show); + panel.click("Off-Artboard Art"); + panel.click_with("Stray Points", egui::Modifiers::SHIFT); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Show Affected Artwork"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(outside)]); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Fix Selected"); + assert!(current(&panel.app()).unwrap().rows.is_empty(), "both findings were fixed"); +} + +#[test] +fn opening_the_menu_on_an_unselected_row_fixes_only_that_finding() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap(); + check(&mut app, Some("document")); + let mut panel = Panel::new(app, super::show); + panel.click("Stray Points"); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Fix Selected"); + let app = panel.app(); + let remaining = ¤t(&app).unwrap().rows; + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].0, "strayPoints"); +} + +#[test] +fn dismissing_the_keyboard_menu_returns_focus_to_the_finding() { + let mut app = app(); + check(&mut app, None); + let mut panel = Panel::new(app, super::show); + panel.focus("Stray Points"); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Show Affected Artwork")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(panel.focused("Stray Points")); + assert!(!panel.shows("Show Affected Artwork")); +} diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 18816efa11..ecbcf6856d 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -64,7 +64,7 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { } /// Closes the open add-on dialog without an answer and rolls its preview back. -fn close_open(app: &mut VectorcraftApp) { +pub(crate) fn close_open(app: &mut VectorcraftApp) { let Some(open) = app.addon_dialogs.open.take() else { return }; app.addon_dialogs.preview_error = None; let id = open.id; @@ -100,8 +100,9 @@ pub(crate) fn open( /// The dialog the menu item of command `id` opens, with no params; `None` for another command. pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option> { - use super::{color, pathtools, select, typetools}; + use super::{color, document, pathtools, select, typetools}; let open: fn(&mut VectorcraftApp) -> Result = match id { + document::FLOOD_FILL => document::open_flood_fill, pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, pathtools::COMMON_TANGENTS => pathtools::tangents::open, diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 9fcf01e5c2..1e38dcc3d8 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -3,15 +3,20 @@ //! each layer's art replaced by an instance). Save a Timestamped Copy of a document never saved //! asks for the folder to put it in ([`save_copy`]). Export All Open Documents as PDF or SVG asks //! for the folder the copies go in ([`export_all`], #4920). Batch Trace Folder asks for the folder of -//! images and then the folder the results go in ([`batch_trace`], #4921). +//! images and then the folder the results go in ([`batch_trace`], #4921). Flood Fill Artboards… +//! opens a dialog ([`open_flood_fill`]) that previews on the canvas and runs +//! `addon.document.floodFillArtboards` on OK. use craft::host::{PickRequest, Picked}; use craft::menu::Node; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; +use super::dialogs::Spec; use crate::VectorcraftApp; use crate::file_asks::{Owner, ask}; -use crate::menus::{Sep, cp}; +use crate::menus::{Sep, c, cp}; /// Save a Timestamped Copy. pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; @@ -21,6 +26,14 @@ pub const EXPORT_ALL: &str = "addon.document.exportAllOpen"; pub const BATCH_TRACE: &str = "addon.document.batchTraceFolder"; /// New Symbols from Layers (Convert Layers to Symbols: with their art replaced by instances). const SYMBOLS: &str = "addon.document.symbolsFromLayers"; +/// Flood Fill Artboards. +pub const FLOOD_FILL: &str = "addon.document.floodFillArtboards"; +/// The layer Flood Fill Artboards puts its rectangles on unless another is named. +const FLOOD_LAYER: &str = "Flood Fill"; +/// The color the Flood Fill Artboards dialog opens with when the current fill is not a solid color. +const GRAY: [f32; 3] = [0.5, 0.5, 0.5]; + +static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None }; /// Object › Plug-ins › Document Tools. pub fn menu() -> Vec { @@ -32,9 +45,123 @@ pub fn menu() -> Vec { Sep, cp("New Symbols from Layers", SYMBOLS, json!({})), cp("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), + Sep, + c("Flood Fill Artboards…", FLOOD_FILL), ] } +/// The rows of the Flood Fill Artboards dialog. +fn flood_rows() -> Vec { + vec![ + Param::new( + "artboards", + tl!("Artboards:"), + ParamKind::choice( + vec![("active".into(), tl!("Active Artboard").into()), ("all".into(), tl!("All Artboards").into())], + Some("active".into()), + ), + ), + Param::new( + "fill", + tl!("Fill:"), + ParamKind::choice(vec![("current".into(), tl!("Current Fill").into()), ("color".into(), tl!("Color").into())], Some("current".into())), + ), + Param::new("color", tl!("Color:"), ParamKind::color(Some(GRAY))).enabled_when("fill", "color"), + Param::new("layer", tl!("Layer:"), ParamKind::text(FLOOD_LAYER)), + ] +} + +/// The working-RGB components `[r, g, b]` of the dialog's display sRGB color, as the engine reads a +/// color array. +fn working_rgb(srgb: [f32; 3]) -> Value { + let [r, g, b] = vectorcraft_color::cms::active().srgb_to_rgb(srgb.map(|v| v.clamp(0.0, 1.0))); + json!([r, g, b]) +} + +/// Flood Fill Artboards' params from the dialog: every artboard or the one the dialog opened on (`board`, kept +/// out of sight), the color only when Color is picked (in the document's working RGB), and the layer named. +fn flood_params(fields: &DialogFields) -> Value { + let mut p = match fields.text("artboards") { + Some("all") => json!({ "all": true }), + _ => json!({ "activeArtboard": fields.int("board").unwrap_or(0) }), + }; + if fields.text("fill") == Some("color") { + let picked = fields.color("color").unwrap_or(GRAY); + // The opening fill, while its shown color is unchanged, keeps its own working components, also + // those outside the displayable sRGB range, and stays RGB in a CMYK document. + let start = (fields.color("startShown") == Some(picked)) + .then(|| fields.text("startColor").and_then(|t| serde_json::from_str::(t).ok())) + .flatten(); + match start { + Some(start) => { + p["color"] = start; + p["keepModel"] = json!(true); + } + None => p["color"] = working_rgb(picked), + } + } + p["layer"] = json!(fields.text("layer").unwrap_or(FLOOD_LAYER)); + p +} + +/// Opens Flood Fill Artboards' dialog on the active artboard and the current fill, or, when there is no fill, on +/// Color with gray. +pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result { + let command = vectorcraft_engine::find_command(FLOOD_FILL).ok_or_else(|| format!("unknown command {FLOOD_FILL}"))?; + (command.enabled)(&app.session)?; + // A reopened dialog reads the fill after the open dialog's preview is rolled back, not the previewed fill. + super::dialogs::close_open(app); + let board = app.view().map_or(0, |v| v.artboard); + let fill = &app.session.paint.fill; + let no_current_fill = fill.is_none(); + let color = fill.color().map_or(GRAY, |c| c.to_rgb().map(|v| v.clamp(0.0, 1.0))); + // An RGB opening fill's working components, unclamped, sent when Color keeps the shown color. + let start_color = fill + .color() + .and_then(|c| match c { + vectorcraft_color::Color::Rgb { r, g, b } => Some([r, g, b]), + _ => None, + }) + .filter(|rgb| rgb.iter().all(|v| v.is_finite())) + .map_or_else(String::new, |rgb| json!(rgb).to_string()); + let fields = DialogFields::from_pairs([ + ("artboards", FieldValue::Text("active".into())), + ("fill", FieldValue::Text(if fill.is_none() { "color" } else { "current" }.into())), + ("color", FieldValue::Color(color)), + ("layer", FieldValue::Text(FLOOD_LAYER.into())), + ("board", FieldValue::Int(board as i64)), + ("startShown", FieldValue::Color(color)), + ("startColor", FieldValue::Text(start_color)), + ]); + let mut layer_clips = std::collections::HashMap::new(); + if let Ok(st) = app.session.doc() { + for layer in st.doc.layers.iter().filter(|layer| layer.is_layer()) { + if let Some(name) = &layer.name { + layer_clips.entry(name.clone()).or_insert_with(|| layer.clips()); + } + } + } + super::dialogs::open(app, &FLOOD_SPEC, fields, move |fields| { + let name = fields.text("layer").unwrap_or_default().trim(); + let reason = if name.is_empty() { + Some(tl!("Name the layer.")) + } else if name.chars().count() > 255 { + Some(tl!("Use at most 255 characters for the layer name.")) + } else if layer_clips.get(name) == Some(&true) { + Some(tl!("The layer holds a clipping mask.")) + } else if no_current_fill && fields.text("fill") == Some("current") { + Some(tl!("There is no current fill.")) + } else { + None + }; + ParamDialog::new(FLOOD_FILL, tl!("Flood Fill Artboards"), flood_rows()) + .ok_enabled(reason.is_none()) + .ok_reason(reason.unwrap_or_default().into()) + .values(Bind::bound(fields)) + .previews(true) + }) +} + /// The params as an object, with the picked folder under `key`. fn with_folder(p: &Value, key: &str, picked: &Picked) -> Result { let folder = picked.first_path().ok_or("no folder picked")?; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 1cc56d18cb..fc77f7a4ab 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -4,6 +4,8 @@ use serde_json::json; use vectorcraft_engine::Session; use super::{BATCH_TRACE, EXPORT_ALL, SAVE_COPY}; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::tests::picks::{poll, scripted}; use crate::{VectorcraftApp, menus}; use craft::host::PickKind; @@ -237,3 +239,293 @@ fn batch_trace_folder_asks_for_both_folders() { assert_eq!(picker.requests().len(), asked + 1, "declining the source asks nothing more"); let _ = std::fs::remove_dir_all(&dir); } + +/// A window, a document of three 100 × 80 artboards with the second active, and a red fill. +fn boards() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + app.sync_views(); + if let Some(v) = app.view_mut() { + v.artboard = 1; + } + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app +} + +/// The names of the document's top-level layers, bottom first. +fn layer_names(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +/// The bounds and fill of each object on the bottom layer. +fn bottom_art(app: &VectorcraftApp) -> Vec<(vectorcraft_geom::Rect, vectorcraft_color::Paint)> { + let doc = &app.session.doc().unwrap().doc; + let art = doc.layers[0].children().map(|c| c.to_vec()).unwrap_or_default(); + art.iter().map(|n| (n.geometric_bounds().unwrap(), n.appearance.fill_paint())).collect() +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn flood_fill_typed_layer_name_previews_and_ok_applies_one_step() { + let app = boards(); + let undo = undo_len(&app); + let artboard = app.session.doc().unwrap().doc.artboards[1].rect; + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + panel.click("Layer"); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Paper"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap()); + { + let app = panel.app(); + assert_eq!(layer_names(&app)[0], "Paper", "the preview makes the typed layer at the bottom"); + assert_eq!(bottom_art(&app), [(artboard, red.clone())], "the active artboard, in the current fill"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app), ["Paper", "Layer 1"]); + assert_eq!(bottom_art(&app), [(artboard, red)]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(app.session.doc().unwrap().history.undo.last().unwrap().label, "Flood Fill Artboards"); +} + +#[test] +fn flood_fill_active_artboard_records_a_relative_action_target() { + let mut app = boards(); + let start = app.session.journal.len(); + let opening_board = app.session.doc().unwrap().doc.artboards[1].rect; + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params["activeArtboard"], json!(1)); + assert!(params.get("artboards").is_none()); + app.view_mut().unwrap().artboard = 2; + host::set(&app, id, "layer", json!("Paper")); + host::frame(&mut app); + assert_eq!(bottom_art(&app)[0].0, opening_board); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(bottom_art(&app)[0].0, opening_board); + let journal = app.session.journal.since(start); + let (_, params) = journal.iter().find(|(cmd, _)| cmd == super::FLOOD_FILL).unwrap(); + assert_eq!(params["activeArtboard"], json!(1)); + let steps = app.session.journal_for_action(start); + let (command, params) = steps.iter().find(|(cmd, _)| cmd == super::FLOOD_FILL).unwrap(); + assert!(params.get("activeArtboard").is_none()); + assert!(params.get("artboards").is_none()); + app.run("file.new", json!({"width": 60, "height": 40})).unwrap(); + app.sync_views(); + let playback_board = app.session.doc().unwrap().doc.artboards[0].rect; + app.run(command, params.clone()).unwrap(); + assert_eq!(bottom_art(&app)[0].0, playback_board); +} + +#[test] +fn flood_fill_cancel_rolls_the_preview_back() { + let app = boards(); + let (undo, doc) = (undo_len(&app), app.session.doc().unwrap().doc.clone()); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + assert_eq!(layer_names(&panel.app())[0], "Flood Fill", "previewed"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!((*app.session.doc().unwrap().doc == *doc, undo_len(&app)), (true, undo), "nothing kept"); +} + +#[test] +fn flood_fill_all_artboards_in_a_chosen_color() { + let srgb = std::sync::Arc::new(vectorcraft_color::cms::Cms::new(&Default::default()).unwrap()); + vectorcraft_color::cms::with_active(srgb, || { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "artboards", json!("all")); + assert_eq!(host::read(&app, id, |f| f.color("color")), Some([1.0, 0.0, 0.0]), "Color opens on the current fill's color"); + host::set(&app, id, "fill", json!("color")); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params, json!({"all": true, "color": [0.0, 0.0, 1.0], "layer": "Flood Fill"})); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#0000ff").unwrap()); + let artboards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| (a.rect, blue.clone())).collect(); + assert_eq!(bottom_art(&app), artboards, "one rectangle per artboard, in the dialog's color"); + }); +} + +/// In a working RGB space other than sRGB, switching from Current Fill to Color without editing the +/// color fills the artboards in the current fill's color. +#[test] +fn flood_fill_color_keeps_the_current_fill_in_a_non_srgb_working_space() { + use vectorcraft_color::{Color, cms}; + let settings = cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }; + let wide = std::sync::Arc::new(cms::Cms::new(&settings).unwrap()); + cms::with_active(wide, || { + assert!(!cms::active().rgb_is_srgb()); + let mut app = boards(); + app.run("paint.setFill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let art = bottom_art(&app); + assert_eq!(art.len(), 1); + let Some(Color::Rgb { r, g, b }) = art[0].1.color() else { panic!("an RGB fill: {:?}", art[0].1) }; + for (got, want) in [(r, 0.6), (g, 0.5), (b, 0.4)] { + assert!((got - want).abs() < 1e-3, "{:?} is the current fill [0.6, 0.5, 0.4]", [r, g, b]); + } + }); +} + +/// A current fill outside the sRGB gamut, whose shown color does not convert back to it, keeps its +/// working components when Color is picked without editing the color. +#[test] +fn flood_fill_color_keeps_an_out_of_srgb_current_fill() { + use vectorcraft_color::cms; + let settings = cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }; + let wide = std::sync::Arc::new(cms::Cms::new(&settings).unwrap()); + cms::with_active(wide, || { + let shown = vectorcraft_color::Color::rgb(0.0, 1.0, 0.0).to_rgb(); + assert_ne!(super::working_rgb(shown), json!([0.0, 1.0, 0.0]), "{shown:?} does not convert back to the fill"); + let mut app = boards(); + app.run("paint.setFill", json!({"color": [0.0, 1.0, 0.0]})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params["color"], json!([0.0, 1.0, 0.0])); + }); +} + +/// In a CMYK document, an RGB current fill kept by picking Color without editing it stays RGB. +#[test] +fn flood_fill_color_keeps_an_rgb_current_fill_in_a_cmyk_document() { + use vectorcraft_color::Color; + let mut app = boards(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("paint.setFill", json!({"color": [0.6, 0.5, 0.4], "keepModel": true})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let art = bottom_art(&app); + assert_eq!(art.len(), 1); + let Some(Color::Rgb { r, g, b }) = art[0].1.color() else { panic!("an RGB fill: {:?}", art[0].1) }; + for (got, want) in [(r, 0.6), (g, 0.5), (b, 0.4)] { + assert!((got - want).abs() < 1e-3, "{:?} is the current fill [0.6, 0.5, 0.4]", [r, g, b]); + } +} + +#[test] +fn flood_fill_layer_name_limit_counts_characters_after_trimming() { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!("é".repeat(256))); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + let name = "é".repeat(255); + host::set(&app, id, "layer", json!(format!(" {name} "))); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], name); +} + +#[test] +fn flood_fill_rejects_a_layer_with_a_clipping_mask_and_keeps_the_dialog_open() { + let mut app = boards(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.clippingMask.toggle", json!({"id": layer.0})).unwrap(); + assert!(app.session.doc().unwrap().doc.node(layer).unwrap().clips()); + let name = app.session.doc().unwrap().doc.node(layer).unwrap().name.clone().unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!(format!(" {name} "))); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + assert_eq!(host::read(&app, id, |f| f.text("layer").map(str::to_owned)), Some(format!(" {name} "))); + host::set(&app, id, "layer", json!("Paper")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], "Paper"); +} + +#[test] +fn flood_fill_current_fill_without_a_fill_keeps_the_dialog_open() { + let mut app = boards(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "layer", json!("Paper")); + host::set(&app, id, "fill", json!("current")); + assert!(!host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.any_dialog_open()); + assert_eq!(host::read(&app, id, |f| f.text("layer").map(str::to_owned)), Some("Paper".to_owned())); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before); + host::set(&app, id, "fill", json!("color")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app)[0], "Paper"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), before + 1); +} + +#[test] +fn flood_fill_menu_dialog_is_refused_without_a_document() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + assert!(app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).is_err(), "the command is off without a document"); + assert!(!app.any_dialog_open()); +} + +/// With New Art Has Basic Appearance off and no fill, reopening the dialog while a Color preview is +/// showing opens it on the fill from before the preview, not on the previewed rectangles' fill. +#[test] +fn flood_fill_reopened_during_a_color_preview_reads_the_fill_before_it() { + let mut app = boards(); + app.run("appearance.setNewArtBasic", json!({"on": false})).unwrap(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).unwrap(); + let id = host::dialog_id(&app); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + host::frame(&mut app); + assert_eq!(layer_names(&app)[0], "Flood Fill", "previewed"); + app.run("ui.menuDialog", json!({"command": super::FLOOD_FILL})).unwrap(); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("fill").map(str::to_owned)), Some("color".to_owned())); +} + +#[test] +fn flood_fill_opens_on_color_without_a_fill_and_needs_a_layer_name() { + let mut app = boards(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("fill").map(str::to_owned)), Some("color".to_owned())); + host::set(&app, id, "layer", json!(" ")); + assert!(!host::confirm(&app, id), "OK is off without a layer name"); + host::set(&app, id, "layer", json!("Back")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(layer_names(&app)[0], "Back"); +} diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index a6aa04dfc7..7a0de94cb4 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -23,7 +23,7 @@ use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row as Line; use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::UnitKind; use craft::ui::text::NumberField; @@ -149,6 +149,8 @@ fn doc_key(app: &VectorcraftApp) -> Option { pub(crate) struct FoldLines { /// The last check of each document. checks: Checks, + /// The immutable check and row on which the context menu opened. + menu: Option<(Weak, usize)>, /// The role rows for the document state they were read for. rows: Rows, } @@ -210,22 +212,45 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } - let Some(checked) = last_check(app) else { return }; + let Some(checked) = last_check(app) else { + app.addon_panels.fold.menu = None; + return; + }; Text::new(crate::i18n::msg(&checked.summary())).show(ui); let findings: Vec = (0u64..) .zip(&checked.issues) .map(|(id, issue)| Finding::new(id, if issue.error { Severity::Error } else { Severity::Warning }, crate::i18n::msg(&issue.message))) .collect(); - let out = - FindingsList::new(tl!("Issues").to_string()).show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) { - Some(finding) => finding.row(&icx.words::()), - None => ListRow::spacer(), - }); - for event in &out.events { - if let CollectionEvent::Activate(n) = event { - select_issue(app, &checked, *n as usize); + let list = FindingsList::new(tl!("Issues").to_string()).id(ui.scope_id().with(("fold-issues", Arc::as_ptr(&checked)))); + let out = list.show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) { + Some(finding) => finding.row(&icx.words::()).row_menu(), + None => ListRow::spacer(), + }); + for event in out.events { + match event { + CollectionEvent::Activate(n) => select_issue(app, &checked, n as usize), + CollectionEvent::ContextMenu(request) => app.addon_panels.fold.menu = Some((Arc::downgrade(&checked), request.key as usize)), + _ => {} } } + let Some((owner, n)) = &app.addon_panels.fold.menu else { return }; + let n = *n; + let Some(issue) = checked.issues.get(n).filter(|_| owner.as_ptr() == Arc::as_ptr(&checked)) else { + app.addon_panels.fold.menu = None; + return; + }; + let shown = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Select Affected Objects")).enabled(!issue.ids.is_empty()).show(ui).ran { + select_issue(app, &checked, n); + } + if MenuItem::new(tl!("Copy Finding")).show(ui).ran { + app.clipboard_out = Some(crate::i18n::msg(&issue.message)); + app.status(tl!("Copied finding")); + } + }); + if shown.output.closed.is_some() { + app.addon_panels.fold.menu = None; + } } /// One role row: (role id, swatch name, the swatch's paint if the document has it, count). @@ -346,6 +371,7 @@ fn role_label(role: &str) -> &str { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(selected) = app.session.active().map(|st| !st.selection.is_empty()) else { + app.addon_panels.fold.menu = None; empty_state(ui, "scissors", tl!("No document"), tl!("Open a document to mark its fold lines.")); return; }; diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 26d9ac729b..ea89dcd928 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -116,6 +116,58 @@ fn each_document_keeps_its_own_check() { assert!(last_check(&app).is_some_and(|kept| Arc::ptr_eq(&kept, &second))); } +#[test] +fn a_finding_menu_selects_its_objects_and_restores_keyboard_focus_on_escape() { + let (mut app, slit) = blank(); + let checked = run_check(&mut app, json!({})).unwrap(); + let row = format!("{}, Error", checked.issues[0].message); + let mut panel = Panel::new(app, super::show_check); + panel.focus(&row); + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Select Affected Objects")); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(panel.focused(&row)); + panel.secondary_click(&row); + panel.frame(); + panel.click_menu_item("Select Affected Objects"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(slit)]); +} + +#[test] +fn a_recheck_and_a_document_switch_dismiss_the_menu_and_an_objectless_finding_can_be_copied() { + let (mut app, a, _) = app(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let checked = run_check(&mut app, json!({})).unwrap(); + let row = format!("{}, Error", checked.issues[0].message); + let mut panel = Panel::new(app, super::show_check); + panel.secondary_click(&row); + panel.frame(); + assert!(!panel.menu_item_enabled("Select Affected Objects")); + panel.click_menu_item("Copy Finding"); + assert_eq!(panel.app().clipboard_out.as_deref(), Some(checked.issues[0].message.as_str())); + assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(a)]); + + panel.secondary_click(&row); + panel.frame(); + assert!(panel.shows("Copy Finding")); + let replacement = run_check(&mut panel.app(), json!({"ids": [a]})).unwrap(); + panel.frame(); + assert!(!panel.shows("Copy Finding")); + assert!(!panel.shows("Select Affected Objects")); + panel.secondary_click(&format!("{}, Error", replacement.issues[0].message)); + panel.frame(); + assert!(panel.shows("Copy Finding")); + panel.app().run("file.new", json!({"width": 100, "height": 100})).unwrap(); + run_check(&mut panel.app(), json!({})).unwrap(); + panel.frame(); + assert!(!panel.shows("Copy Finding")); + assert!(!panel.shows("Select Affected Objects")); +} + /// The messages `addon.packaging.check` gives its issues, one for each code (three for `noCut`). const ISSUE_MESSAGES: [&str; 17] = [ "No cut lines are in the selection.", diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index 65fed545ca..5e25b913c9 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -25,6 +25,7 @@ use crate::VectorcraftApp; use crate::canvas::rulers::general_lengths; use crate::chrome::rank; use crate::edits::{self, EditPath}; +use crate::icons::ToolIcons; use crate::menus::cp; use crate::panels::{Live, live_run}; @@ -51,9 +52,10 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { divider(ui); if tool == "box3d" { + let tools = ToolIcons::of(&app.session.prefs); let shapes: [Choice; 6] = [("box3d", "3D Box"), ("rectangle", "Rectangle"), ("ellipse", "Ellipse"), ("polygon", "Polygon"), ("star", "Star"), ("spiral", "Spiral")] - .map(|(id, label)| (id, label, icon_for_shape(id))); + .map(|(id, label)| (id, label, icon_for_shape(id, tools))); if let Some(shape) = choice(ui, "Shape", &active_shape, &shapes) { app.run("tool.setOption", json!({ "key": "shape", "value": shape })).ok(); } @@ -408,7 +410,8 @@ fn draw_polygon_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, ac end_deg = a1; mode = mode_str(arc_mode); } - let kinds: [Choice; 2] = [("polygon", "Polygon", icon_for_shape("polygon")), ("star", "Star", icon_for_shape("star"))]; + let tools = ToolIcons::of(&app.session.prefs); + let kinds: [Choice; 2] = [("polygon", "Polygon", icon_for_shape("polygon", tools)), ("star", "Star", icon_for_shape("star", tools))]; match choice(ui, "Shape", if is_star { "star" } else { "polygon" }, &kinds) { Some("star") => apply_shape(app, &[("polyIsStar", json!(true))], json!({ "isStar": true, "spokeRatio": spoke })), Some(_) => apply_shape(app, &[("polyIsStar", json!(false))], json!({ "isStar": false })), @@ -508,9 +511,10 @@ fn draw_box3d_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, sele } } -/// The toolbar icon of the shape tool `id`, so the Control bar's shape buttons show the same icon. -fn icon_for_shape(id: &str) -> &'static str { - vectorcraft_tools::tool_info(id).map_or("square-dashed", |t| crate::icons::tool_icon(t.icon)) +/// The toolbar icon of the shape tool `id` in the set `tools` (Tool Icons), so the Control bar's shape buttons show the +/// same icon. +fn icon_for_shape(id: &str, tools: ToolIcons) -> &'static str { + vectorcraft_tools::tool_info(id).map_or("square-dashed", |t| tools.tool_icon(t.icon)) } fn mode_str(m: EllipseMode) -> &'static str { @@ -711,18 +715,24 @@ mod tests { use craft::behavior::IconId; use craft::ui::primitives::has_icon; - use super::icon_for_shape; + use super::{ToolIcons, icon_for_shape}; /// The Control bar's shape buttons look their icons up by tool id; an id that names no tool - /// would show the placeholder instead of the toolbar's icon. + /// would show the placeholder instead of the toolbar's icon. In each Tool Icons set they show + /// the toolbar's icon of that set. #[test] fn every_shape_button_shows_its_tools_icon() { crate::icons::register(); - for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] { - let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool")); - assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}"); - assert!(has_icon(&IconId::new(icon_for_shape(id))), "{id}'s icon {} isn't an icon", icon_for_shape(id)); + craft::ui::primitives::register_app_icons(&crate::icons::CLASSIC_ICONS); + for set in [ToolIcons::Current, ToolIcons::Classic] { + for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] { + let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool")); + let icon = icon_for_shape(id, set); + assert_eq!(icon, set.tool_icon(tool.icon), "{id} in {set:?}"); + assert!(has_icon(&IconId::new(icon)), "{id}'s icon {icon} in {set:?} isn't an icon"); + } + assert_eq!(icon_for_shape("no-such-tool", set), "square-dashed"); } - assert_eq!(icon_for_shape("no-such-tool"), "square-dashed"); + assert_ne!(icon_for_shape("spiral", ToolIcons::Classic), icon_for_shape("spiral", ToolIcons::Current)); } } diff --git a/crates/ui-egui/src/addons/typetools/numbers.rs b/crates/ui-egui/src/addons/typetools/numbers.rs index 68351ad068..250e6788a6 100644 --- a/crates/ui-egui/src/addons/typetools/numbers.rs +++ b/crates/ui-egui/src/addons/typetools/numbers.rs @@ -84,7 +84,9 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { Param::section(tl!("Zeros")), Param::new("leadingZeros", tl!("Leading Zeros"), ParamKind::bool(true)), Param::new("fixedDigits", tl!("Fixed Number of Digits"), ParamKind::bool(false)).enabled_when("leadingZeros", FieldValue::Bool(true)), - Param::new("digits", tl!("Digits:"), ParamKind::int(Some(1), Some(30), 3)).enabled_when("fixedDigits", FieldValue::Bool(true)), + Param::new("digits", tl!("Digits:"), ParamKind::int(Some(1), Some(30), 3)) + .enabled_when("fixedDigits", FieldValue::Bool(true)) + .and_enabled_when_in("leadingZeros", [FieldValue::Bool(true)]), Param::new("trailingZeros", tl!("Trailing Zeros"), ParamKind::bool(false)), Param::new("order", tl!("Order:"), radio(&ORDERS)).enabled_when("shuffle", FieldValue::Bool(false)), Param::new("replace", tl!("Replace:"), radio(&REPLACES)), diff --git a/crates/ui-egui/src/addons/typetools/numbers/tests.rs b/crates/ui-egui/src/addons/typetools/numbers/tests.rs index 79acbf8ef1..bb9f3bcfca 100644 --- a/crates/ui-egui/src/addons/typetools/numbers/tests.rs +++ b/crates/ui-egui/src/addons/typetools/numbers/tests.rs @@ -25,6 +25,24 @@ fn texts(app: &VectorcraftApp, ids: &[u64]) -> Vec { .collect() } +/// Digits takes input only while Leading Zeros and Fixed Number of Digits are both on, since the +/// command gets `digits` only then. +#[test] +fn digits_takes_input_only_with_leading_zeros() { + let (app, _) = app(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + open_item(&mut panel.app(), "Type Tools", "Make Numbers Sequence…"); + panel.frame(); + let dialog = dialog_id(&panel.app()); + set(&panel.app(), dialog, "fixedDigits", json!(true)); + panel.frame(); + assert!(panel.enabled("Digits")); + set(&panel.app(), dialog, "leadingZeros", json!(false)); + panel.frame(); + assert!(read(&panel.app(), dialog, super::params).get("digits").is_none()); + assert!(!panel.enabled("Digits"), "with Leading Zeros off the command gets no digits"); +} + /// The dialog's fields reach the command: an end and fixed digits only when turned on, and OK /// numbers the objects as one undo step. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 571a355846..442ddaffbf 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -11,7 +11,7 @@ use craft::ui::docking::IconGroupSeparator; use craft::ui::list::{CommandHighlight, ThumbRows}; use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; -use craft::ui::runtime::env::{RootEnv, Scale, ScrubDrags, WindowKey}; +use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; use craft::ui::runtime::toast::{self, Toast}; use craft::ui::runtime::windows::WindowHost; @@ -74,6 +74,7 @@ impl VectorcraftApp { pub fn new(mut session: Session, mut services: Services) -> Self { // Every entry point (desktop, web, tests) makes the app before its first pass. super::icons::register(); + craft::ui::primitives::register_app_icons(&super::icons::CLASSIC_ICONS); craft::ui::primitives::register_app_icons(&super::cursors::CURSOR_ICONS); // The font menus and the first file opened need the installed fonts: catalog them now. vectorcraft_text::FontDb::global().scan_in_background(); @@ -167,6 +168,8 @@ impl VectorcraftApp { carry_target: None, last_drag: None, escaped_press: false, + pressed_at: None, + keys_at: None, host_caps_lock: None, committed_preview: false, panes: Default::default(), @@ -916,6 +919,11 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print root.escape_leaves_fields = true; // A held key repeats its command (Cmd+= keeps zooming in). root.shortcuts_repeat = true; + // On Windows and Linux only the keypad digits type an Alt code, and Alt with a top-row digit stays a key press for + // the shortcuts (macOS has no Alt codes). A keypad digit types its code also when the Type tool claims Alt with that + // digit. On Windows the system composes keypad codes, and the app takes their digits out of the frame (the app's + // `windows_alt_codes`). + root.alt_code_keys = AltCodeKeys::Keypad; // The wheel steps a focused number field only while the pointer is over it; elsewhere it scrolls what is under the // pointer. root.pointer_scoped_field_wheel = true; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 83fb4194bc..818863408d 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -97,6 +97,9 @@ impl VectorcraftApp { crate::plugin_runs::show_notice(self, id, r); } placing::settle_swatch_paste(self); + for (uid, from, to) in self.session.take_swatch_renames() { + dialogs::gradient_stop::follow_swatch_rename(self, uid, &from, &to); + } result } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 58b2e6c803..6dcec22bff 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -129,6 +129,12 @@ pub struct CanvasCache { /// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up, /// which gives back a selection tool Cmd lent. pub escaped_press: bool, + /// The input time of the last pass whose pointer button events all landed on a canvas, with no other layer over it: + /// the menus' state key leaves such a press out (`menus::model::last_press`). + pub pressed_at: Option, + /// The input time of the last pass in which the canvas or nothing had the focus, so that the canvas or the app's + /// shortcuts took its keys: the menus' state key leaves those keys out (`menus::model::last_press`). + pub keys_at: Option, /// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the /// next reading; `None` before the first pass. pub host_caps_lock: Option, diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index bfef665bb8..a52c6d64c1 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -1,3 +1,5 @@ +use craft::behavior::IconId; +use craft::menu::Item; use craft::ui::canvas::CanvasSpace; use craft::ui::contract::overlay::Anchor; use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; @@ -47,7 +49,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp .opened_by(opener, Trigger::Manual) .anchor(Anchor::Point(at)) .open(Bind::bound(&mut open)) - .show(ui, |ui, _| craft::menu::context::rows(ui, &nodes)); + .show(ui, |ui, _| craft::menu::context::rows_with_icons(ui, &nodes, canvas_icon)); if shown.output.closed.is_some() || !open { app.ui.context_menu_at = None; app.ui.context_locked = None; @@ -57,6 +59,54 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } } +/// The icon each canvas menu command shows in this menu, so a row can be found by its shape (#4602). A command +/// left out has no glyph that says what it does here, and shows its catalog icon, if any, or none. +const ICONS: &[(&str, &str)] = &[ + ("edit.undo", "undo-2"), + ("edit.redo", "redo-2"), + ("edit.cut", "scissors"), + ("edit.copy", "copy"), + ("edit.paste", "clipboard-paste"), + ("edit.clear", "trash-2"), + ("object.group", "group"), + ("object.ungroup", "ungroup"), + ("object.path.smooth", "dc-smooth"), + ("object.objectsOnPath.attach", "dc-objects-on-path"), + ("path.join", "dc-join"), + ("type.applyBullets", "dc-para-bullets"), + ("type.applyNumbers", "dc-para-numbers"), + ("view.grid", "grid-3x3"), + ("view.rulers", "ruler"), + ("view.guides.lock", "lock"), + ("view.fitArtboard", "maximize-2"), + ("artboard.new", "file-plus"), + ("artboard.duplicate", "copy"), + ("artboard.copy", "copy"), + ("artboard.cut", "scissors"), + ("artboard.delete", "trash-2"), + ("artboard.rearrange", "dc-rearrange"), + ("file.exportSelection", "share-2"), + ("file.exportForScreens", "share-2"), +]; + +/// The icons of rows whose command alone doesn't say what they do: Artboard Options (`tool.options` for the +/// Artboard tool) and the Lock Artboards and Unlock Artboards rows (`artboard.setProps` with `locked`). +const ARTBOARD_OPTIONS_ICON: &str = "dc-artboard-options"; +const LOCK_ICON: &str = "lock"; +const UNLOCK_ICON: &str = "lock-open"; + +/// The canvas menu's icon for `item`: Artboard Options' and the artboard lock rows' by their parameters, otherwise +/// its command's entry in [`ICONS`]. +fn canvas_icon(item: &Item) -> Option { + let params = &item.command.params; + let icon = match item.command.id.as_str() { + "tool.options" => (params["tool"] == "artboard").then_some(ARTBOARD_OPTIONS_ICON), + "artboard.setProps" => params["artboards"][0]["locked"].as_bool().map(|locked| if locked { LOCK_ICON } else { UNLOCK_ICON }), + id => ICONS.iter().find(|(command, _)| *command == id).map(|(_, icon)| *icon), + }; + icon.map(IconId::new) +} + /// The one-shot work of a request at screen point `at`: the facts the menu's rows read, and the selection. fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let p = space.view.to_doc(at); @@ -114,3 +164,47 @@ fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { } at } + +#[cfg(test)] +mod tests { + use craft::behavior::IconId; + use craft::ui::primitives::has_icon; + + use craft::menu::Node; + use serde_json::json; + + use super::{ARTBOARD_OPTIONS_ICON, ICONS, LOCK_ICON, UNLOCK_ICON, canvas_icon}; + use crate::menus::cp; + + /// Each canvas menu icon names a drawn icon and a command: a misspelt icon would leave its row's icon slot + /// empty, and a renamed command would quietly lose its icon. + #[test] + fn every_canvas_menu_icon_is_an_icon_of_a_command() { + crate::icons::register(); + for (id, icon) in ICONS { + assert!(has_icon(&IconId::new(icon)), "{id}'s icon {icon} isn't an icon"); + let ui_command = crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id); + assert!(vectorcraft_engine::find_command(id).is_some() || ui_command, "{id} isn't a command"); + } + for icon in [ARTBOARD_OPTIONS_ICON, LOCK_ICON, UNLOCK_ICON] { + assert!(has_icon(&IconId::new(icon)), "{icon} isn't an icon"); + } + } + + /// Rows that share a command take their icon from their parameters: the Artboard Options glyph goes on + /// Artboard Options (`tool.options` for the Artboard tool), not on another tool's options, and the Lock + /// Artboards and Unlock Artboards rows (`artboard.setProps`) show a closed and an open lock. + #[test] + fn rows_that_share_a_command_take_their_icon_from_its_parameters() { + let icon = |node: Node| match node { + Node::Item(item) => canvas_icon(&item), + _ => None, + }; + let lock = |locked| cp("Lock All", "artboard.setProps", json!({ "artboards": [{ "index": 0, "locked": locked }] })); + assert_eq!(icon(cp("Artboard Options", "tool.options", json!({ "tool": "artboard" }))), Some(IconId::new(ARTBOARD_OPTIONS_ICON))); + assert_eq!(icon(cp("Options", "tool.options", json!({ "tool": "pen" }))), None); + assert_eq!(icon(lock(true)), Some(IconId::new(LOCK_ICON))); + assert_eq!(icon(lock(false)), Some(IconId::new(UNLOCK_ICON))); + assert_ne!(icon(lock(true)), icon(lock(false))); + } +} diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs index 9b2846847e..ec268beb61 100644 --- a/crates/ui-egui/src/canvas/quick_pen_bar.rs +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -19,7 +19,7 @@ use craft::ui::canvas_controls::TaskBar; use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::env::{Direction, Env}; +use craft::ui::runtime::env::{Direction, Env, WordsOverride, with_env}; use vectorcraft_tools::quickpen::{self, Stroke as Action}; use super::{Ui, VectorcraftApp, json}; @@ -31,6 +31,13 @@ pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &Canva if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { return None; } + let lang = app.ui_language(); + let words = super::task_bar::bar_words(lang, "Move Toolbar", "Hide Toolbar", "window.quickPenToolbar.pin", "window.quickPenToolbar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_quick_pen_bar(app, ui, space)) +} + +/// The Quick Pen toolbar of [`quick_pen_bar`], in a scope with the toolbar's words. +fn shown_quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { // PLAN: assumed `super::tool_adapter::in_gesture(app: &VectorcraftApp, ctx: &egui::Context) -> bool` (cv.S3) if super::tool_adapter::in_gesture(app, ui.ctx()) { return None; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 56657ef670..d2bbdf1f5c 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -1,17 +1,18 @@ use craft::behavior::CanvasView; use craft::behavior::{IconId, Mixed}; use craft::color_ui::ui::{PaintChip, PaintChipSize}; +use craft::i18n::WordSet as _; use craft::theme::{Srgba, Variant}; use craft::ui::buttons::{Button, IconButton}; use craft::ui::canvas::CanvasSpace; -use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang}; +use craft::ui::canvas_controls::{CanvasControlWords, TaskBar, TaskBarGrip, TaskBarHang}; use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Text; use craft::ui::menu::PanelRow; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env}; use vectorcraft_doc::NodeKind; use vectorcraft_doc::text::TextKind; use vectorcraft_geom::{Point, Rect}; @@ -442,12 +443,43 @@ fn more_rows(offer: &Offer) -> Vec { ] } +/// VectorCraft's words for a canvas bar's More Options button, its grip (`grip`) and the rows the framework puts in +/// More Options (`hide`, and the commands `pin` and `reset`, named by their titles), over the framework's words. Outside +/// English, a word the language's catalog does not translate keeps the framework's translation. +pub(crate) fn bar_words(lang: crate::i18n::Lang, grip: &'static str, hide: &'static str, pin: &str, reset: &str) -> WordRows { + fn plain(lang: crate::i18n::Lang, english: &'static str) -> (&'static str, &'static str) { + (english, crate::i18n::tr(lang, english)) + } + fn command(lang: crate::i18n::Lang, id: &str) -> (&'static str, &'static str) { + let english = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map_or("", |c| c.1); + (english, crate::i18n::tr_id(lang, id, english)) + } + let words = [ + ("taskBar.more", plain(lang, "More Options")), + ("taskBar.move", plain(lang, grip)), + ("taskBar.hide", plain(lang, hide)), + ("taskBar.pin", command(lang, pin)), + ("taskBar.reset", command(lang, reset)), + ]; + words + .into_iter() + .filter(|(_, (english, shown))| !english.is_empty() && (lang == crate::i18n::Lang::EN || shown != english)) + .filter_map(|(id, (_, shown))| Some((CanvasControlWords::word(id)?, shown))) + .fold(WordRows::new(), |rows, (word, shown)| rows.row(word, shown)) +} + /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions /// ([`offered`]). Its grip drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`super::bar_place::KeyedPlace`]). More Options › Bar Actions turns each action /// and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); with every one of them off, the /// bar still shows its grip and More Options, where they turn back on. Returns the bar's rect on screen. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { + let words = bar_words(app.ui_language(), "Move Bar", "Hide Bar", "window.taskBar.pin", "window.taskBar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_task_bar(app, ui, space)) +} + +/// The Contextual Task Bar of [`task_bar`], in a scope with the bar's words. +fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { let offer = offered(app)?; let key = (app.session.active()?.uid, false); let mut local = app.ui.task_bar_place.for_key(key); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 41d0e93837..df0d8fc387 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -897,13 +897,12 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); } -/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its -/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the -/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts -/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new -/// app, at most 20 times, until the other catalogs held still through it. -#[test] -fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { +/// How many times each frame of `steps` builds the menus' states again, with the Selection tool and a 60 × 30 +/// rectangle at (100, 100) selected and the pointer resting over its middle (`steps` gets that point). The menus are +/// also built again when a process-wide catalog changes, so the fonts and plug-ins are held steady against tests +/// running alongside for the whole run, and the steps run again on a new app, at most 20 times, until the other +/// catalogs held still through them. +fn selection_tool_rebuilds(steps: impl Fn(Pos2, &craft::behavior::CanvasView) -> Vec>) -> (VectorcraftApp, Vec) { let fonts = vectorcraft_text::FontDb::global(); let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); let catalogs = || { @@ -920,33 +919,59 @@ fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap(); app.select_tool("selection"); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); - let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0))); + let from = xf.to_screen(Point::new(130.0, 115.0)); app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); for _ in 0..2 { app_step(&mut app, &ctx, vec![]); } - let none = egui::Modifiers::NONE; - let mut steps = vec![vec![primary(from, true, none)]]; - steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); - steps.push(vec![primary(to, false, none)]); - steps.extend([vec![], vec![], vec![]]); let mut rebuilt = vec![]; - for events in steps { + for events in steps(from, &xf) { let before = app.menus.rebuilds; app_step(&mut app, &ctx, events); rebuilt.push(app.menus.rebuilds - before); } (app, rebuilt) }; - let (app, rebuilt) = (0..20) + (0..20) .find_map(|_| { let before = catalogs(); let out = run(); (catalogs() == before).then_some(out) }) - .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")) +} + +/// A Selection tool move builds the menus' states again once, for the release that commits it. Its press lands on the +/// canvas, and the frame the move begins in and the frames of its previews, which change the document's revision, keep +/// them. +#[test] +fn a_selection_move_rebuilds_the_menus_for_its_release_only() { + let none = egui::Modifiers::NONE; + let (app, rebuilt) = selection_tool_rebuilds(|from, xf| { + let to = xf.to_screen(Point::new(170.0, 135.0)); + let mut steps = vec![vec![primary(from, true, none)]]; + steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); + steps.push(vec![primary(to, false, none)]); + steps.extend([vec![], vec![], vec![]]); + steps + }); assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle"); - assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle"); + assert_eq!(rebuilt[..9].iter().sum::(), 0, "the press and the 8 moves keep the menus: {rebuilt:?}"); + assert_eq!(rebuilt.iter().sum::(), 1, "the release that commits the move rebuilds them once: {rebuilt:?}"); +} + +/// A click on the selected rectangle that leaves it where it was, and F20 pressed and released with no field or dialog +/// taking it and no command on it, change nothing the menus show: no frame builds the menus' states again. +#[test] +fn a_canvas_click_that_changes_nothing_keeps_the_menus() { + let none = egui::Modifiers::NONE; + let f20 = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: none }; + let (app, rebuilt) = selection_tool_rebuilds(|from, _| { + vec![vec![primary(from, true, none)], vec![primary(from, false, none)], vec![f20(true)], vec![f20(false)], vec![], vec![]] + }); + assert_eq!(drawn_paths(&app), vec![Rect::new(100.0, 100.0, 160.0, 130.0)], "the click leaves the rectangle where it was"); + assert_eq!(app.session.active().map(|d| d.selection.objects.len()), Some(1), "the rectangle stays selected"); + assert_eq!(rebuilt, [0; 6], "rebuilds in each frame: press, release, a key press and release, 2 idle"); } /// #6369: only the selection box remains over the temporary halftone, and the original @@ -4489,6 +4514,38 @@ fn plain(app: &VectorcraftApp, id: u64) -> String { } } +/// While the Type tool edits text, a click in the text and an arrow key, which move the caret without an edit, build +/// the menus' states again: the type rows read the caret's range. +#[test] +fn a_click_or_a_key_in_edited_text_rebuilds_the_menus() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = crate::testing::ui_context(); + let id = start_typing(&mut app, &ctx); + typing_frame(&mut app, &ctx, vec![Event::Text("abc".into())]); + typing_frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(101.0, 100.0)); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let left = |pressed| Event::Key { key: egui::Key::ArrowLeft, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + let rebuilds = |app: &mut VectorcraftApp, steps: Vec>| { + let before = app.menus.rebuilds; + for events in steps { + typing_frame(app, &ctx, events); + } + app.menus.rebuilds - before + }; + let click = || vec![vec![Event::PointerMoved(at), button(true)], vec![button(false)]]; + // The first click puts the caret there; the second leaves the document's revision as it is. + rebuilds(&mut app, click()); + let revision = app.session.active().map(|d| d.revision); + assert!(rebuilds(&mut app, click()) > 0, "a click in the text"); + assert_eq!(app.session.active().map(|d| d.revision), revision, "the click changes no revision"); + assert!(rebuilds(&mut app, vec![vec![left(true)], vec![left(false)]]) > 0, "an arrow key in the text"); + assert_eq!(plain(&app, id), "abc", "neither edits the text"); + assert!(app.session.tool_wants_text(), "editing goes on"); +} + /// Starts editing new point type with the Type tool; returns its id. fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 8b2b35db16..70f1080db5 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -656,6 +656,17 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too if ui.ctx().current_pass_index() == 0 && view_press { app.session.tool_press_elsewhere(); } + // A press on the canvas, and a key while the canvas or nothing has the focus, change what the menus show only through + // the document, the tool or a command, which the menus' state key reads, so the key leaves them out + // (`menus::model::last_press`). + let presses: Vec = + ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerButton { pos, .. } = e { Some(*pos) } else { None }).collect()); + if !presses.is_empty() && presses.iter().all(|&at| over(Some(at)) && ui.ctx().layer_id_at(at) == Some(ui.layer_id())) { + app.canvas.pressed_at = Some(ui.input(|i| i.time)); + } + if ui.ctx().memory(|m| m.focused()).is_none_or(|id| id == pass.id) { + app.canvas.keys_at = Some(ui.input(|i| i.time)); + } let view_info = app.view_info(); let mut picked = ToolHostResponse::default(); let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) { diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 82dba96e51..985646a065 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -285,10 +285,15 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui) { fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected: bool) { let label = tl!("Opacity:"); let (mut link, mut typed) = (false, None); + let target = crate::panels::transparency_target(app); group(ui, rank::OPACITY, |ui| { Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |ui, _| { - let number = - NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0))).range(0.0..=100.0).unit("%").scrub_by_label().show(ui); + let number = NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0))) + .range(0.0..=100.0) + .unit("%") + .scrub_by_label() + .edit_target(&target) + .show(ui); link |= number.link; typed = number.edit.events.committed().copied().flatten().or(typed); }); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 626ec7d0ae..fb3032d235 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3163,6 +3163,37 @@ fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() { assert_eq!((0..4).map(|k| lc.kind(k)).collect::>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]); } +/// An unfinished Opacity expression in the Control bar belongs to the object it was typed for: after another object +/// with the same opacity is selected, the field shows that object's value, and further typing starts a new value +/// instead of finishing the old expression. +#[test] +fn the_control_bar_opacity_drops_an_unfinished_value_when_the_selection_changes() { + use egui::{Key, Modifiers}; + 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(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 50, "width": 40, "height": 40})).unwrap()["id"].clone() + }; + let (a, b) = (rect(&mut app, 20.0), rect(&mut app, 200.0)); + app.run("transparency.set", json!({"ids": [a, b], "opacity": 50})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let opacity = |bar: &crate::tests::panel_harness::Panel, id: &serde_json::Value| { + bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().opacity + }; + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 300.0)).frame(); + bar.click_role("Opacity:", Role::SPIN_BUTTON); + bar.key(Key::A, Modifiers::COMMAND); + bar.type_text("20+"); + bar.app().run("select.set", json!({"ids": [b]})).unwrap(); + bar.frame(); + assert_eq!(bar.value_role("Opacity:", Role::SPIN_BUTTON).as_deref(), Some("50%"), "the field shows the other object's value"); + bar.type_text("1"); + bar.key(Key::Enter, Modifiers::NONE); + assert_eq!((opacity(&bar, &a), opacity(&bar, &b)), (0.5, 0.01), "the typing gives the other object 1%, not 20+1"); +} + /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard /// controls while it has room, and the Distribute buttons for two or more selected artboards with /// Align to Artboard and three or more with Align to Selection. A diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index bfe9f1991c..158cf852f8 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -153,6 +153,7 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { } let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host))); crate::dialogs::javascript_files::show_selected(app, &mut dialogs); + crate::dialogs::find_replace::show_action(app, &mut dialogs); // The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it. if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) { open.insert(0, strip); @@ -1463,6 +1464,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val if let Some(r) = crate::dialogs::script_window::dialog_method(app, method, ¶ms) { return wrap(r); } + // Find and Replace presses the button its `action` field names and stays open. + if let Some(r) = crate::dialogs::find_replace::dialog_method(app, ctx, method, ¶ms) { + return wrap(r); + } // `ui.dialog.set {action}` answers the dialog after setting its fields: the app's own key, which the // framework's method does not take. let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None }; @@ -1474,6 +1479,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val }; let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set"); let reply = dialogs.with(|host| { + // A Color Picker whose Recolor Artwork row changed while it was open refuses OK. + if method == "ui.dialog.confirm" + && let Err(reason) = crate::dialogs::color_picker::check_confirm(app, host, ¶ms) + { + return Some(Err(reason)); + } // The answer goes to the dialog the fields went to, even when setting them opens another over it. if answer.is_some() && params["dialog"] == "top" @@ -1486,6 +1497,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { crate::dialogs::effect::normalize_set_mode(app, id, &mut params); } + // A set with `action: confirm` on such a picker changes none of its fields. + if answer == Some("ui.dialog.confirm") + && let Err(reason) = crate::dialogs::color_picker::check_confirm(app, host, ¶ms) + { + return Some(Err(reason)); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { // A Save PDF settings object keeps the options it leaves out. diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 6e29fc182f..d8ca17ce8f 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -5,7 +5,9 @@ //! `datasets`), `datasetFileNaming`, `folder`, `includeSubdirs`, `destination` (`none`, //! `saveAndClose` or `folder`), `destinationFolder`, `overrideOpen`, `overrideSave`, //! `overrideExport` and `stopOnError`. OK plays the action; a source or destination folder left -//! empty, or Data Sets without a document, is an error and the dialog stays open. +//! empty, or Data Sets without a document, is an error and the dialog stays open. After the batch +//! the status bar gives the counts, and when a file or data set failed, a message lists each one +//! with its error. use std::hash::Hash; use std::sync::Arc; @@ -293,17 +295,66 @@ impl ActionDialog for BatchDialog { return Err("open a document with data sets".into()); } let result = app.replay("action.batch", params(&fields, &a.name, commands))?; - let count = result["count"].as_u64().unwrap_or(0); - let failed = result["failed"].as_u64().unwrap_or(0); - if failed > 0 { - app.status(format!("Batch: {count} processed, {failed} failed")); - } else { - app.status(format!("Batch: {count} processed")); - } + report(app, &result); Ok(()) } } +/// How many failed files or data sets the message after a batch lists; the rest are counted. +const LISTED_FAILURES: usize = 10; + +/// How many characters of a failed file's or data set's error the message shows; a longer error +/// ends in "…". +const ERROR_CHARS: usize = 300; + +/// Says in the status bar how many files or data sets the batch `result` processed and how many +/// failed. When any failed, a message lists each failed one with its error ([`failure_lines`]). +fn report(app: &mut VectorcraftApp, result: &Value) { + let count = result["count"].as_u64().unwrap_or(0); + let failed = result["failed"].as_u64().unwrap_or(0); + if failed == 0 { + app.status(format!("Batch: {count} processed")); + return; + } + let summary = format!("Batch: {count} processed, {failed} failed"); + app.status(summary.clone()); + super::confirm::tell(app, &crate::i18n::msg(&summary), &failure_lines(result).join("\n")); +} + +/// One line for each failed file or data set of the batch `result`, in the order the batch ran +/// them: its path or data set name, as it is, and its error in the interface language. The first +/// [`LISTED_FAILURES`] are listed and a line counts the rest; a line says when Stop on Errors +/// ended the batch. +fn failure_lines(result: &Value) -> Vec { + let failures: Vec<(&str, &str)> = result["processed"] + .as_array() + .into_iter() + .flatten() + .filter_map(|row| { + let error = row["error"].as_str()?; + Some((row["path"].as_str().or_else(|| row["dataset"].as_str()).unwrap_or_default(), error)) + }) + .collect(); + let mut lines: Vec = + failures.iter().take(LISTED_FAILURES).map(|(source, error)| format!("{source}: {}", shortened(&crate::i18n::msg(error)))).collect(); + let more = failures.len().saturating_sub(LISTED_FAILURES); + if more > 0 { + lines.push(crate::i18n::tn(more as u64, "and {n} more", "and {n} more")); + } + if result["stopped"] == true { + lines.push(crate::i18n::t("Stop on Errors ended the batch at this error.").to_owned()); + } + lines +} + +/// `text` cut to [`ERROR_CHARS`] characters, with "…" at the end when it was cut. +fn shortened(text: &str) -> String { + match text.char_indices().nth(ERROR_CHARS) { + Some((at, _)) => format!("{}…", &text[..at]), + None => text.to_owned(), + } +} + /// A row that picks one of `entries` for `value`. fn select_row(ui: &mut Ui, name: &str, value: &mut T, entries: &[Entry]) { Field::new(label(name)).show(ui, |ui, _| { @@ -535,6 +586,116 @@ mod tests { assert!(!app.session.replaying()); } + /// Runs the action "Draw" as a batch from the dialog with `fields`, pressing OK in a panel, and + /// gives the panel after the frames that close the dialog and show what follows it. + fn batch_in_panel(app: VectorcraftApp, fields: &[(&str, Value)]) -> Panel { + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + open(&mut panel.app(), 0, 0).unwrap(); + set_fields(&panel.app(), fields); + panel.frame(); + panel.click("OK"); + for _ in 0..4 { + panel.frame(); + } + assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::())); + panel + } + + /// The message the batch left: its text and its lines, one for each failed source. + fn told(panel: &Panel) -> Option<(String, Vec)> { + panel.app().told.0.last().map(|(message, detail)| (message.clone(), detail.lines().map(str::to_owned).collect())) + } + + /// An app holding the action "Draw" with `steps` and a document with the data sets `names`. + fn with_data_sets(steps: Vec, names: &[String]) -> VectorcraftApp { + let mut app = app_with(steps); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + for name in names { + app.run("dataset.new", json!({"name": name})).unwrap(); + } + app + } + + /// A step that fails on every document: Align with nothing selected. + fn failing_align() -> ActionStep { + ActionStep::new("object.align", json!({})) + } + + #[test] + fn a_file_that_fails_is_listed_with_its_error() { + let folder = std::env::temp_dir().join(format!("vc-ui-batch-failed-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let svg = r#""#; + std::fs::write(folder.join("a.svg"), svg).unwrap(); + std::fs::write(folder.join("b.svg"), "not an svg").unwrap(); + let app = app_with(vec![ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))]); + let fields = [("folder", json!(folder.to_string_lossy())), ("destination", json!("none")), ("stopOnError", json!(false))]; + let panel = batch_in_panel(app, &fields); + let _ = std::fs::remove_dir_all(&folder); + assert_eq!(panel.app().ui.status, "Batch: 2 processed, 1 failed"); + let (message, lines) = told(&panel).expect("a message lists the failed file"); + assert_eq!(message, "Batch: 2 processed, 1 failed"); + let bad = folder.join("b.svg").to_string_lossy().into_owned(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let error = lines[0].strip_prefix(&format!("{bad}: ")).unwrap_or_else(|| panic!("{lines:?}")); + assert!(!error.is_empty() && !error.contains("action step"), "the open's own error: {lines:?}"); + assert!(panel.texts().iter().any(|(text, _)| text.contains(&lines[0])), "the message shows the line"); + } + + #[test] + fn a_data_set_that_fails_is_listed_with_its_step_error() { + let names = ["Alpha".to_string(), "Beta".to_string()]; + for (stop, listed) in [(false, vec!["Alpha", "Beta"]), (true, vec!["Alpha"])] { + let app = with_data_sets(vec![failing_align()], &names); + let panel = batch_in_panel(app, &[("source", json!("datasets")), ("destination", json!("none")), ("stopOnError", json!(stop))]); + let (message, lines) = told(&panel).expect("a message lists the failed data sets"); + assert_eq!(message, format!("Batch: {} processed, {} failed", listed.len(), listed.len())); + for (line, name) in lines.iter().zip(&listed) { + assert!(line.starts_with(&format!("{name}: action step 1 (`object.align`) failed: ")), "{lines:?}"); + } + let stopped = lines.last().is_some_and(|line| line == "Stop on Errors ended the batch at this error."); + assert_eq!(lines.len(), listed.len() + usize::from(stop), "{lines:?}"); + assert_eq!(stopped, stop, "{lines:?}"); + } + } + + #[test] + fn many_failures_list_the_first_and_count_the_rest() { + let names: Vec = (1..=25).map(|n| format!("Set {n}")).collect(); + let app = with_data_sets(vec![failing_align()], &names); + let panel = batch_in_panel(app, &[("source", json!("datasets")), ("destination", json!("none")), ("stopOnError", json!(false))]); + let (message, lines) = told(&panel).expect("a message lists the failed data sets"); + assert_eq!(message, "Batch: 25 processed, 25 failed"); + assert_eq!(lines.len(), LISTED_FAILURES + 1, "{lines:?}"); + for (line, name) in lines[..LISTED_FAILURES].iter().zip(&names) { + assert!(line.starts_with(&format!("{name}: action step 1")), "{lines:?}"); + } + assert_eq!(lines[LISTED_FAILURES], "and 15 more"); + } + + #[test] + fn a_batch_without_failures_shows_only_the_counts() { + let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let app = with_data_sets(vec![step], &["Alpha".to_string()]); + let panel = batch_in_panel(app, &[("source", json!("datasets")), ("destination", json!("none"))]); + assert_eq!(panel.app().ui.status, "Batch: 1 processed"); + assert!(told(&panel).is_none()); + assert!(!panel.app().any_dialog_open()); + } + + #[test] + fn a_long_error_is_cut_short() { + let long = "é".repeat(ERROR_CHARS + 50); + let result = json!({ + "processed": [{"path": "/in/a.svg", "error": long}, {"path": "/in/b.svg"}, {"dataset": "Alpha", "error": "short"}], + "count": 3, "failed": 2, "stopped": false, + }); + let lines = failure_lines(&result); + assert_eq!(lines, [format!("/in/a.svg: {}…", "é".repeat(ERROR_CHARS)), "Alpha: short".to_string()]); + assert_eq!(shortened(&"é".repeat(ERROR_CHARS)), "é".repeat(ERROR_CHARS), "an error of the length is kept whole"); + } + #[test] fn data_set_naming_params_follow_dialog_choice() { let mut fields = BatchFields::default(); diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index dd09594490..5812e37270 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -27,7 +27,7 @@ use std::borrow::Cow; use std::sync::{Arc, Weak}; -use craft::behavior::{Mixed, Selection, SelectionChange, keyed}; +use craft::behavior::{EditEvent, EditEvents, Mixed, Selection, SelectionChange, keyed}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; @@ -317,8 +317,20 @@ impl BulletsDialog { fn level(&mut self, ui: &mut Ui) { let value = self.fields.get("listLevel").and_then(Value::as_f64); let edit = NumberField::new(tl!("Level:"), Bind::given(value)).range(1.0..=LIST_LEVELS as f64).commit_decimals(0).show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert("listLevel".into(), json!(v)); + self.land("listLevel", &edit.edit.events); + } + + /// Sets `key` to the number its field's `events` leave: the number entered or the number a canceled edit + /// restores, and no number where a canceled edit restores a blank field. + fn land(&mut self, key: &str, events: &EditEvents>) { + match events.landed() { + Some(Some(v)) => { + self.fields.insert(key.into(), json!(v)); + } + Some(None) if matches!(events.ended(), Some(EditEvent::Cancel { .. })) => { + self.fields.remove(key); + } + _ => {} } } @@ -393,9 +405,7 @@ impl BulletsDialog { .enabled(on == Some(true)) .id_salt("startNumber") .show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert("startNumber".into(), json!(v)); - } + self.land("startNumber", &edit.edit.events); }); } @@ -415,9 +425,7 @@ impl BulletsDialog { fn indent(&mut self, ui: &mut Ui, key: &'static str, label: &'static str) { let value = self.fields.get(key).and_then(Value::as_f64); let edit = NumberField::length(label, Bind::given(value), self.lengths).range(INDENTS).show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert(key.into(), json!(v)); - } + self.land(key, &edit.edit.events); } } @@ -1239,4 +1247,41 @@ mod tests { ok(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Dot).at_level(3))); } + + /// Leaving Level, Start at or an indent on text that is not a number cancels the typing: the field goes back to + /// the number it had before it, or to blank where the paragraphs differ, and so does the type. + #[test] + fn a_canceled_number_edit_restores_the_field_and_the_type() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (mut app, id) = app(); + app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "leftIndent": 30, "start": 0, "end": 0})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1800.0)); + panel.app().run("ui.bulletsAndNumbering", json!({})).unwrap(); + panel.frame(); + set(&mut panel.app(), "startAt", json!(true)); + panel.frame(); + assert!(fields(&panel.app()).get("leftIndent").is_none(), "the paragraphs' left indents differ: blank"); + let state = |panel: &Panel| { + let app = panel.app(); + (sent(&app), first(&app, id)) + }; + for name in ["Level:", "Start at:", "Left Indent:", "First Line Indent:"] { + let before = state(&panel); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("7"); + assert_ne!(state(&panel).0, before.0, "typing into {name} proposes a number"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "leaving {name} keeps the dialog open"); + assert_eq!(state(&panel), before, "leaving {name} on text that is not a number restores it"); + } + } } diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 6863ee28a7..f45fadf201 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -8,7 +8,8 @@ //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog //! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor -//! Artwork shows the library that Limit to Library limits to. The OK for a Save for Web colour table cell shifts the cell's +//! Artwork shows the library that Limit to Library limits to and the document's swatches as they +//! were before its preview, and its OK on a global or spot swatch gives the row that swatch. The OK for a Save for Web colour table cell shifts the cell's //! colour in the table instead ([`super::save_for_web::take_palette_pick`]). //! //! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`, @@ -19,12 +20,13 @@ use std::sync::Arc; use craft::cms::Profile; use craft::cms::convert::CmykConverter; -use craft::color_ui::ui::{ColorPickerDialog, PickedColor, PickerLibrary, PickerSwatches}; +use craft::color_ui::ui::{ColorPickerDialog, PickedColor, PickedSwatch, PickerLibrary, PickerSwatches}; use craft::theme::Srgba; use craft::ui::dialog::{DialogId, DialogResult}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; use vectorcraft_color::cms; +use vectorcraft_color::recolor::ColorKey; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; @@ -81,6 +83,11 @@ pub(crate) struct Open { pub keep: bool, /// The live preview of its colour on the target. pub preview: LivePreview, + /// What its Color Swatches view listed when it opened, over Recolor Artwork; empty otherwise. + pub view: ViewSwatches, + /// The Recolor Artwork row it opened for, as its `from` colors and its `to` color; `None` + /// otherwise. OK answers nothing when the row at its key no longer matches. + pub row: Option, } /// The records of the colour area's open dialogs: one holder, so the app has one field for them. @@ -127,23 +134,91 @@ pub(crate) fn open_picker(app: &VectorcraftApp) -> Option { /// The document's swatches and the swatch libraries as the picker's Color Swatches view: solid /// colours only, tints as their colour. pub(crate) fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { - let solid = |swatches: &[vectorcraft_color::Swatch]| -> Vec<(Label, Srgba)> { - swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect() + swatch_view_of(app, false).0 +} + +/// [`swatch_view`], with the document's swatches as they were before the preview when +/// `before_preview` (over Recolor Artwork, whose `recolor.apply` reads them so), and the libraries +/// it lists, which a pick's place in the view is read against. +fn swatch_view_of(app: &VectorcraftApp, before_preview: bool) -> (PickerSwatches, ViewSwatches) { + let listed = view_libraries(app, before_preview); + let libraries = listed + .iter() + .map(|(_, name, swatches)| { + let cells = swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect(); + PickerLibrary::new(name.clone(), cells) + }) + .collect(); + let kept = listed.into_iter().map(|(key, _, swatches)| (key, swatches)).collect(); + (PickerSwatches::new(libraries, tl!("Open a document to see its swatches.")), kept) +} + +/// The libraries a picker's Color Swatches view lists, as it opened: each with its Limit to Library +/// key and its colour swatches, one for one with the view's cells. +pub(crate) type ViewSwatches = Vec<(String, Vec)>; + +/// The libraries of [`swatch_view_of`] in its order, each with its Limit to Library key, its name +/// and its colour swatches (the swatches the view lists, one for one). +fn view_libraries(app: &VectorcraftApp, before_preview: bool) -> Vec<(String, Label, Vec)> { + let solid = |swatches: &mut dyn Iterator| -> Vec { + swatches.filter(|s| s.paint.color().is_some()).cloned().collect() }; - let mut libraries = Vec::new(); - if let Some(st) = app.session.active() { - let all: Vec<_> = st.doc.swatches.iter().chain(st.doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())).cloned().collect(); - libraries.push(PickerLibrary::new(Label::from(DOCUMENT_SWATCHES), solid(&all))); - } else { - libraries.push(PickerLibrary::new(Label::from(DOCUMENT_SWATCHES), Vec::new())); - } + let doc = app.session.active().map(|st| match &st.interaction { + Some(it) if before_preview => &it.doc, + _ => &st.doc, + }); + let mut libraries = vec![( + swatchlib::DOCUMENT_SWATCHES.to_string(), + Label::from(DOCUMENT_SWATCHES), + doc.map(|doc| solid(&mut doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())))).unwrap_or_default(), + )]; for lib in colour_libraries(app) { let swatches = swatchlib::library(&app.session, &lib.id) - .map(|(_, l)| solid(&l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())).cloned().collect::>())) + .map(|(_, l)| solid(&mut l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())))) .unwrap_or_default(); - libraries.push(PickerLibrary::new(Label::from(lib.name.clone()), swatches)); + libraries.push((lib.id.clone(), Label::from(lib.name.clone()), swatches)); } - PickerSwatches::new(libraries, tl!("Open a document to see its swatches.")) + libraries +} + +/// The swatch a Color Picker over Recolor Artwork answered with: `Some((swatch, color))` for a +/// global or spot swatch that is not a tint of another one (`{name, library}` and its colour, in its +/// own model), `None` for another swatch; outer `None` when the view has no such swatch. `view` is +/// what the picker's view listed when it opened. +fn picked_row_swatch(app: &mut VectorcraftApp, view: &ViewSwatches, picked: PickedSwatch) -> Option> { + let (key, swatches) = view.get(picked.library)?; + let s = swatches.get(picked.index)?; + let keeps = (s.global || s.spot) && matches!(s.paint, Paint::Solid { swatch: None, .. }); + let color = s.paint.color()?; + if keeps + && swatches[..picked.index].iter().any(|w| { + w.name == s.name + && matches!(w.paint, Paint::Solid { swatch: None, .. }) + && w.paint.color().is_some_and(|c| ColorKey::of(&c) == ColorKey::of(&color)) + }) + { + app.status(tl!("The swatch could not be kept because another swatch has its name and color.")); + return Some(None); + } + Some(keeps.then(|| (json!({"name": s.name, "library": key}), color))) +} + +/// Where the first swatch `name` of library `key` with colour `c` (compared as colour keys, as +/// `recolor.apply` finds it) stands in `view`, for a picker reopened over a Recolor Artwork row +/// that has it. +fn view_place(app: &VectorcraftApp, view: &ViewSwatches, name: &str, key: &str, c: &Color) -> Option { + let key = if key == swatchlib::DOCUMENT_SWATCHES { key.to_string() } else { swatchlib::library(&app.session, key)?.0.id }; + view.iter().enumerate().find_map(|(li, (k, swatches))| { + if k != &key { + return None; + } + let fits = |s: &vectorcraft_color::Swatch| { + s.name == name + && matches!(s.paint, Paint::Solid { swatch: None, .. }) + && s.paint.color().is_some_and(|w| ColorKey::of(&w) == ColorKey::of(c)) + }; + swatches.iter().position(fits).map(|i| PickedSwatch::new(li, i)) + }) } /// The index in [`swatch_view`]'s libraries of the library a Limit to Library key names @@ -228,10 +303,28 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; // OK with the artboard's color (or the white that stands in for none) unchanged keeps the artboard as it is. let keep = artboard.is_some() && p.get("color").is_none(); - app.color_dialogs.pickers.push(Open { id, target, start, keep, preview: LivePreview::default() }); + app.color_dialogs.pickers.push(Open { id, target, start, keep, preview: LivePreview::default(), view: Vec::new(), row: None }); Ok(Value::Null) } +/// The reason `ui.dialog.confirm` with `params` fails, when it would confirm a picker whose Recolor +/// Artwork row changed since the picker opened (OK would then answer nothing). The picker stays open. +pub(crate) fn check_confirm(app: &VectorcraftApp, host: &craft::ui::dialog::DialogHost, params: &Value) -> Result<(), String> { + let Ok(id) = craft::automation::dialogs::dialog_id(host, params) else { return Ok(()) }; + let Some(open) = app.color_dialogs.pickers.iter().find(|open| open.id == id) else { return Ok(()) }; + if let (Target::Answer { parent, key }, Some(row)) = (&open.target, &open.row) + && super::recolor::row_identity_in(host, *parent, key).as_ref() != Some(row) + { + return Err(rows_changed()); + } + Ok(()) +} + +/// Why a picker's OK answers nothing over Recolor Artwork. +pub(super) fn rows_changed() -> String { + tl!("The Recolor Artwork rows changed while the Color Picker was open").to_string() +} + /// Once per frame (after the shell pass): opens a picker for each dialog's colour request, previews /// each open picker's colour on the art, hands it the screen picks, and settles the ones that /// closed. @@ -241,12 +334,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let start = request.color.unwrap_or(Srgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }); let key = request.key.clone(); let library = super::recolor::limit_to(&dialogs, parent).and_then(|limit| library_index(app, &limit)); + let over_recolor = super::recolor::is_recolor(&dialogs, parent); + let (swatches, listed) = swatch_view_of(app, over_recolor); + let view = if over_recolor { listed } else { Vec::new() }; + // A row picked from a swatch has that swatch marked again, while the row's colour is its colour. + let row_swatch = super::recolor::row_swatch_of(&dialogs, parent, &key) + .and_then(|(name, lib, to)| view_place(app, &view, &name, &lib, &to)) + .filter(|p| picked_row_swatch(app, &view, *p).flatten().is_some()); let child = ColorPickerDialog::from_request(request) .eyedropper(true) .add_to_swatches(false) .gamut(gamut(app)) .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); + .swatch_view(swatches); + let row = super::recolor::row_identity(&dialogs, parent, &key); let id = dialogs.with(|h| h.open_child(child, parent)); // Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to. if let Some(i) = library @@ -254,7 +355,21 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { { app.status(e); } - app.color_dialogs.pickers.push(Open { id, target: Target::Answer { parent, key }, start, keep: false, preview: LivePreview::default() }); + // A picker set to a layout without the swatches view refuses the mark and keeps the colour. A + // swatch of another library than the one Limit to Library limits to is not marked, so the + // view keeps showing that library. + if let Some(p) = row_swatch.filter(|p| library.is_none_or(|i| p.library == i)) { + let _ = dialogs.with(|h| h.set_json_field(ctx, id, "swatch", json!([p.library, p.index]))); + } + app.color_dialogs.pickers.push(Open { + id, + target: Target::Answer { parent, key }, + start, + keep: false, + preview: LivePreview::default(), + view, + row, + }); } let busy = app.screen_pick.busy(); let mut pickers = std::mem::take(&mut app.color_dialogs.pickers); @@ -310,6 +425,19 @@ fn finish( let preview = std::mem::take(&mut open.preview); match (result, &open.target) { (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => { + // A row that the dialog's rows changed under (`ui.dialog.set`) takes no answer. + if open.row.is_some() && super::recolor::row_identity(dialogs, *parent, key) != open.row { + app.status(rows_changed()); + return; + } + // Over Recolor Artwork, a colour picked from a swatch carries the swatch to the row. + if let Some(swatch) = r.swatch.and_then(|p| picked_row_swatch(app, &open.view, p)) + && super::recolor::is_recolor(dialogs, *parent) + { + super::recolor::answer_swatch(dialogs, *parent, key, swatch); + } + // The pump applies the answer later; it drops it when the row changed in between. + super::recolor::answer_row(dialogs, *parent, open.row.clone()); if !super::save_for_web::take_palette_pick(app, *parent, key, open.start, r.picked.color) { dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 0465d1e322..5592a2c274 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -719,7 +719,7 @@ fn percent<'r>(list: ListRow<'r>, spec: &Percent, value: f64, at: usize, edits: let Percent { column, label, range, edit } = spec; let (edit, field) = (*edit, NumberField::new(*label, Bind::given(Some(value))).range((*range).clone()).unit("%")); list.cell_field(column.clone(), field, move |out| { - if let Some(Some(v)) = out.edit.value().copied() { + if let Some(Some(v)) = out.edit.events.landed().copied() { edits.borrow_mut().push((at, edit(v))); } }) diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 48070f0b41..be02c8046c 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -650,6 +650,36 @@ fn a_highlighted_part_style_applies_only_once_it_is_chosen() { assert_ne!(parts(&p), before, "Enter sets the style"); } +/// Leaving a part's Size or Baseline on text that is not a number cancels the typing, and the part goes back to the +/// value it had before it. +#[test] +fn a_canceled_part_percentage_restores_the_part() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut p = Panel::new(app(), crate::tests::picks::dialogs); + p.room(egui::vec2(1280.0, 1100.0)); + open(&mut p.app()).unwrap(); + new_font(&mut p.app()); + p.frame(); + p.frame(); + let parts = |p: &Panel| dialog(&mut p.app(), |d| d.font().map(|f| f.parts.clone())); + for name in ["Size", "Baseline"] { + let before = parts(&p); + p.click_role(name, Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("37"); + assert_ne!(parts(&p), before, "typing into {name} proposes a value"); + p.type_text("x"); + p.key(Key::Tab, Modifiers::NONE); + p.frame(); + assert!(is_open(&p.app()), "leaving {name} keeps the dialog open"); + assert_eq!(parts(&p), before, "leaving {name} on text that is not a number restores the part"); + } +} + #[test] fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 057eac94eb..0020757e44 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -286,6 +286,8 @@ fn normalized(app: &VectorcraftApp, id: &str, values: Map, fresh: super::effect_rows::clamp_blur_center(&mut values); } else if id == vectorcraft_effects::RASTERIZE { super::raster_effects::preset_of(&mut values); + } else if id == vectorcraft_effects::addons::halftone::HALFTONE { + super::halftone::canonical_style(&mut values); } values } @@ -705,6 +707,19 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn halftone_dialog_normalizes_stored_style_case() { + let mut app = app(); + let node = rect(&mut app, 10); + let effect = vectorcraft_effects::addons::halftone::HALFTONE; + app.run("effect.apply", json!({"ids": [node], "effect": effect, "item": null, "params": {"style": "GRIDDOTS"}})).unwrap(); + app.run("select.set", json!({"ids": [node]})).unwrap(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + let open = app.effect_dialogs.effect.as_ref().unwrap(); + assert_eq!(open.opened["style"], json!("gridDots")); + assert_eq!(fields(&app, id(&app)).text("style"), Some("gridDots")); + } + #[test] fn edit_and_add_new_still_open_after_an_idle_effect_prompt() { for (choice, editing) in [("proceed", true), ("alternate", false)] { @@ -757,17 +772,17 @@ mod tests { assert_eq!((pa["detail"].as_f64(), pb["detail"].as_f64()), (Some(3.0), Some(8.0)), "each keeps its untouched value"); } - /// Zig Zag's Ridges per segment and Roughen's Detail are counts: their rows show no percent sign, while Size - /// with Relative, a share of the object's size, shows one. + /// Zig Zag's Ridges per segment is a plain count and Roughen's Detail a count per inch: neither row shows a + /// percent sign, while Size with Relative, a share of the object's size, shows one. #[test] - fn zig_zag_ridges_and_roughen_detail_show_no_percent_sign() { + fn zig_zag_ridges_and_roughen_detail_show_their_count_units() { use craft::ui::runtime::env::UnitKind; let app = app(); - for (effect, key) in [("distort.zigZag", "ridges"), ("distort.roughen", "detail")] { + for (effect, key, expected) in [("distort.zigZag", "ridges", None), ("distort.roughen", "detail", Some(UnitKind::PerInch))] { let cx = EffectCx::new(&app, effect, false); let rows = super::super::effect_rows::distort(&cx, &DialogFields::new()); let unit = |k: &str| rows.iter().find(|p| p.key == k).map(|p| p.unit); - assert_eq!(unit(key), Some(None), "{effect} {key}"); + assert_eq!(unit(key), Some(expected), "{effect} {key}"); assert_eq!(unit("size"), Some(Some(UnitKind::Percent)), "{effect} size"); } } @@ -1172,6 +1187,29 @@ mod tests { assert_eq!(params(&app, node)["size"], 12.0); } + #[test] + fn a_new_graphics_context_rolls_back_the_old_effect_preview_and_keeps_the_new_opening() { + let mut app = app(); + let node = rect(&mut app, 10); + standalone_effect_source(&mut app); + effect_frame(&mut app); + assert_eq!(params(&app, node)["size"], 16.0); + let history = steps(&app); + + app.adopt_context(&crate::testing::ui_context()); + effect_frame(&mut app); + assert!(!app.session.in_interaction(), "the old context's effect preview is still running"); + assert!(app.effect_dialogs.effect.is_none()); + assert!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(node)).unwrap().appearance.effects.is_empty()); + + standalone_effect_source(&mut app); + effect_frame(&mut app); + assert!(app.effect_dialogs.effect.is_some(), "the old opening's Cancel removed the new opening"); + ok(&mut app); + assert_eq!(params(&app, node)["size"], 16.0); + assert_eq!(steps(&app), history + 1); + } + #[test] fn standalone_effect_ok_cannot_change_the_reloaded_drawing() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index 9ba4858116..023c67cba5 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -88,8 +88,11 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec { /// Zig Zag and Roughen. pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec { let roughen = cx.id == "distort.roughen"; - // PLAN: production suffixes Detail with "/in"; `Param::unit` takes a `UnitKind` and none stands for it - let second = if roughen { count_range("detail", lbl!("Detail:"), 10.0) } else { count_range("ridges", lbl!("Ridges per segment:"), 4.0) }; + let second = if roughen { + count_range("detail", lbl!("Detail:"), 10.0).unit(UnitKind::PerInch) + } else { + count_range("ridges", lbl!("Ridges per segment:"), 4.0) + }; let points: Vec<(String, Label)> = choices(&cx.id, "points") .unwrap_or_default() .iter() diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index decb345a71..884e5848bf 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -697,7 +697,7 @@ impl ExportForScreensDialog { } }; screen_formats::rows(ui, fields, Some(&mut menu)); - let saved = screen_formats::save_preset_row(ui, fields); + let saved = screen_formats::save_preset_row(ui, fields, &mut false); if let Some(pick) = picked.or(saved) { self.pending = Some(pick); } diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 78a24f8868..fc62033bf9 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -17,6 +17,8 @@ //! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the drawing's //! UID and Revert counter in `doc`, and the match in `found` (`{index, count}`). Changing the //! loaded drawing, Find text, or switches restarts the search. [`pump`] runs the requests each frame. +//! Automation presses the buttons through the dialog's `action` field and `ui.dialog.confirm` +//! ([`dialog_method`]). use craft::text::find::FindOptions; use craft::text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons}; @@ -109,6 +111,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result replace_all(app, &form), _ => return None, }; + // A click presses a button as `ui.dialog.confirm` does: `action` goes back to find. + app.ui.find_action = None; Some(ran.unwrap_or_else(|e| said(&e))) }); + report(app, &form, message); +} + +/// Tells the open dialog `message`, or the refreshed match line when there is none, and whether a +/// match is current. +fn report(app: &mut VectorcraftApp, form: &Form, message: Option) { let (matched, match_message) = refresh_match(app, &form.query); + let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { if let Some(d) = host.get_mut::() { if let Some(message) = message.or(match_message) { @@ -351,5 +363,175 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } +/// The values the `action` field takes: the button `ui.dialog.confirm` presses. +const ACTIONS: [&str; 5] = ["find", "replace", "replaceFind", "replaceAll", "done"]; + +/// The `action` field a `ui.dialog.set` gives, as `field` and `value` or as an item of `fields`, taken +/// out of `params`: `Ok(None)` when it gives none, an error when it is not one of [`ACTIONS`]. +fn take_action(params: &mut Value) -> Result, String> { + let Some(o) = params.as_object_mut() else { return Ok(None) }; + // The host's setter refuses the same mix. + if o.contains_key("fields") && (o.contains_key("field") || o.contains_key("value")) { + return Err("`fields` takes the place of `field` and `value`".into()); + } + let mut given = None; + if o.get("field").and_then(Value::as_str) == Some("action") { + o.remove("field"); + given = Some(o.remove("value").unwrap_or(Value::Null)); + } + let mut only_action = false; + if let Some(list) = o.get_mut("fields").and_then(Value::as_array_mut) { + // The framework's limit counts `action` with the other items. + let most = craft::automation::dialogs::MAX_DIALOG_FIELDS; + if list.len() > most { + return Err(format!("`fields` holds {} items; at most {most}", list.len())); + } + let is_action = |item: &Value| item.get("field").and_then(Value::as_str) == Some("action"); + if let Some(last) = list.iter().rev().find(|item| is_action(item)) { + given = Some(last.get("value").cloned().unwrap_or(Value::Null)); + } + let before = list.len(); + list.retain(|item| !is_action(item)); + only_action = list.is_empty() && before > 0; + } + // A list that held only `action` sets nothing else. + if only_action { + o.remove("fields"); + } + match given { + None => Ok(None), + Some(Value::String(a)) if ACTIONS.contains(&a.as_str()) => Ok(Some(a)), + Some(_) => Err("`action` must be find, replace, replaceFind, replaceAll or done".into()), + } +} + +/// The open dialog as `ui.inspect` lists it, `{id, parent, key, fields}` with its `action`, or null. +fn listed(app: &VectorcraftApp) -> Value { + let Some(dialogs) = app.dialogs() else { return Value::Null }; + let mut open = dialogs.with(|host| craft::automation::dialogs::inspect(host)); + show_action(app, &mut open); + let id = dialogs.with(|host| host.get::().map(|d| d.id().value().to_string())); + open.as_array().and_then(|open| open.iter().find(|d| id.as_deref().is_some_and(|id| d["id"] == id)).cloned()).unwrap_or(Value::Null) +} + +/// Adds the `action` field to the open Find and Replace dialog in `ui.inspect`'s `dialogs`. +pub(crate) fn show_action(app: &VectorcraftApp, dialogs: &mut Value) { + let Some(id) = app.dialogs().and_then(|d| d.with(|host| host.get::().map(|d| d.id().value().to_string()))) else { return }; + let action = app.ui.find_action.clone().unwrap_or_else(|| "find".into()); + let shown = dialogs.as_array_mut().and_then(|open| open.iter_mut().find(|d| d["id"] == id.as_str())); + if let Some(fields) = shown.and_then(|d| d.get_mut("fields")).and_then(Value::as_object_mut) { + fields.insert("action".into(), json!(action)); + } +} + +/// `ui.dialog.set` and `ui.dialog.confirm` (`method`) on the open Find and Replace dialog, when +/// `params.dialog` names it: a set takes the `action` field and answers with the dialog as +/// `ui.inspect` lists it, `action` included, and `ui.dialog.confirm`, or a set with +/// `action: "confirm"`, presses the button it names (`find` when none is set) and leaves `action` at +/// `find` again. Every other request is the host's, as is a set with `action: "cancel"` that gives +/// no `action` field: `None`. +pub(crate) fn dialog_method(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: &Value) -> Option> { + if !matches!(method, "ui.dialog.set" | "ui.dialog.confirm") { + return None; + } + let dialogs = app.dialogs()?; + let ours = dialogs.with(|host| { + let id = host.get::().map(StackDialog::id); + id.is_some() && craft::automation::dialogs::dialog_id(host, params).ok() == id + }); + if !ours { + return None; + } + let keys: &[&str] = if method == "ui.dialog.set" { &["dialog", "field", "value", "fields", "action"] } else { &["dialog"] }; + let mut params = params.clone(); + let answer = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { Some(json!("confirm")) }; + let given = if method == "ui.dialog.set" { + match take_action(&mut params) { + Ok(given) => given, + Err(e) => return Some(Err(e)), + } + } else { + None + }; + let confirm = match answer.as_ref().map(Value::as_str) { + None => false, + Some(Some("confirm")) => true, + // Cancel closes it as the host closes any dialog. + Some(Some("cancel")) if given.is_none() => return None, + Some(Some("cancel")) => false, + Some(_) => return Some(Err("`action` must be confirm or cancel".into())), + }; + if let Err(e) = craft::automation::protocol::Params(¶ms).only(None, keys) { + return Some(Err(e)); + } + // The other fields are set first, all or none, as the host sets and checks them. A set that + // gives no `action` and does not confirm goes to the host's setter whole, which refuses one + // with nothing to set. + let sets = ["field", "value", "fields"].iter().any(|k| params.get(k).is_some()) || (given.is_none() && !confirm); + if sets && let Some(Err(e)) = dialogs.with(|host| craft::automation::dialogs::dialog_method(host, ctx, "ui.dialog.set", ¶ms)) { + return Some(Err(e)); + } + if let Some(given) = given { + app.ui.find_action = Some(given); + } + if answer.as_ref().and_then(Value::as_str) == Some("cancel") { + dialogs.with(|host| host.cancel::(ctx)); + return Some(Ok(Value::Null)); + } + Some(if confirm { press(app, ctx) } else { Ok(listed(app)) }) +} + +/// Whether the dialog's `tab` (its `tab` field: `find`, `replace` or `goTo`) shows the button +/// `action` presses, enabled. Every tab shows Done. The Find tab shows Find Next, and the Replace tab +/// shows Find Next, Replace, Replace & Find and Replace All. The Go To tab shows no Find Next: its +/// first button is Go To, which stays disabled while the dialog has no go-to kinds. +fn shown_on(tab: &str, action: &str) -> bool { + match action { + "done" => true, + "find" => matches!(tab, "find" | "replace"), + _ => tab == "replace", + } +} + +/// Presses the button the `action` field names, as a click on it does, and leaves `action` at +/// `find`. Replace and Replace & Find find a match when Find Next has reached none with the Find +/// text and the switches as they are now. Done closes the dialog → the dialog as listed, or null +/// once closed; a refusal is the dialog's message and the error. A button the open tab does not +/// show ([`shown_on`]) and, with an empty Find text, every button but Done run nothing, as a click +/// cannot press them: the press is an error that leaves the document, the message and `action` as +/// they were. +fn press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Result { + let action = app.ui.find_action.clone().unwrap_or_else(|| "find".into()); + let dialogs = app.dialogs().ok_or("no window")?; + let (form, tab) = dialogs + .with(|host| host.get::().map(|d| (form(d), d.json_fields().and_then(|f| f["tab"].as_str().map(str::to_string))))) + .ok_or("no hosted dialog is open")?; + let tab = tab.unwrap_or_default(); + if !shown_on(&tab, &action) { + return Err(format!("the {tab} tab has no button for `action` {action}")); + } + if action == "done" { + app.ui.find_action = None; + dialogs.with(|host| host.cancel::(ctx)); + return Ok(Value::Null); + } + if form.query["find"].as_str().is_none_or(str::is_empty) { + return Err("the Find text is empty".into()); + } + app.ui.find_action = None; + let found = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some()); + let ran = match action.as_str() { + "replace" | "replaceFind" if found => replace(app, &form, action == "replaceFind"), + "replaceAll" => replace_all(app, &form), + _ => find(app, &form), + }; + let message = match &ran { + Ok(m) => Some(m.clone()), + Err(e) => Some(said(e)), + }; + report(app, &form, message); + ran.map(|_| listed(app)) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index e90efe3f8a..dd1dc255e7 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -97,6 +97,213 @@ fn selected(p: &Panel) -> Vec { p.app().session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() } +/// A control request answered at once → its result, or its error. +fn control(p: &Panel, method: &str, params: Value) -> Result { + let (req, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(r) = crate::control::handle(&mut p.app(), p.ctx(), &req) else { panic!("{method} answered later") }; + match r.get("error") { + Some(e) if !e.is_null() => Err(e.as_str().map_or_else(|| e.to_string(), str::to_string)), + _ => Ok(r["result"].clone()), + } +} + +/// The open Find and Replace dialog's `action`, as `ui.inspect` lists it. +fn listed_action(p: &Panel) -> Value { + let r = control(p, "ui.inspect", json!({})).unwrap(); + let open = r["dialogs"].as_array().cloned().unwrap_or_default(); + open.last().map(|d| d["fields"]["action"].clone()).unwrap_or(Value::Null) +} + +fn set_action(p: &Panel, action: &str) { + control(p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": action})).unwrap(); +} + +/// `ui.inspect` lists the dialog's `action`, `find` until a set changes it. `ui.dialog.confirm` +/// presses the button it names, as a click does, keeps the dialog open and puts `action` back to +/// find. Replace and Replace & Find find a match when Find Next reached none; done closes it. +#[test] +fn confirm_presses_the_button_the_action_names() { + let (app, ids) = app_with(&["cat cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + assert_eq!(listed_action(&p), json!("find")); + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + let before = undo_steps(&p); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(matched(&p), Some((ids[0], 0, 3)), "find runs without an action set"); + assert!(message(&p).starts_with("1 / 3"), "{}", message(&p)); + + set_action(&p, "replace"); + assert_eq!(listed_action(&p), json!("replace")); + let shown = control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(plain(&p, ids[0]), "dog cat cat", "replace changes the match found"); + assert_eq!((undo_steps(&p), listed_action(&p)), (before + 1, json!("find"))); + assert_eq!(shown["fields"]["action"], json!("find")); + + // Replace & Find with no match found finds one and changes nothing. + set_action(&p, "replaceFind"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!((plain(&p, ids[0]), matched(&p)), ("dog cat cat".to_string(), Some((ids[0], 4, 7)))); + set_action(&p, "replaceFind"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!((plain(&p, ids[0]), matched(&p)), ("dog dog cat".to_string(), Some((ids[0], 8, 11)))); + + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": "replaceAll", "action": "confirm"})).unwrap(); + assert_eq!((plain(&p, ids[0]), message(&p)), ("dog dog dog".to_string(), "Matches replaced: 1".to_string())); + assert_eq!(undo_steps(&p), before + 3); + + // A set and confirm in one request closes the dialog with done. + let done = json!([{"field": "action", "value": "done"}]); + let closed = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": done, "action": "confirm"})).unwrap(); + assert_eq!(closed, Value::Null); + assert!(!is_open(&p)); +} + +/// An `action` that names no button is refused when it is set, as are the fields set with it, and +/// `action` stays as it was. A set and confirm whose set is refused presses no button. +#[test] +fn an_action_that_names_no_button_is_refused() { + let (app, ids) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let refusal = "`action` must be find, replace, replaceFind, replaceAll or done"; + for v in [json!("jump"), json!(3), json!(null), json!("Replace")] { + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": v})); + assert_eq!(r, Err(refusal.to_string()), "{v}"); + } + let fields = json!([{"field": "replace", "value": "dog"}, {"field": "action", "value": "skip"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert_eq!(r, Err(refusal.to_string())); + assert_eq!((field(&p, "replace"), listed_action(&p)), (json!(""), json!("find"))); + // A field the dialog refuses leaves `action` as it was. + let fields = json!([{"field": "matchCase", "value": "yes"}, {"field": "action", "value": "replaceAll"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert!(r.is_err(), "{r:?}"); + assert_eq!(listed_action(&p), json!("find")); + // A request with a key the method does not take is refused. + assert!(control(&p, "ui.dialog.confirm", json!({"dialog": "top", "action": "replace"})).is_err()); + // A set the host refuses presses nothing, even with `action: "confirm"`. + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}, {"field": "action", "value": "replaceAll"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + for bad in [json!({"fields": {}}), json!({"value": 1}), json!({"field": "nope", "value": 1})] { + let mut request = bad.clone(); + request["dialog"] = json!("top"); + request["action"] = json!("confirm"); + assert!(control(&p, "ui.dialog.set", request).is_err(), "{bad}"); + assert_eq!((plain(&p, ids[0]), listed_action(&p)), ("cat".to_string(), json!("replaceAll")), "{bad}"); + } + assert!(is_open(&p)); +} + +/// With an empty Find text a confirm presses nothing, as the dialog's buttons run nothing: it is +/// refused, and the text, the undo steps, the message and `action` stay as they were. Done still +/// closes the dialog. +#[test] +fn a_confirm_with_no_find_text_presses_nothing() { + let (app, ids) = app_with(&["cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "replace", "value": "dog"})).unwrap(); + assert_eq!(field(&p, "find"), json!("")); + let (before, said) = (undo_steps(&p), message(&p)); + for action in ["find", "replace", "replaceFind", "replaceAll"] { + set_action(&p, action); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err("the Find text is empty".to_string()), "{action}"); + assert_eq!((plain(&p, ids[0]), undo_steps(&p), message(&p)), ("cat cat".to_string(), before, said.clone()), "{action}"); + assert_eq!(listed_action(&p), json!(action)); + } + set_action(&p, "done"); + assert_eq!(control(&p, "ui.dialog.confirm", json!({})), Ok(Value::Null)); + assert!(!is_open(&p)); +} + +/// A confirm presses only a button the open tab shows enabled: on the Find tab the Replace buttons +/// and on the Go To tab Find Next are refused, naming the tab, and the text, the undo steps, the +/// message and `action` stay as they were. Find Next runs on the Find tab, and Done closes the +/// dialog from the Go To tab. +#[test] +fn a_confirm_presses_only_a_button_the_tab_shows() { + let (app, ids) = app_with(&["cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}, {"field": "tab", "value": "find"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + let (before, said) = (undo_steps(&p), message(&p)); + for action in ["replace", "replaceFind", "replaceAll"] { + set_action(&p, action); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err(format!("the find tab has no button for `action` {action}")), "{action}"); + assert_eq!((plain(&p, ids[0]), undo_steps(&p), message(&p)), ("cat cat".to_string(), before, said.clone()), "{action}"); + assert_eq!(listed_action(&p), json!(action)); + } + set_action(&p, "find"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(matched(&p), Some((ids[0], 0, 3)), "Find Next is on the Find tab"); + + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "tab", "value": "goTo"})).unwrap(); + let (at, said) = (from(&p), message(&p)); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err("the goTo tab has no button for `action` find".to_string())); + assert_eq!((from(&p), message(&p), listed_action(&p)), (at, said, json!("find"))); + set_action(&p, "done"); + assert_eq!(control(&p, "ui.dialog.confirm", json!({})), Ok(Value::Null)); + assert!(!is_open(&p)); +} + +/// `fields` given with `field` or `value` is refused, as the host refuses it, even when the list +/// holds only `action`; nothing is set. +#[test] +fn fields_with_field_or_value_is_refused() { + let (app, _) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let refusal = Err("`fields` takes the place of `field` and `value`".to_string()); + let only_action = json!([{"field": "action", "value": "replace"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "find", "value": "cat", "fields": only_action})); + assert_eq!(r, refusal); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "value": "cat", "fields": only_action})); + assert_eq!(r, refusal); + assert_eq!((field(&p, "find"), listed_action(&p)), (json!(""), json!("find"))); +} + +/// A set of other fields answers with `action` listed. A click on a button, like a confirm, puts +/// `action` back to find, and so does opening the dialog again. A `fields` list of more than 256 +/// items is refused, `action` counted with the rest. +#[test] +fn action_is_listed_and_goes_back_to_find() { + let (app, _) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + set_action(&p, "replace"); + let shown = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "find", "value": "cat"})).unwrap(); + assert_eq!((shown["fields"]["find"].clone(), shown["fields"]["action"].clone()), (json!("cat"), json!("replace"))); + assert!(control(&p, "ui.dialog.set", json!({"dialog": "top"})).is_err(), "a set with nothing to set"); + + let mut fields = vec![json!({"field": "find", "value": "cat"}); 256]; + fields.push(json!({"field": "action", "value": "replaceAll"})); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert_eq!(r, Err("`fields` holds 257 items; at most 256".to_string())); + assert_eq!(listed_action(&p), json!("replace")); + + p.click("Find Next"); + assert_eq!(listed_action(&p), json!("find"), "a click"); + + set_action(&p, "replace"); + control(&p, "ui.dialog.cancel", json!({"dialog": "top"})).unwrap(); + assert!(!is_open(&p)); + choose(&p); + p.frame(); + assert_eq!(listed_action(&p), json!("find"), "opening again"); +} + #[test] fn a_cached_match_cannot_replace_text_restored_by_revert() { let (mut app, ids) = app_with(&["Needle Needle"]); diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 7de36ba00e..4d4d38e372 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -134,7 +134,8 @@ pub(crate) fn fidelity_field(ui: &mut Ui, id: &str, v: f64, tool: &str) -> EditE } /// The Fidelity row: a logarithmic slider from the tool's lowest Fidelity to [`FIDELITY_MAX`] with the field at its -/// end, and Accurate and Smooth under the slider's ends. +/// end, and Accurate and Smooth under the slider's ends. The slider's keys and wheel step by [`fidelity_step`], as the +/// field's do. fn fidelity_row(ui: &mut Ui, fields: &mut DialogFields, tool: &str) -> Response { let min = vectorcraft_tools::draw2::min_fidelity(tool); let v = fields.number("fidelity").unwrap_or(1.5); @@ -142,6 +143,7 @@ fn fidelity_row(ui: &mut Ui, fields: &mut DialogFields, tool: &str) -> Response let shown = Row::new().show(ui, |ui, _| { let slid = Slider::new(Bind::given(v), min..=FIDELITY_MAX) .scale(SliderScale::Log) + .stepper(|v, dir, steps| fidelity_step(v, f64::from(dir) * steps)) .marks_labelled([(min, tl!("Accurate")), (FIDELITY_MAX, tl!("Smooth"))]) .label(tl!("Fidelity")) .id_salt("fidelity-slider") diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 790d5742e1..2542cfa6af 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -422,6 +422,43 @@ fn draft_fidelity(panel: &crate::tests::panel_harness::Panel) -> Option { panel.app().dialogs().and_then(|d| d.with(|host| host.get::().and_then(|dialog| dialog.fields().number("fidelity")))) } +/// The Fidelity slider of every freehand tool steps through the field's values: an arrow key takes the next hundredth +/// at the Accurate end, Shift with an arrow multiplies by ten, and a wheel notch takes one step back. +#[test] +fn the_fidelity_slider_keys_and_wheel_step_finely_at_the_low_end() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers, vec2}; + for tool in ["pencil", "paintbrush", "smooth", "blobBrush"] { + let min = vectorcraft_tools::draw2::min_fidelity(tool); + let mut app = app(); + app.run("tool.setOption", json!({"tool": tool, "values": {"fidelity": min}})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1000.0, 1200.0)); + crate::toolbar::open_options(&mut panel.app(), tool).unwrap(); + panel.frame(); + assert_eq!(draft_fidelity(&panel), Some(min), "{tool}"); + // The field comes after the slider, so Shift+Tab from the field gives the slider the focus. + panel.click_role("Fidelity", Role::SPIN_BUTTON); + panel.key(Key::Tab, Modifiers::SHIFT); + let at = |hundredths: f64| fidelity_round(min + hundredths / 100.0); + panel.key(Key::ArrowRight, Modifiers::NONE); + assert_eq!(draft_fidelity(&panel), Some(at(1.0)), "{tool}: an arrow takes the next hundredth"); + panel.key(Key::ArrowRight, Modifiers::NONE); + assert_eq!(draft_fidelity(&panel), Some(at(2.0)), "{tool}"); + panel.key(Key::ArrowRight, Modifiers::SHIFT); + assert_eq!(draft_fidelity(&panel), Some(fidelity_round(at(2.0) * 10.0)), "{tool}: Shift multiplies by ten"); + panel.key(Key::ArrowLeft, Modifiers::NONE); + assert_eq!(draft_fidelity(&panel), Some(fidelity_step(fidelity_round(at(2.0) * 10.0), -1.0)), "{tool}"); + let before = draft_fidelity(&panel).unwrap(); + let thumb = panel.rect_role("Fidelity", Role::SLIDER).center(); + panel.frame_with(vec![egui::Event::PointerMoved(thumb)]); + panel.frame_with(vec![craft::ui::testing::pointer::wheel_lines(-1.0)]); + panel.frame(); + assert_eq!(draft_fidelity(&panel), Some(fidelity_step(before, -1.0)), "{tool}: a wheel notch takes one step"); + assert_eq!(panel.app().session.tool_options_of(tool)["fidelity"].as_f64(), Some(min), "{tool}: the tool changes only on OK"); + } +} + /// The Smooth tool's Fidelity slider and field: a drag or a typed value that Escape cancels leaves the dialog's Fidelity /// and the tool's as they were; a finished drag or a typed value left with Tab sets the dialog's, and OK sets the tool's. #[test] diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index e9e05185b5..2ed369d2da 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -105,6 +105,22 @@ impl TargetKey { } } +/// The swatch last picked in the Swatches view and the stop or point it is picked for. +#[derive(Clone)] +struct PickedSwatch { + target: TargetKey, + name: String, +} + +impl PickedSwatch { + /// The active document's swatch `name`, picked for `target`. + fn of(app: &VectorcraftApp, target: &Target, name: &str) -> Option { + let key = TargetKey::of(app, target)?; + app.session.active()?.doc.swatch(name)?; + Some(Self { target: key, name: name.to_owned() }) + } +} + /// A Color mode command from the popover's menu that has not been seen to finish. struct OwnMode { /// The document's history step when it ran. @@ -262,11 +278,42 @@ fn recolor(mut stops: Vec, i: usize, color: Color, link: Option<(S stops } -/// Solid colours of the document's swatches (groups included), with their names. -fn swatch_colors(app: &VectorcraftApp) -> Vec<(String, Color)> { - let Some(st) = app.session.active() else { return vec![] }; - let d = &st.doc; - d.swatches.iter().chain(d.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter_map(|s| Some((s.name.clone(), s.paint.color()?))).collect() +/// Solid colors of the document's swatches (groups included), with their names, and the entry the target's color +/// comes from: a linked color's tint swatch for that tint, or its global swatch at 100%; an unlinked color's process +/// swatch of that very color. Where several entries qualify, `picked`, the swatch last picked in the popover for this +/// target, is the one. +fn swatch_colors(app: &VectorcraftApp, target: &Target, picked: Option<&PickedSwatch>) -> (Vec<(String, Color)>, Option) { + let Some(st) = app.session.active() else { return (vec![], None) }; + let picked = picked.filter(|p| p.target.matches(app, target)); + let (link, color) = match target { + Target::Stop(paint, i) => { + let stop = &paint.gradient.stops[*i]; + (stop.swatch.as_deref().map(|base| (base, stop.tint)), stop.color) + } + Target::Point(_, point, _) => (None, point.color), + }; + let mut colors = Vec::new(); + let mut selected = None; + for swatch in st.doc.swatches_iter() { + let is_picked = picked.is_some_and(|p| p.name == swatch.name); + let Some(own) = swatch.paint.color() else { continue }; + // Picking this swatch would give the target the color and link it has now. + let source = match (link, swatch.tint_of()) { + (Some((base, tint)), Some((of, own_tint))) => of == base && same_tint(tint, own_tint), + (Some((base, tint)), None) => swatch.global && swatch.name == base && same_tint(tint, 1.0), + (None, _) => !swatch.global && matches!(swatch.paint, Paint::Solid { color: c, swatch: None, .. } if c == color), + }; + if source && (selected.is_none() || is_picked) { + selected = Some(colors.len()); + } + colors.push((swatch.name.clone(), own)); + } + (colors, selected) +} + +/// Whether two tints are the same: stop commands carry a tint as a floating-point percentage. +fn same_tint(first: f32, second: f32) -> bool { + (first - second).abs() <= 2.0 * f32::EPSILON } /// The popover's two views. @@ -317,6 +364,10 @@ struct Feed { /// Percent: the stop's location or the point's spread. amount: f64, swatches: Vec<(String, Color)>, + /// The entry of `swatches` the target's color comes from. + selected_swatch: Option, + /// Picking the displayed swatch changes at least one edited paint. + displayed_swatch_changes_paints: bool, /// `swatches` as the palette draws them, in the same order. tiles: Vec<(Label, Srgba)>, shown: ColorPanelShown, @@ -327,6 +378,8 @@ struct Feed { struct Filed { fields: PopoverFields, swatch: Option<(String, Color)>, + /// Whether the pending swatch pick applies paint. + swatch_changes_paints: bool, eyedropper: bool, panels: Vec, /// Only an actual Shift-cycle changes this; an unchanged local snapshot must not overwrite a menu command. @@ -346,6 +399,8 @@ pub(crate) struct GradientStopPopover { at: Pos2, panel: ColorPanelState, feed: Option, + /// The swatch last picked in the Swatches view and the stop or point it was picked for. + picked_swatch: Option, /// The fields set from outside, applied at confirm. set: PopoverFields, filed: Filed, @@ -363,6 +418,7 @@ impl GradientStopPopover { at: Pos2::ZERO, panel: ColorPanelState::default(), feed: None, + picked_swatch: None, set: PopoverFields::default(), filed: Filed::default(), own_mode: None, @@ -522,19 +578,27 @@ fn swatches(ui: &mut Ui, feed: &Feed, filed: &mut Filed) { Notice::new(Tone::Info, tl!("The document has no colour swatches.").to_owned()).show(ui); return; } - let shown = SwatchPalette::new("Swatches", Bind::given(feed.current), &feed.tiles).show(ui); - let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()) else { return }; - // The first swatch of that colour: the palette reports colours, not cells. - let at = feed.tiles.iter().position(|(_, c)| c.to_rgba() == picked.to_rgba()); - filed.swatch = at.and_then(|i| feed.swatches.get(i)).cloned(); + // Only the entry the target's color comes from is selected, and none when no entry is: a swatch that only draws + // the same color, such as a spot ink an unlinked stop has the color of, is not. + let shown = + SwatchPalette::new("Swatches", Bind::given(feed.current), &feed.tiles).selected_swatch(feed.selected_swatch).select_by_color(false).show(ui); + // Every click remembers the pick. The displayed swatch applies only when an edited paint differs at this stop or point. + // Other swatches apply even when they have the same color. + if let Some(i) = shown.picked_swatch + && let Some(swatch) = feed.swatches.get(i) + { + filed.swatch = Some(swatch.clone()); + filed.swatch_changes_paints = feed.displayed_swatch_changes_paints || Some(i) != feed.selected_swatch; + } } -/// A percent field named `label` over `value`; the number the user entered in this pass. +/// A percent field named `label` over `value`; the number the user entered in this pass, or the number a canceled +/// typing gives back. fn percent_field(ui: &mut Ui, label: String, value: f64) -> Option { let field = Field::new(label.clone()).show(ui, |ui, _| { NumberField::new(label.clone(), Bind::given(Some(value))).unit_kind(UnitKind::Percent).range(0.0..=100.0).step(1.0).show(ui) }); - field.inner?.value().copied().flatten() + field.inner?.edit.events.landed().copied().flatten() } /// The popover's size before it has been drawn, for placing it. @@ -580,10 +644,11 @@ fn place(app: &VectorcraftApp, ctx: &egui::Context, anchor: Anchor) -> Pos2 { } } -/// `target`'s values, the document's swatches and what the Color panel shows, for the popover's body. -fn feed(app: &VectorcraftApp, target: &Target) -> Feed { +/// `target`'s values, the document's swatches with the one `picked` for it selected, and what the Color panel shows, +/// for the popover's body. +fn feed(app: &VectorcraftApp, target: &Target, picked: Option<&PickedSwatch>) -> Feed { let shown = crate::panels::color::shown(app, &crate::panels::color::target_now(app)); - let swatches = swatch_colors(app); + let (swatches, selected_swatch) = swatch_colors(app, target, picked); Feed { point: matches!(target, Target::Point(..)), color: target.color(), @@ -592,6 +657,19 @@ fn feed(app: &VectorcraftApp, target: &Target) -> Feed { amount: f64::from(target.amount()) * 100.0, tiles: swatches.iter().map(|(name, c)| (Label::from(name.clone()), Srgba::from(c32(c)))).collect(), swatches, + selected_swatch, + displayed_swatch_changes_paints: app.session.gradient_edit_paints(!app.session.fill_active).map_or(true, |paints| { + !paints.all_paints_match(|paint| { + let Paint::Gradient(paint) = paint else { return false }; + match target { + Target::Stop(shown, i) => paint.gradient.stops.get(*i).is_some_and(|stop| { + let shown = &shown.gradient.stops[*i]; + stop.swatch == shown.swatch && stop.tint == shown.tint && stop.color == shown.color + }), + Target::Point(_, shown, i) => shown_points(paint).points.get(*i).is_some_and(|point| point.color == shown.color), + } + }) + }), shown, } } @@ -599,8 +677,12 @@ fn feed(app: &VectorcraftApp, target: &Target) -> Feed { /// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`. fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) { let Some(dialogs) = app.dialogs() else { return }; - let Some(anchor) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.anchor)) else { return }; - let feed = feed(app, target); + let Some((anchor, picked)) = + dialogs.with(|host| host.get_by_id::(id).map(|popover| (popover.anchor, popover.picked_swatch.clone()))) + else { + return; + }; + let feed = feed(app, target, picked.as_ref()); let at = place(app, ctx, anchor); dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::(id) { @@ -612,6 +694,23 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar }); } +/// After the swatch `from` of the document `uid` was renamed `to`, the open popover's remembered pick takes the new name +/// when it is that swatch, picked for the selected stop or point. +pub(crate) fn follow_swatch_rename(app: &VectorcraftApp, uid: u64, from: &str, to: &str) { + let Some(target) = selected(app) else { return }; + let Some(dialogs) = app.dialogs() else { return }; + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(dialog_id(KIND)) + && let Some(picked) = &mut popover.picked_swatch + && picked.target.document.0 == uid + && picked.target.matches(app, &target) + && picked.name == from + { + picked.name = to.to_owned(); + } + }); +} + /// Opens the popover on the selected stop (a freeform gradient's selected point) of the active gradient, the stop /// at `index` when it is not the selected one. Nothing opens without a window or a stop to edit. pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { @@ -639,6 +738,9 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { /// Once per frame: applies what the user did in the popover and its confirmed answer, closes it when its stop or /// point goes away, and pushes the target's values for the next frame. One line of `dialogs::host::pump`. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + for (uid, from, to) in app.session.take_swatch_renames() { + follow_swatch_rename(app, uid, &from, &to); + } let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); match dialogs.with(|host| host.take_by_id::(id)) { @@ -696,13 +798,31 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { && !owner.key.point && let Some(index) = app.session.selected_stop() { - // The stop can cross its neighbor when its location changes. + // The stop can cross its neighbor when its location changes. A swatch picked for it moves with it. + let moved = owner.key.clone(); owner.key.index = index; + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(id) + && let Some(picked) = &mut popover.picked_swatch + && picked.target == moved + { + picked.target.index = index; + } + }); } if let Some((name, color)) = filed.swatch && let Some(target) = selected(app) { - pick_swatch(app, &target, &name, color); + if filed.swatch_changes_paints { + pick_swatch(app, &target, &name, color); + } + // Swatches of one color draw alike: the Swatches view shows the one picked, not the first of them. + let picked = selected(app).and_then(|target| PickedSwatch::of(app, &target, &name)); + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(id) { + popover.picked_swatch = picked; + } + }); } for output in &filed.panels { // PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision). @@ -865,6 +985,370 @@ mod tests { } } + /// The popover over `app`, drawn and pumped each frame, open on stop 1 at its Swatches view. + fn swatches_view(app: VectorcraftApp) -> crate::tests::panel_harness::Panel { + let mut panel = crate::tests::panel_harness::Panel::new(app, |app, ui| { + app.dialogs().unwrap().with(|host| host.run(ui)); + host::pump(app, ui.ctx()); + }); + // The popover opens on the fixture's window, which the panel made the app's. + open_popover(&mut panel.app()); + set(&panel.app(), "tab", json!("swatches")).unwrap(); + panel.frame(); + panel + } + + #[test] + fn picking_one_of_two_spot_colors_of_one_color_links_the_stop_to_that_one() { + let mut app = app(); + for name in ["First green ink", "Second green ink"] { + app.run("swatch.new", json!({"name": name, "color": "#00ff00", "spot": true})).unwrap(); + } + let target = selected(&app).unwrap(); + pick_swatch(&mut app, &target, "First green ink", Color::from_hex("#00ff00").unwrap()); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First green ink")); + panel.click("Second green ink"); + assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Second green ink")); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second green ink"), "the view shows the swatch picked"); + panel.app().run("swatch.edit", json!({"name": "Second green ink", "color": "#123456"})).unwrap(); + assert_eq!(stops(&panel.app())[1].color.to_hex(), "#123456", "the stop follows the swatch it was given"); + } + + /// The swatch the open popover's Swatches view shows as the target's, after two fresh frames: the first one's pump + /// feeds the view an edit made outside it, and the second draws that feed. The view draws that swatch's cell + /// selected and no other, and no cell selected when it shows none. + fn shown_swatch(panel: &mut crate::tests::panel_harness::Panel) -> Option { + panel.frame(); + panel.frame(); + let (names, shown) = panel.app().dialogs().unwrap().with(|host| { + let feed = host.get_by_id::(dialog_id(KIND)).and_then(|popover| popover.feed.as_ref()).expect("the view's feed"); + let shown = feed.selected_swatch.and_then(|i| feed.swatches.get(i)).map(|(name, _)| name.clone()); + (feed.swatches.iter().map(|(name, _)| name.clone()).collect::>(), shown) + }); + let drawn: Vec = + names.into_iter().filter(|name| panel.selected_role(name, craft::ui::contract::Role::LIST_BOX_OPTION) == Some(true)).collect(); + assert_eq!(drawn, shown.iter().cloned().collect::>(), "the cells the view draws selected"); + shown + } + + #[test] + fn the_swatches_view_shows_the_process_swatch_picked_among_two_of_one_color() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "the stop's green is no swatch's"); + panel.click("Second teal"); + assert_eq!(stops(&panel.app())[1].color.to_hex(), "#008080"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click("First teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal")); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "the same color again is no edit"); + } + + #[test] + fn the_swatches_view_remembers_a_pick_of_the_fallback_swatch_after_reordering() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + crate::panels::gradient::recolor_selected(&mut app, Color::from_hex("#008080").unwrap(), &json!({})); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the first matching process swatch is the fallback"); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click("First teal"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "the displayed swatch changes no paint"); + let first = panel.app().session.active().unwrap().doc.swatches_iter().position(|s| s.name == "First teal").unwrap(); + panel.app().run("swatch.move", json!({"name": "Second teal", "to": first})).unwrap(); + assert_eq!( + shown_swatch(&mut panel).as_deref(), + Some("First teal"), + "the explicit pick stays selected after the other swatch moves before it" + ); + } + + #[test] + fn the_swatches_view_keeps_the_picked_process_swatch_through_a_rename() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().run("swatch.edit", json!({"name": "Second teal", "newName": "Renamed teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal"), "the renamed swatch stays the one shown"); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "Undo of the rename falls back to the first qualifying swatch"); + panel.click("Second teal"); + panel.app().run("swatch.edit", json!({"name": "First teal", "newName": "Other teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "a rename of the other swatch moves nothing"); + let first = panel.app().session.active().unwrap().doc.swatches_iter().position(|s| s.name == "Other teal").unwrap(); + panel.app().run("swatch.move", json!({"name": "Second teal", "to": first})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "the picked swatch moved before the other stays the one shown"); + } + + #[test] + fn the_swatches_view_keeps_the_picked_swatch_when_the_popover_moves_its_stop_past_a_neighbor() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#008080"}, {"offset": 0.7, "color": "#000000"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [100, 150], "end": [200, 150]}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).expect("the popover").filed.fields.location = Some(90.0); + }); + panel.frame(); + assert_eq!(panel.app().session.selected_stop(), Some(2), "the stop crossed its neighbor"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "the pick moved with its stop"); + } + + #[test] + fn the_swatches_view_keeps_the_picked_swatch_through_a_rename_in_a_batch() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + panel + .app() + .run("command.batch", json!({"commands": [{"command": "swatch.edit", "params": {"name": "Second teal", "newName": "Renamed teal"}}]})) + .unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal")); + } + + #[test] + fn the_swatches_view_keeps_the_pick_when_a_batch_renames_a_swatch_in_another_document() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel + .app() + .run( + "command.batch", + json!({"commands": [ + {"command": "document.activate", "params": {"index": 1}}, + {"command": "swatch.edit", "params": {"name": "Second teal", "newName": "Renamed teal"}}, + {"command": "document.activate", "params": {"index": 0}} + ]}), + ) + .unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + assert!(panel.app().session.documents()[1].doc.swatch("Renamed teal").is_some()); + } + + #[test] + fn the_swatches_view_follows_renames_that_bypass_app_run() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + panel.app().session.execute("swatch.edit", &json!({"name": "Second teal", "newName": "Renamed teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Renamed teal")); + } + + #[test] + fn the_swatches_view_does_not_give_a_deleted_picked_swatch_to_its_neighbor() { + let mut app = app(); + for name in ["First teal", "Second teal", "Third teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().run("swatch.delete", json!({"name": "Second teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the swatch after the deleted one is not taken for it"); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "Undo of the deletion shows the picked swatch again"); + } + + #[test] + fn the_swatches_view_does_not_give_a_deleted_picked_swatch_to_a_replacement() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel.app().run("swatch.delete", json!({"name": "Second teal"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal")); + panel.app().run("swatch.new", json!({"name": "New teal", "color": "#008080"})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "a new swatch in the deleted one's place is not taken for it"); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal")); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal"), "Undo of the deletion shows the picked swatch again"); + } + + #[test] + fn the_swatches_view_does_not_follow_a_replacement_in_a_batch() { + let mut app = app(); + for name in ["First teal", "Second teal"] { + app.run("swatch.new", json!({"name": name, "color": "#008080"})).unwrap(); + } + let mut panel = swatches_view(app); + panel.click("Second teal"); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second teal")); + panel + .app() + .run( + "command.batch", + json!({"commands": [ + {"command": "swatch.delete", "params": {"name": "Second teal"}}, + {"command": "swatch.new", "params": {"name": "New teal", "color": "#008080"}} + ]}), + ) + .unwrap(); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("First teal"), "the replacement does not inherit the pick"); + } + + #[test] + fn the_swatches_view_shows_the_tint_swatch_picked_among_two_of_one_tint() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + let tints: Vec = + (0..2).map(|_| app.run("swatch.new", json!({"swatch": "Green ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_owned()).collect(); + assert_ne!(tints[0], tints[1]); + let mut panel = swatches_view(app); + panel.click(&tints[1]); + let stop = stops(&panel.app())[1].clone(); + assert_eq!((stop.swatch.as_deref(), (stop.tint * 100.0).round()), (Some("Green ink"), 40.0)); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some(tints[1].as_str())); + panel.click(&tints[0]); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some(tints[0].as_str())); + panel.click("Green ink"); + assert_eq!(stops(&panel.app())[1].tint, 1.0); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink")); + } + + #[test] + fn a_spot_color_of_the_stop_color_links_the_stop_and_its_base_resets_a_tint() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "the stop's green is not linked to the ink"); + panel.click("Green ink"); + assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Green ink")); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink")); + + // Two spot inks of the stop's green: the unlinked stop shows neither, and a pick links the stop to that one. + let mut app = self::app(); + for name in ["First green ink", "Second green ink"] { + app.run("swatch.new", json!({"name": name, "color": "#00ff00", "spot": true})).unwrap(); + } + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "the stop's green is linked to neither ink"); + panel.click("Second green ink"); + assert_eq!(stops(&panel.app())[1].swatch.as_deref(), Some("Second green ink")); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Second green ink")); + + let mut app = self::app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + crate::panels::gradient::recolor_selected(&mut app, Color::from_hex("#00ff00").unwrap(), &json!({"swatch": "Green ink", "tint": 40})); + assert_eq!((stops(&app)[1].tint * 100.0).round(), 40.0); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel), None, "a 40% tint is not the ink at 100%"); + panel.click("Green ink"); + let stop = stops(&panel.app())[1].clone(); + assert_eq!((stop.swatch.as_deref(), stop.tint), (Some("Green ink"), 1.0)); + } + + #[test] + fn picking_the_displayed_swatch_recolors_every_selected_objects_stop() { + let mut app = app(); + let first = app.session.active().unwrap().selection.objects[0]; + let mut second_stops = stops(&app); + second_stops[1].set_color(Color::from_hex("#0000ff").unwrap(), None); + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"gradient": {"stops": vectorcraft_tools::params::stops_json(&second_stops)}})).unwrap(); + app.run("swatch.new", json!({"name": "Stop green", "color": "#00ff00"})).unwrap(); + app.run("select.set", json!({"ids": [first.0, second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Stop green")); + panel.click("Stop green"); + let app = panel.app(); + let st = app.session.active().unwrap(); + for id in &st.selection.objects { + let Paint::Gradient(paint) = st.doc.node(*id).unwrap().appearance.paint_at(None, true).unwrap() else { + panic!("expected a gradient"); + }; + assert_eq!(paint.gradient.stops[1].color.to_hex(), "#00ff00"); + } + assert_eq!(st.selection.objects.len(), 2); + } + + #[test] + fn picking_the_displayed_swatch_keeps_every_selected_objects_gradient_swatch_link() { + let mut app = app(); + let first = app.session.active().unwrap().selection.objects[0]; + app.run("swatch.new", json!({"name": "Stop green", "color": stops(&app)[1].color.to_hex()})).unwrap(); + let mut params = crate::panels::swatch_paint_params(&active_paint(&app)); + params["name"] = json!("Linked gradient"); + app.run("swatch.new", params).unwrap(); + app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap(); + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap(); + app.run("select.set", json!({"ids": [first.0, second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Stop green")); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.click("Stop green"); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.selection.objects.len(), 2); + for id in &st.selection.objects { + let Paint::Gradient(paint) = st.doc.node(*id).unwrap().appearance.paint_at(None, true).unwrap() else { + panic!("expected a gradient"); + }; + assert_eq!(paint.swatch.as_deref(), Some("Linked gradient")); + } + assert_eq!(st.history.undo.len(), undo, "the displayed swatch changes no paint"); + } + + #[test] + fn picking_the_stop_swatch_again_keeps_the_gradient_swatch_link() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Green ink", "color": "#00ff00", "spot": true})).unwrap(); + let green = Color::from_hex("#00ff00").unwrap(); + let target = selected(&app).unwrap(); + pick_swatch(&mut app, &target, "Green ink", green); + let mut params = crate::panels::swatch_paint_params(&active_paint(&app)); + params["name"] = json!("Linked gradient"); + app.run("swatch.new", params).unwrap(); + app.run("paint.setFill", json!({"swatch": "Linked gradient"})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = swatches_view(app); + assert_eq!(shown_swatch(&mut panel).as_deref(), Some("Green ink")); + panel.click("Green ink"); + let Paint::Gradient(paint) = active_paint(&panel.app()) else { panic!("expected a gradient") }; + assert_eq!(paint.swatch.as_deref(), Some("Linked gradient")); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + #[test] fn confirm_applies_colour_opacity_and_location() { let mut app = app(); @@ -886,6 +1370,33 @@ mod tests { assert!(set(&app, "color", json!("red")).is_err()); } + /// Leaving Opacity or Location on text that is not a number cancels the typing, and OK then leaves the stop as it + /// was. + #[test] + fn a_canceled_opacity_or_location_leaves_the_stop_as_it_was() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + for name in ["Opacity", "Location"] { + let mut panel = Panel::new(app(), crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open_popover(&mut panel.app()); + panel.frame(); + let before = stops(&panel.app()); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("40"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "leaving {name} keeps the popover open"); + confirm(&mut panel.app()); + assert_eq!(stops(&panel.app()), before, "OK after leaving {name} on text that is not a number leaves the stop as it was"); + } + } + #[test] fn the_popover_discards_a_pending_edit_after_selecting_other_art() { let mut app = app(); @@ -1231,7 +1742,7 @@ mod tests { let mut fx = Fixture::new(move |ui| { let mut app = app.borrow_mut(); let Some(target) = selected(&app) else { return }; - let feed = feed(&app, &target); + let feed = feed(&app, &target, None); let mut filed = Filed::default(); body(ui, &feed, &mut tab, &mut panel, &mut filed); for output in &filed.panels { diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 1eb37190e5..9cd2da74a4 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use std::sync::Arc; -use craft::behavior::{EditEvent, NumberCodec}; +use craft::behavior::{CancelReason, EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; use craft::table::ui::{ CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions, @@ -140,6 +140,8 @@ struct Lines { columns: LineIndex, /// The own width of the column whose edge a drag holds, as it was when the drag began. resize_from: Option>, + /// Cell Style's Column Width and the columns' own widths, as they were when typing a Column Width began. + width_from: Option<(u64, Vec>)>, } impl Lines { @@ -149,6 +151,7 @@ impl Lines { rows: LineIndex::uniform(ROW_H, 0), columns: LineIndex::uniform(digits_px(DEFAULT_WIDTH), MAX_COLS as u32), resize_from: None, + width_from: None, } } @@ -397,7 +400,7 @@ fn graph_grid(app: &mut VectorcraftApp, graph: Option) -> Result bool { file_asks::can(app, craft::host::PickKind::Open) - && (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) + && (app.files_host().files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) } /// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. @@ -633,16 +636,31 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool { let field = whole(&units, tl!("Number of Decimals"), values.decimals.unwrap_or(DEFAULT_DECIMALS), MAX_DECIMALS) .enabled(values.decimals.is_some()) .show(ui); - if let Some(n) = digits(field.edit.value().copied().flatten(), MAX_DECIMALS) { + if let Some(n) = digits(field.edit.events.landed().copied().flatten(), MAX_DECIMALS) { values.decimals = Some(n); } Text::new(tl!("Column Width:")).show(ui); let field = whole(&units, tl!("Column Width"), width(values), MAX_WIDTH).show(ui); - // A value entered with Enter sets every column, also when it is the width shown. Leaving the - // field without a new value keeps the columns' own widths. - let typed = digits(field.edit.value().copied().flatten(), MAX_WIDTH); - if typed.is_some() || field.edit.submitted { - set_width(values, typed.unwrap_or_else(|| width(values))); + let events = &field.edit.events; + if events.began() { + lines.width_from = Some((values.width, values.widths.clone())); + } + if let Some(reason) = events.cancel_reason() { + // A user rollback restores Cell Style's width and the columns' own widths; other cancels keep the host's values. + if let Some((shown, own)) = lines.width_from.take().filter(|_| matches!(reason, CancelReason::Escape | CancelReason::Blur)) { + values.width = shown; + values.widths = own; + } + } else { + // A value entered with Enter sets every column, also when it is the width shown. Leaving the + // field without a new value keeps the columns' own widths. + let typed = digits(events.value().copied().flatten(), MAX_WIDTH); + if typed.is_some() || field.edit.submitted { + set_width(values, typed.unwrap_or_else(|| width(values))); + } + if events.ended().is_some() { + lines.width_from = None; + } } }); lines.sync(extent(values, active(state)), values); @@ -830,6 +848,9 @@ impl StackDialog for GraphDataDialog { load(&self.sheet, &self.state, &mut self.entry); } } + if matches!(field, "width" | "widths") { + self.lines.width_from = None; + } Ok(()) } } @@ -1127,8 +1148,8 @@ mod tests { app.services.read = None; app.services.read_head = None; let files = Arc::new(ScriptedFiles::held().in_browser()); + // The web shell installs its browser file service in the window's context only. app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); - app.host = Arc::new(app.host.with_files(files.clone())); open(&mut app).unwrap(); let mut h = harness(app); h.run_steps(4); @@ -1399,4 +1420,82 @@ mod tests { edit(&app, |d| set_col_digits(&mut d.sheet, 1, 4)); assert_eq!(read(&app, |d| (col_digits(&d.sheet, 1), col_digits(&d.sheet, 3))), (4, 7), "a drag after it gives that column its own width"); } + + /// Leaving Number of Decimals or Column Width on text that is not a number cancels the typing: the decimals go back + /// to what they were, and so do Column Width and the widths columns were given of their own. + #[test] + fn a_canceled_cell_style_number_restores_the_decimals_and_the_widths() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + set_field(&panel.app(), "decimals", json!(2)).unwrap(); + edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4)); + panel.frame(); + let style = |panel: &Panel| read(&panel.app(), |d| (d.sheet.decimals, d.sheet.width, d.sheet.widths.clone())); + for name in ["Number of Decimals", "Column Width"] { + let before = style(&panel); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + assert_ne!(style(&panel), before, "typing into {name} proposes a value"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert_eq!(style(&panel), before, "leaving {name} on text that is not a number restores Cell Style"); + } + } + + /// An outside Column Width replaces a running edit and keeps the columns at the assigned width. + #[test] + fn an_outside_column_width_survives_a_running_edit() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4)); + panel.frame(); + panel.click_role("Column Width", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + set_field(&panel.app(), "width", json!(13)).unwrap(); + let assigned = read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone())); + panel.frame(); + assert_eq!(read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone())), assigned, "the host's column widths survive cancellation"); + } + + /// Outside per-column widths survive invalid Column Width text. + #[test] + fn an_outside_per_column_width_survives_a_running_edit() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + panel.click_role("Column Width", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + set_field(&panel.app(), "widths", json!([null, 13, null])).unwrap(); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert_eq!(read(&panel.app(), |d| d.sheet.widths.clone()), vec![None, Some(13), None], "invalid Column Width text preserves assigned widths"); + } } diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index ebc54223f6..654aebad35 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -2,7 +2,7 @@ //! or CMYK screens, Invert, Clip to Art and Keep Original, previewed live on the canvas; OK keeps //! the preview as one undo step (`object.vectorHalftone`). //! -//! Fields: `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal` (the +//! Fields: `style`, `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal` (the //! command's parameters). The live effect's dialog shows the same rows but Keep Original //! ([`screen_params`]). @@ -33,7 +33,20 @@ pub(crate) struct Open { /// The dialog's fields as it opens: the command's defaults. pub fn fields() -> Value { - json!({"shape": "circle", "frequency": 20, "angle": 45, "mode": "mono", "color": "#000000", "invert": false, "clip": true, "keepOriginal": false}) + json!({"style": "custom", "shape": "circle", "frequency": 20, "angle": 45, "mode": "mono", "color": "#000000", "invert": false, "clip": true, "keepOriginal": false}) +} + +/// The Style picker's choices: their ids and labels. +const STYLES: [(&str, &str); 5] = + [("custom", "Custom"), ("grid", "Grid"), ("gridAngle", "Grid Angle"), ("gridDots", "Grid Dots"), ("gridDotsAngle", "Grid Dots Angle")]; + +/// Spells a stored `style` as the picker's id, matched in any letter case as the effect reads it, +/// so the picker shows it selected and the choice ids stay the ones the dialog accepts. +pub(crate) fn canonical_style(values: &mut serde_json::Map) { + let Some(stored) = values.get("style").and_then(Value::as_str) else { return }; + if let Some((id, _)) = STYLES.iter().find(|(id, _)| id.eq_ignore_ascii_case(stored)) { + values.insert("style".into(), json!(id)); + } } /// A choice's options from `(id, label)` pairs, the labels translated. @@ -56,12 +69,17 @@ pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { ("euclidean", "Euclidean"), ("elliptical", "Elliptical"), ]; - let mut rows = vec![ - Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))), - Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch), - Param::new("angle", tl!("Angle"), ParamKind::range(-90.0, 90.0, 45.0, SliderScale::Linear)).unit(UnitKind::Degrees), - Param::new("mode", tl!("Screens"), ParamKind::choice(options(&[("mono", "Mono"), ("cmyk", "CMYK")]), Some("mono".into()))), - ]; + let styles = STYLES; + let custom = !named_style(fields); + let mut rows = vec![Param::new("style", tl!("Style"), ParamKind::choice(options(&styles), Some("custom".into())))]; + if custom { + rows.push(Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into())))); + } + rows.push(Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch)); + if custom { + rows.push(Param::new("angle", tl!("Angle"), ParamKind::range(-90.0, 90.0, 45.0, SliderScale::Linear)).unit(UnitKind::Degrees)); + } + rows.push(Param::new("mode", tl!("Screens"), ParamKind::choice(options(&[("mono", "Mono"), ("cmyk", "CMYK")]), Some("mono".into())))); if live { rows.push(Param::new("fromArt", tl!("Dot Color from Art"), ParamKind::bool(false)).visible_when("mode", "mono")); } @@ -98,7 +116,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { }; return Err(why.into()); } - let params = Value::Object(json_of(&screen_params(false, &result.fields), &result.fields)); + let params = Value::Object(command_params(&result.fields)); let mut open = app.effect_dialogs.halftone.take().ok_or("the dialog is closed")?; let done = std::mem::take(&mut open.preview).commit(app, CMD, params); if done.is_err() { @@ -119,6 +137,23 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { Ok(Value::Null) } +/// The command's parameters from the dialog's fields. With a named style, the stored Shape and +/// Angle are left out so that the style's own shape and angle apply. +pub(crate) fn command_params(fields: &DialogFields) -> serde_json::Map { + let mut params = json_of(&screen_params(false, fields), fields); + if named_style(fields) { + params.remove("shape"); + params.remove("angle"); + } + params +} + +/// Whether the stored style is a named one, which sets the shape and the angle; Custom, no style +/// and a style this build does not know keep the stored Shape and Angle, so their rows show. +fn named_style(fields: &DialogFields) -> bool { + matches!(fields.text("style").and_then(vectorcraft_effects::addons::halftone::style), Some(Some(_))) +} + /// Runs or ends the open dialog's preview for this frame. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.effect_dialogs.halftone.take() else { return }; @@ -130,7 +165,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let shown = app.dialogs().and_then(|host| { host.with(|h| { h.get_by_id::(open.id).map(|d| { - let params = json_of(&screen_params(false, d.fields()), d.fields()); + let params = command_params(d.fields()); (d.is_previewing(), Value::Object(params)) }) }) @@ -278,6 +313,77 @@ mod tests { assert_eq!(undo_steps(&panel), undo + 1, "the reopened dialog's OK is one undo step"); } + /// A named style sends no Shape or Angle, so the style's own apply; Custom sends both. + #[test] + fn a_named_style_hides_shape_and_angle() { + for (style, shown) in [("custom", true), ("gridDots", false)] { + let mut values = fields(); + values["style"] = json!(style); + let rows = screen_params(false, &DialogFields::new()); + let f = fields_of(&rows, values.as_object().unwrap()); + let sent = command_params(&f); + assert_eq!(sent.get("style"), Some(&json!(style))); + assert_eq!((sent.contains_key("shape"), sent.contains_key("angle")), (shown, shown), "{style}: {sent:?}"); + } + } + + #[test] + fn style_picker_selects_stored_styles_in_any_case() { + for (style, label) in [("GRIDDOTS", "Grid Dots"), ("CUSTOM", "Custom")] { + let mut values = fields(); + values["style"] = json!(style); + let mut values = values.as_object().unwrap().clone(); + canonical_style(&mut values); + let f = fields_of(&screen_params(false, &DialogFields::new()), &values); + let rows = screen_params(false, &f); + let row = rows.iter().find(|p| p.key == "style").unwrap(); + let ParamKind::Choice { options, .. } = &row.kind else { panic!("Style is not a choice") }; + let ids: Vec<&str> = options.iter().map(|(id, _)| id.as_str()).collect(); + assert_eq!(ids, STYLES.map(|(id, _)| id), "{style}: the choice ids stay as the dialog accepts them"); + let selected = options.iter().find(|(id, _)| Some(id.as_str()) == f.text("style")); + assert_eq!(selected.map(|(_, label)| label.as_str()), Some(label), "{style}"); + } + } + + /// A stored style matches Custom in any letter case, as the effect reads it, so Shape and + /// Angle stay on screen and OK sends both. + #[test] + fn custom_style_in_any_case_keeps_shape_and_angle() { + let mut values = fields(); + values["style"] = json!("CUSTOM"); + let f = fields_of(&screen_params(false, &DialogFields::new()), values.as_object().unwrap()); + let rows = screen_params(false, &f); + let shown = |k: &str| rows.iter().any(|p| p.key == k); + assert!(shown("shape") && shown("angle"), "Shape and Angle rows are hidden"); + let sent = command_params(&f); + assert!(sent.contains_key("shape") && sent.contains_key("angle"), "{sent:?}"); + } + + #[test] + fn only_recognized_presets_hide_shape_and_angle() { + for style in [None, Some("custom"), Some("CUSTOM"), Some(""), Some("unknown"), Some("GRIDDOTS")] { + let mut values = fields().as_object().unwrap().clone(); + values.remove("style"); + if let Some(style) = style { + values.insert("style".into(), json!(style)); + } + values.insert("shape".into(), json!("diamond")); + values.insert("angle".into(), json!(23)); + let f = fields_of(&screen_params(false, &DialogFields::new()), &values); + let shown = style != Some("GRIDDOTS"); + for live in [false, true] { + let rows = screen_params(live, &f); + for key in ["shape", "angle"] { + assert_eq!(rows.iter().any(|p| p.key == key), shown, "{style:?}, live={live}, {key}"); + } + } + let sent = command_params(&f); + for key in ["shape", "angle"] { + assert_eq!(sent.get(key), if shown { values.get(key) } else { None }, "{style:?}, {key}"); + } + } + } + /// With Preview off, OK after File > Revert is refused and leaves the restored drawing as it is. #[test] fn vector_halftone_without_preview_refuses_ok_after_file_revert() { diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs index 38c572c1c9..82987ab202 100644 --- a/crates/ui-egui/src/dialogs/host.rs +++ b/crates/ui-egui/src/dialogs/host.rs @@ -7,6 +7,7 @@ use craft::ui::shell::WindowDialogs; use serde_json::Value; use crate::VectorcraftApp; +use crate::graphics::context_tag; /// The most dialogs waiting for an answer at once. pub(crate) const MAX_WAITING: usize = 16; @@ -45,6 +46,8 @@ type Drain = Box Option>; struct Record { id: DialogId, + /// The egui context whose dialog host shows the dialog ([`context_tag`]). + context: u64, drain: Drain, cancel: Option, } @@ -59,6 +62,20 @@ impl Held { } } +/// Cancels the held dialogs opened in another egui context than the app's current one, so every record left is +/// served by the current window's host. Each context has its own host, which numbers its openings from the start: a +/// record of the old host is never answered, and its serial can match an opening of the same key in the new one. +fn retire_other_contexts(app: &mut VectorcraftApp) { + let current = app.ui_ctx.as_ref().map(context_tag); + let (retired, kept): (Vec, Vec) = std::mem::take(&mut app.held.0).into_iter().partition(|record| Some(record.context) != current); + app.held.0 = kept; + for mut record in retired { + if let Some(cancel) = record.cancel.take() { + cancel(app); + } + } +} + fn drain(id: DialogId, serial: u64, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain { Box::new(move |app| { // Without a window nothing can answer: the dialog counts as cancelled so its rollback runs. @@ -106,7 +123,9 @@ pub(crate) fn open_held_with( ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static, options: HeldOptions, ) -> Option { - let host = app.dialogs()?; + retire_other_contexts(app); + let ctx = app.ui_ctx.clone()?; + let host = window_dialogs(&ctx); let dialog = dialog.held_ok(); let (id, serial) = host.with(|h| { let id = match options.parent { @@ -117,7 +136,7 @@ pub(crate) fn open_held_with( })?; // A host key can be reopened before the previous result has been pumped. app.held.0.retain(|record| record.id != id); - app.held.0.push(Record { id, drain: drain::(id, serial, ok), cancel: options.cancel }); + app.held.0.push(Record { id, context: context_tag(&ctx), drain: drain::(id, serial, ok), cancel: options.cancel }); Some(id) } @@ -154,6 +173,8 @@ macro_rules! pumps { /// Runs once per frame after the shell pass: every dialog module's pump, then the held dialogs. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + // The dialog modules see the rollbacks of the dialogs a replaced graphics context took with it. + retire_other_contexts(app); sync(app); pumps!(app, ctx; crate::file_asks::pump, @@ -379,4 +400,56 @@ mod opening_tests { pump(&mut app, &ctx); assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted)); } + + /// Opens the test dialog with an OK and a Cancel that write `name` to `log`. + fn open_logged(app: &mut VectorcraftApp, ctx: &egui::Context, log: &Rc>>, name: &'static str) -> DialogId { + let (answered, cancelled) = (log.clone(), log.clone()); + open_held_with( + app, + dialog(ctx), + move |_, _| { + answered.borrow_mut().push(format!("{name} ok")); + Ok(()) + }, + HeldOptions { parent: None, cancel: Some(Box::new(move |_| cancelled.borrow_mut().push(format!("{name} cancel")))) }, + ) + .unwrap() + } + + #[test] + fn a_new_graphics_context_cancels_the_old_contexts_opening() { + let (mut app, ctx) = app(); + let log = Rc::new(RefCell::new(Vec::new())); + let first = open_logged(&mut app, &ctx, &log, "old"); + let old_serial = app.dialogs().unwrap().with(|h| h.open_serial(first)); + + let fresh = crate::testing::ui_context(); + app.adopt_context(&fresh); + // The new context's host numbers its openings from the start: the same key gets the old opening's serial. + let host = app.dialogs().unwrap(); + let id = host.with(|h| h.open(dialog(&fresh).held_ok())); + assert_eq!((id, host.with(|h| h.open_serial(id))), (first, old_serial)); + assert!(!host.with(|h| h.confirm_by_id(&fresh, id))); + pump(&mut app, &fresh); + assert_eq!(*log.borrow(), ["old cancel"], "the old opening's OK answered the new context's dialog"); + pump(&mut app, &fresh); + assert_eq!(*log.borrow(), ["old cancel"]); + } + + #[test] + fn reopening_a_key_in_a_new_graphics_context_cancels_the_old_opening_first() { + let (mut app, ctx) = app(); + let log = Rc::new(RefCell::new(Vec::new())); + open_logged(&mut app, &ctx, &log, "old"); + + let fresh = crate::testing::ui_context(); + app.adopt_context(&fresh); + let id = open_logged(&mut app, &fresh, &log, "new"); + assert_eq!(*log.borrow(), ["old cancel"], "the old opening's rollback was dropped"); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&fresh, id))); + pump(&mut app, &fresh); + assert_eq!(*log.borrow(), ["old cancel", "new ok"]); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted)); + } } diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index d128aba2e4..0c2f8503ef 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -647,14 +647,16 @@ pub(crate) fn preferred_text_as(app: &VectorcraftApp) -> TextAs { /// or `.ait` file opens as it says: Outlines would open it from its PDF content, without its /// editing data. So does an open with `linkPages`, which refuses Outlines: a linked page shows the /// file's own text. -pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], p: &Value) -> Value { +pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], mut p: Value) -> Value { let given = p.get("textAs").is_some_and(|v| !v.is_null()); let linked = p.get("linkPages").and_then(Value::as_bool) == Some(true); let options = p.is_object() || p.is_null(); if given || linked || !options || preferred_text_as(app) == TextAs::Text || fileio::detect(name, bytes).map(|f| f.id) != Some("pdf") { - return p.clone(); + return p; + } + if !p.is_object() { + p = json!({}); } - let mut p = if p.is_object() { p.clone() } else { json!({}) }; p["textAs"] = json!(TextAs::Outlines.id()); p } diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 0553775449..0b4f34e7bc 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -11,6 +11,7 @@ use std::cell::RefCell; +use craft::behavior::CancelReason; // PLAN: `craft::color_ui` and `craft::theme` need the `craft` facade (feature `color-ui`) in ui-egui's Cargo.toml, which has only `craft-ui`; the owner of the craft-libs pin adds it. use craft::color_ui::ui::{ChosenColor, ColorChoice, NamedColor}; use craft::theme::Srgba; @@ -72,6 +73,8 @@ pub(crate) struct LayerOptionsValue { ids: Vec, /// The fields set in the dialog, by its controls or `ui.dialog.set`. set: Vec<&'static str>, + /// While a typed percentage runs: whether the percentage was set in the dialog when the typing began. + dim_set_before_typing: Option, opened: Option, } @@ -93,6 +96,7 @@ impl Default for LayerOptionsValue { mode: "edit", ids: Vec::new(), set: Vec::new(), + dim_set_before_typing: None, opened: None, } } @@ -362,10 +366,22 @@ fn body(ui: &mut egui::Ui, v: &mut LayerOptionsValue, requested: &RefCell