mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge upstream main into Script Console row menu
This commit is contained in:
commit
26e77f0128
324 files changed
+22572
-1460
No files matched your search
Generated
+27
-6
@@ -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]]
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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.
|
||||
|
||||
+4
-2
@@ -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 `<name>_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.
|
||||
|
||||
@@ -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"] }
|
||||
@@ -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);
|
||||
|
||||
@@ -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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<str>], resolve: impl Fn(&str) -> Option<String>) -> 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<String>, exists: impl Fn(&str) -> bool) -> Option<String> {
|
||||
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option<String>) -> Option<String> {
|
||||
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<String>) -> 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<String> {
|
||||
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<String> {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). 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<AltCodes> = 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<Event>) {
|
||||
/// 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<Event>) -> 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<Event>) {
|
||||
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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<u64> = 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<Vec<u8>>);
|
||||
|
||||
@@ -10,6 +21,7 @@ pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
|
||||
/// 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<DecodedImage, craft_image_codecs::CodecError> {
|
||||
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,
|
||||
|
||||
+15
-3
@@ -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<HitOptions> {
|
||||
#[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<Hi
|
||||
Some(if outline { HitOptions { outline: true, ..opt } } else { opt })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many objects' ancestries [`path_options`] went down on this thread.
|
||||
static PATHS_CHECKED: std::cell::Cell<usize> = 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<NodeId>) -> Vec<NodeId> {
|
||||
|
||||
@@ -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<usize>| {
|
||||
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::<Vec<_>>()
|
||||
};
|
||||
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]
|
||||
|
||||
@@ -43,8 +43,8 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
|
||||
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<Option<(DotShape, f64)>> {
|
||||
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<Self> {
|
||||
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<Point> = 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<CubicBez>| {
|
||||
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<Point> = 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<Point> = 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] {
|
||||
|
||||
@@ -241,29 +241,29 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<AppearanceItem> {
|
||||
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<vectorcraft_three_d::Highlight>,
|
||||
) -> Option<vectorcraft_doc::Node> {
|
||||
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_three_d::Highlight>,
|
||||
) -> 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<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
let facets: Vec<Arc<Node>> = 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::<Option<_>>()?;
|
||||
let facet = |face: &Arc<Node>| {
|
||||
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<Arc<Node>> = faces.iter().map(facet).collect::<Option<_>>()?;
|
||||
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 }))
|
||||
|
||||
@@ -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<Node>]) -> Option<Node> {
|
||||
let faces: Vec<Arc<Node>> = run
|
||||
.iter()
|
||||
.map(|face| match &face.kind {
|
||||
NodeKind::Group { children, clip: false } => children.first().cloned(),
|
||||
_ => Some(face.clone()),
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
let facet = |face: &Arc<Node>| {
|
||||
let mut facet = face.clone();
|
||||
while let NodeKind::Group { children, clip: false } = &facet.kind {
|
||||
facet = children.first()?.clone();
|
||||
}
|
||||
Some(facet)
|
||||
};
|
||||
let faces: Vec<Arc<Node>> = run.iter().map(facet).collect::<Option<_>>()?;
|
||||
if faces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -881,6 +916,21 @@ fn surface_meshes(
|
||||
options: Revolve,
|
||||
(paint, opacity, member): (&Paint, f32, f32),
|
||||
graphics: bool,
|
||||
) -> Result<Vec<crate::SolidMesh>, 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<Vec<crate::SolidMesh>, String> {
|
||||
let color = crate::solids::mesh_color(paint, opacity * member);
|
||||
let list: Vec<crate::MappedGraphic> = 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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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::<usize>();
|
||||
}
|
||||
});
|
||||
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");
|
||||
}
|
||||
@@ -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<Facet>, 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<Facet>,
|
||||
paint: &Paint,
|
||||
(opacity, blend): (f32, BlendMode),
|
||||
colored: bool,
|
||||
faces: bool,
|
||||
parts: Vec<Vec<Arc<Node>>>,
|
||||
) -> 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<Facet>, 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<Facet>, 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<Vec<Arc<Node>>>) -> 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<Facet> {
|
||||
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<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
|
||||
@@ -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<Facet> = 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<Facet> = 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<MeshGraphics>,
|
||||
/// 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<SolidMesh>, 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;
|
||||
@@ -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<Node> {
|
||||
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;
|
||||
|
||||
@@ -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<Material, String> {
|
||||
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 }
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -1029,6 +1029,157 @@ fn red_parts(art: &Node) -> Vec<PathData> {
|
||||
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::<usize>();
|
||||
}
|
||||
});
|
||||
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<FillLayer> {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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::<Vec<_>>();
|
||||
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()));
|
||||
}
|
||||
@@ -243,7 +243,11 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<FacesAndShadow,
|
||||
pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFace>, 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![];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Value> {
|
||||
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) }
|
||||
}
|
||||
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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<Value> {
|
||||
}
|
||||
// The first stays; each later one starts `gap` past where the one before it now ends.
|
||||
let mut end: Option<f64> = 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<NodeId> = 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<f64> = 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<Document> = 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() }))
|
||||
}
|
||||
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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<PathData> {
|
||||
.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, bool>) -> 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<Value> {
|
||||
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<Value> {
|
||||
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<NodeId, bool> = 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;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<NodeId> = (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<Rect> = ids.iter().map(|i| bounds(&s, *i)).collect();
|
||||
let gaps: Vec<f64> = 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<NodeId> = (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();
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -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<Value> {
|
||||
}
|
||||
let series_groups = cached_series_groups(before, &targets);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let compound_groups: HashSet<NodeId> = 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<NodeId> = 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<Value> {
|
||||
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| {
|
||||
|
||||
@@ -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<NodeId> = 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::<Vec<_>>()})).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"] {
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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)?;
|
||||
|
||||
@@ -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<Value> {
|
||||
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::<Vec<_>>(), "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<u32>| 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)
|
||||
}
|
||||
@@ -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<std::sync::Arc<vectorcraft_doc::Node>> {
|
||||
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::<Vec<_>>(), 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]
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -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<u64> = 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<TextRun>, changes: &[Edit]) {
|
||||
note_text_pass();
|
||||
let old = std::mem::take(runs);
|
||||
let mut out: Vec<TextRun> = 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<TextRun>, 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<TextRun>, 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<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let o = Options::parse(p)?;
|
||||
@@ -292,24 +395,43 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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::<usize>::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<Value> {
|
||||
_ => 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<Value> {
|
||||
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)?;
|
||||
|
||||
@@ -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<char>| {
|
||||
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<char>)>, Vec<(usize, usize)>);
|
||||
let cases: Vec<Case> = 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -461,6 +461,20 @@ pub fn read_image(bytes: &[u8]) -> Result<ImageRead> {
|
||||
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<ImageRead> {
|
||||
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`.
|
||||
|
||||
@@ -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<Value>) -> Result<Value> {
|
||||
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<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -19,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<Value> {
|
||||
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<Option<NodeId>> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
// 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);
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -481,6 +481,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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)) {
|
||||
|
||||
@@ -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}));
|
||||
|
||||
@@ -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")))]
|
||||
|
||||
@@ -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<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
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")));
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// 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<Value> {
|
||||
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);
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, 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 pr
Line truncated
|
||||
"{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
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1160,6 +1160,20 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
(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<image::DynamicImage>, icc: Option<Vec<u8>>,
|
||||
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<RasterImage> {
|
||||
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
|
||||
|
||||
@@ -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<usize>,
|
||||
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<Material>, Vec<usize>) {
|
||||
/// 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<Material>, Vec<usize>) {
|
||||
let mut out: Vec<Material> = 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<u8> = vec![];
|
||||
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
|
||||
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, 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<String>| 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 {{");
|
||||
|
||||
@@ -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::<Vec<_>>(), ["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}");
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings 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 <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file 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 <name>_<artboard>.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 <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file 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 <name>_<artboard>.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)
|
||||
),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<u8> {
|
||||
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]
|
||||
|
||||
@@ -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::<std::io::Result<_>>().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<String> = 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();
|
||||
|
||||
@@ -128,6 +128,13 @@ impl StopOwner {
|
||||
#[derive(PartialEq)]
|
||||
pub struct GradientEditPaints(Vec<EditedPaint>);
|
||||
|
||||
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<Value> {
|
||||
})?;
|
||||
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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!([]));
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
|
||||
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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"));
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Value> {
|
||||
} 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<NodeId>| 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<Value> {
|
||||
}
|
||||
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)?;
|
||||
|
||||
@@ -174,6 +174,11 @@ struct Group {
|
||||
document: Option<Shown>,
|
||||
/// An image placed from a DCS file: the plate files of their own its plates were read from.
|
||||
plate_files: Vec<vectorcraft_doc::separated::PlateFile>,
|
||||
/// 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<String>,
|
||||
/// `other_relatives` as a set, looked up for every object added to the group.
|
||||
relatives_seen: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
/// 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<u64>)> {
|
||||
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<String> {
|
||||
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<String> = 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<Group> {
|
||||
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<Found> {
|
||||
/// 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<Found> {
|
||||
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<Item = String> + '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<Found> {
|
||||
(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<String> {
|
||||
@@ -2339,7 +2392,17 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
// 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<String> = (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<String> = 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 [
|
||||
|
||||
@@ -124,7 +124,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Node>, 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<Rect> = 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<Node>, 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<Node>, 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<Vec<NodeId>> {
|
||||
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<Value> {
|
||||
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<Node> = 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<Value> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<u
|
||||
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
|
||||
/// place) stays 0.
|
||||
/// A saved or Recent preset's grid rows, rounded and kept to 0 (columns in their place) to
|
||||
/// [`MAX_ARTBOARDS`], the counts `file.new` takes.
|
||||
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
|
||||
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<DocSettings> {
|
||||
|
||||
/// 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<DocSettings> {
|
||||
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::<Vec<_>>().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),
|
||||
};
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -106,8 +106,8 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `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<Value> {
|
||||
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<Value> {
|
||||
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();
|
||||
|
||||
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let id = s.edit("Make Compound Path", |d, sel| {
|
||||
d.node(backmost).ok_or(EngineError::NoNode(backmost))?;
|
||||
let mut units: Vec<Vec<Arc<Node>>> = 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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
}
|
||||
|
||||
/// 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<vectorcraft_doc::Shared<Appearance>>, out: &mut Vec<Vec<Arc<Node>>>) {
|
||||
/// 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<Node>, out: &mut Vec<Vec<Arc<Node>>>) {
|
||||
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<Value> {
|
||||
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;
|
||||
|
||||
@@ -402,6 +402,15 @@ fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
/// 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<String, Affine>) {
|
||||
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<String, Affine> = 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<String, Affine> {
|
||||
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<String, Affine>) {
|
||||
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.
|
||||
|
||||
@@ -467,6 +467,30 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Vec<NodeId> {
|
||||
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<NodeId> {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>) {
|
||||
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<NodeId> {
|
||||
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) {
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|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 o
Line truncated
|
||||
"{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
Line truncated
|
||||
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<Value>) -> Result<Value> {
|
||||
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.
|
||||
|
||||
@@ -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"))
|
||||
{
|
||||
|
||||
@@ -841,6 +841,15 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<Vec<Row>> {
|
||||
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<Vec<Row>> {
|
||||
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<Color> = 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<Value> {
|
||||
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<String> = vec![];
|
||||
let picked: Vec<Option<Swatch>> = 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<Option<Swatch>> = 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<Value> {
|
||||
// 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<Option<Link>> = 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<Value> {
|
||||
})?;
|
||||
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<Value> {
|
||||
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<ModelRule>)> =
|
||||
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<ModelRule>, Option<(String, String)>);
|
||||
let mut news: Vec<New> = 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<Value> {
|
||||
let map: Vec<Value> = 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::<Vec<_>>(), "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<Value> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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, contai
Line truncated
|
||||
"{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 creatio
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
|
||||
@@ -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<AnchorRef> =
|
||||
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(),
|
||||
};
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -22,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Value> {
|
||||
} 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<Value> {
|
||||
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)?];
|
||||
|
||||
@@ -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<Value>| {
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -977,6 +977,13 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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}))
|
||||
}
|
||||
|
||||
|
||||
@@ -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<usize> {
|
||||
self.first.get(&id).copied()
|
||||
}
|
||||
|
||||
/// [`story_of`] for `id`, its thread found through the index.
|
||||
pub(crate) fn story(&self, id: NodeId) -> Vec<NodeId> {
|
||||
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.
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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<dyn Fn(&Path) -> Result<(), String>>;
|
||||
|
||||
thread_local! {
|
||||
static WRITE_GUARD: RefCell<Option<WriteGuard>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Puts the write guard it replaced back when dropped (also when `f` panics).
|
||||
struct RestoreWriteGuard(Option<WriteGuard>);
|
||||
|
||||
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<T>(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`.
|
||||
|
||||
@@ -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<vectorcraft_tools::PaintDefaults>,
|
||||
/// 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<vectorcraft_tools::PaintDefaults>,
|
||||
/// Conversion of new-art paints waits until a color-mode preview is accepted.
|
||||
|
||||
@@ -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<DocState>,
|
||||
active: Option<usize>,
|
||||
@@ -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<u64>,
|
||||
/// 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<String>,
|
||||
@@ -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<cmd::place::PlaceRead>,
|
||||
/// 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<Option<bool>>,
|
||||
/// 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<cmd::place::QueueRead>,
|
||||
|
||||
@@ -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<u64>,
|
||||
/// 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<Pending>,
|
||||
/// The [`Pending::seq`] of each `document.opened` the running script's commands queued.
|
||||
script_opens: HashSet<u64>,
|
||||
/// 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<u64> =
|
||||
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<Recipient, Arc<Plugin>> = 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<Value> = 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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -254,7 +254,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
// 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<Data, HostError> {
|
||||
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);
|
||||
|
||||
Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user