Merge main into feat/scripts-api-d5-swatches-symbols
No files matched your search
@@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator-
|
||||
For the crates you changed: `cargo fmt`, `cargo clippy -p <crate> --all-targets`, `cargo xtask test` or `cargo nextest run -p <crate>`. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`.
|
||||
|
||||
### Paths and conventions
|
||||
- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`.
|
||||
- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it.
|
||||
- Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns.
|
||||
- Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty.
|
||||
- Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`.
|
||||
|
||||
@@ -1238,6 +1238,7 @@ dependencies = [
|
||||
"craft-browse",
|
||||
"craft-cms",
|
||||
"craft-color-ui",
|
||||
"craft-control",
|
||||
"craft-dialogs",
|
||||
"craft-draw",
|
||||
"craft-font-catalog",
|
||||
@@ -1280,6 +1281,16 @@ dependencies = [
|
||||
"ruzstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ai-agents"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
@@ -1417,8 +1428,13 @@ name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-control-protocol",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1537,6 +1553,16 @@ name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
@@ -2900,6 +2926,7 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"smithay-clipboard",
|
||||
"web-time",
|
||||
"webbrowser",
|
||||
"windows-sys 0.61.2",
|
||||
"winit",
|
||||
]
|
||||
@@ -8637,6 +8664,7 @@ dependencies = [
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"craft",
|
||||
"log",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -9642,6 +9670,22 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webbrowser"
|
||||
version = "1.2.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13b31216ad837f3f4062538be333d8431d37c11832ef86924a3d0ad50defdc2f"
|
||||
dependencies = [
|
||||
"jni",
|
||||
"log",
|
||||
"ndk-context",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"url",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.11"
|
||||
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged.
|
||||
|
||||
- 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.
|
||||
@@ -269,6 +271,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. |
|
||||
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
|
||||
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
|
||||
| 2026-11-15 | minor | Graphic Styles: 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). |
|
||||
|
||||
@@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`).
|
||||
craft = { workspace = true, features = ["automation-agents"] }
|
||||
|
||||
# `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this
|
||||
# process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT),
|
||||
@@ -52,6 +54,7 @@ serde_json = { workspace = true }
|
||||
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = [
|
||||
"apps/vectorcraft/src/agent_settings.rs",
|
||||
"apps/vectorcraft/src/mac_fonts.rs",
|
||||
"apps/vectorcraft/src/prefs_dir.rs",
|
||||
"apps/vectorcraft/src/profile.rs",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! ```text
|
||||
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent]
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
@@ -39,6 +39,10 @@ macro_rules! out {
|
||||
}};
|
||||
}
|
||||
|
||||
/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the
|
||||
/// closed-app choice and the agent folders the app saved.
|
||||
#[path = "../../vectorcraft/src/agent_settings.rs"]
|
||||
mod agent_settings;
|
||||
/// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "../../vectorcraft/src/mac_fonts.rs"]
|
||||
@@ -56,9 +60,11 @@ mod system_fonts;
|
||||
#[path = "../../vectorcraft/src/windows_cores.rs"]
|
||||
mod windows_cores;
|
||||
|
||||
use craft::automation::agents::WhenAppClosed;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server};
|
||||
use vectorcraft_mcp::agents::{LiveBackend, LiveConfig};
|
||||
use vectorcraft_mcp::{Backend, Headless, Remote, Server};
|
||||
|
||||
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as
|
||||
/// ripgrep does; any other write error is reported.
|
||||
@@ -79,9 +85,18 @@ USAGE:
|
||||
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
|
||||
does not take --connect.
|
||||
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
|
||||
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
|
||||
(vectorcraft --control 7979), falling back to a headless in-process session.
|
||||
vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
|
||||
Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI
|
||||
agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection
|
||||
file the window publishes in the settings folder: no port or token to configure, and an app
|
||||
opened after the session started is found too. Otherwise the call runs in a session without
|
||||
a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI
|
||||
Integrations applies (open VectorCraft, a session without a window in the agent folders, or
|
||||
an error); --when-closed overrides it. Files of the open window's agent requests stay in the
|
||||
agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the
|
||||
agent_folders tool names them. --headless always runs without a window.
|
||||
--connect ADDR (deprecated, removed in a later release) drives an app started with
|
||||
vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN.
|
||||
--automation-read-root / --automation-write-root confine the files the agent's commands read
|
||||
(open, place, relink, library loads…) and write (save, export, package, library saves…) to
|
||||
DIR, links followed; each may be given more than once, a path inside any of its folders being
|
||||
@@ -280,6 +295,20 @@ fn with_stores(mut h: Headless) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed`
|
||||
/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with
|
||||
/// the user's stores, or confined to the agent folders without them.
|
||||
fn live_config(dir: std::path::PathBuf, when_closed: Option<WhenAppClosed>) -> LiveConfig {
|
||||
let mut cfg = LiveConfig::new(dir, agent_settings::read_settings);
|
||||
cfg.when_closed = when_closed;
|
||||
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE));
|
||||
cfg.headless = Box::new(|roots| match roots {
|
||||
Some(roots) => Headless::with_document().with_automation_roots(Some(roots)),
|
||||
None => with_stores(Headless::with_document()),
|
||||
});
|
||||
cfg
|
||||
}
|
||||
|
||||
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
|
||||
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
|
||||
if allow {
|
||||
@@ -288,26 +317,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
|
||||
/// plug-ins, so `--connect` is refused and the default does not connect.
|
||||
/// The stderr line `mcp --connect` prints: the flag works for one more release.
|
||||
const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
|
||||
|
||||
/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's
|
||||
/// switch), found through its connection file on every tool call, otherwise a headless session
|
||||
/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and
|
||||
/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless.
|
||||
/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated).
|
||||
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
|
||||
if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) {
|
||||
return help();
|
||||
}
|
||||
let mut connect: Option<String> = None;
|
||||
let mut headless = false;
|
||||
let mut when_closed: Option<String> = None;
|
||||
let mut allow_grants = false;
|
||||
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
// The roots also come as `--flag=DIR`, as the other Craft apps take them.
|
||||
let (flag, inline) = match a.split_once('=') {
|
||||
Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())),
|
||||
Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())),
|
||||
_ => (a.as_str(), None),
|
||||
};
|
||||
match flag {
|
||||
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
|
||||
"--headless" => headless = true,
|
||||
"--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?),
|
||||
"--allow-plugin-grants" => allow_grants = true,
|
||||
"--automation-read-root" | "--automation-write-root" => {
|
||||
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
@@ -328,6 +365,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if safe_mode && connect.is_some() {
|
||||
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
|
||||
}
|
||||
let when_closed = match when_closed.as_deref() {
|
||||
None => None,
|
||||
Some(choice) => {
|
||||
let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?;
|
||||
if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) {
|
||||
return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into());
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
};
|
||||
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
|
||||
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?;
|
||||
@@ -343,13 +390,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
} else if headless || safe_mode || allow_grants {
|
||||
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
|
||||
} else if let Some(addr) = connect {
|
||||
eprintln!("{CONNECT_DEPRECATED}");
|
||||
// Explicit address: fail loudly if the app isn't there.
|
||||
let token = vectorcraft_mcp::control_token()?;
|
||||
Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
|
||||
} else {
|
||||
// No token or no app listening: the headless session answers instead.
|
||||
match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) {
|
||||
Some(r) => Box::new(r),
|
||||
match prefs_dir::prefs_dir() {
|
||||
Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))),
|
||||
// No settings folder (no home folder): no window can be found either, so `--when-closed error`
|
||||
// refuses rather than answering from a session the agent didn't ask for.
|
||||
None if when_closed == Some(WhenAppClosed::Error) => {
|
||||
return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into());
|
||||
}
|
||||
None => Box::new(with_stores(Headless::with_document())),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() {
|
||||
let r = run_in(&config, &[("pdf.preset.list", json!({}))]);
|
||||
assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true));
|
||||
}
|
||||
|
||||
/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one
|
||||
/// release but says it is deprecated before it connects.
|
||||
#[test]
|
||||
fn mcp_when_closed_and_the_deprecated_connect() {
|
||||
let fails = |args: &[&str], why: &str| {
|
||||
let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
|
||||
err.into_owned()
|
||||
};
|
||||
fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error");
|
||||
fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window");
|
||||
fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window");
|
||||
let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated");
|
||||
assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}");
|
||||
}
|
||||
@@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
let pen = host.pointers.borrow().pen();
|
||||
let spec = InstallSpec::new(ShellInfo::current(), Arc::new(SystemWindows)).pen(pen);
|
||||
// The interface faces the page serves are fetched by the stack as text needs them.
|
||||
let fonts = vectorcraft_ui_egui::ui_fonts().fetcher(Arc::new(crate::fonts::BrowserFetcher));
|
||||
let language = taken.borrow().as_ref().map_or_else(i18n::system_lang, VectorcraftApp::ui_language);
|
||||
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, language, Some(Arc::new(crate::fonts::BrowserFetcher)));
|
||||
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
let files = {
|
||||
|
||||
@@ -23,7 +23,10 @@ vectorcraft-text = { workspace = true }
|
||||
# the update client.
|
||||
craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] }
|
||||
craft-nightly = { workspace = true }
|
||||
eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] }
|
||||
# `links` makes egui's OpenUrl output (every link the app opens) start the system browser; without it egui-winit only
|
||||
# logs the request. Remove it when the craft-libs pin includes storytold/craft-libs#5083, which opens links in the
|
||||
# shared app setup.
|
||||
eframe = { workspace = true, features = ["clipboard", "default_fonts", "links", "wayland", "x11"] }
|
||||
egui = { workspace = true }
|
||||
egui_extras = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder
|
||||
//! (`prefs_dir.rs`). The desktop app writes them when they change (`prefs.agents`); `vectorcraft-cli`
|
||||
//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice
|
||||
//! and the agent folders.
|
||||
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
use craft::automation::agents::AgentSettings;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed",
|
||||
/// "allowAgentControl"}`, the framework's `AgentSettings`.
|
||||
pub const SETTINGS_FILE: &str = "agents.json";
|
||||
|
||||
/// The largest settings file read; the settings are a few short strings.
|
||||
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
|
||||
|
||||
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read,
|
||||
/// so neither the app nor the CLI fails over them. One bad value resets only itself.
|
||||
pub fn read_settings(dir: &Path) -> AgentSettings {
|
||||
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
|
||||
let mut text = String::new();
|
||||
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
|
||||
return AgentSettings::default();
|
||||
}
|
||||
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
|
||||
let mut settings = AgentSettings::default();
|
||||
for (key, value) in saved {
|
||||
let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue };
|
||||
if one.contains_key(&key) {
|
||||
one.insert(key, value);
|
||||
if let Ok(next) = serde_json::from_value(Value::Object(one)) {
|
||||
settings = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a
|
||||
/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
|
||||
// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them.
|
||||
#[allow(dead_code)]
|
||||
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
|
||||
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
|
||||
std::fs::write(&partial, text)?;
|
||||
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&partial);
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft::automation::agents::WhenAppClosed;
|
||||
|
||||
// Settings saved by the app read back in the CLI, and a damaged file or value never fails it.
|
||||
#[test]
|
||||
fn saved_settings_read_back_and_bad_values_reset_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(read_settings(dir.path()), AgentSettings::default());
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.read_root = "/in".into();
|
||||
settings.when_app_closed = WhenAppClosed::Headless;
|
||||
write_settings(dir.path(), &settings).unwrap();
|
||||
assert_eq!(read_settings(dir.path()), settings);
|
||||
std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap();
|
||||
assert_eq!(read_settings(dir.path()), AgentSettings::default());
|
||||
std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap();
|
||||
let read = read_settings(dir.path());
|
||||
assert_eq!(read.when_app_closed, WhenAppClosed::Error);
|
||||
assert_eq!(read.read_root, "");
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
//! how the window's frames reach the display (`presentation`).
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod agent_settings;
|
||||
mod automation_args;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
@@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<Stri
|
||||
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
|
||||
}
|
||||
|
||||
/// Agents in the open window (`vectorcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
|
||||
/// names VectorCraft, the window serves agents on loopback and publishes the connection in its
|
||||
/// settings folder, where `vectorcraft-cli mcp` finds it. A connection file a crashed run left is
|
||||
/// removed first. With `--control` (`control_port`, served by `launched`) that channel serves the
|
||||
/// whole run and the link stays off. A nightly and a run without preferences have no link.
|
||||
fn agents_link(ctx: &egui::Context, control_port: Option<u16>, launched: Option<&Listening>) -> Option<vectorcraft_ui_egui::agents::Agents> {
|
||||
use craft::automation::agents::{AgentSwitch, remove_stale_connection};
|
||||
use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn};
|
||||
let dir = prefs_dir::prefs_dir()?;
|
||||
remove_stale_connection(&dir);
|
||||
let switch = AgentSwitch::watch(LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
});
|
||||
let save_dir = dir.clone();
|
||||
let save: SaveFn = Box::new(move |settings| {
|
||||
agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display()))
|
||||
});
|
||||
let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION"));
|
||||
let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save);
|
||||
// The port it listens on (the one the system picked for `--control 0`), none when it couldn't.
|
||||
Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents })
|
||||
}
|
||||
|
||||
/// The control channel's port, and the token's notice with the token itself.
|
||||
type ControlChannel = (Option<u16>, Option<(String, String)>);
|
||||
|
||||
@@ -857,8 +882,6 @@ fn main() -> std::process::ExitCode {
|
||||
Some(pen) => spec.pen(pen),
|
||||
None => spec,
|
||||
};
|
||||
embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
let folders = settings.lock().get().ui.last_folders.clone();
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
@@ -875,7 +898,6 @@ fn main() -> std::process::ExitCode {
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.files(files.clone())
|
||||
.build();
|
||||
host.clone().install(ctx);
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
@@ -900,12 +922,16 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_proof_setups(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
|
||||
load_prefs(&mut app, &settings);
|
||||
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None);
|
||||
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
host.clone().install(ctx);
|
||||
app.host = Arc::new(host);
|
||||
app.adopt_context(&cc.egui_ctx);
|
||||
// A nightly is updated by the Launcher: it never checks for a stable release, which
|
||||
// would install this program's own updater over the nightly build.
|
||||
app.set_startup_update_check(!nightly);
|
||||
load_prefs(&mut app, &settings);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// Loads started later (a preference change, the end of Safe Mode) are waited for,
|
||||
// after the launch's own.
|
||||
@@ -1048,6 +1074,12 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !nightly
|
||||
&& prefs_enabled()
|
||||
&& let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref())
|
||||
{
|
||||
app = app.with_agents(agents);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
open_documents::set_ui(&cc.egui_ctx);
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15 20L18 14L21 20" stroke="#fff" stroke-width="3"/><path d="M15 20L18 14L21 20" stroke="#000" stroke-width="1.2" fill="none"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
|
||||
<path d="M15 20L18 14L21 20" stroke="#000" stroke-width="1.2" fill="none"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 585 B After Width: | Height: | Size: 465 B |
@@ -1 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M16 21A6 6 0 0 1 22 15" stroke="#fff" stroke-width="3"/><path d="M16 21A6 6 0 0 1 22 15" stroke="#000" stroke-width="1.2" fill="none"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
|
||||
<path d="M16 21A6 6 0 0 1 22 15" stroke="#000" stroke-width="1.2" fill="none"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 593 B After Width: | Height: | Size: 469 B |
@@ -1 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15 20L18.5 16.5" stroke="#fff" stroke-width="3"/><path d="M15 20L18.5 16.5" stroke="#000" stroke-width="1.2" fill="none"/><path d="M18 13h4v4h-4Z" stroke="#fff" stroke-width="3"/><path d="M18 13h4v4h-4Z" fill="#000" stroke="#000" stroke-width="1"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
|
||||
<path d="M15 20L18.5 16.5" stroke="#000" stroke-width="1.2" fill="none"/>
|
||||
<path d="M18 13h4v4h-4Z" fill="#000" stroke="#000" stroke-width="1"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 707 B After Width: | Height: | Size: 535 B |
@@ -1 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15.6 14.6L20.4 19.4" stroke="#fff" stroke-width="3"/><path d="M20.4 14.6L15.6 19.4" stroke="#fff" stroke-width="3"/><path d="M18 14V20" stroke="#fff" stroke-width="3"/><path d="M15 17H21" stroke="#fff" stroke-width="3"/><path d="M15.6 14.6L20.4 19.4" stroke="#000" stroke-width="1.2" fill="none"/><path d="M20.4 14.6L15.6 19.4" stroke="#000" stroke-width="1.2" fill="none"/><path d="M18 14V20" stroke="#000" stroke-width="1.2" fill="none"/><path d="M15 17H21" stroke="#000" stroke-width="1.2" fill="none"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
|
||||
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
|
||||
<path d="M15.6 14.6L20.4 19.4" stroke="#000" stroke-width="1.2" fill="none"/>
|
||||
<path d="M20.4 14.6L15.6 19.4" stroke="#000" stroke-width="1.2" fill="none"/>
|
||||
<path d="M18 14V20" stroke="#000" stroke-width="1.2" fill="none"/>
|
||||
<path d="M15 17H21" stroke="#000" stroke-width="1.2" fill="none"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 965 B After Width: | Height: | Size: 685 B |
@@ -1,6 +1,7 @@
|
||||
//! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so
|
||||
//! the corpus tests and fuzz targets under it, and the CI job that runs them, still build.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub use craft_affinity::*;
|
||||
@@ -18,6 +18,7 @@
|
||||
//!
|
||||
//! The crate knows no command and depends on no other VectorCraft crate.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
use std::fmt;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it
|
||||
//! returns (caching them per node) and `object.expandBrush` inserts them as real objects.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
mod calli;
|
||||
mod colorize;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
#![doc(test(attr(deny(unsafe_code))))]
|
||||
|
||||
mod aci;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB),
|
||||
//! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`].
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod blend;
|
||||
pub mod cms;
|
||||
|
||||
@@ -21,11 +21,12 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
|
||||
use vectorcraft_geom::shapes::CornerKind;
|
||||
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile};
|
||||
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use crate::node::{Node, NodeId, NodeKind};
|
||||
use crate::node::{LiveShape, Node, NodeId, NodeKind};
|
||||
use crate::text::TextObject;
|
||||
|
||||
// =====================================================================================
|
||||
@@ -1032,6 +1033,9 @@ enum Shape {
|
||||
/// Paths and compound paths; `members`: the subpath count of each member when both keys are
|
||||
/// compound paths.
|
||||
Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec<usize>, Vec<usize>)> },
|
||||
/// Two live rectangles: each step is a live rectangle whose size, transform and corner radii
|
||||
/// lie between the keys', so their rounded corners stay circular arcs.
|
||||
LiveRect(Box<(LiveRectParts, LiveRectParts)>),
|
||||
/// Text, symbols and images: their transforms interpolate.
|
||||
Placed,
|
||||
/// Anything else: a copy of the nearer key moved and scaled into the interpolated box.
|
||||
@@ -1046,6 +1050,43 @@ pub struct Lerp {
|
||||
shape: Shape,
|
||||
}
|
||||
|
||||
/// A live rectangle's size, transform, corner kinds and corner radii in document units.
|
||||
#[derive(Clone, Debug)]
|
||||
struct LiveRectParts {
|
||||
w: f64,
|
||||
h: f64,
|
||||
radii: [f64; 4],
|
||||
kinds: [CornerKind; 4],
|
||||
xf: Affine,
|
||||
}
|
||||
|
||||
/// The parts of `s` when it is a live rectangle, with its radii as the lengths it draws.
|
||||
fn live_rect(s: &LiveShape) -> Option<LiveRectParts> {
|
||||
let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = s else { return None };
|
||||
let base = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, *w, *h));
|
||||
let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative);
|
||||
let corners = vectorcraft_geom::corners::path_corners(&base);
|
||||
let mut drawn = [0.0; 4];
|
||||
for (c, r) in corners.iter().zip(vectorcraft_geom::corners::fitted_radii(&corners, &resolved)) {
|
||||
if let Some(d) = drawn.get_mut(c.index) {
|
||||
*d = r;
|
||||
}
|
||||
}
|
||||
Some(LiveRectParts { w: *w, h: *h, radii: drawn, kinds: *kinds, xf: *xf })
|
||||
}
|
||||
|
||||
/// The parts of `a` and `b` when steps between them can be live rectangles: both are live
|
||||
/// rectangles with the same corner kinds, turned and reflected alike, and with no scale or shear
|
||||
/// left in their transforms, so each step only moves and resizes and its corners stay circular.
|
||||
fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> {
|
||||
let (x, y) = (live_rect(a)?, live_rect(b)?);
|
||||
let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs());
|
||||
// A rotation or a reflection: unit columns at right angles.
|
||||
let rigid =
|
||||
|c: [f64; 6]| (c[0].hypot(c[1]) - 1.0).abs() < 1e-9 && (c[2].hypot(c[3]) - 1.0).abs() < 1e-9 && (c[0] * c[2] + c[1] * c[3]).abs() < 1e-9;
|
||||
(x.kinds == y.kinds && rigid(p) && rigid(q) && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() < 1e-9)).then_some((x, y))
|
||||
}
|
||||
|
||||
/// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has.
|
||||
fn collapsed(n: &Node, c: Point) -> Node {
|
||||
let mut x = n.clone();
|
||||
@@ -1083,6 +1124,12 @@ impl Lerp {
|
||||
| (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. })
|
||||
| (NodeKind::Image(_), NodeKind::Image(_))
|
||||
| (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed,
|
||||
// A clicked start point asks for anchors to be paired; the path route does that.
|
||||
(NodeKind::Path { live: Some(la), .. }, NodeKind::Path { live: Some(lb), .. })
|
||||
if let Some(parts) = live_rect_pair(la, lb).filter(|_| starts == (None, None)) =>
|
||||
{
|
||||
Shape::LiveRect(Box::new(parts))
|
||||
}
|
||||
_ => match (node_path(a), node_path(b)) {
|
||||
(Some((pa, ra, ma)), Some((pb, rb, mb))) => {
|
||||
Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) }
|
||||
@@ -1145,6 +1192,28 @@ impl Lerp {
|
||||
}
|
||||
}
|
||||
}
|
||||
Shape::LiveRect(parts) => {
|
||||
let (x, y) = &**parts;
|
||||
let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs());
|
||||
let live = LiveShape::Rectangle {
|
||||
w: lerp_f64(x.w, y.w, t),
|
||||
h: lerp_f64(x.h, y.h, t),
|
||||
radii: std::array::from_fn(|i| lerp_f64(x.radii[i], y.radii[i], t)),
|
||||
kinds: x.kinds,
|
||||
radii_relative: false,
|
||||
xf: Affine::new([p[0], p[1], p[2], p[3], lerp_f64(p[4], q[4], t), lerp_f64(p[5], q[5], t)]),
|
||||
};
|
||||
let rule = match &base.kind {
|
||||
NodeKind::Path { rule, .. } => *rule,
|
||||
_ => FillRule::default(),
|
||||
};
|
||||
let mut n = Node::path(NodeId(0), live.to_path(), Appearance::default());
|
||||
if let NodeKind::Path { rule: r, live: l, .. } = &mut n.kind {
|
||||
*r = rule;
|
||||
*l = Some(Box::new(live));
|
||||
}
|
||||
n
|
||||
}
|
||||
Shape::Placed => {
|
||||
let mut n = base.clone();
|
||||
match (&mut n.kind, &a.kind, &b.kind) {
|
||||
@@ -2321,6 +2390,110 @@ mod tests {
|
||||
assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0));
|
||||
}
|
||||
|
||||
/// A live rectangle `w` by `h` at `(x, 0)` with every corner radius `r`.
|
||||
fn rounded(x: f64, w: f64, h: f64, r: f64) -> Node {
|
||||
let live =
|
||||
LiveShape::Rectangle { w, h, radii: [r; 4], kinds: [CornerKind::Round; 4], radii_relative: false, xf: Affine::translate((x, 0.0)) };
|
||||
let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default());
|
||||
if let NodeKind::Path { live: l, .. } = &mut n.kind {
|
||||
*l = Some(Box::new(live));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The step's live radii, after checking that every curve of its outline is a circular arc of
|
||||
/// that radius about the matching corner center.
|
||||
fn round_step_radii(step: &Node) -> [f64; 4] {
|
||||
let Some(LiveShape::Rectangle { radii, .. }) = step.live_shape() else { panic!("a live rectangle step: {step:?}") };
|
||||
let r = radii[0];
|
||||
let b = step.path_data().and_then(|p| p.bounds()).unwrap_or_default();
|
||||
let centers = [(b.x0 + r, b.y0 + r), (b.x1 - r, b.y0 + r), (b.x1 - r, b.y1 - r), (b.x0 + r, b.y1 - r)].map(|(x, y)| Point::new(x, y));
|
||||
let path = step.path_data().map(|p| p.to_bezpath()).unwrap_or_default();
|
||||
let curves = path.segments().filter(|s| matches!(s, vectorcraft_geom::kurbo::PathSeg::Cubic(_))).count();
|
||||
assert_eq!(curves, if r > 1e-9 { 4 } else { 0 }, "one arc per corner: {path:?}");
|
||||
for seg in path.segments() {
|
||||
if let vectorcraft_geom::kurbo::PathSeg::Cubic(c) = seg {
|
||||
for u in [0.0, 0.25, 0.5, 0.75, 1.0] {
|
||||
let p = c.eval(u);
|
||||
let d = centers.iter().map(|q| (p - *q).hypot()).fold(f64::INFINITY, f64::min);
|
||||
assert!((d - r).abs() < 0.01 * r.max(1.0), "{p:?} is {d} from its corner center, not {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
*radii
|
||||
}
|
||||
|
||||
/// Steps between live rectangles are live rectangles whose corner radii lie between the keys'.
|
||||
#[test]
|
||||
fn steps_between_rounded_rectangles_keep_round_corners() {
|
||||
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
|
||||
for r in round_step_radii(&blend.at(0.5)) {
|
||||
assert!((r - 20.0).abs() < 1e-9, "{r}");
|
||||
}
|
||||
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 0.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
|
||||
for t in [0.25, 0.5, 0.75] {
|
||||
for r in round_step_radii(&blend.at(t)) {
|
||||
assert!((r - 30.0 * t).abs() < 1e-9, "{t}: {r}");
|
||||
}
|
||||
}
|
||||
// A radius too large for its rectangle counts as the radius it draws.
|
||||
let blend = Lerp::new(&rounded(0.0, 20.0, 20.0, 100.0), &rounded(300.0, 200.0, 200.0, 10.0), (None, None));
|
||||
for r in round_step_radii(&blend.at(0.5)) {
|
||||
assert!((r - 10.0).abs() < 1e-9, "{r}");
|
||||
}
|
||||
// Keys turned differently keep the anchor-by-anchor route.
|
||||
let mut turned = rounded(300.0, 200.0, 60.0, 30.0);
|
||||
turned.transform(Affine::rotate(0.5), false);
|
||||
assert!(matches!(Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &turned, (None, None)).shape, Shape::Path { .. }));
|
||||
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
|
||||
let mut b = rounded(300.0, 100.0, 100.0, 30.0);
|
||||
a.transform(Affine::rotate(30.0_f64.to_radians()), false);
|
||||
b.transform(Affine::rotate(390.0_f64.to_radians()), false);
|
||||
let blend = Lerp::new(&a, &b, (None, None));
|
||||
assert!(matches!(&blend.shape, Shape::LiveRect(_)));
|
||||
let step = blend.at(0.5);
|
||||
let Some(LiveShape::Rectangle { xf, .. }) = step.live_shape() else { panic!("a live rectangle step") };
|
||||
let Some(LiveShape::Rectangle { xf: first, .. }) = a.live_shape() else { panic!("a live rectangle key") };
|
||||
assert_eq!(xf.as_coeffs()[..4], first.as_coeffs()[..4]);
|
||||
for starts in [(Some(0), None), (None, Some(0))] {
|
||||
assert!(matches!(Lerp::new(&a, &b, starts).shape, Shape::Path { .. }));
|
||||
}
|
||||
b.transform(Affine::scale_non_uniform(-1.0, 1.0), false);
|
||||
assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. }));
|
||||
for scale in [1.0, 1e-200] {
|
||||
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
|
||||
let mut b = rounded(300.0, 100.0, 100.0, 30.0);
|
||||
a.transform(Affine::scale_non_uniform(scale, scale * 1e-12), false);
|
||||
b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false);
|
||||
assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. }));
|
||||
}
|
||||
// Keys whose corner kinds differ keep the anchor-by-anchor route.
|
||||
let mut kinds = [CornerKind::Round; 4];
|
||||
kinds[2] = CornerKind::InvertedRound;
|
||||
let live = LiveShape::Rectangle { w: 200.0, h: 60.0, radii: [30.0; 4], kinds, radii_relative: false, xf: Affine::translate((300.0, 0.0)) };
|
||||
let mut inverted = Node::path(NodeId(1), live.to_path(), Appearance::default());
|
||||
if let NodeKind::Path { live: l, .. } = &mut inverted.kind {
|
||||
*l = Some(Box::new(live));
|
||||
}
|
||||
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &inverted, (None, None));
|
||||
assert!(matches!(blend.shape, Shape::Path { .. }));
|
||||
// The last step is the inverted key's outline.
|
||||
assert_eq!(blend.at(1.0).path_data().and_then(|p| p.bounds()), inverted.path_data().and_then(|p| p.bounds()));
|
||||
// Each step keeps the fill rule of the key it is nearer.
|
||||
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
|
||||
if let NodeKind::Path { rule, .. } = &mut a.kind {
|
||||
*rule = FillRule::EvenOdd;
|
||||
}
|
||||
let blend = Lerp::new(&a, &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
|
||||
assert!(matches!(&blend.shape, Shape::LiveRect(_)));
|
||||
let rule = |n: &Node| match &n.kind {
|
||||
NodeKind::Path { rule, .. } => *rule,
|
||||
_ => panic!("a path step: {n:?}"),
|
||||
};
|
||||
assert_eq!(rule(&blend.at(0.25)), FillRule::EvenOdd);
|
||||
assert_eq!(rule(&blend.at(0.75)), FillRule::NonZero);
|
||||
}
|
||||
|
||||
/// A step between two distorted images has its corners between the keys' corners.
|
||||
#[test]
|
||||
fn steps_between_distorted_images_have_corners_between_theirs() {
|
||||
|
||||
@@ -277,6 +277,57 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the
|
||||
/// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors,
|
||||
/// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a
|
||||
/// [`LiveShape::Path`] with that outline. [`LiveCorners::sources`] before and after the edit map
|
||||
/// the anchors as drawn to the corners they come from.
|
||||
/// Returns `None`, leaving the path unchanged, when the path has no live shape or
|
||||
/// no cut corner, or is a rectangle sheared or scaled unevenly.
|
||||
pub fn edit_corner_anchors(
|
||||
path: &mut PathData,
|
||||
live: &mut Option<Box<LiveShape>>,
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
edit: impl FnOnce(&mut PathData, &BTreeSet<AnchorRef>),
|
||||
) -> Option<()> {
|
||||
live.as_ref()?;
|
||||
if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let scale = (a * a + b * b).max(c * c + d * d).max(1e-12);
|
||||
if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let (mut base, moved, radii, kinds, relative) = {
|
||||
let lc = LiveCorners::new(path, live.as_deref())?;
|
||||
if !lc.drawn.iter().any(|r| *r > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let moved: BTreeSet<usize> = anchors.iter().filter_map(|(si, ai)| lc.sources.get(*si)?.get(*ai).copied()).collect();
|
||||
if moved.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut radii = lc.radii.clone();
|
||||
radii.resize(lc.base.anchor_count(), 0.0);
|
||||
(lc.base.transformed(lc.xf), moved, radii, lc.kinds.clone(), lc.relative)
|
||||
};
|
||||
let mut on_base = BTreeSet::new();
|
||||
let mut k = 0;
|
||||
for (si, sp) in base.subpaths.iter().enumerate() {
|
||||
for ai in 0..sp.anchors.len() {
|
||||
if moved.contains(&k) {
|
||||
on_base.insert((si, ai));
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
edit(&mut base, &on_base);
|
||||
let l = LiveShape::Path { base, radii, kinds, radii_relative: relative };
|
||||
*path = l.to_path();
|
||||
*live = Some(Box::new(l));
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node.
|
||||
//! Keeping the previous `Document` value around is therefore a cheap undo snapshot.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod appearance;
|
||||
pub mod assets;
|
||||
@@ -102,7 +103,7 @@ pub use appearance::{
|
||||
};
|
||||
pub use assets::ExportAsset;
|
||||
pub use compound_shape::ShapeMode;
|
||||
pub use corners::LiveCorners;
|
||||
pub use corners::{LiveCorners, edit_corner_anchors};
|
||||
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
|
||||
pub use graph::{
|
||||
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
//! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells,
|
||||
//! anchored at the object's centre.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod addons;
|
||||
mod adjust;
|
||||
|
||||
@@ -903,7 +903,7 @@ pub struct SymbolOptions {
|
||||
|
||||
impl SymbolOptions {
|
||||
/// The options `d` keeps for symbol `name`.
|
||||
fn of(d: &Document, name: &str) -> Self {
|
||||
pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self {
|
||||
Self {
|
||||
size: stored_natural_size(d, name),
|
||||
registration: d.symbol_registration(name),
|
||||
@@ -914,7 +914,7 @@ impl SymbolOptions {
|
||||
}
|
||||
|
||||
/// Make them the options of `d`'s symbol `name`.
|
||||
fn give(&self, d: &mut Document, name: &str) {
|
||||
pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) {
|
||||
set_natural_size(d, name, self.size);
|
||||
d.set_symbol_registration(name, self.registration);
|
||||
d.set_symbol_export_type(name, self.export_type);
|
||||
|
||||
@@ -10,9 +10,12 @@
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::fileio::{read_file_head, write_file};
|
||||
@@ -77,6 +80,166 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Every stored family name, including regeneration settings and retained style defaults.
|
||||
/// Planning reads a private clone so gathering names never changes the destination.
|
||||
fn family_names(d: &Document) -> Result<BTreeSet<String>> {
|
||||
let mut view = d.clone();
|
||||
let mut names = BTreeSet::new();
|
||||
let mut note = |family: &mut String| {
|
||||
names.insert(family.to_lowercase());
|
||||
};
|
||||
super::textstyles::each_text_mut(&mut view, &mut |text| {
|
||||
for run in &mut text.runs {
|
||||
note(&mut run.style.font_family);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) {
|
||||
if let Some(Value::String(family)) = style.attrs.get_mut("font_family") {
|
||||
note(family);
|
||||
}
|
||||
}
|
||||
let mut graphs = Vec::new();
|
||||
view.visit_stored(|node, _| {
|
||||
if node.extras().graph.is_some() {
|
||||
graphs.push(node.id);
|
||||
}
|
||||
});
|
||||
for id in graphs {
|
||||
if let Some(node) = view.stored_node_mut(id) {
|
||||
graph_families(node, &mut note);
|
||||
}
|
||||
}
|
||||
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
|
||||
graph_families(node, note);
|
||||
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
|
||||
brush_graphs(Arc::make_mut(&mut mask.art), note);
|
||||
}
|
||||
for child in node.children_mut().into_iter().flatten() {
|
||||
brush_graphs(Arc::make_mut(child), note);
|
||||
}
|
||||
}
|
||||
for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) {
|
||||
brush_graphs(art, &mut note);
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) {
|
||||
let labels = &mut graph.label_styles;
|
||||
for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() {
|
||||
visit(&mut style.font_family);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Family fields held directly by one node; the adoption walker owns tree/resource traversal.
|
||||
pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
for run in &mut text.runs {
|
||||
visit(&mut run.style.font_family);
|
||||
}
|
||||
}
|
||||
graph_families(node, visit);
|
||||
}
|
||||
|
||||
/// A fully checked incoming-only rename map and the destination's prospective definitions.
|
||||
pub(super) struct CompositeImport {
|
||||
names: BTreeMap<String, String>,
|
||||
pub(super) combined: Vec<CompositeFont>,
|
||||
}
|
||||
|
||||
impl CompositeImport {
|
||||
pub(super) fn rename(&self, family: &mut String) -> bool {
|
||||
if let Some(name) = self.names.get(&family.to_lowercase()) {
|
||||
let changed = family.as_str() != name.as_str();
|
||||
*family = name.clone();
|
||||
changed
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
|
||||
let db = FontDb::global();
|
||||
let mut number = 2_u64;
|
||||
loop {
|
||||
let suffix = format!(" {number}");
|
||||
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
|
||||
let name = format!("{}{suffix}", stem.trim_end());
|
||||
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
|
||||
&& !reserved.contains(&name.to_lowercase())
|
||||
&& !db.has_installed_family(&name)
|
||||
{
|
||||
return Ok(name);
|
||||
}
|
||||
number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Plan used incoming definitions before changing either document or the font database.
|
||||
/// Keep existing meanings even for an uninstalled family that destination art still names.
|
||||
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
|
||||
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
let mut source_names = BTreeSet::new();
|
||||
for font in &source {
|
||||
font.check().map_err(|why| bad(cmd, why))?;
|
||||
if !source_names.insert(font.name.to_lowercase()) {
|
||||
return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name)));
|
||||
}
|
||||
}
|
||||
let target_families = family_names(target)?;
|
||||
let mut target_taken = target_families.clone();
|
||||
for font in target.composite_fonts.iter() {
|
||||
target_taken.insert(font.name.to_lowercase());
|
||||
target_taken.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let mut reserved = source_families;
|
||||
reserved.extend(target_families);
|
||||
for font in source.iter().chain(target.composite_fonts.iter()) {
|
||||
reserved.insert(font.name.to_lowercase());
|
||||
reserved.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let db = FontDb::global();
|
||||
let mut names = BTreeMap::new();
|
||||
let mut combined = target.composite_fonts.to_vec();
|
||||
for font in source {
|
||||
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
|
||||
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
|
||||
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
|
||||
if needs_alias {
|
||||
// A repeated import reuses its already-installed equal alias.
|
||||
reused = target.composite_fonts.iter().find(equivalent);
|
||||
}
|
||||
let name = match reused {
|
||||
Some(other) => other.name.clone(),
|
||||
None if needs_alias => composite_alias(&font.name, &reserved, cmd)?,
|
||||
None => font.name.clone(),
|
||||
};
|
||||
reserved.insert(name.to_lowercase());
|
||||
names.insert(font.name.to_lowercase(), name.clone());
|
||||
if reused.is_none() {
|
||||
combined.push(CompositeFont { name, ..font });
|
||||
}
|
||||
}
|
||||
// A source document may currently lend fonts to the database. Validate the prospective
|
||||
// document, not composite names temporarily registered by a different document.
|
||||
if combined.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) {
|
||||
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
|
||||
}
|
||||
if CompositeFont::usable(&combined).is_some() {
|
||||
return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together"));
|
||||
}
|
||||
Ok(CompositeImport { names, combined })
|
||||
}
|
||||
|
||||
/// Register the active document's composite fonts in the font database, and remove the ones the
|
||||
/// other open documents (or an earlier active document) defined. Run after each command and when
|
||||
/// another document takes the front, so an undo, a revert, an opened or closed file or a document
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"`
|
||||
//! the objects inside them (see `appearance`).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -115,7 +116,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Move Effect",
|
||||
[],
|
||||
None,
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
has_doc,
|
||||
move_effect
|
||||
),
|
||||
@@ -678,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Can the Appearance panel reorder shared effects on the exact subjects it displays?
|
||||
/// A generated graph design or a selection normalized to different objects has no matching row.
|
||||
pub fn can_reorder_selected_effects(&self) -> bool {
|
||||
let Ok(st) = self.doc() else { return false };
|
||||
let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false };
|
||||
let selected: HashSet<_> = st.selection.subjects().iter().copied().collect();
|
||||
roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the
|
||||
/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing.
|
||||
fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option<Vec<Option<usize>>> {
|
||||
let mut seen = HashSet::with_capacity(ids.len());
|
||||
let mut appearances: Vec<&vectorcraft_doc::Appearance> =
|
||||
ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::<Option<_>>()?;
|
||||
let first = *appearances.get(anchor)?;
|
||||
if source == ItemTarget::Top {
|
||||
return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]);
|
||||
}
|
||||
let item = source.effects_item(first, "effect.move").ok()??;
|
||||
appearances.swap(0, anchor);
|
||||
let shared = SharedStack::of(&appearances);
|
||||
let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::<Option<Vec<_>>>()?;
|
||||
slots.swap(0, anchor);
|
||||
Some(slots)
|
||||
}
|
||||
|
||||
/// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s.
|
||||
fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.move";
|
||||
@@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
let roots = edit_targets(s, p, C)?;
|
||||
// Where an aligned effect would go in each of several different stacks isn't one place.
|
||||
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) {
|
||||
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
|
||||
}
|
||||
let reference = design_reference(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) {
|
||||
// An omitted item and a numbered item can use different anchors and still name the same row.
|
||||
let shared = (!copy && reference.is_none())
|
||||
.then(|| {
|
||||
shared_reorder_slots(d, &roots, src, src.anchor(s, &roots))
|
||||
.filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source))
|
||||
})
|
||||
.flatten();
|
||||
Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Where the effect landed in each object it moved in, in the order of `ids`.
|
||||
let mut landed = vec![];
|
||||
let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| {
|
||||
let mut done = vec![];
|
||||
for id in &roots {
|
||||
for (k, id) in roots.iter().enumerate() {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?);
|
||||
let (si, di) = match &slots {
|
||||
Some(slots) => (slots[k], slots[k]),
|
||||
None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?),
|
||||
};
|
||||
let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue };
|
||||
// Taken out from the top down, so the lower positions stay valid; put back in order.
|
||||
let mut taken: Vec<Effect> = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect();
|
||||
|
||||
@@ -40,6 +40,12 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_do
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "view.showMissingLinks", "Show Missing Links", ["View"], None,
|
||||
"{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}",
|
||||
has_doc, show_missing_links),
|
||||
cmd!(query "links.marked", "Marked Missing Links", [], None,
|
||||
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
|
||||
has_doc, marked),
|
||||
cmd!(
|
||||
query "links.check",
|
||||
"Check Links",
|
||||
@@ -518,6 +524,8 @@ fn refused(link: &LinkInfo, doc_path: Option<&str>) -> Option<craft_docpath::Ref
|
||||
/// the content shown. Its bytes are read only when its size or modification time changed. An image
|
||||
/// placed from a DCS file is modified when one of its plate files of their own changed.
|
||||
fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) {
|
||||
#[cfg(test)]
|
||||
probe_gate::hold(&g.link.path);
|
||||
let Some(mut f) = locate(&g.link, base) else { return (Status::Missing, None) };
|
||||
let l = &g.link;
|
||||
if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) {
|
||||
@@ -536,6 +544,24 @@ fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) {
|
||||
(if same { Status::Ok } else { Status::Modified }, Some(f))
|
||||
}
|
||||
|
||||
/// Whether [`probe`] would find group `g`'s file missing, without reading or hashing its content.
|
||||
/// A changed file is opened to check it can be read, and nothing more: the canvas markers ask only
|
||||
/// this, and with Update Links set to Manually a changed file keeps differing from its stored link,
|
||||
/// so a full probe would read the whole file again on every look while the markers are on.
|
||||
fn missing(g: &Group, base: LinkBase) -> bool {
|
||||
#[cfg(test)]
|
||||
probe_gate::hold(&g.link.path);
|
||||
let Some(f) = locate(&g.link, base) else { return true };
|
||||
let l = &g.link;
|
||||
if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) {
|
||||
return false;
|
||||
}
|
||||
if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified {
|
||||
return false;
|
||||
}
|
||||
fileio::read_file_head(&f.path, 0).is_err()
|
||||
}
|
||||
|
||||
/// Is image `key` of `d` showing its preview (its file not read)?
|
||||
fn previewing(d: &Document, key: &str) -> bool {
|
||||
d.images.get(key).is_none_or(ImageBlob::is_proxy)
|
||||
@@ -2159,6 +2185,7 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))
|
||||
})?;
|
||||
}
|
||||
clear_markers(s, &updated)?;
|
||||
let mut out = json!({ "updated": updated, "missing": missing });
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
@@ -2451,6 +2478,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
not_found.sort();
|
||||
not_found.dedup();
|
||||
clear_markers(s, &relinked)?;
|
||||
let mut out = json!({ "relinked": relinked, "notFound": not_found });
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
@@ -2630,6 +2658,56 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option
|
||||
out
|
||||
}
|
||||
|
||||
/// Missing placed objects, using the same file resolution as the Links panel. Hidden ones are
|
||||
/// included: [`crate::DocState::marked_missing_links`] leaves out what is hidden when it is drawn, so
|
||||
/// artwork shown later is marked without another scan. Also used on the link watch worker, away
|
||||
/// from the UI thread.
|
||||
pub(crate) fn missing_markers(doc: &Document, base: LinkBase) -> Vec<NodeId> {
|
||||
groups(doc, None).iter().filter(|g| !g.ids.is_empty() && missing(g, base)).flat_map(|g| g.ids.iter().copied()).collect()
|
||||
}
|
||||
|
||||
fn show_missing_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
let on = super::switch_or(p, "on", !st.show_missing_links, "view.showMissingLinks")?;
|
||||
// Never probes files here: a changed linked file is read in full to tell whether it still
|
||||
// matches, which would hold up the caller (the desktop UI thread) on a large or slow file.
|
||||
// Turning the overlay on leaves its markers unscanned; the link watch worker scans them
|
||||
// at once ([`Session::missing_link_scan_due`]) and the canvas repaints from its result.
|
||||
// `links.marked` stays the explicit, synchronous inspection. The web build has no worker
|
||||
// and no files to read: its app marks them in place ([`Session::mark_missing_links_in_place`]).
|
||||
if !on || !st.show_missing_links {
|
||||
st.missing_link_markers = None;
|
||||
}
|
||||
st.show_missing_links = on;
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
|
||||
fn marked(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
let ids = if st.show_missing_links { missing_markers(&st.doc, LinkBase::of(st)) } else { vec![] };
|
||||
let images: Vec<Value> = ids
|
||||
.iter()
|
||||
.filter(|id| st.doc.is_visible(**id))
|
||||
.filter_map(|id| {
|
||||
let b = st.doc.node(*id)?.geometric_bounds()?;
|
||||
Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
|
||||
})
|
||||
.collect();
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
Ok(json!({"on": st.show_missing_links, "images": images}))
|
||||
}
|
||||
|
||||
/// Successful repair clears its decoration even when the file's metadata is unchanged.
|
||||
fn clear_markers(s: &mut Session, repaired: &[u64]) -> Result<()> {
|
||||
if !repaired.is_empty()
|
||||
&& let Some((_, ids)) = &mut s.doc_mut()?.missing_link_markers
|
||||
{
|
||||
let repaired: std::collections::HashSet<_> = repaired.iter().copied().collect();
|
||||
ids.retain(|id| !repaired.contains(&id.0));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The format of the file image `im` of `d` shows: its link's extension, else its pixels' type.
|
||||
fn format_label(d: &Document, im: &ImageObject) -> &'static str {
|
||||
if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_separated) {
|
||||
@@ -3319,6 +3397,64 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(shown) }))
|
||||
}
|
||||
|
||||
/// Test seam: hold the probe of one linked path until the test releases it, so a test can
|
||||
/// tell whether a command returned before the probe finished, and on which thread it ran.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod probe_gate {
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A gated path: (open, entered on thread named, finished), and the condition signalling
|
||||
/// each change.
|
||||
#[derive(Default)]
|
||||
pub struct Gate {
|
||||
state: Mutex<(bool, Option<String>, bool)>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
static GATES: Mutex<Vec<(String, Arc<Gate>)>> = Mutex::new(Vec::new());
|
||||
|
||||
impl Gate {
|
||||
/// Gate probes of the link stored as `path` until [`Gate::open`].
|
||||
pub fn close(path: &str) -> Arc<Gate> {
|
||||
let g = Arc::new(Gate::default());
|
||||
GATES.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), g.clone()));
|
||||
g
|
||||
}
|
||||
pub fn open(&self) {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).0 = true;
|
||||
self.changed.notify_all();
|
||||
}
|
||||
/// The name of the thread that entered the probe, waiting up to `limit` for one.
|
||||
pub fn entered(&self, limit: Duration) -> Option<String> {
|
||||
let s = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let (s, _) = self.changed.wait_timeout_while(s, limit, |s| s.1.is_none()).unwrap_or_else(PoisonError::into_inner);
|
||||
s.1.clone()
|
||||
}
|
||||
pub fn finished(&self) -> bool {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).2
|
||||
}
|
||||
}
|
||||
|
||||
/// Called at the start of every probe: blocks while `path` is gated and closed (at most
|
||||
/// ten seconds, so a regression fails the test instead of hanging it).
|
||||
pub(super) fn hold(path: &str) {
|
||||
let gate = GATES.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, g)| g.clone());
|
||||
let Some(g) = gate else { return };
|
||||
let mut s = g.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
s.1 = Some(std::thread::current().name().unwrap_or("").to_string());
|
||||
g.changed.notify_all();
|
||||
let (mut s, _) = g.changed.wait_timeout_while(s, Duration::from_secs(10), |s| !s.0).unwrap_or_else(PoisonError::into_inner);
|
||||
s.2 = true;
|
||||
g.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Stop gating `path`.
|
||||
pub fn remove(path: &str) {
|
||||
GATES.lock().unwrap_or_else(PoisonError::into_inner).retain(|(p, _)| p != path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Blend"],
|
||||
Some("Cmd+Alt+B"),
|
||||
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
|
||||
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way. A start anchor makes rectangles blend anchor by anchor.), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
|
||||
has_doc,
|
||||
blend_make
|
||||
),
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform",
|
||||
[],
|
||||
None,
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects), and a matrix that only moves them moves the uncut corners of a path with rounded Live Corners, which is cut again at its radii; strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
has_doc,
|
||||
transform
|
||||
),
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move…",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+Shift+M"),
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box. On a path with rounded Live Corners, the uncut corner of each selected anchor moves by (dx, dy) and is cut again at its radius.",
|
||||
has_selection_or_guides,
|
||||
move_cmd
|
||||
),
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy (a move by 0 changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with rounded Live Corners, each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target; refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it",
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with rounded Live Corners, the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y)",
|
||||
has_doc,
|
||||
move_anchor
|
||||
),
|
||||
@@ -176,6 +176,118 @@ pub(super) fn path_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
/// Transform `anchors` of path `id` by `xf` when the path has cut Live Corners: the anchors of its
|
||||
/// uncut outline move (with `interpolate` and a move, as [`move_interpolating_handles`] moves
|
||||
/// them) and the corners are cut again with the same radii, so they stay live
|
||||
/// ([`vectorcraft_doc::edit_corner_anchors`]). Returns `None`, changing nothing, for a path
|
||||
/// without cut corners.
|
||||
fn transform_live_corner_anchors(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
id: NodeId,
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
interpolate: bool,
|
||||
) -> Option<()> {
|
||||
let NodeKind::Path { path, live, .. } = &mut d.node_mut(id)?.kind else { return None };
|
||||
let c = xf.as_coeffs();
|
||||
vectorcraft_doc::edit_corner_anchors(path, live, anchors, |base, set| {
|
||||
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
move_interpolating_handles(base, set, Vec2::new(c[4], c[5]));
|
||||
} else {
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = base.anchor_mut(si, ai) {
|
||||
*a = a.transform(xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// For each anchor of path `id` as drawn (per subpath), the anchor of its uncut outline it comes
|
||||
/// from ([`vectorcraft_doc::LiveCorners::sources`]), or `None` when `id` is not a path.
|
||||
fn corner_sources(d: &Document, id: NodeId) -> Option<Vec<Vec<usize>>> {
|
||||
let NodeKind::Path { path, live, .. } = &d.node(id)?.kind else { return None };
|
||||
Some(vectorcraft_doc::LiveCorners::new(path, live.as_deref())?.sources().to_vec())
|
||||
}
|
||||
|
||||
/// After the anchors of path `id` as drawn changed from `before` to `after` (each listing the
|
||||
/// corners they come from, as [`corner_sources`] gives them), point the selected anchors and the
|
||||
/// key anchor of `sel` on that path at the anchors of the same corners, and drop the path's
|
||||
/// selected segments. An unchanged layout leaves `sel` as it is.
|
||||
fn remap_corner_anchors(sel: &mut Selection, id: NodeId, before: &[Vec<usize>], after: &[Vec<usize>]) {
|
||||
if before == after {
|
||||
return;
|
||||
}
|
||||
let source = |(si, ai): AnchorRef| before.get(si).and_then(|v| v.get(ai)).copied();
|
||||
let drawn =
|
||||
|k: usize| after.iter().enumerate().flat_map(move |(si, v)| v.iter().enumerate().filter(move |(_, s)| **s == k).map(move |(ai, _)| (si, ai)));
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
let corners: BTreeSet<usize> = set.iter().filter_map(|r| source(*r)).collect();
|
||||
*set = corners.into_iter().flat_map(drawn).collect();
|
||||
}
|
||||
if let Some((key, r)) = sel.key_anchor
|
||||
&& key == id
|
||||
{
|
||||
sel.key_anchor = source(r).and_then(|k| drawn(k).next()).map(|r| (id, r));
|
||||
}
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
|
||||
/// Snap pixel-aligned path `id`, or the pixel-aligned compound path that holds it, to the pixel
|
||||
/// grid again, with `sel` following its anchors when the snap cuts its Live Corners again with a
|
||||
/// different layout ([`remap_corner_anchors`]).
|
||||
fn snap_keeping_selection(d: &mut Document, id: NodeId, sel: &mut Selection, before: Option<&[Vec<usize>]>) {
|
||||
let top = compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
if let (Some(before), Some(after)) = (before, corner_sources(d, id)) {
|
||||
remap_corner_anchors(sel, id, before, &after);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `apply` on a copy of the active document, followed by the pixel-grid snap that
|
||||
/// [`Session::edit`] makes, leaves the document as it was (a nudge that the snap of a
|
||||
/// pixel-aligned path takes back). Without a pixel-aligned path among `ids` (or a compound path
|
||||
/// holding one) the answer is `false` without trying. An anchor edit turns a live rectangle or
|
||||
/// polygon into a live path with the same outline, radii and kinds; that conversion alone counts
|
||||
/// as no change, while any change to the uncut outline or the corner settings still counts.
|
||||
fn snap_undoes(s: &Session, ids: impl IntoIterator<Item = NodeId>, apply: impl FnOnce(&mut Document, &mut Selection) -> Result<()>) -> Result<bool> {
|
||||
let st = s.doc()?;
|
||||
let ids: Vec<NodeId> = ids.into_iter().collect();
|
||||
if !ids.iter().any(|&id| st.doc.node(compound_or_self(&st.doc, id)).is_some_and(|n| n.extras().pixel_aligned)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut doc = (*st.doc).clone();
|
||||
let mut sel = st.selection.clone();
|
||||
apply(&mut doc, &mut sel)?;
|
||||
super::refresh_pixel_aligned(&st.doc, &mut doc);
|
||||
for &id in &ids {
|
||||
let (Some(NodeKind::Path { path, live, .. }), Some(anchors)) = (st.doc.node(id).map(|n| &n.kind), st.selection.anchors.get(&id)) else {
|
||||
continue;
|
||||
};
|
||||
// A live path keeps its variant through an anchor edit, so only a rectangle or polygon
|
||||
// needs the comparison below.
|
||||
if !matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Rectangle { .. } | vectorcraft_doc::LiveShape::Polygon { .. })) {
|
||||
continue;
|
||||
}
|
||||
// The path and live shape the same anchors, left where they are, would turn this path
|
||||
// into. The drawn path is cut from the live shape, and a recut can differ from the stored
|
||||
// path by rounding, so the live shapes are compared and both fields are restored.
|
||||
let (mut converted_path, mut converted) = (path.clone(), live.clone());
|
||||
if vectorcraft_doc::edit_corner_anchors(&mut converted_path, &mut converted, anchors, |_, _| {}).is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some(NodeKind::Path { path: after_path, live: after, .. }) = doc.node_mut(id).map(|n| &mut n.kind)
|
||||
&& *after == converted
|
||||
{
|
||||
after.clone_from(live);
|
||||
after_path.clone_from(path);
|
||||
}
|
||||
}
|
||||
Ok(doc == *st.doc)
|
||||
}
|
||||
|
||||
fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "path.appendAnchor")?.ok_or_else(|| bad("path.appendAnchor", "missing id"))?;
|
||||
let a = anchor_from_json(p, "path.appendAnchor")?;
|
||||
@@ -278,6 +390,13 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut sel = st.selection.clone();
|
||||
let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) };
|
||||
// A path with a curved segment that bends or holds its anchors is edited anchor by anchor, so
|
||||
// the segment indices found above stay valid.
|
||||
let plain: BTreeSet<NodeId> = bends
|
||||
.iter()
|
||||
.map(|b| b.0)
|
||||
.chain(sel.anchors.iter().filter(|(id, set)| st.selection.anchors.get(id) != Some(*set)).map(|(id, _)| *id))
|
||||
.collect();
|
||||
// Segments that hold their anchors and don't bend, with nothing else to move, change nothing.
|
||||
if held && bends.is_empty() && sel.whole().is_empty() && sel.guides.is_empty() && sel.anchors.values().all(BTreeSet::is_empty) {
|
||||
return ok();
|
||||
@@ -286,15 +405,21 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
|
||||
// `patterns` (default: General › Transform Pattern Tiles) is on.
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &sel.whole())?, ..Scaling::default() };
|
||||
let interpolate = interpolates_handles(s, p, C)?;
|
||||
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, |doc, _| {
|
||||
transform_selected(doc, &sel, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
let apply = |doc: &mut Document, live: &mut Selection| -> Result<()> {
|
||||
transform_selected(doc, &sel, live, &plain, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
for &(id, si, seg) in &bends {
|
||||
if let Some(sp) = path_mut(doc, id)?.subpaths.get_mut(si) {
|
||||
sp.nudge_segment(seg, d);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
};
|
||||
// Anchors and objects selected whole that the pixel-grid snap puts back where they were change
|
||||
// nothing, and record no undo step.
|
||||
if sel.guides.is_empty() && snap_undoes(s, sel.anchors.keys().copied().chain(sel.whole()), apply)? {
|
||||
return ok();
|
||||
}
|
||||
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, apply)?;
|
||||
// Transform Again repeats a move that moved something; a drag records it when it commits. A
|
||||
// move that held segments' anchors is not one move of the selection.
|
||||
let st = s.doc_mut()?;
|
||||
@@ -350,7 +475,7 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
s.edit(label, |doc, live| {
|
||||
transform_selected(doc, &sel, xf, sc, interpolate)?;
|
||||
transform_selected(doc, &sel, live, &BTreeSet::new(), xf, sc, interpolate)?;
|
||||
Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) })
|
||||
})
|
||||
}
|
||||
@@ -359,14 +484,32 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
/// objects selected whole (those with no entry in `sel`'s `anchors`). An object inside
|
||||
/// another selected object, such as a path in a selected group, moves once, with that object.
|
||||
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
|
||||
/// are re-mapped ([`move_interpolating_handles`]).
|
||||
fn transform_selected(doc: &mut Document, sel: &Selection, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
/// are re-mapped ([`move_interpolating_handles`]). A path with rounded Live Corners keeps them
|
||||
/// ([`transform_live_corner_anchors`]), and `live_sel` follows its anchors when the recut changes
|
||||
/// them, except for the paths in `plain`, which are edited anchor by anchor.
|
||||
fn transform_selected(
|
||||
doc: &mut Document,
|
||||
sel: &Selection,
|
||||
live_sel: &mut Selection,
|
||||
plain: &BTreeSet<NodeId>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
sc: Scaling,
|
||||
interpolate: bool,
|
||||
) -> Result<()> {
|
||||
let ids = super::edit::outermost(doc, sel.objects.clone());
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
let delta = vectorcraft_geom::Vec2::new(c[4], c[5]);
|
||||
for id in &ids {
|
||||
match sel.anchors.get(id) {
|
||||
Some(set)
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0]
|
||||
&& !plain.contains(id)
|
||||
&& let Some(before) = corner_sources(doc, *id)
|
||||
&& transform_live_corner_anchors(doc, *id, set, xf, interpolate).is_some() =>
|
||||
{
|
||||
snap_keeping_selection(doc, *id, live_sel, Some(&before));
|
||||
}
|
||||
Some(set) => {
|
||||
let path = path_mut(doc, *id)?;
|
||||
// Only an exact move takes the interpolating path: a near-identity scale or
|
||||
@@ -798,16 +941,19 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return ok();
|
||||
}
|
||||
s.edit("Move", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps to the
|
||||
// pixel grid again.
|
||||
let top = compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
s.edit("Move", |d, sel| {
|
||||
let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p);
|
||||
let before = corner_sources(d, id);
|
||||
let moved = BTreeSet::from([(si, ai)]);
|
||||
let kept = old.and_then(|p0| transform_live_corner_anchors(d, id, &moved, vectorcraft_geom::Affine::translate(pos - p0), false));
|
||||
if kept.is_none() {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
}
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps to the
|
||||
// pixel grid again, and the selection follows a path whose corners were cut again.
|
||||
snap_keeping_selection(d, id, sel, kept.and(before.as_deref()));
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -578,7 +578,7 @@ fn art_of<'a>(nodes: impl Iterator<Item = &'a Arc<Node>>) -> Vec<Node> {
|
||||
}
|
||||
|
||||
/// The art as one object of `d` (its resources added), at its natural size and position.
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Result<Node> {
|
||||
let mut node = match l.art {
|
||||
Art::Image(img, clip) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
@@ -613,7 +613,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))),
|
||||
Art::Document(s, link, bounding) => document::node(d, &s, link, bounding),
|
||||
Art::Vector { src, mut nodes, clip } => {
|
||||
adopt::adopt(d, &src, &mut nodes);
|
||||
adopt::adopt(d, &src, &mut nodes, PLACE)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = clip {
|
||||
children.insert(0, Arc::new(clip_path(d.alloc_id(), r)));
|
||||
@@ -622,7 +622,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
}
|
||||
};
|
||||
node.name = Some(l.name);
|
||||
node
|
||||
Ok(node)
|
||||
}
|
||||
|
||||
/// `node` moved and scaled by `m` as a whole: strokes, effects and pattern tiles go along.
|
||||
@@ -817,22 +817,86 @@ impl Session {
|
||||
if self.doc()?.uid != read.job.doc {
|
||||
return Err(bad(PLACE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
// Deleted, changed, or another object with its id: an undo that removes the object frees
|
||||
// its id for the next object made.
|
||||
if st.doc.node(old) != read.job.replaced.as_ref() {
|
||||
// Keep the asynchronous target check against the drawing currently on show.
|
||||
if self.doc()?.doc.node(old) != read.job.replaced.as_ref() {
|
||||
return Err(bad(PLACE, "replace: the object to replace was changed or deleted"));
|
||||
}
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
// Provisional reselection and placement are one outside command. Deferring their
|
||||
// notifications must not make an asynchronous handoff part of an unrelated tool drag.
|
||||
if self.depth == 0 && !self.previewing && !self.in_tool_actions {
|
||||
self.command_with_settled_warnings(|s| s.outside_interaction(PLACE, ¶ms, |s| s.place_read_handoff(read, ¶ms)))
|
||||
} else {
|
||||
self.place_read_handoff(read, ¶ms)
|
||||
}
|
||||
}
|
||||
|
||||
fn place_read_handoff(&mut self, read: PlaceRead, params: &Value) -> Result<Value> {
|
||||
let mut rollback = None;
|
||||
let mut reselect = None;
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
if st.selection.objects != [old] || st.selection.symbol_part.is_some() {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
// Adoption may now fail. Its provisional selection must not escape that error.
|
||||
rollback = Some((
|
||||
self.active,
|
||||
st.clone(),
|
||||
self.paint.clone(),
|
||||
self.fill_active,
|
||||
self.pending_paint.clone(),
|
||||
self.active_appearance_item.clone(),
|
||||
self.batch_paint_docs.clone(),
|
||||
self.journal.len(),
|
||||
self.journal.held(),
|
||||
));
|
||||
self.journal.hold(Some(self.journal.first_kept()));
|
||||
reselect = Some(old);
|
||||
}
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
let r = self.execute(PLACE, ¶ms);
|
||||
let outer_tool_actions = self.in_tool_actions;
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = true;
|
||||
}
|
||||
let result = (|| {
|
||||
if let Some(old) = reselect {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
self.execute(PLACE, params)
|
||||
})();
|
||||
self.place_hand_off = None;
|
||||
r
|
||||
if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback {
|
||||
if result.is_err() {
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == before.uid) {
|
||||
let revision = st.revision.max(before.revision);
|
||||
*st = before;
|
||||
st.revision = revision + 1;
|
||||
}
|
||||
self.active = active;
|
||||
self.paint = paint;
|
||||
self.fill_active = fill_active;
|
||||
self.pending_paint = pending;
|
||||
self.active_appearance_item = appearance;
|
||||
self.batch_paint_docs = paint_docs;
|
||||
self.journal.truncate(journal);
|
||||
for group in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) {
|
||||
group.journal.retain(|&(n, _)| n < journal);
|
||||
group.steps.retain(|&(n, _)| n < journal);
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
self.sync_front_profiles();
|
||||
super::compositefonts::sync(self);
|
||||
}
|
||||
self.journal.hold(held);
|
||||
}
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = outer_tool_actions;
|
||||
self.after_command(result.is_ok().then_some(PLACE));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,7 +1062,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let mut node = transformed(build(d, loaded, link), m);
|
||||
let mut node = transformed(build(d, loaded, link)?, m);
|
||||
if let Some((old_image, (_, q, _))) = distorted {
|
||||
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
|
||||
}
|
||||
@@ -1266,7 +1330,7 @@ fn thumbnail_png(l: Loaded, px: f64) -> Result<String> {
|
||||
let natural = l.natural;
|
||||
let mut d = Document::new(natural.width().max(1.0), natural.height().max(1.0));
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
let node = build(&mut d, l, None);
|
||||
let node = build(&mut d, l, None)?;
|
||||
d.insert(layer, 0, node)?;
|
||||
let k = px.clamp(1.0, MAX_THUMBNAIL) / natural.width().max(natural.height()).max(1e-9);
|
||||
let png = vectorcraft_render::Renderer::new().render_region(&d, natural, k, false).to_png().map_err(EngineError::Other)?;
|
||||
|
||||
@@ -5,13 +5,16 @@
|
||||
//! defines differently keeps its colour, unlinked. Text styles are left as they are: the art carries
|
||||
//! its own formatting.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::super::Result;
|
||||
use super::super::clipboard::SymbolOptions;
|
||||
use super::super::compositefonts::{CompositeImport, node_families, plan_import};
|
||||
use super::unique_name;
|
||||
|
||||
/// Visit `n` and every descendant (children and opacity-mask art) mutably.
|
||||
@@ -52,9 +55,56 @@ fn paint_refs(p: &mut Paint, f: &mut impl FnMut(Ref)) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Visit only the records the shared reader accepted, in their original order. Consuming
|
||||
/// each accepted record once also leaves ignored duplicate surfaces and capped records alone.
|
||||
fn accepted_graphic_refs<T: PartialEq>(
|
||||
list: &mut serde_json::Value,
|
||||
accepted: Vec<T>,
|
||||
parse: impl Fn(&serde_json::Value) -> Option<T>,
|
||||
f: &mut impl FnMut(Ref),
|
||||
) {
|
||||
let Some(list) = list.as_array_mut() else { return };
|
||||
let mut accepted = accepted.into_iter().peekable();
|
||||
for value in list {
|
||||
let Some(next) = accepted.peek() else { break };
|
||||
if parse(value).as_ref() != Some(next) {
|
||||
continue;
|
||||
}
|
||||
let _ = accepted.next();
|
||||
if let Some(serde_json::Value::String(symbol)) = value.get_mut("symbol") {
|
||||
f(Ref::Symbol(symbol));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol references in accepted Graphics and Map Art records, including fill/stroke effects.
|
||||
/// Each stored name is visited once, so a rename cannot feed a second rename in the same map.
|
||||
fn appearance_graphic_refs(appearance: &mut vectorcraft_doc::Appearance, f: &mut impl FnMut(Ref)) {
|
||||
use vectorcraft_render::effects as fx;
|
||||
|
||||
if fx::appearance_graphic_symbols(appearance).is_empty() {
|
||||
return;
|
||||
}
|
||||
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
|
||||
for effect in effects.iter_mut().chain(items.iter_mut().flat_map(|item| item.effects_mut())) {
|
||||
if fx::takes_graphics(&effect.id) {
|
||||
let accepted = fx::mapped_graphics(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::GRAPHICS) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::MappedGraphic::from_value(value).ok(), f);
|
||||
}
|
||||
} else if fx::takes_map_art(&effect.id) {
|
||||
let accepted = fx::surface_maps(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::MAP_ART) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::SurfaceMap::from_value(value).ok(), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every resource reference in `n` and its descendants.
|
||||
fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
each_mut(n, &mut |n| {
|
||||
appearance_graphic_refs(&mut n.appearance, f);
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(fl) => paint_refs(&mut fl.paint, f),
|
||||
@@ -71,6 +121,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
for r in &mut t.runs {
|
||||
paint_refs(&mut r.style.fill, f);
|
||||
paint_refs(&mut r.style.stroke, f);
|
||||
if let Some(inline) = &mut r.inline {
|
||||
f(Ref::Symbol(&mut inline.symbol));
|
||||
}
|
||||
}
|
||||
if let Some(fonts) = &mut t.file_fonts {
|
||||
fonts.map_keys(|key| f(Ref::Image(key)));
|
||||
@@ -81,6 +134,14 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(extras) = n.extras_if_any() {
|
||||
extras
|
||||
.symbol_overrides
|
||||
.iter_mut()
|
||||
.flat_map(|override_| [&mut override_.fill, &mut override_.stroke])
|
||||
.flatten()
|
||||
.for_each(|paint| paint_refs(paint, f));
|
||||
}
|
||||
// A color-masked image's masked pixels come along, and the key they were made from
|
||||
// follows the image's.
|
||||
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
|
||||
@@ -162,7 +223,16 @@ fn canon(dst: &Document, n: &Node) -> Node {
|
||||
own.images.insert(k.clone(), blob.clone());
|
||||
}
|
||||
}
|
||||
own.reid(n)
|
||||
let mut canonical = own.reid(n);
|
||||
// Derived layout caches do not define the stored art's resource identity.
|
||||
each_mut(&mut canonical, &mut |node| {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
text.cached_bounds = None;
|
||||
text.cached_baselines.clear();
|
||||
text.cached_ink = None;
|
||||
}
|
||||
});
|
||||
canonical
|
||||
}
|
||||
|
||||
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
@@ -220,12 +290,273 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
/// Apply the final resource-name plan to one incoming reference.
|
||||
fn rename_ref(r: Ref<'_>, maps: [&Renames; 5]) {
|
||||
let (map, key) = match r {
|
||||
Ref::Image(key) => (maps[0], key),
|
||||
Ref::Symbol(key) => (maps[1], key),
|
||||
Ref::Pattern(key) => (maps[2], key),
|
||||
Ref::Brush(key) => (maps[3], key),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|key| maps[4].get(key)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(key.as_str()) {
|
||||
*key = new.clone();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum ResourceKind {
|
||||
Symbol,
|
||||
Pattern,
|
||||
Brush,
|
||||
}
|
||||
|
||||
type ResourceKey = (ResourceKind, String);
|
||||
|
||||
/// A source definition's dependencies whose planned names have not been finalized yet.
|
||||
fn pending_dependencies(key: &ResourceKey, src: &Document, brushes: &[Brush], pending: &BTreeSet<ResourceKey>) -> BTreeSet<ResourceKey> {
|
||||
let mut dependencies = BTreeSet::new();
|
||||
let mut note = |r: Ref<'_>| {
|
||||
let key = match r {
|
||||
Ref::Symbol(name) => (ResourceKind::Symbol, name.clone()),
|
||||
Ref::Pattern(name) => (ResourceKind::Pattern, name.clone()),
|
||||
Ref::Brush(name) => (ResourceKind::Brush, name.clone()),
|
||||
Ref::Image(_) | Ref::Swatch(_) => return,
|
||||
};
|
||||
if pending.contains(&key) {
|
||||
dependencies.insert(key);
|
||||
}
|
||||
};
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
if let Some(symbol) = src.symbols.iter().find(|symbol| symbol.name == key.1) {
|
||||
refs(&mut (*symbol.art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
if let Some(pattern) = src.pattern(&key.1) {
|
||||
for art in &pattern.art {
|
||||
refs(&mut (**art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
if let Some(mut brush) = brushes.iter().find(|brush| brush.name == key.1).cloned() {
|
||||
for art in brush_art(&mut brush) {
|
||||
refs(art, &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dependencies
|
||||
}
|
||||
|
||||
/// Prefer the original name, then only canonical numbered variants from `unique_name`.
|
||||
/// A free original name keeps its planned copy; another incoming name is never stolen.
|
||||
fn matching_name<T>(base: &str, definitions: &[T], used: &[String], name: impl Fn(&T) -> &str, same: impl Fn(&T) -> bool) -> Option<String> {
|
||||
let original = definitions.iter().find(|definition| name(definition) == base)?;
|
||||
if same(original) {
|
||||
return Some(base.to_string());
|
||||
}
|
||||
let prefix = format!("{base} ");
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut aliases: Vec<_> = definitions
|
||||
.iter()
|
||||
.filter_map(|definition| {
|
||||
let candidate = name(definition);
|
||||
// Match the first definition, as the document name lookups do.
|
||||
if !seen.insert(candidate.to_string()) {
|
||||
return None;
|
||||
}
|
||||
let suffix = candidate.strip_prefix(&prefix)?;
|
||||
if suffix.starts_with('0') || !suffix.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let number = suffix.parse::<u64>().ok()?;
|
||||
(number >= 2 && !used.iter().any(|used| used == candidate)).then_some((number, definition))
|
||||
})
|
||||
.collect();
|
||||
aliases.sort_unstable_by_key(|(number, _)| *number);
|
||||
aliases.into_iter().find_map(|(_, definition)| same(definition).then(|| name(definition).to_string()))
|
||||
}
|
||||
|
||||
/// Compare final incoming content, not the original references or destination's resource name.
|
||||
fn reusable_name(
|
||||
key: &ResourceKey,
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
maps: [&Renames; 5],
|
||||
) -> Option<String> {
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?;
|
||||
let mut incoming = source.clone();
|
||||
refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps));
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.symbols,
|
||||
&used.symbols,
|
||||
|symbol| &symbol.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_symbol(dst, &normalized, &incoming) && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
let mut incoming = src.pattern(&key.1)?.clone();
|
||||
for art in &mut incoming.art {
|
||||
refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps));
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.patterns,
|
||||
&used.patterns,
|
||||
|pattern| &pattern.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_pattern(dst, &normalized, &incoming)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone();
|
||||
for art in brush_art(&mut incoming) {
|
||||
refs(art, &mut |r| rename_ref(r, maps));
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
dst_brushes,
|
||||
&used.brushes,
|
||||
|brush| &brush.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
for art in brush_art(&mut normalized) {
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
normalized == incoming
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalize each copied definition only after its copied dependencies. Each key/edge is
|
||||
/// processed once; a cycle (and its unresolved parents) conservatively keeps the planned copies.
|
||||
fn reuse_remapped_resources(
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
fixed: [&Renames; 2],
|
||||
changing: [&mut Renames; 3],
|
||||
) {
|
||||
let [symbols, patterns, brushes] = changing;
|
||||
let mut pending = BTreeSet::new();
|
||||
for (kind, map) in [(ResourceKind::Symbol, &*symbols), (ResourceKind::Pattern, &*patterns), (ResourceKind::Brush, &*brushes)] {
|
||||
pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone())));
|
||||
}
|
||||
let mut waiting = BTreeMap::new();
|
||||
let mut parents: BTreeMap<ResourceKey, Vec<ResourceKey>> = BTreeMap::new();
|
||||
let mut ready = BTreeSet::new();
|
||||
for key in &pending {
|
||||
let dependencies = pending_dependencies(key, src, src_brushes, &pending);
|
||||
if dependencies.is_empty() {
|
||||
ready.insert(key.clone());
|
||||
}
|
||||
waiting.insert(key.clone(), dependencies.len());
|
||||
for dependency in dependencies {
|
||||
parents.entry(dependency).or_default().push(key.clone());
|
||||
}
|
||||
}
|
||||
while let Some(key) = ready.pop_first() {
|
||||
let maps = [fixed[0], &*symbols, &*patterns, &*brushes, fixed[1]];
|
||||
if let Some(name) = reusable_name(&key, dst, src, src_brushes, dst_brushes, used, maps) {
|
||||
let map = match key.0 {
|
||||
ResourceKind::Symbol => &mut *symbols,
|
||||
ResourceKind::Pattern => &mut *patterns,
|
||||
ResourceKind::Brush => &mut *brushes,
|
||||
};
|
||||
map.insert(key.1.clone(), (Some(name), false));
|
||||
}
|
||||
for parent in parents.remove(&key).into_iter().flatten() {
|
||||
if let Some(count) = waiting.get_mut(&parent) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
ready.insert(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap only incoming users before resource equality decides whether to share or copy.
|
||||
/// Report actual family renaming for the final copied-resource reuse phase.
|
||||
fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) {
|
||||
let mut staged = src.clone();
|
||||
let mut aliased = false;
|
||||
for node in nodes.iter_mut() {
|
||||
each_mut(node, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) {
|
||||
each_mut(Arc::make_mut(&mut symbol.art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) {
|
||||
for art in &mut pattern.art {
|
||||
each_mut(Arc::make_mut(art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) {
|
||||
for art in brush_art(brush) {
|
||||
each_mut(art, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
(staged, aliased)
|
||||
}
|
||||
|
||||
/// Discover the incoming resource frontier and its composite-font users before planning
|
||||
/// names or changing either document. Resource order and the no-composite fast path stay shared.
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, BTreeSet<String>) {
|
||||
let mut used = Used::default();
|
||||
let composites = !src.composite_fonts.is_empty();
|
||||
let mut families = BTreeSet::new();
|
||||
let mut note_family = |name: &mut String| {
|
||||
families.insert(name.to_lowercase());
|
||||
};
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(n, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
let src_brushes = vectorcraft_brush::library(src);
|
||||
// Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while
|
||||
@@ -254,8 +585,29 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
}
|
||||
for mut a in art {
|
||||
refs(&mut a, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
}
|
||||
(used, src_brushes, families)
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes);
|
||||
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
|
||||
// All representability/validation errors precede incoming or destination mutation.
|
||||
let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
|
||||
let staged;
|
||||
let mut aliased = false;
|
||||
let src = if let Some(plan) = &plan {
|
||||
(staged, aliased) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan);
|
||||
&staged
|
||||
} else {
|
||||
src
|
||||
};
|
||||
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
|
||||
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
|
||||
@@ -264,7 +616,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
&used.symbols,
|
||||
|n| src.symbols.iter().find(|s| s.name == n),
|
||||
|n| dst.symbols.iter().find(|s| s.name == n),
|
||||
|a, b| same_symbol(dst, a, b),
|
||||
|a, b| same_symbol(dst, a, b) && SymbolOptions::of(dst, &a.name) == SymbolOptions::of(src, &b.name),
|
||||
|c| dst.symbols.iter().any(|s| s.name == c),
|
||||
);
|
||||
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
|
||||
@@ -330,23 +682,14 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
|
||||
}
|
||||
|
||||
let mut rename = |r: Ref| {
|
||||
let (map, k) = match r {
|
||||
Ref::Image(k) => (&images, k),
|
||||
Ref::Symbol(k) => (&symbols, k),
|
||||
Ref::Pattern(k) => (&patterns, k),
|
||||
Ref::Brush(k) => (&brushes, k),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|k| swatches.get(k)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(k.as_str()) {
|
||||
*k = new.clone();
|
||||
}
|
||||
};
|
||||
if aliased || symbols.values().any(|(_, copy)| *copy) {
|
||||
reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]);
|
||||
}
|
||||
|
||||
if let Some(plan) = plan {
|
||||
dst.composite_fonts = plan.combined.into();
|
||||
}
|
||||
let mut rename = |r: Ref| rename_ref(r, [&images, &symbols, &patterns, &brushes, &swatches]);
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut rename);
|
||||
}
|
||||
@@ -375,6 +718,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
|
||||
def.art = Arc::new(dst.reid(&def.art));
|
||||
dst.symbols.push(def);
|
||||
SymbolOptions::of(src, old).give(dst, new);
|
||||
}
|
||||
}
|
||||
for (old, new) in copies(&patterns) {
|
||||
@@ -406,4 +750,5 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
dst.swatches.push(w);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -178,6 +178,10 @@ fn opened_document_art(
|
||||
super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false);
|
||||
}
|
||||
l.doc.drop_edit_modes();
|
||||
// Measure and crop in this source's composite fonts, not those of the front document.
|
||||
// The existing thread-local loan restores its caller's context on every return or unwind.
|
||||
let source_fonts = l.doc.composite_fonts.clone();
|
||||
let _source_fonts = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts);
|
||||
// The native file does not store type's layout bounds. Measure them before cropping or
|
||||
// copying the art, so the placed group keeps the positions of aligned point type.
|
||||
for warning in crate::Session::refresh_text_bounds(&mut l.doc) {
|
||||
@@ -544,7 +548,7 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, cmd)?;
|
||||
let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?;
|
||||
let mut nodes = a.nodes;
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes);
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes, cmd)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = a.clip {
|
||||
children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r)));
|
||||
|
||||
@@ -750,6 +750,7 @@ pub const SWITCHING_LABELS: &[&str] = &[
|
||||
"Lock Guides",
|
||||
"Hide Slices",
|
||||
"Show Print Tiling",
|
||||
"Show Missing Links",
|
||||
"Lock Grid",
|
||||
"Edit Envelope",
|
||||
"Edit Contents",
|
||||
@@ -980,6 +981,8 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
|
||||
(&["View"], "Show Corner Widget"),
|
||||
(&["View"], "Show Live Paint Gaps"),
|
||||
(&["View"], "Hide Live Paint Gaps"),
|
||||
(&["View"], "Show Curvature Comb"),
|
||||
(&["View"], "Hide Curvature Comb"),
|
||||
(&["View"], "Guides"),
|
||||
(&["View"], "Smart Guides"),
|
||||
(&["View"], "Perspective Grid"),
|
||||
|
||||
@@ -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); 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
|
||||
"{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 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 properti
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -63,6 +63,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
engine_drop
|
||||
),
|
||||
cmd!(
|
||||
query "script.palettes",
|
||||
"List Script Palettes",
|
||||
[],
|
||||
None,
|
||||
"{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run; a hidden palette lists its controls as they were when it was hidden, until show() shows it again → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}",
|
||||
always,
|
||||
palettes
|
||||
),
|
||||
cmd!(
|
||||
query "script.palette.event",
|
||||
"Script Palette Event",
|
||||
[],
|
||||
None,
|
||||
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler",
|
||||
always,
|
||||
palette_event
|
||||
),
|
||||
cmd!(
|
||||
query "script.console",
|
||||
"Script Console",
|
||||
@@ -268,6 +286,36 @@ fn engine_drop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"dropped": true, "name": name}))
|
||||
}
|
||||
|
||||
fn palettes(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let list: Vec<Value> = s.script_palettes().iter().map(script::palettes::palette_json).collect();
|
||||
Ok(json!({
|
||||
"palettes": list,
|
||||
"waiting": s.script_palette_events_waiting(),
|
||||
"limit": script::palettes::MAX_PALETTES,
|
||||
"waitingLimit": script::palettes::MAX_WAITING,
|
||||
}))
|
||||
}
|
||||
|
||||
fn palette_event(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "script.palette.event";
|
||||
let Some(id) = p.get("palette").and_then(Value::as_u64) else {
|
||||
return Err(bad(C, "`palette` must be a palette's id, as script.palettes lists it"));
|
||||
};
|
||||
let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) };
|
||||
let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) };
|
||||
let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?;
|
||||
// With nobody to ask, the event runs now or not at all: it is not kept for after an open undo
|
||||
// group or a drag in another document, which a run cannot start in.
|
||||
if !s.script_frames && s.palette_run_blocked() {
|
||||
return Err(EngineError::Other(script::OPEN_EDIT.to_string()));
|
||||
}
|
||||
let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?;
|
||||
if s.script_frames {
|
||||
return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()}));
|
||||
}
|
||||
s.script_palette_run_waiting()
|
||||
}
|
||||
|
||||
fn console_lines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(s.script_console().to_json())
|
||||
}
|
||||
|
||||
@@ -132,6 +132,10 @@ pub struct DocState {
|
||||
pub spelling_ignored: std::collections::BTreeSet<String>,
|
||||
/// View → Show Transparency Grid, per document (saved view state, not undoable).
|
||||
pub transparency_grid: bool,
|
||||
/// View → Show Missing Links: transient canvas decoration, never document artwork.
|
||||
pub show_missing_links: bool,
|
||||
/// Last worker scan, tied to the exact document snapshot it inspected.
|
||||
pub missing_link_markers: Option<(Arc<Document>, Vec<NodeId>)>,
|
||||
/// The format Save writes ([`cmd::fileio::SAVE_FORMATS`]): the one the document was opened
|
||||
/// from or last saved as.
|
||||
pub format: &'static str,
|
||||
@@ -491,6 +495,30 @@ impl SameContent {
|
||||
}
|
||||
|
||||
impl DocState {
|
||||
/// Cached missing links still present and visible in the current art. Geometry-only edits
|
||||
/// keep their markers moving with the objects; relinking or embedding drops them immediately.
|
||||
pub fn marked_missing_links(&self) -> Vec<NodeId> {
|
||||
if !self.show_missing_links {
|
||||
return vec![];
|
||||
}
|
||||
let Some((before, ids)) = &self.missing_link_markers else { return vec![] };
|
||||
fn link(n: &vectorcraft_doc::Node) -> Option<&vectorcraft_doc::LinkInfo> {
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) => im.link.as_ref(),
|
||||
NodeKind::PlacedDocument(p) => Some(&p.link),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
ids.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
let old = before.node(*id).and_then(link);
|
||||
let now = self.doc.node(*id).and_then(link);
|
||||
now.is_some() && now == old && self.doc.is_visible(*id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn new(mut doc: Document, path: Option<String>) -> Self {
|
||||
let active_layer = doc.default_layer();
|
||||
// Saved view state lives here while the document is open (saves write it back).
|
||||
@@ -532,6 +560,8 @@ impl DocState {
|
||||
mask_view: None,
|
||||
spelling_ignored: Default::default(),
|
||||
transparency_grid,
|
||||
show_missing_links: false,
|
||||
missing_link_markers: None,
|
||||
format: "vectorcraft",
|
||||
save_options: Default::default(),
|
||||
save_artboards: vec![],
|
||||
|
||||
@@ -93,7 +93,7 @@ impl AutomationRoots {
|
||||
|
||||
/// Roots that grant no access of either kind: inside [`confine`] with them, every path a
|
||||
/// command reads or writes is refused.
|
||||
pub(crate) fn none() -> Arc<Self> {
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: Vec::new(), write: Vec::new() })
|
||||
}
|
||||
|
||||
@@ -124,6 +124,11 @@ impl AutomationRoots {
|
||||
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
|
||||
}
|
||||
|
||||
/// The folders of the kind `access`, as people read them.
|
||||
pub fn folders(&self, access: Access) -> impl Iterator<Item = &Path> {
|
||||
self.of(access).iter().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// The roots of the kind `access`.
|
||||
fn of(&self, access: Access) -> &[Root] {
|
||||
match access {
|
||||
@@ -151,6 +156,13 @@ impl AutomationRoots {
|
||||
Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) })
|
||||
}
|
||||
|
||||
/// Whether these roots grant everything `other` grants: each root of `other` lies inside one of
|
||||
/// these roots of the same kind.
|
||||
pub(crate) fn contains(&self, other: &Self) -> bool {
|
||||
let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved)));
|
||||
within(&self.read, &other.read) && within(&self.write, &other.write)
|
||||
}
|
||||
|
||||
/// The roots for people: `read A, B; write C` (`none` for a kind without any).
|
||||
pub fn describe(&self) -> String {
|
||||
let list = |roots: &[Root]| {
|
||||
@@ -283,6 +295,42 @@ impl ScopeHandle {
|
||||
Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Whether this scope allows everything `other` allows: its roots are none, or each root of
|
||||
/// `other` lies inside one of its roots of the same kind, and its script gate is none or the
|
||||
/// same gate.
|
||||
fn covers(&self, other: &Self) -> bool {
|
||||
let gate = match (&self.1, &other.1) {
|
||||
(None, _) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
(Some(_), None) => false,
|
||||
};
|
||||
gate && self.roots_cover(other)
|
||||
}
|
||||
|
||||
/// Whether this scope's roots are none, or each root of `other` lies inside one of its roots
|
||||
/// of the same kind.
|
||||
fn roots_cover(&self, other: &Self) -> bool {
|
||||
match (self.roots(), other.roots()) {
|
||||
(None, _) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(&a, &b) || a.contains(&b),
|
||||
(Some(_), None) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this scope allows everything the calling thread's scope allows
|
||||
/// ([`ScopeHandle::covers`]) and the calling thread's roots cover this scope's roots too, so
|
||||
/// work run in the calling thread's scope reaches the same files this scope reaches.
|
||||
pub(crate) fn matches_current(&self) -> bool {
|
||||
let current = Self::capture();
|
||||
self.covers(¤t) && current.roots_cover(self)
|
||||
}
|
||||
|
||||
/// Whether this scope and `other` allow the same: each covers the other, and reads are exempt
|
||||
/// from the gate in both or in neither.
|
||||
pub fn same(&self, other: &Self) -> bool {
|
||||
self.2 == other.2 && self.covers(other) && other.covers(self)
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
let Self(scope, gate, exempt) = self;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and
|
||||
//! reduce to commands, so every gesture is journaled and replayable.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod cmd;
|
||||
pub mod file_access;
|
||||
@@ -399,6 +400,9 @@ pub struct Session {
|
||||
pub(crate) script_style_trail: script::StyleTrail,
|
||||
/// While a slice of a script runs in this session.
|
||||
pub(crate) script_in_run: bool,
|
||||
/// The ScriptUI palettes the named engines' runs showed, and the events that wait for a run
|
||||
/// ([`script::palettes`]).
|
||||
pub(crate) script_palettes: script::palettes::Palettes,
|
||||
/// A script's `file.new` asked for Overprint Preview, which is turned on when the run ends and
|
||||
/// is not turned on when the run fails.
|
||||
pub(crate) overprint_after_run: bool,
|
||||
|
||||
@@ -27,9 +27,24 @@ use crate::{Result, Session};
|
||||
/// A file's size and modification time (nanoseconds since 1970).
|
||||
pub type Stamp = (u64, u128);
|
||||
|
||||
/// Stamps of a document's linked files taken on a worker thread: (document uid, [(file,
|
||||
/// object ids, stamp)]), the condition the worker signals when it ends, and whether it has.
|
||||
pub type LinkScan = Arc<(Mutex<Option<(u64, Vec<(String, Vec<u64>, Option<Stamp>)>)>>, Condvar, AtomicBool)>;
|
||||
/// A document's linked-file scan, the condition the worker signals when it ends, and whether
|
||||
/// it has. Includes missing-link marker ids when their view toggle is enabled.
|
||||
pub type LinkScan = Arc<(Mutex<Option<LinkScanResult>>, Condvar, AtomicBool)>;
|
||||
|
||||
/// A worker's stamps and optional missing-link overlay scan of the same document snapshot.
|
||||
pub struct LinkScanResult {
|
||||
uid: u64,
|
||||
stamps: Vec<(String, Vec<u64>, Option<Stamp>)>,
|
||||
markers: Option<(Arc<vectorcraft_doc::Document>, Vec<vectorcraft_doc::NodeId>)>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl LinkScanResult {
|
||||
/// A look's stamps of document `uid`'s linked files, with no missing-link scan.
|
||||
pub(crate) fn stamps(uid: u64, stamps: Vec<(String, Vec<u64>, Option<Stamp>)>) -> Self {
|
||||
Self { uid, stamps, markers: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Held by a look's worker: marks the look as ended and wakes [`Session::wait_link_scan`] when
|
||||
/// dropped, whether the worker returned or unwound.
|
||||
@@ -83,6 +98,29 @@ pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether the active document shows missing links but has no marker scan yet (the overlay
|
||||
/// was just turned on, or its first scan saw art that has since changed): the desktop app
|
||||
/// then starts a look at once instead of waiting for the next periodic one.
|
||||
pub fn missing_link_scan_due(&self) -> bool {
|
||||
self.link_scan.is_none() && self.active().is_some_and(|st| st.show_missing_links && st.missing_link_markers.is_none())
|
||||
}
|
||||
|
||||
/// Find the active document's missing links again, here and now, when it shows them and its art
|
||||
/// changed since they were last found (or they never were); returns whether it did. This reads
|
||||
/// linked files on the calling thread, so only the web app calls it: it has no files to read,
|
||||
/// so every linked file is missing there, and no link watch worker to scan in the background.
|
||||
/// Artwork restored or placed while the overlay is on is then marked too. The desktop app
|
||||
/// scans on the worker instead ([`Session::start_link_scan`]).
|
||||
pub fn mark_missing_links_in_place(&mut self) -> bool {
|
||||
let Some(st) = self.active_mut() else { return false };
|
||||
if !st.show_missing_links || st.missing_link_markers.as_ref().is_some_and(|(seen, _)| Arc::ptr_eq(seen, &st.doc)) {
|
||||
return false;
|
||||
}
|
||||
let ids = crate::cmd::links::missing_markers(&st.doc, crate::cmd::links::LinkBase::of(st));
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
true
|
||||
}
|
||||
|
||||
/// Start stamping the active document's linked files on a worker thread, unless a look is
|
||||
/// still running, a script is running (or the build has no files to look at: the web app).
|
||||
pub fn start_link_scan(&mut self) {
|
||||
@@ -94,7 +132,14 @@ impl Session {
|
||||
// A confined caller's roots, else what the caller that opened the document may read (the
|
||||
// desktop frame is unconfined).
|
||||
let opened_by = st.opened_by.clone();
|
||||
let marker_doc = st.show_missing_links.then(|| st.doc.clone());
|
||||
let links_from = st.links_from.clone();
|
||||
if files.is_empty() {
|
||||
// Nothing linked, so nothing missing: an empty scan, which also ends
|
||||
// [`Session::missing_link_scan_due`] without starting a worker.
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid) {
|
||||
st.missing_link_markers = st.show_missing_links.then(|| (st.doc.clone(), vec![]));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let slot: LinkScan = Arc::default();
|
||||
@@ -103,12 +148,18 @@ impl Session {
|
||||
let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || {
|
||||
// Marks the look as ended when the worker returns or unwinds.
|
||||
let _ended = Ended(out.clone());
|
||||
let stamps = scope.run(|| {
|
||||
let (stamps, markers) = scope.run(|| {
|
||||
crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || {
|
||||
files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect()
|
||||
let stamps = files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect();
|
||||
let markers = marker_doc.map(|doc| {
|
||||
let base = crate::cmd::links::LinkBase::of_files(doc_path.as_deref(), links_from.as_deref());
|
||||
let ids = crate::cmd::links::missing_markers(&doc, base);
|
||||
(doc, ids)
|
||||
});
|
||||
(stamps, markers)
|
||||
})
|
||||
});
|
||||
*out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps));
|
||||
*out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(LinkScanResult { uid, stamps, markers });
|
||||
});
|
||||
if spawned.is_ok() {
|
||||
self.link_scan = Some(slot);
|
||||
@@ -123,8 +174,15 @@ impl Session {
|
||||
return None;
|
||||
}
|
||||
self.link_scan.take_if(|scan| ended_without_stamps(scan, |ended| ended.load(Ordering::SeqCst)));
|
||||
let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?;
|
||||
let LinkScanResult { uid, stamps, markers } = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?;
|
||||
self.link_scan = None;
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid)
|
||||
&& st.show_missing_links
|
||||
&& let Some((doc, ids)) = markers
|
||||
&& Arc::ptr_eq(&st.doc, &doc)
|
||||
{
|
||||
st.missing_link_markers = Some((doc, ids));
|
||||
}
|
||||
Some(self.apply_link_stamps(uid, stamps, false))
|
||||
}
|
||||
|
||||
|
||||
@@ -222,13 +222,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
|
||||
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
|
||||
}
|
||||
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
// A palette's handler that a palette's `update()` runs plays the actions of the run that showed
|
||||
// the palette, as the handler's own run would.
|
||||
let handler = h.palette_actions.borrow();
|
||||
let actions = handler.as_deref().unwrap_or(&h.actions);
|
||||
let found: Vec<&Playable> = actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
let p = match found.as_slice() {
|
||||
[p] => *p,
|
||||
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[p] => (*p).clone(),
|
||||
[] if !actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
|
||||
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
|
||||
};
|
||||
drop(handler);
|
||||
if p.steps.is_empty() {
|
||||
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
|
||||
}
|
||||
|
||||
@@ -222,6 +222,9 @@ pub(crate) struct Dialogs {
|
||||
approved: Cell<Option<OnYes>>,
|
||||
/// The error that ended the run when an answer could not reach the script.
|
||||
failed: RefCell<Option<RunError>>,
|
||||
/// An answer could not reach the script, so a dialog still open when the run ends is listed
|
||||
/// with the answer `"error"`.
|
||||
answer_failed: Cell<bool>,
|
||||
records: RefCell<Vec<Value>>,
|
||||
record_bytes: Cell<usize>,
|
||||
count: Cell<u64>,
|
||||
@@ -247,6 +250,7 @@ impl Dialogs {
|
||||
on_yes: Cell::new(None),
|
||||
approved: Cell::new(None),
|
||||
failed: RefCell::default(),
|
||||
answer_failed: Cell::new(false),
|
||||
records: RefCell::default(),
|
||||
record_bytes: Cell::new(0),
|
||||
count: Cell::new(0),
|
||||
@@ -295,6 +299,7 @@ impl Dialogs {
|
||||
self.window_waiting.set(false);
|
||||
if let Err(e) = realm.answer(event.data()) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
self.answer_failed.set(true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -447,24 +452,32 @@ impl Dialogs {
|
||||
}
|
||||
|
||||
/// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most
|
||||
/// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits.
|
||||
/// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. The report lists the dialog
|
||||
/// with the answer, or with `"error"` when the answer could not reach the script.
|
||||
pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool {
|
||||
let fits = match &answer {
|
||||
DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES,
|
||||
_ => true,
|
||||
};
|
||||
let mut waiting = self.waiting.borrow_mut();
|
||||
let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false };
|
||||
self.record(d, answer.json());
|
||||
*waiting = None;
|
||||
if !waiting.as_ref().is_some_and(|d| d.kind == answer.kind() && fits) {
|
||||
return false;
|
||||
}
|
||||
let Some(d) = waiting.take() else { return false };
|
||||
drop(waiting);
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
if let Err(e) = realm.answer(data) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
match realm.answer(data) {
|
||||
Ok(()) => self.record(&d, answer.json()),
|
||||
Err(e) => {
|
||||
self.record(&d, json!("error"));
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
self.answer_failed.set(true);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -493,15 +506,17 @@ impl Dialogs {
|
||||
self.approved.take()
|
||||
}
|
||||
|
||||
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`.
|
||||
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`, or
|
||||
/// `"error"` when an answer could not reach the script.
|
||||
pub(crate) fn stopped(&self) {
|
||||
self.on_yes.set(None);
|
||||
let answer = if self.answer_failed.replace(false) { json!("error") } else { json!("stop") };
|
||||
if let Some(d) = self.waiting.borrow_mut().take() {
|
||||
self.record(&d, json!("stop"));
|
||||
self.record(&d, answer.clone());
|
||||
}
|
||||
self.window_waiting.set(false);
|
||||
if let Some(showing) = self.window.borrow_mut().take() {
|
||||
self.end_record(&showing, json!("stop"));
|
||||
self.end_record(&showing, answer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -853,9 +853,24 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
|
||||
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
// Deleting every path of a compound path would leave it empty, so a compound path that
|
||||
// clips counts as deleted too.
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
let masks: Vec<u64> = ids
|
||||
.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
|
||||
@@ -497,6 +497,19 @@ fn edit_paint(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::
|
||||
edit_path(h, item, id, params)
|
||||
}
|
||||
|
||||
/// A script's new path goes on the active layer while it is shown and unlocked, or the topmost
|
||||
/// shown, unlocked layer otherwise. While an opacity mask, pattern or symbol is being edited,
|
||||
/// the path goes on the layer recorded by that edit mode. `create::on_layer` validates the layer.
|
||||
fn new_path_layer(st: &crate::DocState) -> Option<NodeId> {
|
||||
let d = &st.doc;
|
||||
if let Some(layer) =
|
||||
d.mask_edit.map(|e| e.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)).or_else(|| d.symbol_edit.as_ref().map(|e| e.layer))
|
||||
{
|
||||
return Some(layer);
|
||||
}
|
||||
st.current_layer().filter(|l| d.is_editable(*l)).or_else(|| d.default_layer())
|
||||
}
|
||||
|
||||
/// Runs a path creation command with its layer placement recorded.
|
||||
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
let mut params = params.clone();
|
||||
@@ -672,23 +685,92 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or
|
||||
/// layer that keeps other objects, or a compound path or group that clips one and would be left
|
||||
/// with no visible path or visible type that lays out glyphs to clip by.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let d = &st.doc;
|
||||
if h.session.borrow().menu.guides_locked
|
||||
&& let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
&& let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
{
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
|
||||
}
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
let locks = st.doc.locked_artboards();
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
let mut next: Vec<_> = d.layers.iter().collect();
|
||||
let mut nodes = Vec::new();
|
||||
while let Some(n) = next.pop() {
|
||||
nodes.push(n);
|
||||
next.extend(n.children().into_iter().flatten());
|
||||
}
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut affected: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
for n in nodes.iter().rev() {
|
||||
if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) {
|
||||
affected.insert(n.id);
|
||||
}
|
||||
}
|
||||
// Type is laid out only inside a mask that loses a path; no other outline decides a refusal.
|
||||
let mut in_mask = std::collections::HashSet::new();
|
||||
for n in &nodes {
|
||||
if n.clips()
|
||||
&& let Some(mask) = n.children().and_then(|k| k.first())
|
||||
&& affected.contains(&mask.id)
|
||||
{
|
||||
let mut stack = vec![mask];
|
||||
while let Some(m) = stack.pop() {
|
||||
if in_mask.insert(m.id) {
|
||||
stack.extend(m.children().into_iter().flatten());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut geometry = std::collections::HashSet::new();
|
||||
let mut masks = Vec::new();
|
||||
for n in nodes.into_iter().rev() {
|
||||
let kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
// Clear removes compound paths emptied of direct members, but keeps empty groups.
|
||||
if matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& !kids.is_empty()
|
||||
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
|
||||
{
|
||||
going.insert(n.id);
|
||||
}
|
||||
// A clip outline takes in visible paths and the glyphs of visible type, as
|
||||
// `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no
|
||||
// outline. A list marker is a glyph too, so whitespace-only type is laid out as well.
|
||||
let shape = n.visible
|
||||
&& match &n.kind {
|
||||
NodeKind::Path { .. } => true,
|
||||
NodeKind::Text(t) => {
|
||||
in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
// A clipping group's outline is its first member's alone.
|
||||
let inner =
|
||||
if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) };
|
||||
if n.visible && ((shape && !going.contains(&n.id)) || inner) {
|
||||
geometry.insert(n.id);
|
||||
}
|
||||
if n.clips()
|
||||
&& let Some(mask) = kids.first()
|
||||
&& affected.contains(&mask.id)
|
||||
&& !geometry.contains(&mask.id)
|
||||
&& kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
&& masks.len() < 20
|
||||
{
|
||||
masks.push(mask.id.0);
|
||||
}
|
||||
}
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
@@ -698,6 +780,12 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !masks.is_empty() {
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
}
|
||||
@@ -717,7 +805,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
@@ -883,7 +971,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
};
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
|
||||
if unpainted {
|
||||
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
|
||||
@@ -1554,7 +1642,8 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
|
||||
/// [`see_points`] for each path whose points the run has read, after each command, so that a
|
||||
/// change that a later command reverses still makes the points stale. Paths under the object that
|
||||
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
|
||||
/// object model's own, and their points stay valid. A document that is the one the run last looked
|
||||
/// object model's own, and their points stay valid; the other Global Edit members, which take the
|
||||
/// object model's edit too, are looked at as well. A document that is the one the run last looked
|
||||
/// at is skipped, as are its paths. The look is charged by the objects it looks at.
|
||||
pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
let (keys, looked_at): (Vec<(u64, u64)>, u64) = {
|
||||
@@ -1564,7 +1653,8 @@ pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostErr
|
||||
let mut keys = Vec::new();
|
||||
let mut looked_at = 0u64;
|
||||
docs.retain(|uid, before| {
|
||||
let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc);
|
||||
let state = s.documents().iter().find(|d| d.uid == *uid);
|
||||
let after = state.map(|st| &st.doc);
|
||||
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
|
||||
return true;
|
||||
}
|
||||
@@ -1574,16 +1664,28 @@ pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostErr
|
||||
return false;
|
||||
}
|
||||
// Editing a path in an Objects on Path group can move the other paths in the group, so
|
||||
// the outermost such group is looked at in place of the path.
|
||||
// the outermost such group is looked at in place of the path. While Global Edit is on,
|
||||
// an edit of the selected member (also one made by moving a group that holds it) is
|
||||
// given to the other members, so each of them, or the outermost Objects on Path group
|
||||
// holding it, is looked at too. Subtrees the command left as they were are skipped.
|
||||
// Each node is paired with the node of the same id under the same parent now, so that no
|
||||
// node is searched for through the whole document.
|
||||
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
|
||||
Some(item) => {
|
||||
let group = before
|
||||
.ancestry(item.id)
|
||||
.and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)));
|
||||
let id = group.unwrap_or(item.id);
|
||||
node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))).into_iter().collect()
|
||||
let root = |id: NodeId| {
|
||||
before
|
||||
.ancestry(id)
|
||||
.and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)))
|
||||
.unwrap_or(id)
|
||||
};
|
||||
let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten();
|
||||
let mut roots = std::collections::HashSet::new();
|
||||
std::iter::once(item.id)
|
||||
.chain(members)
|
||||
.map(root)
|
||||
.filter(|id| roots.insert(*id))
|
||||
.filter_map(|id| node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))))
|
||||
.collect()
|
||||
}
|
||||
None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at),
|
||||
};
|
||||
@@ -1625,6 +1727,8 @@ pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostErr
|
||||
false
|
||||
}
|
||||
});
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
(keys, looked_at)
|
||||
};
|
||||
if looked_at > 0 {
|
||||
|
||||
@@ -220,6 +220,9 @@ pub(crate) struct Setup {
|
||||
pub script: Option<String>,
|
||||
/// The script's text with the files it includes, whose SHA-256 the grants it keeps are for.
|
||||
pub source: String,
|
||||
/// The SHA-256 the grants are for in place of `source`'s: for the run of a ScriptUI palette's
|
||||
/// handler, the one of the script that showed the palette.
|
||||
pub own: Option<String>,
|
||||
/// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]).
|
||||
pub data_dir: Option<std::path::PathBuf>,
|
||||
/// The code the run's named engine kept from its earlier runs: the SHA-256 of each source
|
||||
@@ -309,7 +312,7 @@ impl Disk {
|
||||
let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned());
|
||||
let web = cfg!(target_arch = "wasm32");
|
||||
let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok());
|
||||
let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes());
|
||||
let own = setup.own.unwrap_or_else(|| vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()));
|
||||
let script = script.map(|p| (p, own.clone()));
|
||||
let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned);
|
||||
let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect();
|
||||
@@ -381,6 +384,11 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SHA-256 the run's grants are for ([`Setup::own`]).
|
||||
pub(crate) fn own(&self) -> &str {
|
||||
&self.own
|
||||
}
|
||||
|
||||
/// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new.
|
||||
fn saw(&mut self, hash: String) -> bool {
|
||||
if self.ran_too_much || self.ran.contains(&hash) || self.own == hash {
|
||||
|
||||
@@ -48,6 +48,11 @@
|
||||
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
|
||||
//! documents back and keeps the engine's globals; an internal error drops the engine.
|
||||
//!
|
||||
//! A run in a named engine can show ScriptUI palettes ([`palettes`]), which stay open after it and
|
||||
//! whose events run as runs of their own in that engine, one at a time once no run is going. A run
|
||||
//! of that engine whose own code calls `update()` handles the waiting events inside the run
|
||||
//! instead. A palette closes with its engine.
|
||||
//!
|
||||
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
|
||||
//! only after the run's changes are kept, for the frontend to send once the person approves them
|
||||
//! ([`printing`]).
|
||||
@@ -58,10 +63,12 @@ pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
pub mod palettes;
|
||||
pub mod printing;
|
||||
pub mod scriptui;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
pub use palettes::{ScriptPalette, Waiting};
|
||||
pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue};
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -111,6 +118,9 @@ pub const MAX_LOG_LINES: usize = 10_000;
|
||||
pub const MAX_LOG_BYTES: usize = 4 << 20;
|
||||
/// The most bytes of `args` given to one run, as JSON.
|
||||
pub const MAX_ARGS_BYTES: usize = 1 << 20;
|
||||
/// The shortest run time between two ScriptUI `update()` calls that each end the slice, so the app
|
||||
/// draws the window (VectorCraft's own value, about one frame).
|
||||
const UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16);
|
||||
/// The `vc.run` calls one slice makes before the interface draws again.
|
||||
const SLICE_HOST_CALLS: u32 = 256;
|
||||
/// The bytes that may cross between a script and the host in one run.
|
||||
@@ -848,6 +858,8 @@ struct Host {
|
||||
started: Option<std::time::Instant>,
|
||||
/// The time since [`Host::started`] at which a `$.sleep` ends.
|
||||
wake_at: Cell<Option<std::time::Duration>>,
|
||||
/// The time since [`Host::started`] at which a ScriptUI `update()` last ended the slice.
|
||||
drawn_at: Cell<Option<std::time::Duration>>,
|
||||
/// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]).
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
/// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one).
|
||||
@@ -856,6 +868,13 @@ struct Host {
|
||||
dollar: dollar::RunState,
|
||||
/// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it.
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The named engine the run is in; `None` for a new realm.
|
||||
engine: Option<String>,
|
||||
/// The script file the run was read from; `None` for a script given as text.
|
||||
file: Option<String>,
|
||||
/// For the run of a palette's handler, the palette's id and the event, until the palette takes
|
||||
/// it ([`palettes`]).
|
||||
palette_event: RefCell<Option<palettes::Queued>>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// While a slice runs: the documents the interface has open ([`World::docs`] of the run's
|
||||
@@ -863,6 +882,10 @@ struct Host {
|
||||
interface_docs: RefCell<Vec<DocState>>,
|
||||
/// The actions `app.doScript` can play.
|
||||
actions: Vec<actions::Playable>,
|
||||
/// While a palette's `update()` gives a waiting event to its palette, the actions of the run
|
||||
/// that showed that palette, which `app.doScript` plays in place of [`Host::actions`]. A
|
||||
/// palette's `paletteTake` sets them and its `palettePending` clears them.
|
||||
palette_actions: RefCell<Option<Vec<actions::Playable>>>,
|
||||
/// The index of each open document's active artboard as the run starts, by document uid. The
|
||||
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
|
||||
active_artboards: Vec<(u64, usize)>,
|
||||
@@ -1098,6 +1121,24 @@ impl Host {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A palette's `update()` in the script's own code: in the app, ends the slice so the palette is
|
||||
/// drawn as the script left it, at most once per [`UPDATE_INTERVAL`] of the run's time. →
|
||||
/// whether it does, and the palette's controls are to be given now. Without a clock (the web
|
||||
/// build), and in a run with nobody to draw for, the palette is drawn when the slice or the run
|
||||
/// ends for another reason.
|
||||
fn update_drawn(&self) -> bool {
|
||||
if !self.framed {
|
||||
return false;
|
||||
}
|
||||
let Some(now) = self.elapsed() else { return false };
|
||||
if self.drawn_at.get().is_some_and(|t| now.saturating_sub(t) < UPDATE_INTERVAL) {
|
||||
return false;
|
||||
}
|
||||
self.drawn_at.set(Some(now));
|
||||
self.pause.set(true);
|
||||
true
|
||||
}
|
||||
|
||||
/// The time left of a `$.sleep`, or none when the run is not asleep.
|
||||
fn asleep(&self) -> Option<std::time::Duration> {
|
||||
let wake = self.wake_at.get()?;
|
||||
@@ -2044,6 +2085,7 @@ impl Session {
|
||||
match gone {
|
||||
Some(engine) => {
|
||||
drop(engine);
|
||||
self.keep_engines_palettes();
|
||||
Ok(())
|
||||
}
|
||||
None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))),
|
||||
@@ -2331,6 +2373,7 @@ impl Session {
|
||||
lost
|
||||
});
|
||||
drop(lost);
|
||||
self.keep_engines_palettes();
|
||||
// The job's working copy went with it, with the documents the run opened.
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
@@ -2352,6 +2395,10 @@ impl Session {
|
||||
/// A script can't start while a document holds a drag in progress or an undo group, which its
|
||||
/// one undo step could not take in.
|
||||
fn settle_for_script(&mut self) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
if SETTLE_FAILS.with(Cell::get) {
|
||||
return Err(EngineError::Other("the open edit could not be settled".into()));
|
||||
}
|
||||
self.finish_tool_edit_later()?;
|
||||
if self.active().is_some() {
|
||||
cmd::settle_interaction(self)?;
|
||||
@@ -2364,6 +2411,7 @@ impl Session {
|
||||
|
||||
/// Begins a run of `request`. → the run's name.
|
||||
pub(crate) fn script_start(&mut self, request: Request) -> Result<String> {
|
||||
let palette_event = self.script_palettes.starting.take();
|
||||
self.settle_for_script()?;
|
||||
// In a build where a fault ends the program, every unsaved document has a copy first.
|
||||
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
|
||||
@@ -2485,6 +2533,7 @@ impl Session {
|
||||
script: request.file.clone(),
|
||||
// The text with its included files, so a changed included file asks again.
|
||||
source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()),
|
||||
own: palette_event.as_ref().and_then(|q| q.grants.clone()),
|
||||
data_dir: self.script_data_dir.clone(),
|
||||
engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| {
|
||||
let m = m.borrow();
|
||||
@@ -2502,13 +2551,18 @@ impl Session {
|
||||
kept_maps,
|
||||
started: clock(),
|
||||
wake_at: Cell::new(None),
|
||||
drawn_at: Cell::new(None),
|
||||
can_wait: realm.wait_flag(),
|
||||
eval_strict: Cell::new(None),
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
engine: engine.clone(),
|
||||
file: request.file.clone(),
|
||||
palette_event: RefCell::new(palette_event),
|
||||
dom: dom::State::new(self.documents(), heap_bytes),
|
||||
interface_docs: RefCell::new(Vec::new()),
|
||||
actions: request.actions,
|
||||
palette_actions: RefCell::new(None),
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
artboard_picks,
|
||||
run_docs: RefCell::new(
|
||||
@@ -2585,6 +2639,7 @@ impl Session {
|
||||
// error drops a kept one.
|
||||
let keep = !fresh && e.kind != RunErrorKind::Internal;
|
||||
self.return_engine(engine.as_deref(), &link, keep.then_some(realm));
|
||||
self.keep_engines_palettes();
|
||||
let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0);
|
||||
close_run(self, &host, &mut report, ending(&e.kind));
|
||||
let message = failure_text(&report);
|
||||
@@ -2733,6 +2788,7 @@ impl Session {
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
close_run(self, &job.host, &mut report, ending(&e.kind));
|
||||
self.end_job(job, e.kind == RunErrorKind::Internal);
|
||||
self.keep_engines_palettes();
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
@@ -2879,7 +2935,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script";
|
||||
pub(crate) const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script";
|
||||
const INVALID_RESULT: &str = "the script left a document that cannot be kept";
|
||||
const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written";
|
||||
const JOB_GONE: &str = "the script's run is no longer available";
|
||||
@@ -3074,6 +3130,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
let scope = job.scope.clone();
|
||||
let realm = &mut job.realm;
|
||||
let named = job.engine.is_some();
|
||||
let host = &job.host;
|
||||
let started = clock();
|
||||
let r = scope.run(|| {
|
||||
@@ -3084,12 +3141,34 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
}
|
||||
// Point changes that still wait in the object model are written when the script ends. Between
|
||||
// slices the run's documents are put aside, so they can wait across slices.
|
||||
realm.advance(SLICE_FUEL).and_then(|progress| {
|
||||
let progress = realm.advance(SLICE_FUEL).and_then(|progress| {
|
||||
if matches!(progress, Progress::Done(_)) {
|
||||
dom::flush(host).map_err(end_flush_error)?;
|
||||
}
|
||||
Ok(progress)
|
||||
})
|
||||
});
|
||||
// A limit that ends a palette's handler which `update()` took leaves the handler's
|
||||
// actions in place of the run's: once the run ends, the refresh's getters play the
|
||||
// run's own.
|
||||
if !matches!(progress, Ok(Progress::Paused)) {
|
||||
*host.palette_actions.borrow_mut() = None;
|
||||
}
|
||||
match progress {
|
||||
// The palettes of a named engine show the controls as the run left them. A getter
|
||||
// the refresh reads may change points, which are written before the run ends.
|
||||
Ok(Progress::Done(v)) if named => realm.refresh_script_ui().and_then(|()| {
|
||||
dom::flush(host).map_err(end_flush_error)?;
|
||||
Ok(Progress::Done(v))
|
||||
}),
|
||||
// A failed run keeps its globals, so its palettes show what it left too; a refresh
|
||||
// that fails as well (the fuel is spent, a stop) leaves them as they were, and the
|
||||
// run's error keeps its place.
|
||||
Err(e) if named && e.kind != RunErrorKind::Internal => {
|
||||
realm.refresh_script_ui_after_error();
|
||||
Err(e)
|
||||
}
|
||||
r => r,
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(started) = started {
|
||||
@@ -3166,6 +3245,8 @@ thread_local! {
|
||||
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: makes the next slice panic.
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: makes settling the open edits before a run fail.
|
||||
pub(crate) static SETTLE_FAILS: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: makes the next command a member runs past the script fence panic before it runs.
|
||||
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
|
||||
@@ -0,0 +1,536 @@
|
||||
//! ScriptUI palettes (`new Window("palette")`, [`vectorcraft_js::scriptui`]): windows a run in a
|
||||
//! named engine (`#targetengine`) shows, which stay open after the run ends and take clicks and
|
||||
//! changes while the person goes on working.
|
||||
//!
|
||||
//! A palette needs a named engine, which keeps its controls and handlers between runs: in a script
|
||||
//! without `#targetengine`, or with `main`, `new Window("palette")` throws. `show()` returns at once.
|
||||
//! Each click, change or close the person gives a palette waits here, and then runs as a run of its
|
||||
//! own in the palette's engine, which takes the mutation lease like any other run: one event at a
|
||||
//! time, oldest first, each starting only once no run is going. A new click, change or close replaces
|
||||
//! the most recent waiting event of the same kind for the same control or palette only when that
|
||||
//! event has the same file access scope. Otherwise the new event waits at the end of the line. A click or
|
||||
//! close replaces an event only after its palette's last waiting change. A palette's `update()` in
|
||||
//! a run of the palette's engine takes the events that wait for that engine's palettes and runs their
|
||||
//! handlers in that run instead ([`Palettes::take_for`]).
|
||||
//!
|
||||
//! A palette closes when its script calls `close()` or the person closes it, unless `onClose`
|
||||
//! returns `false`; when its engine is dropped or ends with an internal error; and with the session.
|
||||
//! Hiding or closing a palette drops the events that wait for it. An error in a handler ends that
|
||||
//! handler's run like any failed run, with its report, and leaves the palette open.
|
||||
//!
|
||||
//! The limits here are VectorCraft's own: [`MAX_PALETTES`] and [`MAX_WAITING`].
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::actions::Playable;
|
||||
use super::scriptui::{self, ScriptUiDialog, UiEvent, UiKind, UiValue};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The most palettes a session keeps, shown or hidden.
|
||||
pub const MAX_PALETTES: usize = 16;
|
||||
/// The most events that wait for a run, for every palette together.
|
||||
pub const MAX_WAITING: usize = 64;
|
||||
|
||||
/// A palette a run showed.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptPalette {
|
||||
/// Its number in the session, which no other palette of the session has had.
|
||||
pub id: u64,
|
||||
/// The named engine its handlers run in.
|
||||
pub engine: String,
|
||||
/// The script file of the run that first showed it, whose folder its handlers read in; `None`
|
||||
/// for a script given as text.
|
||||
pub file: Option<String>,
|
||||
/// Its controls, as the last `show()`, `add()` or handler left them.
|
||||
pub dialog: ScriptUiDialog,
|
||||
pub visible: bool,
|
||||
/// The SHA-256 the file grants of the script that first showed it are kept for, which its
|
||||
/// handlers' runs keep using: the grants allowed with Always. A grant allowed once is the
|
||||
/// showing run's alone, as for any later run of the script.
|
||||
pub(crate) grants: String,
|
||||
}
|
||||
|
||||
/// What became of an event given to a palette.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Waiting {
|
||||
/// It waits at the end of the line.
|
||||
Added,
|
||||
/// It took the place of a waiting event for the same control.
|
||||
Merged,
|
||||
}
|
||||
|
||||
/// An event given to a palette, waiting for its run or handed to it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Queued {
|
||||
pub(crate) palette: u64,
|
||||
pub(crate) event: UiEvent,
|
||||
/// The id of the control of a click or a change ([`super::scriptui::UiNode::id`]), by which the
|
||||
/// event finds its control again when a run adds or removes controls before it; `None` for a
|
||||
/// close.
|
||||
pub(crate) element: Option<u64>,
|
||||
/// For a list's change, the list's items as the palette showed them when the event was given and
|
||||
/// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list
|
||||
/// still has.
|
||||
pub(crate) list: Option<(Vec<String>, f64)>,
|
||||
/// Once its run starts, the SHA-256 the file grants of the palette's script are kept for, which
|
||||
/// the run takes as its own ([`super::files::Setup::own`]).
|
||||
pub(crate) grants: Option<String>,
|
||||
/// The file access scope of the request that gave the event, which its run keeps, narrowed to
|
||||
/// the scope in force when the run starts ([`crate::file_access::ScopeHandle::within_current`]).
|
||||
pub(crate) scope: crate::file_access::ScopeHandle,
|
||||
/// The number of the request that gave the event last: an event that takes the place of a
|
||||
/// waiting one takes a new number.
|
||||
pub(crate) ticket: u64,
|
||||
}
|
||||
|
||||
/// The palettes of a session, and the events that wait for a run.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Palettes {
|
||||
list: Vec<ScriptPalette>,
|
||||
/// The actions `app.doScript` plays in each palette's handlers, by palette id: those of the
|
||||
/// run that first showed the palette.
|
||||
actions: Vec<(u64, Vec<Playable>)>,
|
||||
waiting: VecDeque<Queued>,
|
||||
last_id: u64,
|
||||
/// The number the last event given took ([`Queued::ticket`]).
|
||||
last_ticket: u64,
|
||||
/// The number of the event whose run started last.
|
||||
started_ticket: Option<u64>,
|
||||
/// While [`Session::script_palette_run_waiting`] runs an event, the numbers of the events its
|
||||
/// run takes inside it (`update()`).
|
||||
taken_inline: Option<Vec<u64>>,
|
||||
/// The event the run that starts next handles ([`Session::script_palette_start`]).
|
||||
pub(crate) starting: Option<Queued>,
|
||||
}
|
||||
|
||||
/// Does `event`, for the control whose id is `element`, share the waiting `q`'s place in line: a
|
||||
/// click on the same control, a change of it, or a close?
|
||||
fn same_place(q: &Queued, event: &UiEvent, element: Option<u64>) -> bool {
|
||||
let same_kind = matches!(
|
||||
(&q.event, event),
|
||||
(UiEvent::Click(_), UiEvent::Click(_)) | (UiEvent::Change(..), UiEvent::Change(..)) | (UiEvent::Close, UiEvent::Close)
|
||||
);
|
||||
same_kind && q.element == element
|
||||
}
|
||||
|
||||
/// The control of a click or a change.
|
||||
fn control_of(event: &mut UiEvent) -> Option<&mut usize> {
|
||||
match event {
|
||||
UiEvent::Click(c) | UiEvent::Change(c, _) => Some(c),
|
||||
UiEvent::Close => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Palettes {
|
||||
fn find(&mut self, id: u64, engine: &str) -> Option<&mut ScriptPalette> {
|
||||
self.list.iter_mut().find(|p| p.id == id && p.engine == engine)
|
||||
}
|
||||
|
||||
/// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`, whose
|
||||
/// handlers take the showing run's `actions`. → its id.
|
||||
pub(crate) fn show(
|
||||
&mut self,
|
||||
id: Option<u64>,
|
||||
engine: &str,
|
||||
(file, grants, actions): (Option<String>, String, &[Playable]),
|
||||
dialog: ScriptUiDialog,
|
||||
) -> std::result::Result<u64, String> {
|
||||
if let Some(p) = id.and_then(|id| self.find(id, engine)) {
|
||||
p.dialog = dialog;
|
||||
p.visible = true;
|
||||
return Ok(p.id);
|
||||
}
|
||||
if self.list.len() >= MAX_PALETTES {
|
||||
return Err(format!("show: a session keeps at most {MAX_PALETTES} script palettes; close one first"));
|
||||
}
|
||||
self.last_id += 1;
|
||||
self.list.push(ScriptPalette { id: self.last_id, engine: engine.to_string(), file, dialog, visible: true, grants });
|
||||
if !actions.is_empty() {
|
||||
self.actions.push((self.last_id, actions.to_vec()));
|
||||
}
|
||||
Ok(self.last_id)
|
||||
}
|
||||
|
||||
/// The palette's controls as a handler or `add()` left them. → false when it is closed.
|
||||
pub(crate) fn update(&mut self, id: u64, engine: &str, dialog: ScriptUiDialog) -> bool {
|
||||
let Some(p) = self.find(id, engine) else { return false };
|
||||
p.dialog = dialog;
|
||||
true
|
||||
}
|
||||
|
||||
/// `hide()`. → false when it is closed.
|
||||
pub(crate) fn hide(&mut self, id: u64, engine: &str) -> bool {
|
||||
let Some(p) = self.find(id, engine) else { return false };
|
||||
p.visible = false;
|
||||
self.waiting.retain(|q| q.palette != id);
|
||||
true
|
||||
}
|
||||
|
||||
/// `close()`, once `onClose` allowed it. → false when it was closed already.
|
||||
pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool {
|
||||
let before = self.list.len();
|
||||
self.list.retain(|p| !(p.id == id && p.engine == engine));
|
||||
let closed = self.list.len() != before;
|
||||
if closed {
|
||||
self.waiting.retain(|q| q.palette != id);
|
||||
self.actions.retain(|(p, _)| *p != id);
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// Closes the palettes of the engines `keep` does not keep, with their waiting events.
|
||||
fn keep_engines(&mut self, keep: impl Fn(&str) -> bool) {
|
||||
self.list.retain(|p| keep(&p.engine));
|
||||
let open: Vec<u64> = self.list.iter().map(|p| p.id).collect();
|
||||
self.waiting.retain(|q| open.contains(&q.palette));
|
||||
self.actions.retain(|(p, _)| open.contains(p));
|
||||
}
|
||||
|
||||
/// Puts `event` for the shown palette `id` in line, once it is checked against the palette.
|
||||
fn wait(&mut self, id: u64, event: UiEvent) -> std::result::Result<Waiting, String> {
|
||||
let Some(p) = self.list.iter().find(|p| p.id == id) else { return Err(format!("there is no script palette {id}")) };
|
||||
if !p.visible {
|
||||
return Err(format!("the script palette {id} is hidden"));
|
||||
}
|
||||
let mut event = scriptui::check_event(&p.dialog, event)?;
|
||||
let list = match &event {
|
||||
UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)),
|
||||
_ => None,
|
||||
};
|
||||
let element = control_of(&mut event).and_then(|c| p.dialog.nodes.get(*c)).map(|n| n.id);
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
// Only the most recent event for the same place can merge, in the same file access scope.
|
||||
// A click or close merges only after its palette's last waiting change, and a change only
|
||||
// after its palette's last waiting click or close.
|
||||
let closing = matches!(event, UiEvent::Click(_) | UiEvent::Close);
|
||||
let after = self.waiting.iter().rposition(|q| q.palette == id && matches!(q.event, UiEvent::Change(..)) == closing).map_or(0, |at| at + 1);
|
||||
let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element));
|
||||
let ticket = self.last_ticket.wrapping_add(1);
|
||||
if let Some(slot) = at.filter(|q| q.scope.same(&scope)) {
|
||||
slot.event = event;
|
||||
slot.list = list;
|
||||
slot.ticket = ticket;
|
||||
self.last_ticket = ticket;
|
||||
return Ok(Waiting::Merged);
|
||||
}
|
||||
if self.waiting.len() >= MAX_WAITING {
|
||||
return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept"));
|
||||
}
|
||||
self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope, ticket });
|
||||
self.last_ticket = ticket;
|
||||
Ok(Waiting::Added)
|
||||
}
|
||||
|
||||
/// The oldest waiting event whose palette is still shown, given to its control in the palette
|
||||
/// as the runs since left it, and that palette. An event whose control the palette
|
||||
/// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for
|
||||
/// example because a handler disabled or hid it, is dropped.
|
||||
fn next(&mut self) -> Option<(ScriptPalette, Queued)> {
|
||||
while let Some(q) = self.waiting.pop_front() {
|
||||
if let Some(taken) = self.checked(q) {
|
||||
return Some(taken);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other
|
||||
/// engines' palettes keep their places in line. Events whose file access scopes do not cover
|
||||
/// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest
|
||||
/// first, preserving the order within each scope.
|
||||
fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> {
|
||||
loop {
|
||||
let at = self.oldest_for(engine)?;
|
||||
let q = self.waiting.remove(at)?;
|
||||
if let Some(taken) = self.checked(q) {
|
||||
return Some(taken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The taken event `q` given to its control in its palette, and that palette, or `None` when it
|
||||
/// is dropped ([`Palettes::next`]).
|
||||
fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?;
|
||||
if let Some(c) = control_of(&mut q.event) {
|
||||
*c = p.dialog.index_of(q.element?)?;
|
||||
}
|
||||
// A list's change whose list a run changed since goes to its run, which ends with the
|
||||
// error that says so, when the list can still take a change: the choice is checked
|
||||
// without its item, which the list may no longer have.
|
||||
let list_changed = match (&q.event, &q.list) {
|
||||
(UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => {
|
||||
p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(c) = list_changed {
|
||||
scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).ok()?;
|
||||
} else {
|
||||
q.event = scriptui::check_event(&p.dialog, q.event).ok()?;
|
||||
}
|
||||
Some((p.clone(), q))
|
||||
}
|
||||
|
||||
/// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()`
|
||||
/// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]), with
|
||||
/// the actions its handlers play: those of the run that first showed its palette.
|
||||
pub(crate) fn take_for(&mut self, engine: &str) -> Option<(Queued, Vec<Playable>)> {
|
||||
let q = self.next_of(engine).map(|(_, q)| q)?;
|
||||
if let Some(taken) = self.taken_inline.as_mut() {
|
||||
taken.push(q.ticket);
|
||||
}
|
||||
let actions = self.actions.iter().find(|(id, _)| *id == q.palette).map(|(_, a)| a.clone()).unwrap_or_default();
|
||||
Some((q, actions))
|
||||
}
|
||||
|
||||
/// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`]
|
||||
/// would then check and take.
|
||||
pub(crate) fn waits_for(&self, engine: &str) -> bool {
|
||||
self.oldest_for(engine).is_some()
|
||||
}
|
||||
|
||||
/// The place of the oldest event for a palette of `engine`, when a palette's `update()` in a
|
||||
/// run of that engine may take it ([`Palettes::next_of`]): the run reaches the same files the
|
||||
/// event's scope reaches, so the handler runs with neither more nor less access than in a run
|
||||
/// of its own. Any other event waits for a run of its own.
|
||||
fn oldest_for(&self, engine: &str) -> Option<usize> {
|
||||
self.waiting.iter().position(|q| q.scope.matches_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine))
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` in a `#targetengine` line, quoted with a quote it does not hold.
|
||||
fn engine_line(name: &str) -> String {
|
||||
let quote = if name.contains('"') { '\'' } else { '"' };
|
||||
format!("#targetengine {quote}{name}{quote}")
|
||||
}
|
||||
|
||||
/// The source of a palette's handler run: its engine, and the call that hands the event to the
|
||||
/// palette, which takes it from the run's host.
|
||||
fn handler_source(engine: &str) -> String {
|
||||
format!("{}\nthis[{:?}]();\n", engine_line(engine), vectorcraft_js::scriptui::PALETTE_EVENT_GLOBAL)
|
||||
}
|
||||
|
||||
/// The event `event` (`click`, `change` or `close`) for `dialog`, from `script.palette.event`'s
|
||||
/// `control` (a control's index, or its name or text) and `value` (an edit field's text, a slider's
|
||||
/// number, or a list's item index or null).
|
||||
pub(crate) fn parse_event(
|
||||
dialog: &ScriptUiDialog,
|
||||
event: &str,
|
||||
control: Option<&Value>,
|
||||
value: Option<&Value>,
|
||||
) -> std::result::Result<UiEvent, String> {
|
||||
if event == "close" {
|
||||
if control.is_some() || value.is_some() {
|
||||
return Err("a close takes no `control` and no `value`".into());
|
||||
}
|
||||
return Ok(UiEvent::Close);
|
||||
}
|
||||
let id = match control {
|
||||
Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?,
|
||||
Some(Value::String(s)) => dialog.find(s).ok_or_else(|| format!("the palette has no control named {}", super::dialogs::cut_to(s, 64)))?,
|
||||
_ => return Err("`control` must be a control's index, name or text".into()),
|
||||
};
|
||||
let list = dialog.nodes.get(id).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox));
|
||||
let event = match (event, value) {
|
||||
("click", None) => UiEvent::Click(id),
|
||||
("click", Some(_)) => return Err("a click takes no `value`".into()),
|
||||
("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())),
|
||||
("change", Some(Value::Number(v))) if list => match scriptui::list_index(v) {
|
||||
Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))),
|
||||
None => return Err("a list's `value` must be an item index or null".into()),
|
||||
},
|
||||
("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))),
|
||||
("change", Some(Value::Null)) if list => UiEvent::Change(id, UiValue::Index(None)),
|
||||
("change", _) => return Err("a change's `value` must be a string, a number, or for a list an item index or null".into()),
|
||||
_ => return Err("`event` must be click, change or close".into()),
|
||||
};
|
||||
scriptui::check_event(dialog, event)
|
||||
}
|
||||
|
||||
/// A palette as `script.palettes` lists it.
|
||||
pub(crate) fn palette_json(p: &ScriptPalette) -> Value {
|
||||
let controls: Vec<Value> = p
|
||||
.dialog
|
||||
.nodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(1)
|
||||
.map(|(i, n)| {
|
||||
let mut c = Map::new();
|
||||
c.insert("index".into(), json!(i));
|
||||
c.insert("kind".into(), json!(kind_id(n.kind)));
|
||||
c.insert("name".into(), json!(n.name));
|
||||
c.insert("text".into(), json!(n.text));
|
||||
c.insert("enabled".into(), json!(n.enabled));
|
||||
c.insert("visible".into(), json!(n.visible));
|
||||
match n.kind {
|
||||
UiKind::CheckBox | UiKind::RadioButton => {
|
||||
c.insert("value".into(), json!(n.checked));
|
||||
}
|
||||
UiKind::Slider | UiKind::ProgressBar => {
|
||||
c.insert("value".into(), json!(n.value));
|
||||
}
|
||||
UiKind::DropDownList | UiKind::ListBox => {
|
||||
c.insert("items".into(), json!(n.items));
|
||||
c.insert("selection".into(), json!(n.selection));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Value::Object(c)
|
||||
})
|
||||
.collect();
|
||||
json!({"id": p.id, "engine": p.engine, "title": p.dialog.title(), "visible": p.visible, "controls": controls})
|
||||
}
|
||||
|
||||
fn kind_id(kind: UiKind) -> &'static str {
|
||||
match kind {
|
||||
UiKind::Dialog => "palette",
|
||||
UiKind::Group => "group",
|
||||
UiKind::Panel => "panel",
|
||||
UiKind::StaticText => "statictext",
|
||||
UiKind::EditText => "edittext",
|
||||
UiKind::Button => "button",
|
||||
UiKind::CheckBox => "checkbox",
|
||||
UiKind::RadioButton => "radiobutton",
|
||||
UiKind::DropDownList => "dropdownlist",
|
||||
UiKind::ListBox => "listbox",
|
||||
UiKind::Slider => "slider",
|
||||
UiKind::ProgressBar => "progressbar",
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The palettes the named engines' runs showed and have not closed, shown or hidden, in the
|
||||
/// order they were first shown.
|
||||
pub fn script_palettes(&self) -> &[ScriptPalette] {
|
||||
&self.script_palettes.list
|
||||
}
|
||||
|
||||
/// How many palette events wait for a run.
|
||||
pub fn script_palette_events_waiting(&self) -> usize {
|
||||
self.script_palettes.waiting.len()
|
||||
}
|
||||
|
||||
/// The changes that wait for a run, as (palette id, the id of the control they change).
|
||||
pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> {
|
||||
self.script_palettes
|
||||
.waiting
|
||||
.iter()
|
||||
.filter(|q| matches!(q.event, UiEvent::Change(..)))
|
||||
.filter_map(|q| q.element.map(|e| (q.palette, e)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event
|
||||
/// waits, no run is going, and no undo group is open, which a run cannot start in, nor a drag
|
||||
/// in a document other than the active one. A drag in the active document is not counted,
|
||||
/// since starting the run settles it.
|
||||
pub fn script_palette_can_start(&self) -> bool {
|
||||
!self.script_palettes.waiting.is_empty() && !self.script_running() && !self.palette_run_blocked()
|
||||
}
|
||||
|
||||
/// Whether an open edit keeps a palette event's run from starting: an undo group, the
|
||||
/// session's or a document's, or a drag in a document other than the active one (starting the
|
||||
/// run settles a drag in the active one).
|
||||
pub(crate) fn palette_run_blocked(&self) -> bool {
|
||||
let active = self.active().map(|d| d.uid);
|
||||
self.undo_group_open() || self.docs.iter().any(|d| d.interaction.is_some() && Some(d.uid) != active)
|
||||
}
|
||||
|
||||
/// Whether an undo group is open, the session's or a document's, which a run cannot start in.
|
||||
pub(crate) fn undo_group_open(&self) -> bool {
|
||||
self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some())
|
||||
}
|
||||
|
||||
/// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going
|
||||
/// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it
|
||||
/// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait.
|
||||
pub fn script_palette_event(&mut self, id: u64, event: UiEvent) -> std::result::Result<Waiting, String> {
|
||||
self.script_palettes.wait(id, event)
|
||||
}
|
||||
|
||||
/// Starts the run of the oldest waiting palette event, when no run is going. → `None` when a
|
||||
/// run is going or no event waits; otherwise the run's name, or the error that ended it before
|
||||
/// it began. An open edit that cannot be settled gives its error, and the events keep waiting.
|
||||
pub fn script_palette_start(&mut self) -> Option<Result<String>> {
|
||||
if self.script_running() || self.script_palettes.waiting.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// An event waits while a drag or an undo group is open, which a run cannot start in.
|
||||
if let Err(e) = self.settle_for_script() {
|
||||
return Some(Err(e));
|
||||
}
|
||||
let (palette, mut queued) = self.script_palettes.next()?;
|
||||
self.script_palettes.started_ticket = Some(queued.ticket);
|
||||
queued.grants = Some(palette.grants.clone());
|
||||
let title = palette.dialog.title();
|
||||
let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() };
|
||||
let locale = super::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language));
|
||||
let actions = self.script_palettes.actions.iter().find(|(id, _)| *id == palette.id).map(|(_, a)| a.clone()).unwrap_or_default();
|
||||
let request = super::Request {
|
||||
name,
|
||||
name_given: true,
|
||||
file: palette.file.clone(),
|
||||
checked_real: None,
|
||||
source: handler_source(&palette.engine),
|
||||
args: Map::new(),
|
||||
fuel: super::DEFAULT_FUEL,
|
||||
locale,
|
||||
answers: Vec::new(),
|
||||
module: false,
|
||||
actions,
|
||||
};
|
||||
// The run takes the scope of the request that gave the event, within the scope in force now.
|
||||
let scope = queued.scope.clone().within_current();
|
||||
self.script_palettes.starting = Some(queued);
|
||||
let r = scope.run(|| self.script_start(request));
|
||||
self.script_palettes.starting = None;
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// Closes the palettes whose engine the session no longer keeps.
|
||||
pub(crate) fn keep_engines_palettes(&mut self) {
|
||||
let names: Vec<String> = self.script_engines().into_iter().map(|(name, ..)| name).collect();
|
||||
self.script_palettes.keep_engines(|e| names.iter().any(|n| n == e));
|
||||
}
|
||||
|
||||
/// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn,
|
||||
/// in their order in line. → the report of the event just given, wherever it waited, or an
|
||||
/// error when it was dropped without a run. An event whose run could not begin, for example
|
||||
/// because the recovery copies could not be saved, ends this, and the events after it keep
|
||||
/// waiting: with its error, or with the given event's result when that one has run. An open
|
||||
/// edit that cannot be settled ends this with its error, and the given event no longer waits.
|
||||
pub(crate) fn script_palette_run_waiting(&mut self) -> Result<Value> {
|
||||
let want = self.script_palettes.last_ticket;
|
||||
let mut mine = None;
|
||||
loop {
|
||||
if !self.script_running()
|
||||
&& !self.script_palettes.waiting.is_empty()
|
||||
&& let Err(e) = self.settle_for_script()
|
||||
{
|
||||
// A caller that gives the event again then does not give it twice.
|
||||
self.script_palettes.waiting.retain(|q| q.ticket != want);
|
||||
return mine.unwrap_or(Err(e));
|
||||
}
|
||||
let Some(started) = self.script_palette_start() else { break };
|
||||
// A later event whose run cannot begin leaves the given event's result as it is.
|
||||
if let Err(e) = started {
|
||||
return mine.unwrap_or(Err(e));
|
||||
}
|
||||
self.script_palettes.taken_inline = Some(Vec::new());
|
||||
let r = self.script_run_to_end();
|
||||
// A run of the same engine can take the event while it runs (`update()`): its report
|
||||
// is then the event's.
|
||||
let inline = self.script_palettes.taken_inline.take().is_some_and(|t| t.contains(&want));
|
||||
if mine.is_none() && (self.script_palettes.started_ticket == Some(want) || inline) {
|
||||
mine = Some(r);
|
||||
}
|
||||
}
|
||||
mine.unwrap_or_else(|| {
|
||||
Err(EngineError::Other("the script palette event was dropped without a run: its palette or control can no longer take it".into()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run
|
||||
//! gives when it shows one, checked and laid out here before the app draws it, and the events the
|
||||
//! person or `script.run`'s `answers` give back.
|
||||
//! person or `script.run`'s `answers` give back. A palette (`new Window("palette")`) is described
|
||||
//! and laid out the same way; [`super::palettes`] keeps it and its events, and the host functions
|
||||
//! `palette`, `paletteShow`, `paletteUpdate`, `paletteHide`, `paletteClose` and `paletteEvent` here
|
||||
//! act for a run in a named engine, and throw [`PALETTE_NEEDS_ENGINE`] in any other.
|
||||
//!
|
||||
//! A description lists the dialog first and each control after the container that holds it. It is
|
||||
//! refused with an error thrown at `show()` when a control's container comes after it or is not a
|
||||
@@ -36,6 +39,7 @@ use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError};
|
||||
pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES};
|
||||
|
||||
use super::Host;
|
||||
use super::palettes::Queued;
|
||||
|
||||
/// The largest size or place, in pixels, of a dialog or a control in it.
|
||||
pub const MAX_EXTENT: f32 = 8192.0;
|
||||
@@ -143,6 +147,9 @@ pub struct UiNode {
|
||||
/// list from one that holds the same texts again.
|
||||
pub items_revision: u64,
|
||||
pub selection: Option<usize>,
|
||||
/// How many times a list's items were added or removed, which a palette's waiting change of
|
||||
/// the list is checked against.
|
||||
pub revision: f64,
|
||||
pub multiline: bool,
|
||||
pub readonly: bool,
|
||||
pub rect: UiRect,
|
||||
@@ -208,6 +215,12 @@ impl ScriptUiDialog {
|
||||
};
|
||||
by(true).or_else(|| by(false))
|
||||
}
|
||||
|
||||
/// The index in [`Self::nodes`] of the control whose id ([`UiNode::id`]) is `id`, if the dialog
|
||||
/// has one.
|
||||
pub fn index_of(&self, id: u64) -> Option<usize> {
|
||||
self.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A value a control takes in a change.
|
||||
@@ -516,6 +529,7 @@ pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
|
||||
items,
|
||||
items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64),
|
||||
selection,
|
||||
revision: number(field(f, "revision")).unwrap_or(0.0),
|
||||
multiline: flag("multiline"),
|
||||
readonly: flag("readonly"),
|
||||
rect: UiRect::default(),
|
||||
@@ -709,7 +723,132 @@ fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>
|
||||
|
||||
/// Adds `Window` to the realm, for the run `link` holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> {
|
||||
realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))])
|
||||
realm.define_script_ui(vec![
|
||||
("open".into(), function(link, open)),
|
||||
("wait".into(), function(link, wait)),
|
||||
("end".into(), function(link, end)),
|
||||
("palette".into(), function(link, palette)),
|
||||
("paletteShow".into(), function(link, palette_show)),
|
||||
("paletteUpdate".into(), function(link, palette_update)),
|
||||
("paletteHide".into(), function(link, palette_hide)),
|
||||
("paletteClose".into(), function(link, palette_close)),
|
||||
("paletteEvent".into(), function(link, palette_event)),
|
||||
("paletteTake".into(), function(link, palette_take)),
|
||||
("palettePending".into(), function(link, palette_pending)),
|
||||
("paletteDraw".into(), function(link, palette_draw)),
|
||||
])
|
||||
}
|
||||
|
||||
/// The error of `new Window("palette")` in a run without a named engine.
|
||||
pub const PALETTE_NEEDS_ENGINE: &str = "Window: a palette needs a named engine, which keeps its controls and handlers after the script ends; put a #targetengine line with a name other than main at the top of the script";
|
||||
|
||||
/// The named engine of the run, for a palette.
|
||||
fn palette_engine(host: &Host) -> Result<&str, HostError> {
|
||||
host.engine.as_deref().ok_or_else(|| HostError::Error(PALETTE_NEEDS_ENGINE.into()))
|
||||
}
|
||||
|
||||
/// A palette's id as a script holds it: a whole number from 1, or none.
|
||||
fn palette_id(d: Option<&Data>) -> Option<u64> {
|
||||
match d {
|
||||
Some(Data::Number(n)) if *n >= 1.0 && n.fract() == 0.0 && *n < 9.0e15 => Some(*n as u64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `new Window("palette")`: refused in a run without a named engine.
|
||||
fn palette(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
palette_engine(host)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A palette's `show()`, with its description and its id (none the first time). → its id.
|
||||
fn palette_show(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
let dialog = described(host, args)?;
|
||||
let id = palette_id(args.get(1));
|
||||
let grants = host.disk.borrow().own().to_string();
|
||||
let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants, &host.actions), dialog);
|
||||
shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range)
|
||||
}
|
||||
|
||||
/// The palette `id`'s controls as a handler, `add()` or `update()` left them.
|
||||
fn palette_update(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
let dialog = described(host, args)?;
|
||||
if let Some(id) = palette_id(args.get(1)) {
|
||||
host.session.borrow_mut().script_palettes.update(id, &engine, dialog);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A palette's `update()` in the script's own code asks whether the app draws the palette now
|
||||
/// ([`Host::update_drawn`]). → `true` when it does, and the script then gives the palette's
|
||||
/// controls through `paletteUpdate`.
|
||||
fn palette_draw(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
palette_engine(host)?;
|
||||
Ok(Data::Bool(host.update_drawn()))
|
||||
}
|
||||
|
||||
/// A palette's `update()` takes the oldest event the person gave a palette of the run's engine,
|
||||
/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. Until the next
|
||||
/// `palettePending`, `app.doScript` plays the actions of the run that showed the event's palette.
|
||||
fn palette_take(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
let taken = host.session.borrow_mut().script_palettes.take_for(&engine);
|
||||
let (data, actions) = match taken {
|
||||
Some((queued, actions)) => (event_data(queued), Some(actions)),
|
||||
None => (Data::Null, None),
|
||||
};
|
||||
*host.palette_actions.borrow_mut() = actions;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Whether an event waits for a palette of the run's engine, which a palette's `update()` asks
|
||||
/// before it gives the palettes' controls and takes the event with `paletteTake`, and once more
|
||||
/// after the event's handlers end. `app.doScript` then plays the run's own actions again.
|
||||
fn palette_pending(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
*host.palette_actions.borrow_mut() = None;
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
Ok(Data::Bool(host.session.borrow().script_palettes.waits_for(&engine)))
|
||||
}
|
||||
|
||||
fn palette_hide(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
if let Some(id) = palette_id(args.first()) {
|
||||
host.session.borrow_mut().script_palettes.hide(id, &engine);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn palette_close(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
if let Some(id) = palette_id(args.first()) {
|
||||
host.session.borrow_mut().script_palettes.close(id, &engine);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The event a palette handler's run is for, once: `{palette, event, id, value, element, items}`,
|
||||
/// as `show()` takes a dialog's event with the palette's id added, the id of a click's or a
|
||||
/// change's control (`element`, [`UiNode::id`]), which the run finds the control by, and for a
|
||||
/// list's change the items the palette showed; `null` for any other run, and after the first call.
|
||||
fn palette_event(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) };
|
||||
Ok(event_data(queued))
|
||||
}
|
||||
|
||||
/// The waiting event `queued` as a script takes it ([`palette_event`]).
|
||||
fn event_data(queued: Queued) -> Data {
|
||||
let Data::Object(mut fields) = queued.event.data() else { return Data::Null };
|
||||
fields.push(("palette".into(), Data::Number(queued.palette as f64)));
|
||||
if let Some(element) = queued.element {
|
||||
fields.push(("element".into(), Data::Number(element as f64)));
|
||||
}
|
||||
if let Some((items, revision)) = queued.list {
|
||||
fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect())));
|
||||
fields.push(("revision".into(), Data::Number(revision)));
|
||||
}
|
||||
Data::Object(fields)
|
||||
}
|
||||
|
||||
fn described(host: &Host, args: &[Data]) -> Result<ScriptUiDialog, HostError> {
|
||||
|
||||
@@ -198,6 +198,7 @@ impl Session {
|
||||
script_high_water: Default::default(),
|
||||
script_style_trail: Default::default(),
|
||||
script_in_run: false,
|
||||
script_palettes: Default::default(),
|
||||
overprint_after_run: false,
|
||||
script_unfenced: None,
|
||||
script_printers: None,
|
||||
|
||||
@@ -661,6 +661,7 @@ impl Session {
|
||||
self.pending_paint = None;
|
||||
// The previous preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
|
||||
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
|
||||
// A selected object's converted appearance must not replace the current paints while
|
||||
@@ -877,6 +878,7 @@ impl Session {
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// A canceled preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
|
||||
// the document has it again, not as a preview left it. An interaction that changed only the
|
||||
// defaults (`defaultsOnly: true`) leaves the defaults it began with.
|
||||
|
||||
@@ -25,6 +25,12 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run a command callback and keep warnings from every preview it settles or restores.
|
||||
pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
let (r, settled) = self.collect_settled_warnings(f);
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
}
|
||||
|
||||
/// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
|
||||
fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
|
||||
let Some(d) = self.active_mut() else { return (spec.enabled)(self) };
|
||||
@@ -121,10 +127,9 @@ impl Session {
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
let r = if self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| {
|
||||
self.command_with_settled_warnings(|s| {
|
||||
if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) }
|
||||
});
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
})
|
||||
} else {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
@@ -253,6 +258,10 @@ impl Session {
|
||||
// after an undone or redone Assign Profile, a failed or panicked command's documents put
|
||||
// back, and a batch step, before the next step converts through them.
|
||||
self.sync_front_profiles();
|
||||
if self.depth != 0 {
|
||||
// The next batch step can measure/outline definitions this step adopted.
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
if r.is_err() && self.depth == 0 {
|
||||
self.batch_paint_docs.clear();
|
||||
// A failed or panicked command's documents are put back: type is drawn in their
|
||||
|
||||
@@ -118,6 +118,7 @@ mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod missing_links;
|
||||
mod moved;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
@@ -196,6 +197,7 @@ mod script_folder;
|
||||
mod script_include;
|
||||
mod script_io;
|
||||
mod script_modules;
|
||||
mod script_palettes;
|
||||
mod script_print;
|
||||
mod script_raster_capture;
|
||||
mod script_run;
|
||||
|
||||
@@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() {
|
||||
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() {
|
||||
let mut s = session();
|
||||
let (a, b) = reversed_pair(&mut s);
|
||||
for (id, item) in [(a, 1), (b, 2)] {
|
||||
for effect in ["distort.twist", "distort.roughen"] {
|
||||
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect}));
|
||||
}
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [b.0, a.0]}));
|
||||
let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone());
|
||||
let before = appearances(&s);
|
||||
for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] {
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
|
||||
let moved = run(&mut s, "effect.move", params);
|
||||
assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor");
|
||||
assert_eq!(moved["index"], json!(0));
|
||||
for (appearance, item) in appearances(&s).iter().zip([1, 2]) {
|
||||
let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(ids, ["distort.roughen", "distort.twist"]);
|
||||
assert!(appearance.effects_at(Some(0)).unwrap().is_empty());
|
||||
}
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(appearances(&s), before);
|
||||
}
|
||||
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
|
||||
for destination in [0, 2] {
|
||||
assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err());
|
||||
assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list");
|
||||
}
|
||||
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"}));
|
||||
let before = appearances(&s);
|
||||
assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err());
|
||||
assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row");
|
||||
}
|
||||
|
||||
/// `effect.move`'s reply names where the effect landed in the object whose row the active item is
|
||||
/// (the first selected object), also when that object paints above the others.
|
||||
#[test]
|
||||
|
||||
@@ -152,7 +152,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
// The worker takes its turn after the slot is read and before the flag is, if the slot is free.
|
||||
let ended = link_watch::ended_without_stamps(&scan, |flag| {
|
||||
if let Ok(mut slot) = scan.0.try_lock() {
|
||||
*slot = Some((uid, stamps.clone()));
|
||||
*slot = Some(link_watch::LinkScanResult::stamps(uid, stamps.clone()));
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
}
|
||||
flag.load(Ordering::SeqCst)
|
||||
@@ -163,7 +163,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
let scan = scan.clone();
|
||||
move || {
|
||||
let _ended = link_watch::Ended(scan.clone());
|
||||
*scan.0.lock().unwrap() = Some((uid, stamps));
|
||||
*scan.0.lock().unwrap() = Some(link_watch::LinkScanResult::stamps(uid, stamps));
|
||||
}
|
||||
});
|
||||
worker.join().unwrap();
|
||||
|
||||
@@ -1241,3 +1241,258 @@ fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transf
|
||||
let asked = double_click(&mut s, "directSelection");
|
||||
assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}");
|
||||
}
|
||||
|
||||
/// Live radii of every corner of path `id`, or `None` when it has no Live Corners left.
|
||||
fn live_radii(s: &Session, id: NodeId) -> Option<Vec<f64>> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n)?;
|
||||
let all = lc.all();
|
||||
Some(all.iter().map(|k| lc.drawn_radius(*k)).collect())
|
||||
}
|
||||
|
||||
/// #10545: moving an anchor of a rounded rectangle moves its corner and keeps every corner live
|
||||
/// at its radius, in one undo step.
|
||||
#[test]
|
||||
fn moving_an_anchor_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 0, "y": 25})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert_eq!(n.path_data().unwrap().anchor_count(), 8);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(corners(&s, id), ([10.0; 4], [CornerKind::Round; 4], 8));
|
||||
}
|
||||
|
||||
/// #10545: dragging direct-selected anchors of a rounded rectangle keeps its corners live, and
|
||||
/// the corner they belong to moves by the drag.
|
||||
#[test]
|
||||
fn dragging_selected_anchors_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let before = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
// The two ends of the top-left corner's arc.
|
||||
let arc: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(arc.len(), 2);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": arc, "mode": "set"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": -20, "dy": 0})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
let after = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
assert!(after.x0 < before.x0 - 10.0 && (after.x1 - before.x1).abs() < 1e-6, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path() {
|
||||
for xf in [Affine::scale_non_uniform(2.0, 1.0), Affine::new([1.0, 0.0, 0.5, 1.0, 10.0, 10.0])] {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
let live = LiveShape::Rectangle { w: 50.0, h: 60.0, radii: [10.0; 4], kinds: Default::default(), radii_relative: false, xf };
|
||||
let mut expected = live.to_path();
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let NodeKind::Path { path, live: slot, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not a path") };
|
||||
*path = expected.clone();
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
let delta = vectorcraft_geom::Vec2::new(-20.0, 5.0);
|
||||
let a = expected.anchor_mut(0, 0).unwrap();
|
||||
*a = a.transform(Affine::translate(delta));
|
||||
let target = a.p;
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 0, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": delta.x, "dy": delta.y, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(n.live_shape().is_none(), "{command}: {xf:?}");
|
||||
assert_eq!(n.path_data().unwrap(), &expected, "{command}: {xf:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_remaps_the_whole_anchor_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected: BTreeSet<_> = [0, 2].into_iter().map(|k| *lc.anchors_of(&BTreeSet::from([k])).first().unwrap()).collect();
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([0])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(50.0, 30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected);
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 0)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": 50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
assert_eq!(selected_anchors(&s, id), Some(lc.anchors_of(&BTreeSet::from([0, 2]))), "{command}");
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id), "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected = lc.anchors_of(&BTreeSet::from([1]));
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([2])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, -30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected.clone());
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": moved.1, "x": target.x, "y": target.y})).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources);
|
||||
assert_eq!(lc.anchors_of(&BTreeSet::from([1])), selected);
|
||||
assert_eq!(selected_anchors(&s, id), Some(selected));
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_corner_layout_keeps_the_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, anchors(&[0, 1, 2]));
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let sources = LiveCorners::of(n).unwrap().sources().to_vec();
|
||||
let target = n.path_data().unwrap().subpaths[0].anchors[4].p + vectorcraft_geom::Vec2::new(-20.0, 0.0);
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 4, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -20, "dy": 0, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().sources(), sources);
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_keeps_the_key_anchor_on_its_corner() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, key, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
// The top right corner moves to the middle of the rectangle.
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([1])).first().unwrap();
|
||||
let key = *lc.anchors_of(&BTreeSet::from([3])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, 30.0);
|
||||
(BTreeSet::from([moved, key]), moved, key, target, lc.sources().to_vec())
|
||||
};
|
||||
let sel = &mut s.doc_mut().unwrap().selection;
|
||||
sel.anchors.insert(id, selected);
|
||||
sel.key_anchor = Some((id, key));
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
let now = s.doc().unwrap().selection.key_anchor;
|
||||
assert_eq!(now, lc.anchors_of(&BTreeSet::from([3])).first().map(|r| (id, *r)), "{command}");
|
||||
assert_ne!(now, Some((id, key)), "{command}: the key anchor's index changed with the recut");
|
||||
}
|
||||
}
|
||||
|
||||
/// A nudge of a pixel-aligned rounded rectangle's edge that the pixel-grid snap takes back
|
||||
/// changes nothing and records no undo step.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_records_no_undo_step() {
|
||||
let (mut s, id) = session();
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(left.len(), 4);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
// A first move by a whole point makes the rectangle a live path; the snap keeps that move.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// The same nudge on a rounded rectangle that no anchor edit has touched yet records no undo
|
||||
/// step and leaves it a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_keeps_a_live_rectangle() {
|
||||
for x in [10, 50, 137] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "x = {x}");
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })), "x = {x}");
|
||||
assert_eq!(s.doc().unwrap().doc, doc, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same nudge with a second pixel-aligned rectangle selected whole, which the snap also takes
|
||||
/// back, records no undo step and leaves the rounded rectangle a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_with_an_object_selected_whole_records_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let whole = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [whole.0]})).unwrap();
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [whole.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.whole(), vec![whole]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })));
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Canvas marker state and command API, independent of artwork and link update preferences.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::tests_links::{Folder, RED, place, png, session, write};
|
||||
use crate::*;
|
||||
|
||||
fn marked(s: &mut Session) -> Vec<u64> {
|
||||
s.execute("links.marked", &json!({})).unwrap()["images"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_toggle_is_transient_per_document_and_validated() {
|
||||
let mut s = session();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
for p in [json!({"on": "false"}), json!({"on": 1}), json!({"on": []})] {
|
||||
assert!(s.execute("view.showMissingLinks", &p).is_err());
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().show_missing_links);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({})).unwrap(), json!({"on": false}));
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_follow_files_relink_update_and_embed() {
|
||||
let dir = Folder::new("marker-lifecycle");
|
||||
let path = dir.file("art.png");
|
||||
let replacement = dir.file("replacement.png");
|
||||
let bytes = png(40, 40, RED);
|
||||
write(&path, &bytes);
|
||||
write(&replacement, &bytes);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let saved = vectorcraft_format::save_file(&doc);
|
||||
let pixels = vectorcraft_render::Renderer::new().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels;
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection, selection);
|
||||
assert_eq!(st.history.undo.len(), undo);
|
||||
assert_eq!(vectorcraft_format::save_file(&st.doc), saved);
|
||||
assert_eq!(
|
||||
vectorcraft_render::Renderer::new().render_region(&st.doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels,
|
||||
pixels
|
||||
);
|
||||
s.execute("links.relink", &json!({"ids": [id.0], "path": replacement})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
write(&replacement, &bytes);
|
||||
s.execute("links.update", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() {
|
||||
for mode in ["automatically", "askWhenModified", "manually"] {
|
||||
let dir = Folder::new(&format!("marker-watch-{mode}"));
|
||||
let path = dir.file("art.png");
|
||||
let bytes = png(20, 20, RED);
|
||||
write(&path, &bytes);
|
||||
let mut s = session();
|
||||
s.prefs.update_links = mode.into();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert_eq!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1, vec![id]);
|
||||
write(&path, &bytes);
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
let seen = s.doc().unwrap().missing_link_markers.as_ref().unwrap().0.clone();
|
||||
s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 3, "height": 4})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&seen, &s.doc().unwrap().missing_link_markers.as_ref().unwrap().0));
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
// Switching the toggle off while a look is pending must not resurrect its markers.
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_missing_links_on_returns_before_the_file_probe_and_scans_on_the_link_watcher() {
|
||||
use crate::cmd::links::probe_gate::{self, Gate};
|
||||
use std::time::Duration;
|
||||
let dir = Folder::new("marker-toggle-nonblocking");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let stored = crate::tests_links::image(&s, id).link.unwrap().path;
|
||||
let gate = Gate::close(&stored);
|
||||
// The toggle returns while the probe of the (slow) linked file is held closed.
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
assert!(!gate.finished(), "the toggle waited for the file probe");
|
||||
assert_eq!(gate.entered(Duration::ZERO), None, "the toggle probed the file on the calling thread");
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
// The desktop app starts the watcher's look at once, and the probe runs there.
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
assert_eq!(gate.entered(Duration::from_secs(10)).as_deref(), Some("link-watch"));
|
||||
assert!(s.poll_link_scan().is_none(), "the look ended before its probe was released");
|
||||
gate.open();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
probe_gate::remove(&stored);
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.missing_link_scan_due());
|
||||
// Turning it on again while on keeps the markers; off clears them.
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_scan_for_a_document_without_links_ends_without_a_worker() {
|
||||
let mut s = session();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(s.link_scan.is_none());
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_hidden_when_the_overlay_turns_on_is_marked_once_shown() {
|
||||
let dir = Folder::new("marker-hidden-then-shown");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
// Found by the desktop's link watch worker, and in place as the web app does.
|
||||
for in_place in [false, true] {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let mark = |s: &mut Session| {
|
||||
if in_place {
|
||||
s.mark_missing_links_in_place();
|
||||
} else {
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
}
|
||||
};
|
||||
mark(&mut s);
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty(), "hidden art is not marked");
|
||||
s.execute("object.showAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id], "shown art is marked without another scan");
|
||||
if in_place {
|
||||
// Artwork restored while the overlay is on is marked again.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.mark_missing_links_in_place());
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.mark_missing_links_in_place(), "unchanged art is not looked at again");
|
||||
}
|
||||
write(&path, &png(20, 20, RED));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_include_placed_documents_and_exclude_hidden_art() {
|
||||
let dir = Folder::new("marker-placed");
|
||||
let path = dir.file("placed.vectorcraft");
|
||||
write(&path, &vectorcraft_format::save_file(&vectorcraft_doc::Document::new(40.0, 20.0)));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::PlacedDocument(_)));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
s.execute("object.move", &json!({"ids": [id.0], "dx": 15, "dy": 10})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
@@ -171,6 +171,38 @@ fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
|
||||
}
|
||||
|
||||
/// Divide refuses a cutting line with more segments than its planar map takes, instead of
|
||||
/// dividing the square without the line, and leaves the document and the undo history as they were.
|
||||
#[test]
|
||||
fn divide_refuses_cutting_lines_past_the_segment_cap() {
|
||||
let mut s = session();
|
||||
let base = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let cutter = NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 50}, {"x": 110, "y": 50}]})).unwrap()["id"].as_u64().unwrap());
|
||||
// A zigzag across the square with one segment more than the cap, the square's four sides aside.
|
||||
let segments = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS - 3;
|
||||
s.edit("zigzag", |d, sel| {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
bp.move_to((-10.0, 40.0));
|
||||
for i in 1..=segments {
|
||||
let x = -10.0 + 120.0 * i as f64 / segments as f64;
|
||||
bp.line_to((x, if i % 2 == 0 { 40.0 } else { 60.0 }));
|
||||
}
|
||||
// Unfilled, so the zigzag stays open and cuts.
|
||||
let n = d.node_mut(cutter).unwrap();
|
||||
n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
|
||||
n.kind = NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false };
|
||||
sel.set([cutter, base]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo_len = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("select fewer paths"), "{e}");
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclude_makes_compound() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -200,6 +200,30 @@ fn prompt_cancel_returns_null() {
|
||||
assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true]));
|
||||
}
|
||||
|
||||
/// A prompt's answer that the engine's nearly full heap cannot hold ends the run, and the report
|
||||
/// lists the prompt with the answer `"error"`, not the text that did not reach the script.
|
||||
#[test]
|
||||
fn a_prompt_answer_that_cannot_reach_the_script_is_listed_as_an_error() {
|
||||
use crate::script::TEST_ENGINE_HEAP;
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20)));
|
||||
let mut s = one_doc();
|
||||
let filled = headless(
|
||||
&mut s,
|
||||
"#targetengine full\nvar head = null, c = 'x';\nwhile (c.length < 4096) c += c;\nfor (var i = 0; ; i++) head = {s: c + i, n: head};",
|
||||
json!([]),
|
||||
);
|
||||
framed(&mut s, "#targetengine full\nvar a = prompt('Name', '');");
|
||||
let waited = pump(&mut s).is_none();
|
||||
let answered = s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES))));
|
||||
let ended = pump(&mut s);
|
||||
let report = s.script_report();
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(None));
|
||||
assert!(filled.unwrap_err().to_string().contains("Heap"));
|
||||
assert!(waited && answered);
|
||||
assert!(ended.unwrap().is_err(), "the answer did not fit in the heap");
|
||||
assert_eq!(report.unwrap()["dialogs"][0]["answer"], "error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialog_loop_stops_or_exhausts() {
|
||||
let mut s = one_doc();
|
||||
|
||||
@@ -2713,6 +2713,32 @@ fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() {
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// `removeAll()` on the `pathItems` of a compound path that clips a group keeping other art
|
||||
/// would leave an empty clipping path, so it throws and deletes nothing, as deleting the clipping
|
||||
/// path itself does. Removing some of its paths still works.
|
||||
#[test]
|
||||
fn removing_all_the_paths_of_a_clipping_compound_path_is_refused() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [compound.0, other.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
run(&mut s, "var g = app.activeDocument.groupItems[0]; g.compoundPathItems[0].zOrder(ZOrderMethod.BRINGTOFRONT); g.clipped = true;").unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound));
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete a clipping path"), "{e}");
|
||||
assert!(e.contains(&compound.0.to_string()), "{e}");
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
run(&mut s, "app.activeDocument.compoundPathItems[0].pathItems[0].remove();").unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.node(compound).and_then(|n| n.children()).map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it
|
||||
/// is runs no command, also in a layer whose ruler guides are above its art.
|
||||
#[test]
|
||||
@@ -3684,6 +3710,377 @@ fn scoped_remove_all_refuses_a_clipping_compound_path() {
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// Runs the document's `pathItems.removeAll()`, then logs its error message and the number of paths.
|
||||
const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m = '';\
|
||||
try { p.removeAll(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(p.length);";
|
||||
|
||||
/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the
|
||||
/// group keeps other art, and deletes nothing, as the scoped collections do.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_refuses_a_clipping_path() {
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
|
||||
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.parent_of(a).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(a));
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
// The script catches the error and counts the paths before the run ends, so the run's own
|
||||
// rollback cannot hide a deletion.
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
|
||||
assert!(e.contains(&a.0.to_string()), "{out:?}");
|
||||
assert!(!e.contains(&b.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// The document's `pathItems.removeAll()` would empty a compound path that clips a group keeping
|
||||
/// other art, so it throws and deletes nothing.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_refuses_to_empty_a_clipping_compound_path() {
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [compound.0, t.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [compound.0]})).unwrap();
|
||||
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
|
||||
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound));
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
|
||||
assert!(e.contains(&compound.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// A clipping mask made of a group of paths, as an imported SVG mask with several shapes is, would
|
||||
/// be left empty by the document's `pathItems.removeAll()`, so it throws and deletes nothing.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() {
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(outer).unwrap().clips());
|
||||
assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask));
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
|
||||
assert!(e.contains(&mask.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// Type clips by its glyph outlines, so a clipping group that keeps type after its paths go still
|
||||
/// clips, and the document's `pathItems.removeAll()` deletes every path.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_keeps_a_clipping_group_that_holds_type() {
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(outer).unwrap().clips());
|
||||
assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask));
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
assert_eq!(out[0], json!(""), "{out:?}");
|
||||
assert_eq!(out[1], json!(0));
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(a).is_none() && d.node(b).is_none());
|
||||
assert!(d.node(t).is_some() && d.node(u).is_some());
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// Type with no characters to draw gives no clip outline, so a clipping group whose paths would
|
||||
/// leave only such type makes the document's `pathItems.removeAll()` throw and delete nothing.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_refuses_when_only_blank_type_would_clip() {
|
||||
let (mut s, a, _) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) {
|
||||
tx.runs.iter_mut().for_each(|r| r.text = " ".into());
|
||||
}
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
|
||||
assert!(e.contains(&mask.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// A clipping group nested in a clipping mask clips by its first member only, so type it clips does
|
||||
/// not keep the outer mask's outline, and the document's `pathItems.removeAll()` names the outer
|
||||
/// mask too.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() {
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [b.0, t.0]})).unwrap();
|
||||
let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, nested.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
for (g, first) in [(nested, b), (outer, mask)] {
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(g).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != first);
|
||||
*clip = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
|
||||
assert!(e.split(": ").last().unwrap_or_default().split(", ").any(|id| id == mask.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A numbered paragraph whose text is a single space still draws its number, which clips, so the
|
||||
/// document's `pathItems.removeAll()` deletes the paths of a clipping group that keeps it.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_keeps_a_clipping_group_whose_type_draws_only_a_list_number() {
|
||||
use vectorcraft_doc::text::{NumberStyle, ParaList};
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) {
|
||||
tx.runs.iter_mut().for_each(|r| r.text = " ".into());
|
||||
let mut styles = tx.paragraph_styles();
|
||||
styles.iter_mut().for_each(|p| p.list = Some(ParaList::numbered(NumberStyle::Arabic)));
|
||||
tx.set_paragraph_styles(styles);
|
||||
}
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) {
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty());
|
||||
}
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
assert_eq!(out[0], json!(""), "{out:?}");
|
||||
assert_eq!(out[1], json!(0));
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(a).is_none() && d.node(b).is_none());
|
||||
assert!(d.node(t).is_some() && d.node(u).is_some());
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// Area type too short for its first line lays out no glyphs and gives no clip outline, so a
|
||||
/// clipping group whose paths would leave only such type makes the document's
|
||||
/// `pathItems.removeAll()` throw and delete nothing.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_refuses_when_only_overset_type_would_clip() {
|
||||
let (mut s, a, _) = doc();
|
||||
let t = NodeId(
|
||||
s.execute("text.create", &json!({"x": 10, "y": 250, "size": 12, "area": {"width": 100, "height": 1}, "text": "hi"})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) {
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty());
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
|
||||
assert!(e.contains(&mask.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// Hidden type does not clip, so a clipping group whose paths would leave only hidden type makes
|
||||
/// the document's `pathItems.removeAll()` throw and delete nothing.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_refuses_when_only_hidden_type_would_clip() {
|
||||
let (mut s, a, _) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(n) = d.node_mut(t) {
|
||||
n.visible = false;
|
||||
}
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
|
||||
assert!(e.contains(&mask.0.to_string()), "{out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() {
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let empty = NodeId(s.execute("object.newGroup", &json!({"parent": mask.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(outer).unwrap().clips());
|
||||
assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask));
|
||||
assert!(d.node(empty).unwrap().children().unwrap().is_empty());
|
||||
let before = d.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
assert_eq!(
|
||||
out[0],
|
||||
json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0))
|
||||
);
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() {
|
||||
for compound in [false, true] {
|
||||
let (mut s, a, b) = doc();
|
||||
let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
|
||||
s.execute(if compound { "object.compoundPath.make" } else { "object.group" }, &json!({})).unwrap();
|
||||
let sibling = s.active().unwrap().doc.parent_of(b).unwrap();
|
||||
let layer = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(layer).unwrap().clips());
|
||||
assert_eq!(d.node(layer).and_then(|n| n.children()).map(|k| k[0].id), Some(a));
|
||||
let before = d.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
if compound {
|
||||
assert_eq!(out, [json!(""), json!(0)]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(sibling).is_none());
|
||||
assert!(!d.node(layer).unwrap().clips());
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
} else {
|
||||
assert_eq!(
|
||||
out[0],
|
||||
json!(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}",
|
||||
a.0
|
||||
))
|
||||
);
|
||||
assert_eq!(out[1], json!(3));
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound
|
||||
/// path's paint and pixel alignment, as Release Compound Path gives them.
|
||||
#[test]
|
||||
|
||||
@@ -680,6 +680,68 @@ fn document_path_creators_use_the_active_layer_during_isolation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A locked or hidden active layer does not take a script's new path: the path goes on the
|
||||
/// topmost shown, unlocked layer, where the app's own creation commands put new art.
|
||||
#[test]
|
||||
fn document_path_creators_skip_a_locked_or_hidden_active_layer() {
|
||||
for (prop, value) in [("locked", true), ("visible", false)] {
|
||||
for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] {
|
||||
let (mut s, _, _) = doc();
|
||||
let editable = s.active().unwrap().active_layer.unwrap();
|
||||
let top = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(top));
|
||||
s.execute("layer.setProps", &json!({"id": top.0, prop: value})).unwrap();
|
||||
let before = node(&s, editable).children().unwrap().len();
|
||||
log(&mut s, &format!("app.activeDocument.pathItems.{create};"));
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.node(top).unwrap().children().unwrap().is_empty(), "{prop} {create}");
|
||||
let children = st.doc.node(editable).unwrap().children().unwrap();
|
||||
assert_eq!(children.len(), before + 1, "{prop} {create}");
|
||||
let made = children.last().unwrap();
|
||||
assert!(matches!(made.kind, NodeKind::Path { .. }), "{prop} {create}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// While an opacity mask is being edited, a locked mask layer refuses a script's new path instead
|
||||
/// of the path going on an ordinary layer outside the mask.
|
||||
#[test]
|
||||
fn document_path_creators_refuse_a_locked_mask_editing_layer() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let layer = s.active().unwrap().doc.mask_edit.unwrap().layer;
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(layer));
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
let before = art(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.add();");
|
||||
assert!(e.contains("onLayer must name an editable layer"), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_creators_use_the_mask_editing_layer_after_the_active_layer_changes() {
|
||||
let (mut s, a, _) = doc();
|
||||
let ordinary = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let layer = s.active().unwrap().doc.mask_edit.unwrap().layer;
|
||||
s.execute("layer.setCurrent", &json!({"id": ordinary.0})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": ordinary.0, "locked": true})).unwrap();
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(ordinary));
|
||||
let before = node(&s, layer).children().unwrap().len();
|
||||
let ordinary_before = node(&s, ordinary).children().unwrap().len();
|
||||
log(&mut s, "app.activeDocument.pathItems.add();");
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.mask_edit.unwrap().layer, layer);
|
||||
let children = st.doc.node(layer).unwrap().children().unwrap();
|
||||
assert_eq!(children.len(), before + 1);
|
||||
assert!(matches!(children.last().unwrap().kind, NodeKind::Path { .. }));
|
||||
// The mask's art is stored on its object, which stays on the ordinary layer; that layer gains
|
||||
// no path of its own.
|
||||
assert_eq!(node(&s, ordinary).children().unwrap().len(), ordinary_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_writes_refuse_generated_graph_design_paths() {
|
||||
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
|
||||
@@ -1920,6 +1982,71 @@ fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_change
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
|
||||
/// Global Edit gives an edit of one member to the others, so a point read of another member before
|
||||
/// the edit is stale afterwards, even when an undo puts the member back.
|
||||
#[test]
|
||||
fn a_point_of_another_global_edit_member_is_stale_after_an_edit_and_undo() {
|
||||
let (mut s, a, _) = doc();
|
||||
let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0);
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "edit"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
assert_eq!(r["count"], json!(2), "{r}");
|
||||
let before = art(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\
|
||||
vc.log(m.pathPoints[0].anchor);\
|
||||
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]];\
|
||||
vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();",
|
||||
);
|
||||
assert_ne!(out[0], out[1], "the other member took the edit");
|
||||
assert_eq!(art(&s), before);
|
||||
let e = failure(
|
||||
&mut s,
|
||||
"var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\
|
||||
var mp = m.pathPoints[0]; mp.anchor;\
|
||||
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]]; app.undo();\
|
||||
mp.anchor;",
|
||||
);
|
||||
assert!(e.contains("Stale path point"), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
|
||||
/// Moving a group that holds the selected Global Edit member moves the other members too, so a
|
||||
/// point read of another member before the move is stale afterwards.
|
||||
#[test]
|
||||
fn a_point_of_another_global_edit_member_is_stale_after_its_group_moves_and_undoes() {
|
||||
let (mut s, a, b) = doc();
|
||||
let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0);
|
||||
s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let r = s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
assert_eq!(r["count"], json!(2), "{r}");
|
||||
let before = art(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var P = app.activeDocument.pathItems, m = P.getByName('m');\
|
||||
vc.log(m.pathPoints[0].anchor);\
|
||||
app.activeDocument.groupItems[0].translate(10, 0);\
|
||||
vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();",
|
||||
);
|
||||
assert_ne!(out[0], out[1], "the other member took the move");
|
||||
assert_eq!(art(&s), before);
|
||||
let e = failure(
|
||||
&mut s,
|
||||
"var P = app.activeDocument.pathItems, m = P.getByName('m');\
|
||||
var mp = m.pathPoints[0]; mp.anchor;\
|
||||
app.activeDocument.groupItems[0].translate(10, 0); app.undo();\
|
||||
mp.anchor;",
|
||||
);
|
||||
assert!(e.contains("Stale path point"), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
|
||||
/// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke.
|
||||
fn doc_with_paints() -> (Session, NodeId) {
|
||||
let (mut s, a, _) = doc();
|
||||
|
||||
@@ -409,11 +409,14 @@ impl Session {
|
||||
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
|
||||
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
|
||||
/// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd
|
||||
/// press armed ([`Self::behind_armed`]).
|
||||
/// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press
|
||||
/// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown
|
||||
/// direction handle to mirror the opposite handle.
|
||||
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
|
||||
let id = self.lent_tool(self.tool.id(), mods)?;
|
||||
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
|
||||
(!behind).then_some(id)
|
||||
let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods));
|
||||
(!behind && !kept).then_some(id)
|
||||
}
|
||||
|
||||
/// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks
|
||||
|
||||
@@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let end = Point::new(180.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Down, end, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let p = anchor(&s, id).p;
|
||||
let shifted = Mods { shift: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let raw = Point::new(180.0, 150.0);
|
||||
pointer(&mut s, PointerKind::Drag, raw, shifted);
|
||||
assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, raw, shifted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
// A second object widens the selection's bounding box so its top-middle handle lands on the
|
||||
// curve's outgoing handle end at (180, 100).
|
||||
let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]}));
|
||||
let boxed = ViewInfo { show_bbox: true, ..view() };
|
||||
let end = Point::new(180.0, 100.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let a = anchor(&s, id);
|
||||
let both = Mods { alt: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle");
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
assert_eq!(anchor(&s, id), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() {
|
||||
let mut s = session();
|
||||
@@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() {
|
||||
assert_content(&s, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() {
|
||||
let mut s = session();
|
||||
let id = blend(&mut s);
|
||||
let (a, keys, _) = blend_state(&s, id);
|
||||
pointer(&mut s, PointerKind::Down, a.h_out, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
let (after, after_keys, _) = blend_state(&s, id);
|
||||
near(after.p, a.p);
|
||||
assert_mirrored(after, q, AnchorKind::Smooth);
|
||||
assert_eq!(after_keys, keys, "the key objects did not move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -62,9 +62,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||||
/// Copy does.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "alert confirm length prompt prototype"),
|
||||
("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"),
|
||||
("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "__vcPaletteEvent alert confirm length prompt prototype"),
|
||||
("%vcPaletteEvent.", "length"),
|
||||
("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show update"),
|
||||
("Object.prototype.", "reflect toSource"),
|
||||
("UnitValue.", "baseUnit baseUnit= length prototype"),
|
||||
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
|
||||
|
||||
@@ -119,6 +119,78 @@ fn picked_handles_stay_picked_after_they_are_dragged() {
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0));
|
||||
}
|
||||
|
||||
/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone
|
||||
/// and mirrors its opposite handle; the other picked handle stays where it is.
|
||||
#[test]
|
||||
fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let a = anchor(&s, id, 1);
|
||||
near(a.h_out, Point::new(180.0, 160.0));
|
||||
near(a.h_in, Point::new(20.0, 40.0));
|
||||
assert_eq!(a.kind, AnchorKind::Smooth);
|
||||
near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without
|
||||
/// Cmd/Ctrl then moves both.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during
|
||||
/// one.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() {
|
||||
for escape in [false, true] {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift);
|
||||
if escape {
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
}
|
||||
pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift);
|
||||
let x = if escape { 180.0 } else { 220.0 };
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both
|
||||
/// picked.
|
||||
#[test]
|
||||
fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd);
|
||||
near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag
|
||||
/// then moves only the handle pressed.
|
||||
#[test]
|
||||
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind,
|
||||
OpacityMask, StrokeLayer, Symbol,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -1020,6 +1020,167 @@ fn hidden_layers_open_hidden() {
|
||||
assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}");
|
||||
}
|
||||
|
||||
fn dash_painted_nodes(nodes: &[Arc<Node>], out: &mut Vec<Node>) {
|
||||
for n in nodes {
|
||||
match &n.kind {
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push((**n).clone()),
|
||||
_ => {
|
||||
if let Some(children) = n.children() {
|
||||
dash_painted_nodes(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Original synthetic rectangle, independent of the artwork in #10476.
|
||||
fn dash_compat_document(pattern: Vec<f64>) -> Document {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let mut stroke = StrokeLayer::new(solid(Color::BLACK), 4.0);
|
||||
stroke.dash = Some(Dash { pattern, offset: 2.5, align_corners: false });
|
||||
stroke.overprint = true;
|
||||
let ap = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))), AppearanceItem::Stroke(stroke)],
|
||||
..Appearance::default()
|
||||
};
|
||||
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 180.0, 80.0)), ap);
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
fn ai_dash_outputs(doc: &Document) -> Vec<(String, Vec<String>, Document)> {
|
||||
let out = export_ai_editing(doc, &opts()).unwrap();
|
||||
let legacy = crate::export_legacy_ai(doc, &crate::LegacyAiOptions::default()).unwrap();
|
||||
let legacy_back = crate::import(&legacy.bytes).unwrap().document;
|
||||
vec![
|
||||
(String::from_utf8(out.program).unwrap().replace("\r\n", "\n"), out.warnings, read_back(doc)),
|
||||
(String::from_utf8(legacy.bytes).unwrap().replace("\r\n", "\n"), legacy.warnings, legacy_back),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_reduce_repetitions_and_keep_small_patterns_editable() {
|
||||
for (pattern, emitted) in [
|
||||
(vec![33.5673; 5], "[33.5673] 2.5 d"),
|
||||
(vec![33.5673; 10], "[33.5673] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0, 3.0, 2.0, 1.0, 3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
|
||||
(vec![0.25], "[0.25] 2.5 d"),
|
||||
(vec![0.25, 0.5], "[0.25 0.5] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0], "[3 2 1 2 3 4] 2.5 d"),
|
||||
] {
|
||||
let doc = dash_compat_document(pattern.clone());
|
||||
for (text, warnings, back) in ai_dash_outputs(&doc) {
|
||||
assert!(text.contains(emitted), "{pattern:?}: missing {emitted}: {text}");
|
||||
assert!(warnings.is_empty(), "{pattern:?}: {warnings:?}");
|
||||
let mut art = vec![];
|
||||
dash_painted_nodes(&back.layers, &mut art);
|
||||
assert_eq!(art.len(), 1);
|
||||
let st = art[0].appearance.stroke().unwrap();
|
||||
assert_eq!(st.width, 4.0);
|
||||
assert!(st.overprint);
|
||||
assert_eq!(st.dash.as_ref().unwrap().offset, 2.5);
|
||||
let got = &st.dash.as_ref().unwrap().pattern;
|
||||
for i in 0..pattern.len() * got.len() * 2 {
|
||||
assert_eq!(pattern[i % pattern.len()], got[i % got.len()]);
|
||||
}
|
||||
assert!(art[0].appearance.fill().is_some());
|
||||
}
|
||||
assert_eq!(doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap().dash.as_ref().unwrap().pattern, pattern);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_that_exceed_six_effective_lengths_are_outlined_with_a_warning() {
|
||||
for pattern in [vec![3.0, 2.0, 1.0, 2.0, 3.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]] {
|
||||
let doc = dash_compat_document(pattern);
|
||||
let original = &doc.layers[0].children().unwrap()[0];
|
||||
let path = original.path_data().unwrap();
|
||||
let expected = vectorcraft_effects::stroke::outline_region(path, FillRule::NonZero, original.appearance.stroke().unwrap()).to_bezpath();
|
||||
for (text, warnings, back) in ai_dash_outputs(&doc) {
|
||||
assert!(warnings.iter().any(|w| w.contains("filled outlines")), "{warnings:?}");
|
||||
assert!(
|
||||
!text.lines().filter(|l| l.ends_with(" d")).any(|l| {
|
||||
let array = l.rsplit_once('[').unwrap().1.split(']').next().unwrap();
|
||||
let n = array.split_whitespace().count();
|
||||
n > 6 || (n % 2 == 1 && n * 2 > 6)
|
||||
}),
|
||||
"{text}"
|
||||
);
|
||||
let mut art = vec![];
|
||||
dash_painted_nodes(&back.layers, &mut art);
|
||||
assert!(art.iter().all(|n| n.appearance.stroke().is_none()), "{art:?}");
|
||||
assert_eq!(art.len(), 2, "fill and outlined stroke keep their paint order");
|
||||
assert_eq!(art[0].appearance.fill().unwrap().paint, solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
let fill = art[1].appearance.fill().unwrap();
|
||||
assert_eq!(fill.paint, solid(Color::BLACK));
|
||||
assert!(fill.overprint);
|
||||
let got = art[1].stroke_path().unwrap();
|
||||
for y in 5..85 {
|
||||
for x in 5..185 {
|
||||
let p = vectorcraft_geom::Point::new(f64::from(x) + 0.123, f64::from(y) + 0.123);
|
||||
assert_eq!(got.winding(p) != 0, expected.winding(p) != 0, "at {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_in_linked_styles_also_respect_the_reader_limit() {
|
||||
for (pattern, live) in [(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false), (vec![33.5673; 5], true)] {
|
||||
let mut doc = dash_compat_document(pattern);
|
||||
let n = Arc::make_mut(&mut Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap()[0]);
|
||||
n.appearance.stroke_mut().unwrap().overprint = false;
|
||||
n.extras_mut().graphic_style = Some(7);
|
||||
let mut style = vectorcraft_doc::GraphicStyle::new("Dashed", (*n.appearance).clone());
|
||||
style.id = 7;
|
||||
doc.graphic_styles.push(style);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let text = String::from_utf8(out.program).unwrap();
|
||||
assert!(!text.contains("[3 2 1 2 3 4 5 6]"), "a style dictionary must not keep an incompatible dash list");
|
||||
if live {
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert!(text.contains("1 (Dashed) XW"), "an equivalent dash representation keeps the style link");
|
||||
assert!(text.contains("[33.5673] 2.5 d"));
|
||||
} else {
|
||||
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_in_legacy_text_reduce_or_outline_without_becoming_solid() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
|
||||
// Existing licensed test face, with original single-letter artwork.
|
||||
vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
|
||||
for (pattern, live) in [(vec![33.5673; 5], true), (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false)] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let st = CharStyle {
|
||||
font_family: HEIGHT_FAMILY.into(),
|
||||
size: 48.0,
|
||||
fill: solid(Color::rgb(0.0, 1.0, 0.0)),
|
||||
stroke: solid(Color::BLACK),
|
||||
stroke_width: 2.0,
|
||||
stroke_dash: Some(Dash { pattern, offset: 2.5, align_corners: false }),
|
||||
..CharStyle::default()
|
||||
};
|
||||
let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "T", st);
|
||||
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
|
||||
let out = crate::export_legacy_ai(&doc, &crate::LegacyAiOptions::default()).unwrap();
|
||||
let text = String::from_utf8(out.bytes).unwrap().replace("\r\n", "\n");
|
||||
assert_eq!(text.contains("0 To\n"), live, "irreducible type strokes must take the outline fallback");
|
||||
if live {
|
||||
assert!(text.contains("[33.5673] 2.5 d"));
|
||||
} else {
|
||||
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
|
||||
assert!(text.matches("\nf\n").count() >= 2, "the glyph's fill and dashed stroke are both painted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A 200 × 100 document of a gradient fill, a compound path, an image and a symbol instance, and
|
||||
/// what the data holds as plain paths: type.
|
||||
fn unsupported() -> Document {
|
||||
|
||||
@@ -71,7 +71,7 @@ pub(super) const LIVE: &str =
|
||||
"repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps";
|
||||
pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps";
|
||||
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
|
||||
pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps";
|
||||
|
||||
@@ -364,7 +364,7 @@ fn plain_key(k: &Node) -> bool {
|
||||
&& i.effects().is_empty()
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s))
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s) || !dash_read_back(s))
|
||||
});
|
||||
plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none();
|
||||
});
|
||||
|
||||
@@ -258,7 +258,7 @@ fn plain_within(art: &Node, masks: u32) -> bool {
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& matches!(i.paint(), Paint::Solid { .. } | Paint::None)
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s))
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s))
|
||||
});
|
||||
// A group's own fills and strokes aren't written.
|
||||
let group_paint = matches!(n.kind, NodeKind::Group { .. }) && items.iter().any(|i| !i.paint().is_none());
|
||||
@@ -519,7 +519,7 @@ impl Writer<'_> {
|
||||
let name = st.brush.as_deref()?;
|
||||
self.brush_set();
|
||||
let (plugin, kind) = self.live_brush(name).map(|b| (b.plugin, b.brush.kind.clone()))?;
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
|
||||
return None;
|
||||
}
|
||||
let ops = self.color_ops(&st.paint, true);
|
||||
|
||||
@@ -8,7 +8,6 @@ use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType};
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2};
|
||||
|
||||
use super::{MAX_NEST, Writer, Xy};
|
||||
@@ -367,7 +366,7 @@ impl Writer<'_> {
|
||||
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
|
||||
/// write it)?
|
||||
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
|
||||
self.direct(&s.paint) && stroke::is_plain(s)
|
||||
self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
|
||||
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
|
||||
|
||||
@@ -404,7 +404,7 @@ impl Writer<'_> {
|
||||
if st.brush.is_some() {
|
||||
return self.brush_filter(s, st, visible);
|
||||
}
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
|
||||
return None;
|
||||
}
|
||||
let ops = self.color_ops(&st.paint, true);
|
||||
@@ -1077,6 +1077,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) ->
|
||||
let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count();
|
||||
ap.items.retain(|i| !i.paint().is_none());
|
||||
ap.contents_index = (below > 0).then_some(below);
|
||||
// The writer shortens repeated dash lists without changing their painted period.
|
||||
// Compare those representations equally so a linked style can stay live.
|
||||
for i in &mut ap.items {
|
||||
if let AppearanceItem::Stroke(st) = i
|
||||
&& let Some(d) = st.dash.as_mut().filter(|d| d.is_dashed())
|
||||
&& let Some(pattern) = ai_ops::dash_pattern(&d.pattern)
|
||||
{
|
||||
d.pattern = pattern.to_vec();
|
||||
}
|
||||
}
|
||||
for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
|
||||
e.params = normalized_params(e);
|
||||
}
|
||||
|
||||
@@ -425,8 +425,8 @@ fn plain_wrap_art(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
|
||||
let painted = || match super::visible_items(n).as_slice() {
|
||||
[] => true,
|
||||
[AppearanceItem::Fill(f)] => solid(&f.paint),
|
||||
[AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
[AppearanceItem::Stroke(s)] => solid(&s.paint) && crate::ai_ops::plain_stroke(s),
|
||||
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && crate::ai_ops::plain_stroke(s),
|
||||
_ => false,
|
||||
};
|
||||
let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2);
|
||||
|
||||
@@ -179,7 +179,28 @@ pub(crate) fn window_samples(samples: &[u8], w: u32, channels: usize, [x0, y0, x
|
||||
out
|
||||
}
|
||||
|
||||
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`.
|
||||
/// The shortest equivalent dash list the AI reader can hold. Odd lists repeat twice before
|
||||
/// dash/gap parity repeats. Keep at most six effective lengths: longer lists can make the
|
||||
/// reader reject the entire file (#10476). Compare exactly, so no dash or gap changes length.
|
||||
pub(crate) fn dash_pattern(pattern: &[f64]) -> Option<&[f64]> {
|
||||
(1..=pattern.len().min(6))
|
||||
.filter(|n| n % 2 == 0 || *n <= 3)
|
||||
.find(|n| pattern.len().is_multiple_of(*n) && pattern.iter().enumerate().all(|(i, v)| *v == pattern[i % n]))
|
||||
.map(|n| &pattern[..n])
|
||||
}
|
||||
|
||||
/// Invalid or empty dashes already draw solid; valid dashes need an exact short representation.
|
||||
pub(crate) fn dash_fits(st: &StrokeLayer) -> bool {
|
||||
st.dash.as_ref().filter(|d| d.is_dashed()).is_none_or(|d| dash_pattern(&d.pattern).is_some())
|
||||
}
|
||||
|
||||
/// A plain AI stroke, including the reader's dash-list limit. Other strokes use filled outlines.
|
||||
pub(crate) fn plain_stroke(st: &StrokeLayer) -> bool {
|
||||
vectorcraft_effects::stroke::is_plain(st) && dash_fits(st)
|
||||
}
|
||||
|
||||
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. Callers check
|
||||
/// [`dash_fits`] first; irreducible longer patterns belong in their outline fallback.
|
||||
pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
|
||||
let cap = match st.cap {
|
||||
LineCap::Butt => ps::LineCap::Butt,
|
||||
@@ -191,6 +212,6 @@ pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
|
||||
LineJoin::Round => ps::LineJoin::Round,
|
||||
LineJoin::Bevel => ps::LineJoin::Bevel,
|
||||
};
|
||||
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| (d.pattern.as_slice(), d.offset));
|
||||
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).and_then(|d| dash_pattern(&d.pattern).map(|p| (p, d.offset)));
|
||||
ps::push_line_style(s, st.width, cap, join, st.miter_limit, dash);
|
||||
}
|
||||
@@ -22,4 +22,4 @@ mod pixels;
|
||||
|
||||
pub(crate) use filters::Stream;
|
||||
#[cfg(test)]
|
||||
pub(crate) use ops::measured;
|
||||
pub(crate) use ops::{max_data, measured, with_data_limit};
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::ops::MAX_DATA;
|
||||
use super::ops::max_data;
|
||||
use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err};
|
||||
use craft_stream_codecs::CcittParams;
|
||||
|
||||
@@ -44,7 +44,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
out.extend(std::iter::repeat_n(b, 257 - usize::from(n)));
|
||||
}
|
||||
}
|
||||
if out.len() > MAX_DATA {
|
||||
if out.len() > max_data() {
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
/// zlib data inflated, and how many bytes of `raw` it took.
|
||||
fn flate(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
let mut z = flate2::Decompress::new(true);
|
||||
let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(MAX_DATA));
|
||||
let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(max_data()));
|
||||
loop {
|
||||
let before = (z.total_in(), z.total_out());
|
||||
if out.capacity() - out.len() < 64 * 1024 {
|
||||
@@ -62,7 +62,7 @@ fn flate(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
}
|
||||
let input = raw.get(z.total_in() as usize..).unwrap_or_default();
|
||||
let status = z.decompress_vec(input, &mut out, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?;
|
||||
if out.len() > MAX_DATA {
|
||||
if out.len() > max_data() {
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
}
|
||||
match status {
|
||||
@@ -79,7 +79,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
|
||||
let mut out = vec![];
|
||||
let used = lzw_into(raw, &mut |bytes| {
|
||||
out.extend_from_slice(bytes);
|
||||
if out.len() > MAX_DATA {
|
||||
if out.len() > max_data() {
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
}
|
||||
Ok(())
|
||||
@@ -238,10 +238,10 @@ fn dct(raw: &[u8]) -> Res<(Vec<u8>, usize, u8)> {
|
||||
/// `EndOfBlock` the rows end at the end-of-block code (EOFB, or RTC in Group 3) regardless of
|
||||
/// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0.
|
||||
/// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an
|
||||
/// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused.
|
||||
/// `ioerror`. Rows that would take more than [`max_data`] bytes are refused.
|
||||
fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec<u8>, usize)> {
|
||||
let row = (settings.columns as usize).div_ceil(8).max(1);
|
||||
let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX);
|
||||
let most = u32::try_from(max_data() / row).unwrap_or(u32::MAX);
|
||||
if !settings.end_of_block && settings.rows > i64::from(most) {
|
||||
return Err(PsError::Limit("decoded data is too large"));
|
||||
}
|
||||
|
||||
@@ -6,7 +6,38 @@ use super::{
|
||||
};
|
||||
|
||||
/// Most bytes one filter or image reads.
|
||||
pub(super) const MAX_DATA: usize = 1 << 28;
|
||||
const MAX_DATA: usize = 1 << 28;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The most bytes one filter or image reads on this thread ([`MAX_DATA`] unless a test lowered it).
|
||||
static DATA_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_DATA) };
|
||||
}
|
||||
|
||||
/// The most bytes one filter or image reads: [`MAX_DATA`].
|
||||
#[cfg(not(test))]
|
||||
pub(super) const fn max_data() -> usize {
|
||||
MAX_DATA
|
||||
}
|
||||
|
||||
/// The most bytes one filter or image reads: [`DATA_LIMIT`] of this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn max_data() -> usize {
|
||||
DATA_LIMIT.get()
|
||||
}
|
||||
|
||||
/// Runs `f` with [`max_data`] set to `limit` on this thread, and restores it afterwards.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_data_limit<R>(limit: usize, f: impl FnOnce() -> R) -> R {
|
||||
struct Restore(usize);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
DATA_LIMIT.set(self.0);
|
||||
}
|
||||
}
|
||||
let _restore = Restore(DATA_LIMIT.replace(limit));
|
||||
f()
|
||||
}
|
||||
|
||||
/// Decoded bytes the measuring of an image's data left out charges one operation for. A program's
|
||||
/// budget grows by 64 operations for each byte of it, so the data of one image compressed up to
|
||||
@@ -410,7 +441,7 @@ impl Interp<'_> {
|
||||
Stream::Buf { data, pos: 0, rgb }
|
||||
}
|
||||
p @ Obj::Array { .. } => {
|
||||
let raw = self.gather(&p, MAX_DATA)?;
|
||||
let raw = self.gather(&p, max_data())?;
|
||||
let (data, _, rgb) = decode(&spec, &raw)?;
|
||||
self.charge_decoded(data.len())?;
|
||||
Stream::Buf { data, pos: 0, rgb }
|
||||
@@ -600,7 +631,7 @@ impl Interp<'_> {
|
||||
if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) };
|
||||
let Some(kept) = row.checked_mul(oh).filter(|k| *k <= max_data()) else { return Ok(None) };
|
||||
self.alloc(kept)?;
|
||||
// The compressed data: what the filters before the last one decode, or the file itself.
|
||||
let compressed = if head.is_empty() {
|
||||
@@ -618,7 +649,7 @@ impl Interp<'_> {
|
||||
};
|
||||
let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize);
|
||||
// Past the image's data and as much again the data is not an image's: it stops there.
|
||||
let most = row.saturating_mul(s.h).saturating_add(MAX_DATA);
|
||||
let most = row.saturating_mul(s.h).saturating_add(max_data());
|
||||
let mut sink = |mut chunk: &[u8]| -> Res {
|
||||
while !chunk.is_empty() {
|
||||
let (r, off) = (seen / row.max(1), seen % row.max(1));
|
||||
@@ -829,7 +860,7 @@ impl Interp<'_> {
|
||||
let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n));
|
||||
let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h));
|
||||
// What is read: an image past the pixel cap is reduced from the samples read.
|
||||
charged = total.min(MAX_DATA);
|
||||
charged = total.min(max_data());
|
||||
self.alloc(charged)?;
|
||||
let raw = self.source_bytes(&src, charged)?;
|
||||
by_rows(&raw, (mrow, stencil.h), (drow, image.h))
|
||||
@@ -838,7 +869,7 @@ impl Interp<'_> {
|
||||
stencil.bpc = image.bpc;
|
||||
(stencil.w, stencil.h) = (image.w, image.h);
|
||||
let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8);
|
||||
charged = row.saturating_mul(image.h).min(MAX_DATA);
|
||||
charged = row.saturating_mul(image.h).min(max_data());
|
||||
self.alloc(charged)?;
|
||||
let raw = self.source_bytes(&src, charged)?;
|
||||
by_samples(&raw, image.w, image.h, n, image.bpc)
|
||||
@@ -1020,7 +1051,7 @@ impl Interp<'_> {
|
||||
// skipped), while one within the pixel cap whose samples are still too much data
|
||||
// (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane
|
||||
// is refused).
|
||||
let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else {
|
||||
let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= max_data()) else {
|
||||
if step > 1 {
|
||||
return Ok(self.leave_out(&s));
|
||||
}
|
||||
|
||||
@@ -17,6 +17,39 @@ use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err};
|
||||
|
||||
/// Most operations one file may run, whatever its length.
|
||||
const MAX_OPS: u64 = 50_000_000;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The most operations one file may run on this thread, whatever its length ([`MAX_OPS`] unless
|
||||
/// a test lowered it).
|
||||
static OPS_LIMIT: std::cell::Cell<u64> = const { std::cell::Cell::new(MAX_OPS) };
|
||||
}
|
||||
|
||||
/// The most operations one file may run, whatever its length: [`MAX_OPS`].
|
||||
#[cfg(not(test))]
|
||||
const fn max_ops() -> u64 {
|
||||
MAX_OPS
|
||||
}
|
||||
|
||||
/// The most operations one file may run, whatever its length: [`OPS_LIMIT`] of this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn max_ops() -> u64 {
|
||||
OPS_LIMIT.get()
|
||||
}
|
||||
|
||||
/// Runs `f` with [`max_ops`] set to `limit` on this thread, and restores it afterwards.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_ops_limit<R>(limit: u64, f: impl FnOnce() -> R) -> R {
|
||||
struct Restore(u64);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
OPS_LIMIT.set(self.0);
|
||||
}
|
||||
}
|
||||
let _restore = Restore(OPS_LIMIT.replace(limit));
|
||||
f()
|
||||
}
|
||||
|
||||
/// More operations a file may run for each byte of its program: a large file that draws a lot
|
||||
/// runs proportionally more, and stays bounded by its length.
|
||||
const OPS_PER_BYTE: u64 = 64;
|
||||
@@ -228,7 +261,7 @@ impl<'a> Interp<'a> {
|
||||
resources,
|
||||
depth: 0,
|
||||
ops: 0,
|
||||
max_ops: MAX_OPS.saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)),
|
||||
max_ops: max_ops().saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)),
|
||||
allocated: 0,
|
||||
seed: 1,
|
||||
saves: vec![],
|
||||
|
||||
@@ -7,9 +7,9 @@ use vectorcraft_color::{Color, GradientKind, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use crate::import::data::measured;
|
||||
use crate::import::data::{max_data, measured, with_data_limit};
|
||||
use crate::import::graphics::{GState, Out, tilings_compared};
|
||||
use crate::import::interp::Interp;
|
||||
use crate::import::interp::{Interp, max_ops, with_ops_limit};
|
||||
use crate::import::obj::Obj;
|
||||
use crate::import::{Dsc, import};
|
||||
use crate::{EpsOptions, Level, Preview, Raster};
|
||||
@@ -1282,11 +1282,16 @@ fn read_counting_tilings(body: &str) -> (crate::Imported, u64) {
|
||||
}
|
||||
|
||||
/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and
|
||||
/// how many decoded bytes the measuring of images' data left out decoded.
|
||||
/// how many decoded bytes the measuring of images' data left out decoded. The reading thread
|
||||
/// reads with this thread's data and operation limits ([`with_data_limit`], [`with_ops_limit`]).
|
||||
fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ps = eps(body);
|
||||
std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok());
|
||||
let (data, ops) = (max_data(), max_ops());
|
||||
std::thread::spawn(move || {
|
||||
let read = with_ops_limit(ops, || with_data_limit(data, || import(&ps)));
|
||||
tx.send((read, tilings_compared(), measured())).ok()
|
||||
});
|
||||
let (read, compared, measured) =
|
||||
rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish"));
|
||||
(read.unwrap(), compared, measured)
|
||||
|
||||
@@ -686,11 +686,15 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() {
|
||||
/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure
|
||||
/// is called until the data ends; when its first filter decompresses to more than the reader
|
||||
/// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is
|
||||
/// measured without keeping it.
|
||||
/// measured without keeping it. The reader holds 1 MiB here, and each filter's data decompresses
|
||||
/// to 2 MiB: Flate and LZW data is measured in full (run-length data is measured by its run
|
||||
/// lengths, without decoding it).
|
||||
#[test]
|
||||
fn the_data_of_an_image_too_large_to_hold_is_skipped() {
|
||||
const LIMIT: usize = 1 << 20;
|
||||
const DECODED: usize = 2 * LIMIT;
|
||||
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
|
||||
let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]);
|
||||
let zeros = crate::ps::deflate(&vec![0u8; DECODED]);
|
||||
// Predicted rows aren't decoded a row at a time: such an image is left out.
|
||||
let mut flate =
|
||||
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
|
||||
@@ -699,7 +703,7 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
|
||||
// The same through LZW, which counts the codes up to its end-of-data code.
|
||||
let mut lzw =
|
||||
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec();
|
||||
lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true));
|
||||
lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; DECODED], true));
|
||||
lzw.extend(format!("\n{after}").as_bytes());
|
||||
// Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of
|
||||
// 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in
|
||||
@@ -707,24 +711,29 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
|
||||
// run's length and stays off by one.
|
||||
let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec();
|
||||
run_length.extend([2, 200, 200, 200]);
|
||||
run_length.extend([129u8, 200].repeat((300 << 20) / 128));
|
||||
run_length.extend([129u8, 200].repeat(DECODED / 128));
|
||||
run_length.push(128);
|
||||
run_length.extend(format!("\n{after}").as_bytes());
|
||||
for program in [
|
||||
format!(
|
||||
"/F currentfile 0 (%%EndData) /SubFileDecode filter def \
|
||||
10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}"
|
||||
)
|
||||
.into_bytes(),
|
||||
flate,
|
||||
lzw,
|
||||
run_length,
|
||||
for (program, measured) in [
|
||||
(
|
||||
format!(
|
||||
"/F currentfile 0 (%%EndData) /SubFileDecode filter def \
|
||||
10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}"
|
||||
)
|
||||
.into_bytes(),
|
||||
0,
|
||||
),
|
||||
(flate, DECODED as u64),
|
||||
(lzw, DECODED as u64),
|
||||
(run_length, 0),
|
||||
] {
|
||||
let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned();
|
||||
let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
|
||||
file.extend(&program);
|
||||
file.extend(b"\nshowpage\n%%EOF\n");
|
||||
let r = import(&file).unwrap();
|
||||
let before = crate::import::data::measured();
|
||||
let r = crate::import::data::with_data_limit(LIMIT, || import(&file)).unwrap();
|
||||
assert_eq!(crate::import::data::measured() - before, measured, "{text}");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings);
|
||||
let o = super::tests::objects(&r.document);
|
||||
assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings);
|
||||
@@ -733,18 +742,24 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
|
||||
}
|
||||
|
||||
/// Measuring the data of an image too large to hold decompresses it, and that is charged to the
|
||||
/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed
|
||||
/// zeros is left out and measured again each time a loop runs the stream from its start, runs out
|
||||
/// of the budget after it measured the data in full more than once and at most five times.
|
||||
/// operation budget: a program kept in a reusable stream, whose image over compressed zeros is
|
||||
/// left out and measured again each time a loop runs the stream from its start, runs out of the
|
||||
/// budget after it measured the data in full more than once and at most five times. The reader
|
||||
/// holds 1 MiB here, the zeros decompress to 4 MiB, and the budget a file has whatever its length
|
||||
/// pays for measuring them twice.
|
||||
#[test]
|
||||
fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() {
|
||||
const LIMIT: usize = 1 << 20;
|
||||
const DECODED: usize = 4 * LIMIT;
|
||||
let mut program =
|
||||
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
|
||||
program.extend(crate::ps::deflate(&vec![0u8; 300 << 20]));
|
||||
program.extend(crate::ps::deflate(&vec![0u8; DECODED]));
|
||||
let hex: String = program.iter().map(|b| format!("{b:02x}")).collect();
|
||||
let measured =
|
||||
super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop"));
|
||||
assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured");
|
||||
let body = format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop");
|
||||
let measured = super::interp::with_ops_limit(DECODED as u64 / 8, || {
|
||||
crate::import::data::with_data_limit(LIMIT, || super::tests::runs_out_of_budget_measuring(&body))
|
||||
});
|
||||
assert!((DECODED as u64 + 1..=5 * DECODED as u64).contains(&measured), "{measured} bytes measured");
|
||||
}
|
||||
|
||||
/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is
|
||||
|
||||
@@ -125,8 +125,7 @@ const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in pro
|
||||
const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
|
||||
/// Wedges a conic gradient is written as: one a degree.
|
||||
const CONIC_WEDGES: usize = 360;
|
||||
const STROKES: &str =
|
||||
"strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines";
|
||||
const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, gradients, brushes, arrowheads) are written as filled outlines";
|
||||
const IMAGE_ALPHA: &str = "transparent image pixels are written over white";
|
||||
const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art";
|
||||
const DEEP_DISTORTED: &str =
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::writer::Writer;
|
||||
use super::{
|
||||
Affine, AreaOptions, BezPath, CharPosition, CharStyle, CompositeFont, Document, Gradient, GradientKind, Paint, ParaStyle, PathAlign, PathEffect,
|
||||
StrokeLayer, TextKind, TextObject, Write, latin, ps, stroke,
|
||||
StrokeLayer, TextKind, TextObject, Write, latin, ps,
|
||||
};
|
||||
|
||||
/// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd`, `[`, the stops
|
||||
@@ -111,6 +111,9 @@ pub(super) fn holds_as_text(t: &TextObject) -> bool {
|
||||
r.inline.is_none()
|
||||
&& solid(&r.style.fill)
|
||||
&& solid(&r.style.stroke)
|
||||
// Long dash lists can reject the entire AI file. Keep their glyph paint by
|
||||
// taking the existing type-outline path instead of writing a solid stroke.
|
||||
&& (!r.style.has_stroke() || crate::ai_ops::dash_fits(&r.style.stroke_layer()))
|
||||
&& (if r.style.all_caps { r.text.to_uppercase() } else { r.text.clone() }).chars().all(|c| latin::encode(c).is_some())
|
||||
})
|
||||
}
|
||||
@@ -221,5 +224,5 @@ pub(super) fn direct_fill(p: &Paint) -> bool {
|
||||
|
||||
/// Can stroke `s` be written as the stroke of a path object (a plain line of a colour)?
|
||||
pub(super) fn direct_stroke(s: &StrokeLayer) -> bool {
|
||||
matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s)
|
||||
matches!(s.paint, Paint::Solid { .. }) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
@@ -34,6 +34,7 @@
|
||||
//! - `ai_graph`: the records of a live graph those two write around its group.
|
||||
//! - `gradient_key`: the key those two find gradient definitions by.
|
||||
//! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing.
|
||||
#![doc(test(attr(deny(unsafe_code))))]
|
||||
|
||||
mod ai_editing;
|
||||
mod ai_graph;
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
//! already; [`save_with`] writes a version 1 document with them negated back for an older file
|
||||
//! version ([`vectorcraft_doc::twist`]).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod atomic;
|
||||
|
||||
@@ -219,12 +219,333 @@ pub fn circular_arc(c: CubicBez) -> Option<(Point, f64)> {
|
||||
((l0 - handle).abs() <= HANDLE_TOL * handle && (l3 - handle).abs() <= HANDLE_TOL * handle).then_some((center, radius))
|
||||
}
|
||||
|
||||
/// One tooth of a curvature comb: it starts on the curve at `at` and ends at `tip`, along the
|
||||
/// curve's normal on the side away from its center of curvature, `scale` times the curvature long.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct CombTooth {
|
||||
pub at: Point,
|
||||
pub tip: Point,
|
||||
/// The first tooth of the comb, the first after a point or segment that has no tooth, or the
|
||||
/// first after the curve turns back on itself (a cusp between two teeth): a line through the
|
||||
/// tips starts again here.
|
||||
pub start: bool,
|
||||
/// The index of the segment the tooth sits on.
|
||||
pub segment: usize,
|
||||
}
|
||||
|
||||
/// The most teeth a curvature comb draws in all.
|
||||
pub const MAX_COMB_TEETH: usize = 20_000;
|
||||
|
||||
/// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t`
|
||||
/// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment
|
||||
/// gives teeth of no length, its ends included. A point of a curved segment where it has no
|
||||
/// direction (a handle drawn back onto its anchor) gives no tooth, and neither does a segment
|
||||
/// with no length, a segment whose points are not finite, or a `scale` that is not finite. When
|
||||
/// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when
|
||||
/// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath.
|
||||
pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec<CombTooth> {
|
||||
let n = sp.segment_count();
|
||||
if n == 0 || !scale.is_finite() || max_teeth < 2 {
|
||||
return vec![];
|
||||
}
|
||||
let per = if samples.max(2).saturating_mul(n) <= max_teeth { samples.max(2) } else { 2 };
|
||||
let stride = (per * n).div_ceil(max_teeth).max(1);
|
||||
let mut teeth = Vec::with_capacity((per * n / stride).min(max_teeth));
|
||||
let mut start = true;
|
||||
// The direction of the last curved tooth, carried across segments so that a cusp at an
|
||||
// anchor also starts a new line through the tips.
|
||||
let mut previous_direction: Option<Vec2> = None;
|
||||
for seg in (0..n).step_by(stride) {
|
||||
if stride > 1 {
|
||||
start = true;
|
||||
previous_direction = None;
|
||||
}
|
||||
let c = sp.segment(seg);
|
||||
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) {
|
||||
start = true;
|
||||
previous_direction = None;
|
||||
continue;
|
||||
}
|
||||
let (d1, d2) = (c.deriv(), c.deriv().deriv());
|
||||
// The control polygon's length sets what counts as no speed.
|
||||
let size = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot();
|
||||
let chord = c.p3 - c.p0;
|
||||
let line = sp.segment_is_line(seg) && chord.hypot() > 0.0;
|
||||
for i in 0..per {
|
||||
if teeth.len() >= max_teeth {
|
||||
return teeth;
|
||||
}
|
||||
let t = i as f64 / (per - 1) as f64;
|
||||
if line {
|
||||
// A line stored with its handles on its anchors has no speed at its ends, but a
|
||||
// direction and no curvature all along.
|
||||
let at = c.eval(t);
|
||||
previous_direction = None;
|
||||
if !at.is_finite() {
|
||||
start = true;
|
||||
continue;
|
||||
}
|
||||
teeth.push(CombTooth { at, tip: at, start, segment: seg });
|
||||
start = false;
|
||||
continue;
|
||||
}
|
||||
let (v, a) = (d1.eval(t).to_vec2(), d2.eval(t).to_vec2());
|
||||
let speed = v.hypot();
|
||||
if speed <= CUSP_SHARE * size || !speed.is_finite() {
|
||||
start = true;
|
||||
previous_direction = None;
|
||||
continue;
|
||||
}
|
||||
let k = v.cross(a) / (speed * speed * speed);
|
||||
let direction = v / speed;
|
||||
start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0);
|
||||
previous_direction = Some(direction);
|
||||
let normal = Vec2::new(-direction.y, direction.x);
|
||||
let at = c.eval(t);
|
||||
let tip = at - normal * (k * scale);
|
||||
if !at.is_finite() || !tip.is_finite() {
|
||||
start = true;
|
||||
previous_direction = None;
|
||||
continue;
|
||||
}
|
||||
teeth.push(CombTooth { at, tip, start, segment: seg });
|
||||
start = false;
|
||||
}
|
||||
}
|
||||
teeth
|
||||
}
|
||||
|
||||
/// Does the line through the tips of `teeth`, the comb of `sp` ([`curvature_comb`]), close where
|
||||
/// it starts: `sp` is closed, only segments with no length lie between its last tooth and its
|
||||
/// first across the seam, the two sit on the same point, and the curve does not turn back on itself at its
|
||||
/// first anchor. A comb that skips segments to keep to its budget does not close across the ones
|
||||
/// it skipped at the end.
|
||||
pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool {
|
||||
let (Some(first), Some(last)) = (teeth.first(), teeth.last()) else {
|
||||
return false;
|
||||
};
|
||||
let n = sp.segment_count();
|
||||
if !sp.closed || teeth.len() < 2 || first.at.distance(last.at) >= 1e-9 {
|
||||
return false;
|
||||
}
|
||||
// Only segments with no length may lie between the last tooth and the first across the seam.
|
||||
let no_length = |i: usize| start_direction(sp.segment(i)) == Vec2::ZERO;
|
||||
if !(last.segment + 1..n).chain(0..first.segment).all(no_length) {
|
||||
return false;
|
||||
}
|
||||
match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) {
|
||||
(Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Anchor, shapes};
|
||||
use kurbo::Rect;
|
||||
|
||||
fn tooth_len(t: &CombTooth) -> f64 {
|
||||
t.at.distance(t.tip)
|
||||
}
|
||||
|
||||
/// A circle's comb points away from the center, each tooth `scale` times the cubic's own
|
||||
/// curvature at its point ([`curvature_circle_with`] without arcs), all within 3% of
|
||||
/// `scale / r` (the usual cubic of a quarter turn strays that little from its circle).
|
||||
#[test]
|
||||
fn the_comb_of_a_circle_has_teeth_of_one_length() {
|
||||
let pd = shapes::ellipse(Rect::new(50.0, 50.0, 250.0, 250.0));
|
||||
let sp = &pd.subpaths[0];
|
||||
let teeth = curvature_comb(sp, 9, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 9 * sp.segment_count());
|
||||
assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "one unbroken comb");
|
||||
let center = Point::new(150.0, 150.0);
|
||||
for (i, t) in teeth.iter().enumerate() {
|
||||
let (seg, at) = (i / 9, (i % 9) as f64 / 8.0);
|
||||
let r = curvature_circle_with(sp.segment(seg), at, false, false).unwrap().radius;
|
||||
assert!((tooth_len(t) * r - 1000.0).abs() < 1e-6, "{t:?} {r}");
|
||||
assert!((tooth_len(t) - 10.0).abs() < 0.3, "{t:?}");
|
||||
assert!(t.tip.distance(center) > t.at.distance(center), "outward: {t:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A straight line has teeth of no length, its two ends included.
|
||||
#[test]
|
||||
fn the_comb_of_a_line_is_flat() {
|
||||
let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 40.0), Point::new(200.0, 0.0)], false);
|
||||
let teeth = curvature_comb(&sp, 5, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 10);
|
||||
assert!(teeth.iter().all(|t| tooth_len(t) < 1e-9), "{teeth:?}");
|
||||
assert_eq!(teeth[4].at, Point::new(100.0, 40.0), "the corner has a tooth on each side");
|
||||
}
|
||||
|
||||
/// Two quarter circles of radius 100 and 50 that meet in one direction: the teeth double in
|
||||
/// length at the anchor they share.
|
||||
#[test]
|
||||
fn the_comb_jumps_where_the_curvature_does() {
|
||||
let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan();
|
||||
let a0 = Anchor { h_out: Point::new(100.0 * k, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) };
|
||||
let a1 = Anchor {
|
||||
h_in: Point::new(100.0, 100.0 - 100.0 * k),
|
||||
h_out: Point::new(100.0, 100.0 + 50.0 * k),
|
||||
..Anchor::corner(Point::new(100.0, 100.0))
|
||||
};
|
||||
let a2 = Anchor { h_in: Point::new(50.0 + 50.0 * k, 150.0), ..Anchor::corner(Point::new(50.0, 150.0)) };
|
||||
let sp = SubPath::new(vec![a0, a1, a2], false);
|
||||
let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 6);
|
||||
let (before, after) = (tooth_len(&teeth[2]), tooth_len(&teeth[3]));
|
||||
assert!((after / before - 2.0).abs() < 1e-9, "{before} {after}");
|
||||
assert!((before - 10.0).abs() < 0.3, "{before}");
|
||||
assert!(teeth[2].at.distance(teeth[3].at) < 1e-9, "both teeth start on the shared anchor");
|
||||
assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "a smooth anchor keeps one unbroken comb");
|
||||
}
|
||||
|
||||
/// Two segments that meet at a cusp on their shared anchor: the first segment ends heading
|
||||
/// down and the second starts heading up, so the line through the tips starts again there.
|
||||
#[test]
|
||||
fn the_comb_breaks_at_a_cusp_on_an_anchor() {
|
||||
let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) };
|
||||
let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) };
|
||||
let a2 = Anchor { h_in: Point::new(200.0, -25.0), ..Anchor::corner(Point::new(200.0, 0.0)) };
|
||||
let sp = SubPath::new(vec![a0, a1, a2], false);
|
||||
let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 6);
|
||||
assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, false, true, false, false]);
|
||||
assert!(!comb_closes(&sp, &teeth), "an open subpath does not close");
|
||||
}
|
||||
|
||||
/// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a
|
||||
/// cusp elsewhere, and stays open when the first anchor is the cusp.
|
||||
#[test]
|
||||
fn the_comb_closes_unless_its_first_anchor_is_a_cusp() {
|
||||
let closed = |h_in: Point| {
|
||||
let a0 = Anchor { h_in, h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) };
|
||||
let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) };
|
||||
let a2 = Anchor { h_in: Point::new(200.0, -25.0), h_out: Point::new(200.0, 50.0), ..Anchor::corner(Point::new(200.0, 0.0)) };
|
||||
SubPath::new(vec![a0, a1, a2], true)
|
||||
};
|
||||
let smooth = closed(Point::new(0.0, 50.0));
|
||||
let teeth = curvature_comb(&smooth, 3, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.iter().filter(|t| t.start).count(), 2, "the cusp at the second anchor breaks the comb");
|
||||
assert!(comb_closes(&smooth, &teeth));
|
||||
let cusp = closed(Point::new(0.0, -50.0));
|
||||
assert!(!comb_closes(&cusp, &curvature_comb(&cusp, 3, 1000.0, MAX_COMB_TEETH)));
|
||||
let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let sp = &circle.subpaths[0];
|
||||
assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH)));
|
||||
}
|
||||
|
||||
/// A segment with no length and a handle drawn back onto its anchor do not panic and give no
|
||||
/// tooth where the curve has no direction; a scale that is not finite gives no comb.
|
||||
#[test]
|
||||
fn the_comb_skips_points_with_no_direction() {
|
||||
let p = Point::new(10.0, 10.0);
|
||||
assert!(curvature_comb(&SubPath::polyline(&[p, p], false), 4, 1000.0, MAX_COMB_TEETH).is_empty());
|
||||
let curve = SubPath::new(
|
||||
vec![Anchor { h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }, Anchor::corner(Point::new(100.0, 100.0))],
|
||||
false,
|
||||
);
|
||||
let teeth = curvature_comb(&curve, 5, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 4, "the end whose handle sits on its anchor has no tooth: {teeth:?}");
|
||||
assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, false, false]);
|
||||
let back = SubPath::new(
|
||||
vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor { h_in: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(100.0, 100.0)) }],
|
||||
false,
|
||||
);
|
||||
let teeth = curvature_comb(&back, 5, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 4, "the start, whose handle sits on its anchor, has no tooth: {teeth:?}");
|
||||
assert!(teeth[0].start, "the comb starts after the point with no tooth");
|
||||
assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}");
|
||||
assert!(curvature_comb(&curve, 5, f64::NAN, MAX_COMB_TEETH).is_empty());
|
||||
}
|
||||
|
||||
/// A cusp between samples starts a new line through the comb's tips after the cusp.
|
||||
#[test]
|
||||
fn the_comb_breaks_at_a_cusp_between_samples() {
|
||||
let bp = kurbo::BezPath::from_svg("M0 0 C100 100 0 100 100 0").unwrap();
|
||||
let sp = &crate::PathData::from_bezpath(&bp).subpaths[0];
|
||||
let teeth = curvature_comb(sp, 6, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 6, "the cusp falls between teeth");
|
||||
assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, false, true, false, false]);
|
||||
assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}");
|
||||
}
|
||||
|
||||
/// A tooth whose tip overflows is skipped, and the next finite tooth starts a new envelope.
|
||||
#[test]
|
||||
fn the_comb_breaks_after_a_nonfinite_tip() {
|
||||
let sp = SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(Point::new(-1.0, 1.0), Point::new(-1.0, 1.0), Point::new(-1.0 / 3.0, -1.0 / 3.0)),
|
||||
Anchor::with_handles(Point::new(1.0, 1.0), Point::new(1.0 / 3.0, -1.0 / 3.0), Point::new(1.0, 1.0)),
|
||||
],
|
||||
false,
|
||||
);
|
||||
let teeth = curvature_comb(&sp, 5, f64::MAX, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 4, "the middle tooth overflows");
|
||||
assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}");
|
||||
assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, true, false]);
|
||||
assert!(teeth[1].at.x < 0.0 && teeth[2].at.x > 0.0, "the gap is inside the segment");
|
||||
}
|
||||
|
||||
/// A speed whose cube underflows gives no tooth, and the first finite tooth starts the comb.
|
||||
#[test]
|
||||
fn the_comb_skips_a_tip_when_speed_cubed_underflows() {
|
||||
let sp = SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(Point::ORIGIN, Point::ORIGIN, Point::new(1e-109, 0.0)),
|
||||
Anchor::with_handles(Point::ORIGIN, Point::new(1e-101, 1e-101), Point::ORIGIN),
|
||||
],
|
||||
false,
|
||||
);
|
||||
let teeth = curvature_comb(&sp, 5, 1.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 4, "the first tooth has a nonfinite tip");
|
||||
assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}");
|
||||
assert!(teeth[0].start && teeth[0].at.x > 0.0, "the comb starts after the skipped tooth");
|
||||
}
|
||||
|
||||
/// A subpath with more segments than the budget allows keeps to it, with teeth spread to its
|
||||
/// far end rather than stopping part way.
|
||||
#[test]
|
||||
fn the_comb_is_capped_and_spread() {
|
||||
let points: Vec<Point> = (0..30_001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect();
|
||||
let sp = SubPath::polyline(&points, false);
|
||||
let teeth = curvature_comb(&sp, 16, 1.0, 1000);
|
||||
assert!(teeth.len() <= 1000 && teeth.len() >= 900, "{}", teeth.len());
|
||||
assert!(teeth.last().is_some_and(|t| t.at.x > 29_000.0), "{:?}", teeth.last());
|
||||
assert_eq!(teeth.iter().filter(|t| t.start).count() * 2, teeth.len(), "each sampled segment starts a new line through the tips");
|
||||
let few = curvature_comb(&sp, 16, 1.0, 100_000);
|
||||
assert_eq!(few.len(), 60_000, "too many for 16 on each, so 2 on each");
|
||||
}
|
||||
|
||||
/// A capped comb that skips the last segment does not close, even when the last segment it
|
||||
/// samples ends on the first anchor: the line through the tips would cross the skipped loop.
|
||||
#[test]
|
||||
fn a_capped_comb_does_not_close_across_a_skipped_segment() {
|
||||
let sp = SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(Point::new(0.0, 0.0), Point::new(-50.0, -50.0), Point::new(50.0, 50.0)),
|
||||
Anchor::with_handles(Point::new(100.0, 0.0), Point::new(80.0, 40.0), Point::new(120.0, 20.0)),
|
||||
Anchor::with_handles(Point::new(100.0, 100.0), Point::new(140.0, 80.0), Point::new(60.0, 140.0)),
|
||||
Anchor::with_handles(Point::new(0.0, 0.0), Point::new(30.0, 120.0), Point::new(-60.0, 60.0)),
|
||||
],
|
||||
true,
|
||||
);
|
||||
let teeth = curvature_comb(&sp, 16, 1000.0, 4);
|
||||
let (first, last) = (&teeth[0], &teeth[teeth.len() - 1]);
|
||||
assert!(last.segment < 3, "the closing segment is skipped: {teeth:?}");
|
||||
assert!(first.at.distance(last.at) < 1e-9, "the last sampled tooth sits on the first anchor");
|
||||
assert!(!comb_closes(&sp, &teeth), "the comb does not close across the skipped last segment");
|
||||
assert!(comb_closes(&sp, &curvature_comb(&sp, 16, 1000.0, MAX_COMB_TEETH)), "the full comb closes");
|
||||
let mut anchors: Vec<Anchor> = sp.anchors.iter().copied().collect();
|
||||
anchors[0].h_in = anchors[0].p;
|
||||
anchors.insert(0, Anchor { h_in: Point::new(-50.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) });
|
||||
let seam = SubPath::new(anchors, true);
|
||||
let full = curvature_comb(&seam, 16, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(full.first().map(|t| t.segment), Some(1), "the segment of no length at the seam has no teeth");
|
||||
assert!(comb_closes(&seam, &full), "the comb closes across a segment of no length");
|
||||
}
|
||||
|
||||
/// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter
|
||||
/// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150).
|
||||
#[test]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape};
|
||||
use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape};
|
||||
|
||||
use crate::path::{FillRule, PathData};
|
||||
|
||||
@@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> {
|
||||
|
||||
/// Distance from `p` to the nearest point on the path outline.
|
||||
pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 {
|
||||
path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt()
|
||||
path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt()
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of the path's stroke of width `width`?
|
||||
pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool {
|
||||
let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol);
|
||||
quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol
|
||||
let radius = width / 2.0 + tol;
|
||||
if !path.bounding_box().inflate(radius, radius).contains(p) {
|
||||
return false;
|
||||
}
|
||||
if !radius.is_finite() {
|
||||
return distance_to_outline(path, p) <= radius;
|
||||
}
|
||||
|
||||
// Keep candidates whose squared distance could underflow near a zero radius.
|
||||
let search_radius = radius.max(f64::MIN_POSITIVE.sqrt());
|
||||
path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius)
|
||||
}
|
||||
|
||||
// A Bézier stays inside the bounds of its control points. A line projection is
|
||||
// already cheap, so only check the bounds before running a curve solver.
|
||||
fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool {
|
||||
let bounds = match segment {
|
||||
PathSeg::Line(_) => return false,
|
||||
PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2),
|
||||
PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3),
|
||||
};
|
||||
outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1)
|
||||
}
|
||||
|
||||
fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool {
|
||||
// Leave room for rounding in the curve evaluation and the distance comparison.
|
||||
let scale = p.abs().max(low.abs()).max(high.abs()).max(radius);
|
||||
let padded = radius + 8.0 * f64::EPSILON * scale;
|
||||
p < low - padded || p > high + padded
|
||||
}
|
||||
|
||||
fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 {
|
||||
#[cfg(test)]
|
||||
OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1));
|
||||
segment.nearest(p, 1e-9).distance_sq
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static OUTLINE_NEAREST_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for
|
||||
@@ -185,6 +223,53 @@ mod tests {
|
||||
assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_hit_skips_distant_curves_without_changing_results() {
|
||||
let mut path = BezPath::new();
|
||||
for i in 0..96 {
|
||||
let x = f64::from(i) * 16.0;
|
||||
path.move_to((x, 0.0));
|
||||
path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0));
|
||||
}
|
||||
path.move_to((512.0, 0.0));
|
||||
path.quad_to((513.0, 4.0), (514.0, 0.0));
|
||||
|
||||
for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] {
|
||||
assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit);
|
||||
assert!(path.bounding_box().contains(point));
|
||||
OUTLINE_NEAREST_CALLS.with(|count| count.set(0));
|
||||
assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit);
|
||||
assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls);
|
||||
}
|
||||
|
||||
assert_stroke_hits_at_cutoff();
|
||||
}
|
||||
|
||||
fn assert_stroke_hits_at_cutoff() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.line_to((0.0, 0.0));
|
||||
path.quad_to((4.0, 8.0), (8.0, 0.0));
|
||||
path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0));
|
||||
path.close_path();
|
||||
path.move_to((2.0, -3.0));
|
||||
path.line_to((2.0, -3.0));
|
||||
|
||||
for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] {
|
||||
let transformed = transform * path.clone();
|
||||
for x in -2..23 {
|
||||
for y in -5..9 {
|
||||
let point = transform * Point::new(f64::from(x), f64::from(y));
|
||||
let distance = distance_to_outline(&transformed, point);
|
||||
for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] {
|
||||
let inside = transformed.bounding_box().inflate(radius, radius).contains(point);
|
||||
assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evenodd_hole() {
|
||||
let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//!
|
||||
//! Coordinates are document points (1/72 in), y pointing down.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod anchors;
|
||||
pub mod arc;
|
||||
|
||||
@@ -730,6 +730,11 @@ impl Interp {
|
||||
!self.frames.is_empty() || self.promises.draining
|
||||
}
|
||||
|
||||
/// Whether promise jobs wait to run.
|
||||
pub(crate) fn jobs_waiting(&self) -> bool {
|
||||
!self.promises.queue.is_empty()
|
||||
}
|
||||
|
||||
/// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's
|
||||
/// code ended with `completion`, which this gives back.
|
||||
pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult<Value> {
|
||||
@@ -887,9 +892,10 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of
|
||||
/// them described, and how many there are; the run's notes are cleared.
|
||||
pub(crate) fn take_unhandled(&mut self) -> (Vec<crate::Rejection>, usize) {
|
||||
let rejected = std::mem::take(&mut self.promises.rejected);
|
||||
/// them described, and how many there are. The run's notes stay until the next run starts, so a
|
||||
/// later call leaves out a promise that has a handler since.
|
||||
pub(crate) fn unhandled(&mut self) -> (Vec<crate::Rejection>, usize) {
|
||||
let rejected = self.promises.rejected.clone();
|
||||
let mut out = Vec::new();
|
||||
let mut attribution = Vec::new();
|
||||
let mut count = 0;
|
||||
|
||||
@@ -131,6 +131,7 @@
|
||||
//! `await` (ECMA-262 2017 section 25.5, <https://262.ecma-international.org/8.0/#sec-async-function-objects>).
|
||||
//! An `await` suspends its function's frame until the value settles, and a promise job resumes it.
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod ast;
|
||||
mod builtins;
|
||||
|
||||
@@ -489,7 +489,7 @@ impl Realm {
|
||||
}
|
||||
match result {
|
||||
Ok(v) => {
|
||||
self.rejections = interp.take_unhandled();
|
||||
self.rejections = interp.unhandled();
|
||||
Ok(interp.to_js_value(&v))
|
||||
}
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
@@ -755,6 +755,53 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as
|
||||
/// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the
|
||||
/// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause
|
||||
/// does; what it throws ends the run. The promise jobs a getter queues run in the same fuel,
|
||||
/// and the host then gets the controls once more ([`crate::scriptui::refresh`]). The run's
|
||||
/// report of unhandled rejections ([`Realm::unhandled_rejections`]) is then made again: it
|
||||
/// takes in the rejections of those jobs and leaves out a run's rejection that a getter or a
|
||||
/// job gave a handler.
|
||||
pub fn refresh_script_ui(&mut self) -> Result<(), RunError> {
|
||||
let interp = &mut self.interp;
|
||||
let total = interp.fuel;
|
||||
let cap = self.unbroken_fuel.min(total);
|
||||
interp.fuel = cap;
|
||||
let r = crate::scriptui::refresh(interp);
|
||||
let used = cap - interp.fuel;
|
||||
interp.fuel = total - used;
|
||||
match r {
|
||||
Ok(()) => {
|
||||
self.rejections = self.interp.unhandled();
|
||||
Ok(())
|
||||
}
|
||||
// A refresh that fails reports no rejection, as after any failed run.
|
||||
Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => {
|
||||
self.rejections = (Vec::new(), 0);
|
||||
self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop)
|
||||
}
|
||||
Err(e) => {
|
||||
self.rejections = (Vec::new(), 0);
|
||||
self.outcome(Err(e)).map(drop)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Realm::refresh_script_ui`] after a run that failed: what the refresh throws is dropped,
|
||||
/// and the run's error keeps its place ([`Realm::error_source`], [`Realm::error_mark`]) and
|
||||
/// its thrown value. The report of unhandled rejections stays empty, as after any failed run.
|
||||
pub fn refresh_script_ui_after_error(&mut self) {
|
||||
let (tag, mark) = (self.interp.error_tag, self.interp.error_mark);
|
||||
let thrown = self.interp.last_thrown.clone();
|
||||
let rejections = std::mem::take(&mut self.rejections);
|
||||
let _ = self.refresh_script_ui();
|
||||
self.interp.error_tag = tag;
|
||||
self.interp.error_mark = mark;
|
||||
self.interp.last_thrown = thrown;
|
||||
self.rejections = rejections;
|
||||
}
|
||||
|
||||
/// Adds the global constructors `File` and `Folder`, whose file system work the host functions
|
||||
/// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`,
|
||||
/// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`,
|
||||
|
||||
@@ -308,8 +308,10 @@ fn a_stop_from_end_when_show_fails_ends_the_run() {
|
||||
#[test]
|
||||
fn types_that_are_not_available_yet_throw_errors_that_say_so() {
|
||||
for (source, want) in [
|
||||
("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"),
|
||||
("new Window('palette { b: Button {} }')", "Window: a window of type palette is not available yet; use dialog"),
|
||||
("new Window('window')", "Window: a window of type window is not available yet; use dialog or palette"),
|
||||
("new Window('window { b: Button {} }')", "Window: a window of type window is not available yet; use dialog or palette"),
|
||||
("new Window('palette')", "Window: this host shows no palettes"),
|
||||
("new Window('palette { b: Button {} }')", "Window: this host shows no palettes"),
|
||||
("new Window('dialog').add('p: TabbedPanel {}')", "add: the control type tabbedpanel is not available yet"),
|
||||
("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"),
|
||||
("new Window('dialog').add('wobble')", "add: there is no control type wobble"),
|
||||
@@ -706,6 +708,824 @@ fn a_show_that_waits_resumes_with_the_host_s_answer() {
|
||||
assert_eq!(seen.borrow().ends, vec![(1.0, true)]);
|
||||
}
|
||||
|
||||
/// What a palette host was asked: each call's name and its palette id (0 for none).
|
||||
type Calls = Rc<RefCell<Vec<(String, f64)>>>;
|
||||
|
||||
/// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives
|
||||
/// the events in `events`, in order, then `null`.
|
||||
fn palette_realm(events: Vec<Data>) -> (Realm, Calls) {
|
||||
palette_realm_with(events, Vec::new(), Vec::new())
|
||||
}
|
||||
|
||||
/// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`,
|
||||
/// whose `palettePending` says whether any of them is left, and whose `paletteDraw` gives the
|
||||
/// answers in `draws`, in order, then `false`.
|
||||
fn palette_realm_with(events: Vec<Data>, taken: Vec<Data>, draws: Vec<bool>) -> (Realm, Calls) {
|
||||
let mut r = Realm::new();
|
||||
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
let calls: Calls = Rc::default();
|
||||
let events = Rc::new(RefCell::new(VecDeque::from(events)));
|
||||
let id_of = |args: &[Data], at: usize| match args.get(at) {
|
||||
Some(Data::Number(n)) => *n,
|
||||
_ => 0.0,
|
||||
};
|
||||
let record = |name: &'static str, at: usize| -> HostFunction {
|
||||
let c = calls.clone();
|
||||
Rc::new(move |args| {
|
||||
c.borrow_mut().push((name.to_string(), id_of(&args, at)));
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let c = calls.clone();
|
||||
let show: HostFunction = Rc::new(move |args| {
|
||||
let given = id_of(&args, 1);
|
||||
let id = if given > 0.0 { given } else { 1.0 + c.borrow().iter().filter(|(n, _)| n == "paletteShow").count() as f64 };
|
||||
c.borrow_mut().push(("paletteShow".into(), id));
|
||||
Ok(Data::Number(id))
|
||||
});
|
||||
let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null)));
|
||||
let taken = Rc::new(RefCell::new(VecDeque::from(taken)));
|
||||
let c = calls.clone();
|
||||
let left = taken.clone();
|
||||
let take: HostFunction = Rc::new(move |_| {
|
||||
c.borrow_mut().push(("paletteTake".into(), 0.0));
|
||||
Ok(left.borrow_mut().pop_front().unwrap_or(Data::Null))
|
||||
});
|
||||
let c = calls.clone();
|
||||
let pending: HostFunction = Rc::new(move |_| {
|
||||
c.borrow_mut().push(("palettePending".into(), 0.0));
|
||||
Ok(Data::Bool(!taken.borrow().is_empty()))
|
||||
});
|
||||
let draws = RefCell::new(VecDeque::from(draws));
|
||||
let c = calls.clone();
|
||||
let draw: HostFunction = Rc::new(move |_| {
|
||||
c.borrow_mut().push(("paletteDraw".into(), 0.0));
|
||||
Ok(Data::Bool(draws.borrow_mut().pop_front().unwrap_or(false)))
|
||||
});
|
||||
let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into())));
|
||||
let items = vec![
|
||||
("open".into(), HostItem::Function(none.clone())),
|
||||
("wait".into(), HostItem::Function(none.clone())),
|
||||
("end".into(), HostItem::Function(none)),
|
||||
("palette".into(), HostItem::Function(record("palette", 0))),
|
||||
("paletteShow".into(), HostItem::Function(show)),
|
||||
("paletteUpdate".into(), HostItem::Function(record("paletteUpdate", 1))),
|
||||
("paletteHide".into(), HostItem::Function(record("paletteHide", 0))),
|
||||
("paletteClose".into(), HostItem::Function(record("paletteClose", 0))),
|
||||
("paletteEvent".into(), HostItem::Function(event)),
|
||||
("paletteTake".into(), HostItem::Function(take)),
|
||||
("palettePending".into(), HostItem::Function(pending)),
|
||||
("paletteDraw".into(), HostItem::Function(draw)),
|
||||
];
|
||||
r.define_script_ui(items).unwrap();
|
||||
(r, calls)
|
||||
}
|
||||
|
||||
fn palette_event(palette: f64, event: Data) -> Data {
|
||||
let Data::Object(mut fields) = event else { return Data::Null };
|
||||
fields.push(("palette".into(), Data::Number(palette)));
|
||||
Data::Object(fields)
|
||||
}
|
||||
|
||||
fn names(calls: &Calls) -> Vec<String> {
|
||||
calls.borrow().iter().map(|(n, _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2)), palette_event(1.0, change(3, Data::String("typed".into())))]);
|
||||
let made = r
|
||||
.run(
|
||||
"var p = new Window('palette', 'Tools'); var label = p.add('statictext', undefined, 'idle'); \
|
||||
var b = p.add('button', undefined, 'Go'); var t = p.add('edittext', undefined, ''); var log = []; \
|
||||
b.onClick = function () { log.push('click'); label.text = 'clicked'; }; \
|
||||
t.onChange = function () { log.push('change ' + t.text); }; String(p.show())",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(made, JsValue::String("undefined".into()), "show() gives undefined without waiting");
|
||||
assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]);
|
||||
r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into()));
|
||||
let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count();
|
||||
assert_eq!(updates(&calls), 1, "the handlers give the host nothing");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(updates(&calls), 2, "the refresh after the run gives the host the new controls");
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_runs_no_handler_once_its_button_was_taken_out_of_the_palette() {
|
||||
// The button's onClick getter takes it out of the palette and gives a function.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \
|
||||
Object.defineProperty(b, 'onClick', {get: function () { p.remove(b); return function () { log.push('ran'); }; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "the getter's function does not run");
|
||||
// A capturing listener on the palette takes the button out before the button's own turn.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \
|
||||
b.onClick = function () { log.push('click'); }; b.addEventListener('click', function () { log.push('listener'); }); \
|
||||
p.addEventListener('click', function () { log.push('capture'); p.remove(b); }, true); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("capture".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_is_dropped_when_a_getter_read_for_it_disables_its_button_or_a_group_above() {
|
||||
for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(3))]);
|
||||
r.run(&format!(
|
||||
"var armed = false, log = []; var p = new Window('palette'); var label = p.add('statictext', undefined, 'L'); \
|
||||
var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \
|
||||
Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \
|
||||
p.show(); armed = true;"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_is_dropped_when_a_getter_read_after_its_button_disables_the_button_or_a_group_above() {
|
||||
for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(&format!(
|
||||
"var armed = false, log = []; var p = new Window('palette'); \
|
||||
var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \
|
||||
var label = p.add('statictext', undefined, 'L'); \
|
||||
Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \
|
||||
p.show(); armed = true;"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}");
|
||||
}
|
||||
// A getter that gives the button's state, and disables it while it says the button is visible.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var armed = false, log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show(); \
|
||||
Object.defineProperty(b, 'visible', {get: function () { b.enabled = false; return true; }}); b.enabled = true;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()));
|
||||
// Without a getter that disables anything, the same click runs its handler.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("click".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_throws_when_an_item_s_text_comes_from_a_getter() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(0.0), seen_list_change(0.0)]);
|
||||
// The first item's getter gives `label`, which the second item's getter changes after the
|
||||
// first was compared.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; var label = 'a', armed = false; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; \
|
||||
Object.defineProperty(l.items[0], 'text', {get: function () { return label; }}); \
|
||||
Object.defineProperty(l.items[1], 'text', {get: function () { if (armed) { label = 'z'; } return 'b'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
for arm in ["false", "true"] {
|
||||
let e = r.run(&format!("armed = {arm}; label = 'a'; try {{ Window.__vcPaletteEvent(); 'none'; }} catch (e) {{ e.message; }}")).unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "armed {arm}");
|
||||
}
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_asks_the_host_once_more_after_a_handler_s_exception() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new());
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () { throw new Error('broken'); }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let thrown = r.run("try { p.update(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(thrown, JsValue::String("broken".into()));
|
||||
let asked: Vec<String> = names(&calls).into_iter().filter(|n| n == "palettePending" || n == "paletteTake").collect();
|
||||
assert_eq!(asked, ["palettePending", "paletteTake", "palettePending"], "the host learns the event's handlers ended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_palette_runs_on_close_which_can_keep_it_open() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, close()), palette_event(1.0, close()), palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; \
|
||||
var asked = 0; p.onClose = function () { asked++; p.close(); return asked > 1; }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open");
|
||||
assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(true), "a palette onClose kept open stays visible");
|
||||
r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again");
|
||||
assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(false), "a closed palette is not visible");
|
||||
assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1);
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
}
|
||||
|
||||
fn count(calls: &Calls, name: &str) -> usize {
|
||||
calls.borrow().iter().filter(|(n, _)| n == name).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_in_the_script_s_own_code_gives_the_controls_only_when_the_host_draws_the_palette() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true, false, false, true]);
|
||||
r.start(
|
||||
"var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 4); p.show(); \
|
||||
for (var k = 1; k <= 4; k++) { bar.value = k; p.update(); }",
|
||||
)
|
||||
.unwrap();
|
||||
while r.advance(1_000_000).unwrap() == Progress::Paused {}
|
||||
assert_eq!(count(&calls, "paletteDraw"), 4, "each update() asks whether the palette is drawn");
|
||||
assert_eq!(count(&calls, "paletteUpdate"), 1 + 2, "show(), then only the update() calls the host draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_in_a_handler_neither_asks_to_draw_the_palette_nor_gives_its_controls() {
|
||||
let (mut r, calls) = palette_realm_with(vec![palette_event(1.0, click(2))], Vec::new(), vec![true; 3]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); var b = p.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.start("Window.__vcPaletteEvent();").unwrap();
|
||||
while r.advance(1_000_000).unwrap() == Progress::Paused {}
|
||||
assert_eq!(count(&calls, "paletteDraw"), 0, "a handler cannot pause, so its update() is not drawn");
|
||||
assert_eq!(count(&calls, "paletteUpdate"), before, "the handler's update() calls give the host no controls");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 1, "the controls go to the host once the run ends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(2))], Vec::new());
|
||||
let done = r
|
||||
.run(
|
||||
"var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100); \
|
||||
var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; \
|
||||
cancel.onClick = function () { stopped = true; }; p.show(); \
|
||||
var k = 0; while (!stopped && k < 100) { k++; bar.value = k; p.update(); } k + ':' + stopped",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick");
|
||||
assert_eq!(count(&calls, "paletteTake"), 1, "update() takes events while one waits");
|
||||
assert!(count(&calls, "palettePending") >= 2, "update() asks again after each event");
|
||||
let order = names(&calls);
|
||||
let take = order.iter().position(|n| n == "paletteTake");
|
||||
let last_update = order.iter().rposition(|n| n == "paletteUpdate");
|
||||
assert!(take.zip(last_update).is_some_and(|(t, u)| u < t), "the host gets the controls before the event is taken");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_a_getter_calls_while_a_click_waits_leaves_the_click_to_the_update_taking_it() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new());
|
||||
let done = r
|
||||
.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; var armed = false; \
|
||||
b.onClick = function () { clicks++; }; \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { reads++; p.update(); } return 'P'; }}); \
|
||||
p.show(); armed = true; p.update(); clicks + ':' + (reads > 0)",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(done, JsValue::String("1:true".into()), "the getter's update() runs, and the click's onClick runs once");
|
||||
assert_eq!(count(&calls, "paletteTake"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_throws_for_a_window_that_is_not_showing() {
|
||||
let (mut r, _, _) = realm(vec![click(12)]);
|
||||
let source = format!(
|
||||
"{FORM} var before = 'none'; try {{ w.update(); }} catch (e) {{ before = e.message; }} var during = 'none'; \
|
||||
ok.onClick = function () {{ w.update(); during = 'ran'; w.close(1); }}; [w.show(), before, during].join('|')"
|
||||
);
|
||||
assert_eq!(r.run(&source).unwrap(), JsValue::String("1|update: the window is not showing|ran".into()));
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
let hidden = r
|
||||
.run(
|
||||
"var p = new Window('palette'); var log = []; try { p.update(); } catch (e) { log.push('before show'); } \
|
||||
p.show(); p.update(); p.hide(); try { p.update(); } catch (e) { log.push('hidden'); } log.join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(hidden, JsValue::String("before show,hidden".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_on_a_showing_dialog_its_group_or_its_panel_runs_in_a_handler() {
|
||||
let (mut r, _, _) = realm(vec![click(12)]);
|
||||
let source = format!(
|
||||
"{FORM} var done = 'none'; ok.onClick = function () {{ bar.value = 7; w.update(); g.update(); p.update(); done = 'ran'; w.close(1); }}; \
|
||||
[w.show(), done].join('|')"
|
||||
);
|
||||
assert_eq!(r.run(&source).unwrap(), JsValue::String("1|ran".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_follows_whether_the_host_shows_a_palette_not_its_visible_property() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true; 4]);
|
||||
r.run("var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); p.show();").unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.start(
|
||||
"var log = []; p.visible = false; p.update(); g.update(); log.push('shown'); \
|
||||
p.hide(); p.visible = true; try { p.update(); } catch (e) { log.push('hidden'); } \
|
||||
try { b.update(); } catch (e) { log.push(e.name); } log.join()",
|
||||
)
|
||||
.unwrap();
|
||||
let log = loop {
|
||||
if let Progress::Done(v) = r.advance(1_000_000).unwrap() {
|
||||
break v;
|
||||
}
|
||||
};
|
||||
assert_eq!(log, JsValue::String("shown,hidden,TypeError".into()));
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the palette and its group each give the host the controls while it shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_after_its_items_changed_throws() {
|
||||
let seen = |index: f64| {
|
||||
let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null };
|
||||
fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())])));
|
||||
// The two items the list was made with.
|
||||
fields.push(("revision".into(), Data::Number(2.0)));
|
||||
Data::Object(fields)
|
||||
};
|
||||
let (mut r, _) = palette_realm(vec![seen(1.0), seen(1.0), seen(1.0), seen(1.0)]);
|
||||
r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();")
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent(); l.removeAll(); l.add('item', 'c'); l.add('item', 'd');").unwrap();
|
||||
let message = "a palette's list changed before the person's choice was taken";
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(message.into()), "the same number of items, other texts");
|
||||
r.run("l.removeAll(); l.add('item', 'a');").unwrap();
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(message.into()), "fewer items");
|
||||
r.run("l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap();
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(message.into()), "new items with the same texts");
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into()));
|
||||
}
|
||||
|
||||
/// A palette list change as the host gives it: the item index, the items the person saw (`a` and
|
||||
/// `b`) and the revision of a list made with those two items.
|
||||
fn seen_list_change(index: f64) -> Data {
|
||||
let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null };
|
||||
fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())])));
|
||||
fields.push(("revision".into(), Data::Number(2.0)));
|
||||
Data::Object(fields)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_after_an_item_s_text_changed_throws() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();")
|
||||
.unwrap();
|
||||
r.run("l.items[1].text = 'z';").unwrap();
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "the same items, one with another text");
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The event reads the first item's text twice: for the palette's description, then to compare
|
||||
// it with the items the person saw. The second read turns the getter back into a plain text and
|
||||
// replaces the items with ones of the same texts, so only the list's revision tells them apart.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; var first = l.items[0]; \
|
||||
Object.defineProperty(first, 'text', {configurable: true, get: function () { if (reads >= 0 && ++reads == 2) { \
|
||||
Object.defineProperty(first, 'text', {value: 'a', writable: true, enumerable: true, configurable: true}); \
|
||||
l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()));
|
||||
assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_finds_its_control_by_its_id() {
|
||||
let of = |id: usize, element: f64| {
|
||||
let Data::Object(mut fields) = palette_event(1.0, click(id)) else { return Data::Null };
|
||||
fields.push(("element".into(), Data::Number(element)));
|
||||
Data::Object(fields)
|
||||
};
|
||||
// The palette is element 1, the group 2 and the button 3. The host's indexes are stale: 1 is
|
||||
// the group, and after the group is removed, 2 is past the end.
|
||||
let (mut r, _) = palette_realm(vec![of(1, 3.0), of(2, 3.0), of(1, 99.0)]);
|
||||
r.run("var p = new Window('palette'); var g = p.add('group'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; p.show();")
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0), "the click reaches the control with its id");
|
||||
r.run("p.remove(g); Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0), "the click follows the control after a control before it is removed");
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into()), "no control with the id");
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_on_a_button_a_getter_removed_runs_no_handler_and_throws() {
|
||||
// The palette is element 1, the label 2 and the button 3.
|
||||
let Data::Object(mut fields) = palette_event(1.0, click(2)) else { panic!("an event is an object") };
|
||||
fields.push(("element".into(), Data::Number(3.0)));
|
||||
let (mut r, _) = palette_realm(vec![Data::Object(fields)]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \
|
||||
var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \
|
||||
Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.remove(b); } return 'idle'; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
// The event reads the label's text for the palette's description, which removes the button.
|
||||
let given = r.run("armed = true; try { Window.__vcPaletteEvent(); 'given'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(given, JsValue::String("a palette event names a control the palette no longer holds".into()));
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the removed button's handler does not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \
|
||||
var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \
|
||||
Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.close(); } return 'idle'; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
// The event reads the label's text for the palette's description, which closes the palette.
|
||||
r.run("armed = true; Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the click is not given to a closed palette");
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_runs_no_more_listeners_once_one_closed_the_palette() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var later = 0; \
|
||||
b.addEventListener('click', function () { p.close(); }); b.addEventListener('click', function () { later++; }); \
|
||||
p.addEventListener('click', function () { later++; }); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
assert_eq!(r.run("later").unwrap(), JsValue::Number(0.0), "neither the next listener nor the palette's runs after the close");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The event reads the first item's text twice: for the palette's description, then to compare
|
||||
// it with the items the person saw. The second read closes the palette.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \
|
||||
Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("none".into()));
|
||||
assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_disabled_or_hid_the_list() {
|
||||
for disable in ["l.enabled = false;", "l.visible = false;"] {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The second read of the first item's text, which compares it with the items the person
|
||||
// saw, disables the list.
|
||||
r.run(&format!(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; \
|
||||
Object.defineProperty(l.items[0], 'text', {{get: function () {{ if (reads >= 0 && ++reads == 2) {{ {disable} }} return 'a'; }}}}); \
|
||||
p.show();"
|
||||
))
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("none".into()), "{disable}");
|
||||
assert_eq!(r.run("[got.join(), String(l.selection)].join()").unwrap(), JsValue::String(",null".into()), "{disable}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_does_not_turn_over_a_check_box_its_value_getter_disabled() {
|
||||
// Whichever read of `value` disables the box, the click neither sets it nor runs its handler.
|
||||
for read in 1..=4 {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(&format!(
|
||||
"var p = new Window('palette'); var c = p.add('checkbox', undefined, 'On'); var clicks = 0, on = false, reads = -1; \
|
||||
Object.defineProperty(c, 'value', {{get: function () {{ if (reads >= 0 && ++reads == {read}) {{ c.enabled = false; }} return on; }}, \
|
||||
set: function (v) {{ on = v; }}}}); c.onClick = function () {{ clicks++; }}; p.show(); reads = 0;"
|
||||
))
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
let got = r.run(&format!("reads >= {read} ? [clicks, on].join() : 'not read'")).unwrap();
|
||||
assert!(got == JsValue::String("0,false".into()) || (read > 1 && got == JsValue::String("not read".into())), "read {read}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_palette_is_not_described_after_the_run() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.run(
|
||||
"var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); p.hide(); \
|
||||
Object.defineProperty(p, 'text', {get: function () { throw new Error('read'); }});",
|
||||
)
|
||||
.unwrap();
|
||||
let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count();
|
||||
let before = updates(&calls);
|
||||
r.refresh_script_ui().expect("a hidden palette's throwing title getter is not read");
|
||||
assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \
|
||||
Object.defineProperty(b, 'onClick', {get: function () { reads++; p.close(); return function () { clicks++; }; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a closed palette does not run");
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_whose_getter_hid_the_palette() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \
|
||||
Object.defineProperty(b, 'onClick', {get: function () { reads++; p.hide(); return function () { clicks++; }; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a hidden palette does not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_once_a_listener_hid_and_showed_the_palette_again() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \
|
||||
p.addEventListener('click', function () { heard++; p.hide(); p.show(); }, true); \
|
||||
b.onClick = function () { clicks++; }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(
|
||||
r.run("[heard, clicks, p.visible].join()").unwrap(),
|
||||
JsValue::String("1,0,true".into()),
|
||||
"a click the palette took before a hide is not its click after the palette shows again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_once_a_capturing_listener_disabled_its_group() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \
|
||||
g.addEventListener('click', function () { heard++; g.enabled = false; }, true); \
|
||||
b.onClick = function () { clicks++; }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[heard, clicks].join()").unwrap(), JsValue::String("1,0".into()), "a control in a disabled group takes no click");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_refresh_that_fails_reports_no_rejection() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }}); \
|
||||
p.show(); Promise.reject(new Error('early')); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.unhandled_rejection_count(), 1, "the run left the rejection unhandled");
|
||||
assert!(r.refresh_script_ui().is_err());
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed refresh reports no rejection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_the_list() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The second read of the first item's text, which compares it with the items the person saw,
|
||||
// removes the list from the palette.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \
|
||||
Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.remove(l); } return 'a'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into()));
|
||||
assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]);
|
||||
// The second read of the second item's text, which compares it with the items the person saw,
|
||||
// changes the first item's text, which that comparison already took.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \
|
||||
Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()));
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_whose_palette_update_a_getter_breaks_still_returns_the_control() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.run(
|
||||
"var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var armed = false; \
|
||||
Object.defineProperty(label, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'idle'; }}); \
|
||||
var list = p.add('listbox', undefined, ['a']); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let added = r
|
||||
.run(
|
||||
"armed = true; var c, d, m = []; try { c = p.add('button', undefined, 'New'); } catch (e) { m.push(e.message); } \
|
||||
try { d = list.add('item', 'b'); } catch (e) { m.push(e.message); } \
|
||||
try { list.remove(0); } catch (e) { m.push(e.message); } \
|
||||
try { p.remove(c); } catch (e) { m.push(e.message); } armed = false; \
|
||||
[String(c && c.text), String(d && d.text), list.items.length, p.children.length, m.length].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(added, JsValue::String("New,b,1,2,0".into()), "each change is made once and gives its result");
|
||||
// A later error is at its own line, not at the getter's.
|
||||
let e = r.run("armed = true;\np.add('button', undefined, 'Other');\narmed = false;\nthrow new Error('later');").unwrap_err();
|
||||
assert_eq!((e.message.contains("later"), e.line), (true, 4), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_jobs_a_palette_getter_queues_while_the_palette_is_refreshed_run() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var ran = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \
|
||||
Promise.resolve().then(function () { ran++; b.text = 'Done'; }); Promise.reject(new Error('late')); } return 'P'; }}); \
|
||||
p.show(); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again after the jobs ran");
|
||||
assert_eq!(r.unhandled_rejections().len(), 1, "the job's rejection is the run's");
|
||||
assert_eq!(r.run("[ran, b.text].join()").unwrap(), JsValue::String("1,Done".into()), "the job the getter queued ran with the refresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_s_rejection_that_a_palette_getter_handles_during_the_refresh_is_not_reported() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var armed = false, caught = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \
|
||||
early.catch(function () { caught++; }); } return 'P'; }}); \
|
||||
p.show(); var early = Promise.reject(new Error('early')); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (1, 1), "the run left the rejection unhandled");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "the getter gave it a handler");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejection_a_palette_getter_makes_while_a_failed_run_is_refreshed_is_not_reported() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \
|
||||
Promise.reject('late'); } return 'P'; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r.run("armed = true; throw new Error('failed');").is_err());
|
||||
r.refresh_script_ui_after_error();
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed run reports no rejection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_jobs_a_palette_getter_queues_on_every_refresh_run_without_another_refresh() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var n = 0, reads = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); \
|
||||
Object.defineProperty(p, 'text', {get: function () { reads++; \
|
||||
Promise.resolve().then(function () { n++; }); return 'Title'; }});",
|
||||
)
|
||||
.unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again once after the jobs run");
|
||||
assert_eq!(r.run("reads > 0 && n === reads").unwrap(), JsValue::Bool(true), "every getter read's job runs before the refresh returns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_jobs_a_palette_getter_queues_during_refresh_leave_waiting_clicks_queued() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var clicks = 0, jobs = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { clicks++; }; \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { \
|
||||
Promise.resolve().then(function () { jobs++; p.update(); }); } return 'P'; }}); \
|
||||
p.show(); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteTake"), 0, "the refresh leaves the waiting click queued");
|
||||
assert_eq!(r.run("jobs > 0 && clicks === 0").unwrap(), JsValue::Bool(true), "the promise jobs run without dispatching the click");
|
||||
assert_eq!(r.run("armed = false; p.update(); clicks").unwrap(), JsValue::Number(1.0), "a later update takes the waiting click");
|
||||
assert_eq!(count(&calls, "paletteTake"), 1, "the refresh restores the event-taking guard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_on_close_throws_stays_whole_while_the_close_ends() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, close())]);
|
||||
r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.onClose = function () { throw {tag: 'kept'}; }; p.show();").unwrap();
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let thrown = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { String(e.tag); }");
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert_eq!(thrown.unwrap(), JsValue::String("kept".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_closed_the_palette_and_on_close_changed_the_list() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The second read of the first item's text closes the palette, and its `onClose` adds an item.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \
|
||||
p.onClose = function () { l.add('item', 'c'); }; \
|
||||
Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("none".into()), "the event for a closed palette is dropped without an error");
|
||||
assert_eq!(r.run("[reads >= 2, l.items.length, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("true,3,,null".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_s_visible_follows_hide_and_show() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
let v = r
|
||||
.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); var a = p.visible; p.hide(); var b = p.visible; p.show(); [a, b, p.visible].join()")
|
||||
.unwrap();
|
||||
assert_eq!(v, JsValue::String("true,false,true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_close_inside_a_dialog_s_on_close_does_nothing() {
|
||||
let (mut r, seen, _) = realm(vec![close(), click(13)]);
|
||||
let source = format!(
|
||||
"{FORM} var asked = 0; w.onClose = function () {{ asked++; if (asked == 1) {{ w.close(5); return false; }} return true; }}; [w.show(), asked].join()"
|
||||
);
|
||||
assert_eq!(r.run(&source).unwrap(), JsValue::String("2,2".into()), "the dialog waited for the click on Cancel");
|
||||
assert_eq!(seen.borrow().ends, vec![(2.0, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_whose_ends_add_up_past_the_largest_number_stay_finite() {
|
||||
let (mut r, seen, _) = realm(vec![close()]);
|
||||
r.run("var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); b.bounds = {x: 1e308, y: 0, width: 1e308, height: 20}; w.show()")
|
||||
.unwrap();
|
||||
let described = nodes(&seen.borrow().descriptions[0]);
|
||||
let want = Data::Array(vec![Data::Number(1e308), Data::Number(0.0), Data::Number(f64::MAX), Data::Number(20.0)]);
|
||||
assert_eq!(field(&described[1], "bounds"), &want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); p.hide(); p.show();").unwrap();
|
||||
let shows: Vec<f64> = calls.borrow().iter().filter(|(n, _)| n == "paletteShow" || n == "paletteHide").map(|(_, id)| *id).collect();
|
||||
assert_eq!(shows, [1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findelement_items_and_selection_follow_the_list() {
|
||||
let (mut r, _, _) = realm(Vec::new());
|
||||
|
||||
@@ -22,7 +22,9 @@ vectorcraft-format = { workspace = true }
|
||||
vectorcraft-tools = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
craft = { workspace = true, features = ["automation"] }
|
||||
# `automation-agents` and `control-agents`: plain `mcp` finds the open window through the ArtCraft
|
||||
# Launcher's switch and the connection file, with the shared live client and the agent folders.
|
||||
craft = { workspace = true, features = ["automation", "automation-agents", "control-agents"] }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//! Agents in the open window: the CLI's side of the ArtCraft Launcher's switch.
|
||||
//!
|
||||
//! While the launcher's *Settings › AI agents* switch names VectorCraft (behind the suite's `AI-MCP`
|
||||
//! flag), the desktop app serves its control channel on loopback and publishes where in its
|
||||
//! settings folder (`craft::automation::agents::AgentLink`, `vectorcraft_ui_egui::agents`). Plain
|
||||
//! `vectorcraft-cli mcp` reads that file on every tool call ([`LiveBackend`], over the shared
|
||||
//! `craft::automation::agents::Live`), so an MCP client's configuration holds no port and no token,
|
||||
//! and the app may start, quit or move to another port while the client stays connected. Adding
|
||||
//! VectorCraft to MCP clients is the launcher's job (one entry for every Craft app); VectorCraft
|
||||
//! writes no client configuration.
|
||||
//!
|
||||
//! What is VectorCraft's here: its launcher id, its window client ([`Window`], which makes the app
|
||||
//! prove it holds the token before it proves it holds it too) and its headless session
|
||||
//! ([`Headless`] with the agent folders as automation roots).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft::automation::agents::{self as shared, AgentSettings, Consent, HeadlessFolders, Route, WhenAppClosed};
|
||||
use craft::automation::client::{CALL_TIMEOUT, CONNECT_TIMEOUT, MAX_REPLY_BYTES};
|
||||
use craft::automation::security::{self, ProofRole};
|
||||
use craft::control::agents::{AgentFolders, folders_answer};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::file_access::{Access, AutomationRoots};
|
||||
|
||||
use crate::backend::Backend;
|
||||
use crate::headless::Headless;
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names VectorCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "vectorcraft";
|
||||
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/VectorCraft`).
|
||||
pub const APP_NAME: &str = "VectorCraft";
|
||||
/// The desktop app's file name beside the CLI (without `.exe`).
|
||||
pub const APP_EXE: &str = "vectorcraft";
|
||||
/// The method the `agent_folders` tool calls: the folders this session's file commands may use.
|
||||
pub const FOLDERS_METHOD: &str = "agent.folders";
|
||||
/// What a tool that needs the window says in a session without one.
|
||||
pub const NEEDS_WINDOW: &str = "needs the open VectorCraft window: open VectorCraft with AI agents on (ArtCraft Launcher › Settings › AI agents) and run `vectorcraft-cli mcp` without --headless";
|
||||
|
||||
/// Whether the person lets agents use VectorCraft now: with the suite's `AI-MCP` flag, the
|
||||
/// launcher's switch. VectorCraft had no agent consent of its own before the switch, so without
|
||||
/// the flag agents get a session without a window.
|
||||
pub fn allowed_now() -> bool {
|
||||
shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
/// The automation roots for `folders`: what a session with these folders may open and save. A kind
|
||||
/// without a folder is refused, and so is everything when there is no folder at all.
|
||||
pub fn roots_for(folders: &AgentFolders) -> Result<Arc<AutomationRoots>, String> {
|
||||
let read: Vec<&Path> = folders.read.as_deref().into_iter().collect();
|
||||
let write: Vec<&Path> = folders.write.as_deref().into_iter().collect();
|
||||
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
|
||||
}
|
||||
|
||||
/// The `agent_folders` answer of a headless session confined to `roots` (`None`: not confined).
|
||||
/// With more than one folder of a kind (`--automation-read-root` given twice), `read_folders` /
|
||||
/// `write_folders` list them all.
|
||||
pub(crate) fn headless_folders(roots: Option<&AutomationRoots>) -> Value {
|
||||
let Some(roots) = roots else {
|
||||
// A session started without automation roots (`--headless` without them, or with the
|
||||
// agents switch off) isn't confined: say so rather than claim it has no folders.
|
||||
return json!({
|
||||
"read_folder": null,
|
||||
"write_folder": null,
|
||||
"unrestricted": true,
|
||||
"note": "This session was started without automation roots: its file commands open and save wherever the user can.",
|
||||
});
|
||||
};
|
||||
let (read, write): (Vec<&Path>, Vec<&Path>) = (roots.folders(Access::Read).collect(), roots.folders(Access::Write).collect());
|
||||
let mut folders = AgentFolders::default();
|
||||
folders.read = read.first().map(|p| p.to_path_buf());
|
||||
folders.write = write.first().map(|p| p.to_path_buf());
|
||||
let mut answer = folders_answer(&folders);
|
||||
for (key, all) in [("read_folders", &read), ("write_folders", &write)] {
|
||||
if all.len() > 1
|
||||
&& let Some(o) = answer.as_object_mut()
|
||||
{
|
||||
o.insert(key.into(), json!(all.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>()));
|
||||
}
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
// ---- The open window ---------------------------------------------------------------------------
|
||||
|
||||
/// How often a call waiting for its reply looks whether it was cancelled.
|
||||
const CANCEL_POLL: Duration = Duration::from_millis(100);
|
||||
|
||||
/// One authenticated connection to the open window. The app proves it holds the token first
|
||||
/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the
|
||||
/// wire, and a program that took a stale port learns nothing derived from it.
|
||||
pub struct Window {
|
||||
addr: SocketAddr,
|
||||
token: String,
|
||||
conn: Option<(BufReader<TcpStream>, TcpStream)>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
/// A client for the window on `127.0.0.1:port` with `token`; connects on the first call.
|
||||
pub fn new(port: u16, token: String) -> Self {
|
||||
Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 }
|
||||
}
|
||||
|
||||
/// Connects and runs the challenge handshake.
|
||||
pub fn connect(&mut self) -> Result<(), String> {
|
||||
self.conn = None;
|
||||
let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?;
|
||||
stream.set_nodelay(true).ok();
|
||||
stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
|
||||
let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream);
|
||||
let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?;
|
||||
let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}), false)?
|
||||
.map_err(|e| format!("{} refused challenge authentication ({e}); the agent token was not used", self.addr))?;
|
||||
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned);
|
||||
let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else {
|
||||
return Err(format!("{} answered the challenge without a proof; the agent token was not used", self.addr));
|
||||
};
|
||||
if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
|
||||
return Err(format!("{} could not prove it holds VectorCraft's agent token; nothing was sent to it", self.addr));
|
||||
}
|
||||
let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?;
|
||||
round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}), false)?
|
||||
.map_err(|e| format!("VectorCraft refused the agent token: {e}"))?;
|
||||
self.conn = Some(conn);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends one request and reads the reply with its `id` (lines for other ids are skipped): `Err`
|
||||
/// when the connection failed or the call was cancelled while it waited, `Ok(Err)` when the app
|
||||
/// answered with an error. With `cancellable`, a cancelled MCP call stops waiting.
|
||||
fn round_trip(
|
||||
conn: &mut (BufReader<TcpStream>, TcpStream),
|
||||
id: u64,
|
||||
method: &str,
|
||||
params: Value,
|
||||
cancellable: bool,
|
||||
) -> Result<Result<Value, String>, String> {
|
||||
let (reader, writer) = conn;
|
||||
let line = json!({"id": id, "method": method, "params": params}).to_string();
|
||||
writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?;
|
||||
let deadline = Instant::now() + CALL_TIMEOUT;
|
||||
loop {
|
||||
let reply = read_line(reader, deadline, cancellable)?;
|
||||
let v: Value = serde_json::from_slice(&reply).map_err(|e| format!("bad reply from the window: {e}"))?;
|
||||
if v.get("id").and_then(Value::as_u64) != Some(id) {
|
||||
continue;
|
||||
}
|
||||
return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(v.get("result").cloned().unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// One reply line, at most [`MAX_REPLY_BYTES`], read by `deadline`.
|
||||
fn read_line(reader: &mut BufReader<TcpStream>, deadline: Instant, cancellable: bool) -> Result<Vec<u8>, String> {
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err("the window did not answer in time".into());
|
||||
}
|
||||
reader.get_ref().set_read_timeout(Some(left.min(CANCEL_POLL))).map_err(|e| e.to_string())?;
|
||||
let room = (MAX_REPLY_BYTES + 1).saturating_sub(line.len() as u64);
|
||||
// `read_until` keeps what it read before a timeout, so the line goes on where it stopped.
|
||||
match reader.by_ref().take(room).read_until(b'\n', &mut line) {
|
||||
Ok(0) => return Err("the window closed the connection".into()),
|
||||
Ok(_) if line.ends_with(b"\n") => return Ok(line),
|
||||
Ok(_) if line.len() as u64 > MAX_REPLY_BYTES => return Err("the window's reply is too long".into()),
|
||||
Ok(_) => return Err("the window closed the connection".into()),
|
||||
Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
|
||||
if cancellable && vectorcraft_engine::cancel::is_cancelled() {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == ErrorKind::Interrupted => {}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for Window {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
if self.conn.is_none() {
|
||||
self.connect().map_err(|e| format!("the VectorCraft window is not reachable: {e}; `{method}`: nothing was sent"))?;
|
||||
}
|
||||
let id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1).max(1);
|
||||
let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) };
|
||||
let cancellable = vectorcraft_engine::cancel::is_cancellable();
|
||||
match round_trip(conn, id, method, params, cancellable) {
|
||||
Ok(answer) => answer,
|
||||
// Never sent again: the request may have run. The next call reconnects.
|
||||
Err(e) => {
|
||||
self.conn = None;
|
||||
if e == "cancelled" {
|
||||
return Err(format!(
|
||||
"the VectorCraft window: `{method}` cancelled; the app may still finish what it was asked, which can't be stopped from here"
|
||||
));
|
||||
}
|
||||
Err(format!("lost the connection to the VectorCraft window ({e}); `{method}` may or may not have run: inspect state before retrying"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
format!("the open VectorCraft window ({})", self.addr)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- The live backend --------------------------------------------------------------------------
|
||||
|
||||
type SharedWindow = Arc<Mutex<Window>>;
|
||||
/// The headless session stays on the server's thread, as the backend does.
|
||||
type SharedHeadless = Rc<RefCell<Headless>>;
|
||||
|
||||
/// Makes each new headless session (the CLI attaches the user's stores) from its automation roots.
|
||||
pub type HeadlessMaker = Box<dyn Fn(Option<Arc<AutomationRoots>>) -> Headless + Send + Sync>;
|
||||
|
||||
/// What plain `vectorcraft-cli mcp` needs to find the window.
|
||||
pub struct LiveConfig {
|
||||
/// The app's settings folder: connection file, token file and agent settings.
|
||||
pub config_dir: PathBuf,
|
||||
/// Reads the agent settings saved in a settings folder (`agents.json`).
|
||||
pub read_settings: fn(&Path) -> AgentSettings,
|
||||
/// Overrides the app's closed-app choice (`--when-closed`).
|
||||
pub when_closed: Option<WhenAppClosed>,
|
||||
/// The command's folders (`--automation-read-root`, `--automation-write-root`).
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't.
|
||||
pub launch: Option<shared::LaunchFn>,
|
||||
pub launch_timeout: Duration,
|
||||
/// Whether agents may use the app now ([`allowed_now`]); tests replace it.
|
||||
pub allowed: fn() -> bool,
|
||||
/// The default agent folder for an empty folder setting; tests replace it.
|
||||
pub default_folder: Option<PathBuf>,
|
||||
/// Makes each new headless session.
|
||||
pub headless: HeadlessMaker,
|
||||
}
|
||||
|
||||
impl LiveConfig {
|
||||
/// The settings in `config_dir` as `read_settings` reads them, the launcher's switch, the
|
||||
/// default agent folder, and a plain headless session with a document.
|
||||
pub fn new(config_dir: PathBuf, read_settings: fn(&Path) -> AgentSettings) -> Self {
|
||||
Self {
|
||||
config_dir,
|
||||
read_settings,
|
||||
when_closed: None,
|
||||
read_roots: Vec::new(),
|
||||
write_root: None,
|
||||
launch: None,
|
||||
launch_timeout: shared::LAUNCH_TIMEOUT,
|
||||
allowed: allowed_now,
|
||||
default_folder: craft::control::agents::default_folder(APP_NAME),
|
||||
headless: Box::new(|roots| Headless::with_document().with_automation_roots(roots)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain `vectorcraft-cli mcp`: every call goes to the open window while the person lets agents
|
||||
/// use it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup
|
||||
/// is the shared `craft::automation::agents::Live`; a session that went headless stays headless.
|
||||
pub struct LiveBackend {
|
||||
live: shared::Live<SharedWindow, SharedHeadless>,
|
||||
config_dir: PathBuf,
|
||||
read_settings: fn(&Path) -> AgentSettings,
|
||||
default_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LiveBackend {
|
||||
pub fn new(cfg: LiveConfig) -> Self {
|
||||
let LiveConfig { config_dir, read_settings, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } =
|
||||
cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
|
||||
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
|
||||
let mut window = Window::new(w.port, w.token.clone());
|
||||
window.connect()?;
|
||||
Ok(Arc::new(Mutex::new(window)))
|
||||
};
|
||||
let make_headless = move |wanted: &HeadlessFolders| -> Result<SharedHeadless, String> {
|
||||
let roots = if wanted.read.is_empty() && wanted.write.is_none() {
|
||||
None
|
||||
} else {
|
||||
let read: Vec<&Path> = wanted.read.iter().map(PathBuf::as_path).collect();
|
||||
let write: Vec<&Path> = wanted.write.as_deref().into_iter().collect();
|
||||
Some(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
|
||||
};
|
||||
Ok(Rc::new(RefCell::new(headless(roots))))
|
||||
};
|
||||
let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, make_headless);
|
||||
shared_cfg.when_closed = when_closed;
|
||||
shared_cfg.read_roots = read_roots;
|
||||
shared_cfg.write_root = write_root;
|
||||
shared_cfg.launch = launch;
|
||||
shared_cfg.launch_timeout = launch_timeout;
|
||||
shared_cfg.default_folder = default_folder.clone();
|
||||
Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder }
|
||||
}
|
||||
|
||||
/// The folders the open window lets agents use, as the window opens them.
|
||||
fn window_folders(&self) -> Value {
|
||||
folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for LiveBackend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.live.resolve()? {
|
||||
Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()),
|
||||
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(h) => h.borrow_mut().call(method, params),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
matches!(self.live.resolve(), Ok(Route::Window(_)))
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"the open VectorCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window"
|
||||
.into()
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,12 @@ impl Remote {
|
||||
|
||||
impl Backend for Remote {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
if method == crate::agents::FOLDERS_METHOD {
|
||||
return Err(format!(
|
||||
"the app at {} was started with --control, so agent folders don't apply: its own --automation-read-root and --automation-write-root, if given, confine it",
|
||||
self.addr
|
||||
));
|
||||
}
|
||||
let addr = self.addr.clone();
|
||||
let client = self.open_client(method)?;
|
||||
// The app can't stop what it runs, but a cancelled call stops waiting for it.
|
||||
|
||||
@@ -163,13 +163,11 @@ impl Headless {
|
||||
}
|
||||
None if KEYBOARD_ONLY.contains(&id) => {
|
||||
return Err(format!(
|
||||
"`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, `--connect` included"
|
||||
"`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, in the open window too"
|
||||
));
|
||||
}
|
||||
None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => {
|
||||
return Err(format!(
|
||||
"`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`"
|
||||
));
|
||||
return Err(format!("`{id}` is a desktop UI command (`ui: true`): it {}", crate::agents::NEEDS_WINDOW));
|
||||
}
|
||||
None => self.session.check_params(id, params).map_err(|e| e.to_string())?,
|
||||
}
|
||||
@@ -451,9 +449,8 @@ impl Headless {
|
||||
"app.save" => self.save(p),
|
||||
"app.export" => self.export(p),
|
||||
"app.quit" => Ok(Value::Null),
|
||||
m if m.starts_with("ui.") => {
|
||||
Err(format!("`{m}` needs the desktop app (start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`)"))
|
||||
}
|
||||
crate::agents::FOLDERS_METHOD => Ok(crate::agents::headless_folders(self.roots.as_deref())),
|
||||
m if m.starts_with("ui.") => Err(format!("`{m}` {}", crate::agents::NEEDS_WINDOW)),
|
||||
other => Err(format!("unknown method `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,16 +4,24 @@
|
||||
//! JSON-RPC 2.0, hand-written (no async runtime). The server exposes VectorCraft as a set of MCP
|
||||
//! tools and resources and forwards everything to a [`Backend`]:
|
||||
//!
|
||||
//! - [`agents::LiveBackend`] (plain `vectorcraft-cli mcp`) sends each call to the open window
|
||||
//! while the ArtCraft Launcher's switch lets agents use VectorCraft, through the connection file
|
||||
//! the window publishes ([`agents::Window`]). While agents may not use it, calls go to a
|
||||
//! [`Headless`] session; while they may but VectorCraft is closed, the closed-app choice of
|
||||
//! Preferences › AI Integrations (or `--when-closed`) starts the app, uses a headless session in
|
||||
//! the agent folders, or answers with an error.
|
||||
//! - [`Remote`] talks to a running desktop app through its loopback JSON-lines control channel
|
||||
//! (`vectorcraft --control 7979`): one `{"id","method","params"}` line in, one
|
||||
//! `{"id","ok","result"|"error"}` line out.
|
||||
//! (`vectorcraft --control 7979`, `vectorcraft-cli mcp --connect`, deprecated): one
|
||||
//! `{"id","method","params"}` line in, one `{"id","ok","result"|"error"}` line out.
|
||||
//! - [`Headless`] hosts an in-process [`vectorcraft_engine::Session`] and implements the same
|
||||
//! control-channel method names itself (rendering screenshots with `vectorcraft-render`), so agents
|
||||
//! can draw and look at the result without a window.
|
||||
//!
|
||||
//! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod agents;
|
||||
mod backend;
|
||||
mod headless;
|
||||
mod intake;
|
||||
|
||||
@@ -405,7 +405,7 @@ Method:
|
||||
removeWord / dictionary; for this document only, text.spelling.ignoreAll.
|
||||
4. Prefer those commands over inventing replacements. screenshot if the layout may reflow.
|
||||
|
||||
Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); use --connect for the underlines.",
|
||||
Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); the underlines need the open window.",
|
||||
},
|
||||
PromptDef {
|
||||
name: "variables-bind",
|
||||
|
||||
@@ -4,6 +4,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::{Backend, Headless, PROTOCOL_VERSION, Remote, Server, tool_definitions};
|
||||
|
||||
mod agents;
|
||||
mod batchdraw;
|
||||
mod concurrency;
|
||||
mod conventions;
|
||||
@@ -279,10 +280,11 @@ fn tool_schemas_are_valid() {
|
||||
"transform",
|
||||
"create_graph",
|
||||
"text_wrap",
|
||||
"agent_folders",
|
||||
] {
|
||||
assert!(names.contains(want), "missing tool {want}");
|
||||
}
|
||||
assert_eq!(tools.len(), 33, "parity docs and #6460 expect 33 MCP tools");
|
||||
assert_eq!(tools.len(), 34, "parity docs and #6460 expect 34 MCP tools (agent_folders: #10621)");
|
||||
}
|
||||
|
||||
/// Headless `command_list` must expose engine commands that a stale release CLI used to omit (#6460).
|
||||
@@ -335,7 +337,7 @@ fn headless_command_list_includes_ui_commands() {
|
||||
}
|
||||
let r = call(&mut s, 40, "command_run", json!({"id": "view.fitArtboard", "params": {}}));
|
||||
assert_eq!(r["isError"], true, "{r}");
|
||||
assert!(text_of(&r).contains("--connect"), "{r}");
|
||||
assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}");
|
||||
}
|
||||
|
||||
/// Desktop commands that the app refuses for every automated request are not offered through
|
||||
@@ -1102,7 +1104,7 @@ fn answer_dialog_needs_the_desktop_app() {
|
||||
let mut s = server();
|
||||
let r = call(&mut s, 1, "answer_dialog", json!({"action": "confirm"}));
|
||||
assert_eq!(r["isError"], true, "{r}");
|
||||
assert!(text_of(&r).contains("needs the desktop app"), "{r}");
|
||||
assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}");
|
||||
}
|
||||
|
||||
/// How long a fake app waits for [`Remote`] to connect or to send, and how long a test waits for
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Plain `mcp` in front of the open window (`crate::agents`): the window gets the calls only while
|
||||
//! agents are allowed and it proves it holds the token; otherwise the closed-app choice applies.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use craft::automation::agents::{AgentSettings, Connection, TOKEN_FILE, WhenAppClosed, write_connection};
|
||||
use craft::automation::security::{AuthStep, ServerHandshake};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::TempFolder;
|
||||
use crate::Backend;
|
||||
use crate::agents::{FOLDERS_METHOD, LiveBackend, LiveConfig};
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// A stand-in for the window's control server holding `token`: it authenticates as the shared
|
||||
/// server does and answers every request with `{"window": true, "method"}`. The count is of the
|
||||
/// requests it got after authentication.
|
||||
fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let served = Arc::new(AtomicUsize::new(0));
|
||||
let count = served.clone();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { return };
|
||||
let count = count.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut writer = stream.try_clone().unwrap();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut signed_in = false;
|
||||
for line in BufReader::new(stream).lines() {
|
||||
let Ok(line) = line else { return };
|
||||
let reply = if signed_in {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}})
|
||||
} else {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
signed_in = matches!(step, AuthStep::Authenticated);
|
||||
reply
|
||||
};
|
||||
if writeln!(writer, "{reply}").is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
(port, served)
|
||||
}
|
||||
|
||||
/// Publishes a window on `port` in the settings folder `dir`, as the app's agents link does, with
|
||||
/// [`TOKEN`] in its token file.
|
||||
fn publish(dir: &Path, port: u16) {
|
||||
let token_file = dir.join(TOKEN_FILE);
|
||||
std::fs::write(&token_file, TOKEN).unwrap();
|
||||
// The client reads only a token its owner alone can read, as the app writes it.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
write_connection(dir, &Connection::new(port, token_file, "VectorCraft test")).unwrap();
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn closed_port() -> u16 {
|
||||
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
fn settings_headless(_: &Path) -> AgentSettings {
|
||||
let mut s = AgentSettings::default();
|
||||
s.when_app_closed = WhenAppClosed::Headless;
|
||||
s
|
||||
}
|
||||
|
||||
fn settings_error(_: &Path) -> AgentSettings {
|
||||
let mut s = AgentSettings::default();
|
||||
s.when_app_closed = WhenAppClosed::Error;
|
||||
s
|
||||
}
|
||||
|
||||
fn live(dir: &Path, allowed: fn() -> bool, read_settings: fn(&Path) -> AgentSettings, default_folder: PathBuf) -> LiveBackend {
|
||||
let mut cfg = LiveConfig::new(dir.to_path_buf(), read_settings);
|
||||
cfg.allowed = allowed;
|
||||
cfg.default_folder = Some(default_folder);
|
||||
LiveBackend::new(cfg)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_mcp_reaches_the_window_while_agents_are_allowed() {
|
||||
let dir = TempFolder::new("agents-window");
|
||||
let (port, served) = fake_window(TOKEN);
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
assert!(b.has_ui());
|
||||
let r = b.call("document.inspect", json!({})).unwrap();
|
||||
assert_eq!(r["window"], true, "{r}");
|
||||
assert!(served.load(Ordering::SeqCst) >= 1);
|
||||
// The window's folders are the agent folders as the window opens them: the default one here.
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy()));
|
||||
assert_eq!(folders["write_folder"], folders["read_folder"]);
|
||||
}
|
||||
|
||||
// With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with
|
||||
// only the command's folders: the closed-app choice (an error here) is for agents the person let in.
|
||||
#[test]
|
||||
fn with_agents_off_plain_mcp_runs_headless() {
|
||||
let dir = TempFolder::new("agents-off");
|
||||
let mut b = live(&dir, || false, settings_error, dir.file("Agents"));
|
||||
assert!(!b.has_ui());
|
||||
let r = b.call("document.inspect", json!({}));
|
||||
assert!(r.as_ref().is_ok_and(|r| r["window"] != true), "{r:?}");
|
||||
assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true);
|
||||
assert!(!dir.file("Agents").exists(), "the agent folder is made only for agents the person let in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_cannot_prove_the_token_gets_nothing() {
|
||||
let dir = TempFolder::new("agents-bad-token");
|
||||
let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
let e = b.call("document.inspect", json!({})).unwrap_err();
|
||||
assert!(e.contains("could not prove"), "{e}");
|
||||
assert_eq!(served.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
|
||||
let dir = TempFolder::new("agents-stale");
|
||||
publish(&dir, closed_port());
|
||||
let mut b = live(&dir, || true, settings_error, dir.file("Agents"));
|
||||
let e = b.call("document.inspect", json!({})).unwrap_err();
|
||||
assert!(e.contains("isn't running"), "{e}");
|
||||
|
||||
// Headless: a session without a window, confined to the agent folders.
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
assert!(!b.has_ui());
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders["read_folder"], json!(std::fs::canonicalize(dir.file("Agents")).map(shown).unwrap()));
|
||||
let outside = dir.file("outside.svg");
|
||||
std::fs::write(&outside, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="3"/>"#).unwrap();
|
||||
let e = b.call("app.open", json!({"path": outside.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
}
|
||||
|
||||
/// A canonical path as the automation roots show it: without Windows' `\\?\` prefix.
|
||||
fn shown(p: PathBuf) -> String {
|
||||
let s = p.to_string_lossy().into_owned();
|
||||
s.strip_prefix(r"\\?\").map_or(s.clone(), str::to_owned)
|
||||
}
|
||||
@@ -27,7 +27,16 @@ fn headless_links_report_missing_files_and_relink() {
|
||||
let r = run(&mut h, "document.open", json!({"path": file("doc.vectorcraft")}));
|
||||
assert_eq!(r["missingLinks"][0]["ids"], json!([id]), "{r}");
|
||||
assert_eq!(run(&mut h, "links.check", json!({}))["missing"], 1);
|
||||
assert_eq!(run(&mut h, "links.marked", json!({})), json!({"on": false, "images": []}));
|
||||
assert_eq!(run(&mut h, "view.showMissingLinks", json!({"on": true})), json!({"on": true}));
|
||||
let markers = run(&mut h, "links.marked", json!({}));
|
||||
assert_eq!(markers["images"][0]["id"], id);
|
||||
assert_eq!(markers["images"][0]["bounds"].as_array().unwrap().len(), 4);
|
||||
run(&mut h, "view.showMissingLinks", json!({"on": false}));
|
||||
assert_eq!(run(&mut h, "links.marked", json!({}))["images"], json!([]));
|
||||
run(&mut h, "view.showMissingLinks", json!({"on": true}));
|
||||
let r = run(&mut h, "links.relink", json!({"ids": [id], "path": file("b.png")}));
|
||||
assert_eq!(r["relinked"], json!([id]));
|
||||
assert_eq!(run(&mut h, "links.check", json!({}))["links"][0]["status"], "ok");
|
||||
assert_eq!(run(&mut h, "links.marked", json!({}))["images"], json!([]));
|
||||
}
|
||||