Merge main into feat/scripts-api-layer-path-items

This commit is contained in:
dotCooCoo
2026-12-04 08:00:07 -08:00
66 changed files with 5239 additions and 308 deletions
Generated
+27
View File
@@ -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"
@@ -8638,6 +8664,7 @@ dependencies = [
name = "vectorcraft-cli"
version = "0.25.1"
dependencies = [
"craft",
"log",
"objc2-core-foundation",
"objc2-core-text",
+1
View File
@@ -271,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). |
+3
View File
@@ -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",
+64 -12
View File
@@ -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())),
}
};
+17
View File
@@ -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}");
}
+2 -1
View File
@@ -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 = {
+77
View File
@@ -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, "");
}
}
+36 -4
View File
@@ -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);
+51
View File
@@ -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::*;
+1 -1
View File
@@ -103,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,
+136
View File
@@ -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;
+2 -2
View File
@@ -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
),
+163 -17
View File
@@ -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()
+1
View File
@@ -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",
+30
View File
@@ -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![],
+6 -1
View File
@@ -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 {
+65 -7
View File
@@ -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))
}
+16 -1
View File
@@ -857,9 +857,24 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
/// The ids (at most 20) among `ids` that are the clipping path of a group or layer that keeps other
/// objects once `ids` are deleted. Deleting one would leave the next object clipping the rest.
/// Deleting every path of a compound path would leave it empty, so a compound path that clips
/// counts as deleted too.
pub(super) fn kept_clipping_paths(d: &Document, ids: &[NodeId]) -> Vec<u64> {
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
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());
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);
+15 -2
View File
@@ -425,6 +425,19 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node)
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
}
/// 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();
@@ -801,7 +814,7 @@ fn make_in(
fn make(h: &super::Host, doc: Doc, container: Option<NodeId>, id: &str, params: &Value, reversed: bool) -> Answer {
keeping_paint(h, || {
make_in(h, doc, container, |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]}))?;
@@ -965,7 +978,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}))?;
+1
View File
@@ -118,6 +118,7 @@ mod livecorners;
mod maskview;
pub(super) mod menucmds;
mod mesh_picks;
mod missing_links;
mod moved;
mod nativefile;
mod newart;
+2 -2
View File
@@ -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();
+255
View File
@@ -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, &params).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, &params).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, &params).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, &params).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);
}
+221
View File
@@ -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());
}
+26
View File
@@ -2820,6 +2820,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]
@@ -815,6 +815,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")] {
+3 -1
View File
@@ -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 }
+336
View File
@@ -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()
}
}
+6
View File
@@ -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.
+4 -7
View File
@@ -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}`")),
}
}
+9 -2
View File
@@ -4,9 +4,15 @@
//! 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.
@@ -15,6 +21,7 @@
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod agents;
mod backend;
mod headless;
mod intake;
+1 -1
View File
@@ -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",
+5 -3
View File
@@ -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
+158
View File
@@ -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)
}
+9
View File
@@ -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!([]));
}
+3 -2
View File
@@ -103,7 +103,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"command_list",
"List commands",
"Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id headless needs --connect). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.",
"Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id needs the open window). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.",
obj(
json!({"filter": string("Case-insensitive id, label or menu substring"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabled_only": {"type":"boolean"}, "brief": {"type":"boolean", "description": BRIEF}}),
&[],
@@ -161,7 +161,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"list_commands",
"List commands",
"List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id run headless needs --connect). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.",
"List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id needs the open window). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.",
obj(
json!({"filter": string("Case-insensitive substring matched against id, label and menu path (e.g. \"align\", \"Object\")"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabledOnly": {"type": "boolean", "description": "Only commands that can run right now"}, "brief": {"type": "boolean", "description": BRIEF}}),
&[],
@@ -528,5 +528,6 @@ pub fn tool_definitions() -> Vec<Value> {
),
tool("undo", "Undo", "Undo the last change (Edit → Undo). redo reapplies it.", empty(), false),
tool("redo", "Redo", "Redo the last undone change (Edit → Redo): the change the last undo took back.", empty(), false),
tool(craft::control::agents::FOLDERS_TOOL, "Agent folders", craft::control::agents::FOLDERS_TOOL_DESCRIPTION, empty(), true),
]
}
+1
View File
@@ -219,6 +219,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<ToolResult, Str
j(b.call("ui.set", json!({"panel": req_str(a, "panel")?}))?)
}
"screenshot" => screenshot(b, a),
craft::control::agents::FOLDERS_TOOL => j(b.call(crate::agents::FOLDERS_METHOD, json!({}))?),
"open_file" => {
let path = absolute_path(b, req_str(a, "path")?)?;
let mut p = json!({"path": path});
+2 -8
View File
@@ -11,7 +11,7 @@ pub(super) fn req_str<'a>(a: &'a Args, k: &str) -> Result<&'a str, String> {
}
/// A file tool's path made absolute against this process's working directory when it goes to the app
/// (`--connect`). Headless, and for an empty path, it is returned as given.
/// (the open window). Headless, and for an empty path, it is returned as given.
pub(super) fn absolute_path(b: &dyn Backend, p: &str) -> Result<String, String> {
if p.is_empty() || !b.has_ui() {
return Ok(p.to_owned());
@@ -25,13 +25,7 @@ pub(super) fn exec(b: &mut dyn Backend, cmd: &str, params: Value) -> Result<Valu
}
pub(super) fn need_ui(b: &dyn Backend, tool: &str) -> Result<(), String> {
if b.has_ui() {
Ok(())
} else {
Err(format!(
"`{tool}` needs the desktop app: run `vectorcraft --control 7979` and start the server with `vectorcraft-cli mcp --connect 127.0.0.1:7979`"
))
}
if b.has_ui() { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) }
}
/// Paint argument → `paint.setFill` / `paint.setStroke` params.
+6
View File
@@ -171,6 +171,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
),
("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"),
("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"),
(
"prefs.agents",
"AI Integrations",
"",
"{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences",
),
("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"),
(
"view.refreshMonitorProfile",
+3 -1
View File
@@ -78,7 +78,9 @@ log = { workspace = true }
# Floating panels open in OS windows of their own on the desktop; on the web they stay in the page.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# The folder picker and the updater are native only (`craft/Cargo.toml`: rfd and getrandom have no wasm build).
craft = { workspace = true, features = ["dialogs", "update"] }
# Agents in the open window (`src/agents.rs`): the ArtCraft Launcher's switch, the link host with its control
# server and the Agents page of Preferences (`automation-agents`), and the default agent folder (`control-agents`).
craft = { workspace = true, features = ["dialogs", "update", "automation-agents", "control-agents"] }
# The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in
# Cargo.lock with the time-zone crates `clock` uses.
chrono = { workspace = true, features = ["clock"] }
+188
View File
@@ -0,0 +1,188 @@
//! Agents in the open window: while the ArtCraft Launcher's *Settings › AI agents* switch names
//! VectorCraft, the window serves its control channel to agents on loopback.
//!
//! The switch, the control server, its token and the connection file `vectorcraft-cli mcp` finds
//! the window by are the framework's (`craft::automation::agents::AgentSwitch` and `AgentLink`).
//! VectorCraft supplies its agent settings (saved by `prefs.agents`), answers the requests with its
//! own control methods ([`crate::control`]) and confines every file they open or save to the agent
//! folders: those set in Preferences › AI Integrations, or `Documents/ArtCraft/Agents/VectorCraft`
//! for an empty one. Without a folder of a kind, that kind of access is refused.
use std::path::PathBuf;
use std::sync::Arc;
use craft::automation::ControlChannel;
use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
use craft::ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use vectorcraft_engine::file_access::{self, AutomationRoots};
use crate::VectorcraftApp;
/// 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 Preferences page of the agent settings, and the key they sit under in its draft.
pub const PAGE: &str = "integrations";
/// The page's title in Preferences, as PhotoCraft names it.
pub const PAGE_TITLE: &str = "AI Integrations";
/// Saves the agent settings where `vectorcraft-cli mcp` reads them; `Err` says why it couldn't.
pub type SaveFn = Box<dyn Fn(&AgentSettings) -> Result<(), String>>;
/// The agents link of the open window.
pub struct Agents {
/// The link; `None` while the launch options (`--control`) manage the control channel.
link: Option<AgentLink>,
/// The status shown while the launch options manage the control channel.
launch: AgentLinkStatus,
switch: AgentSwitch,
settings: AgentSettings,
save: SaveFn,
default_folder: Option<PathBuf>,
}
impl Agents {
/// The link for the window, keeping its token and connection file in `settings_dir` and naming
/// `app` (the version string) in the connection file, following `switch` with the saved
/// `settings`; `save` stores the settings when `prefs.agents` changes them.
pub fn new(settings_dir: Option<PathBuf>, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn) -> Self {
Self {
link: Some(AgentLink::new(settings_dir, app)),
launch: AgentLinkStatus::default(),
switch,
settings,
save,
default_folder: craft::control::agents::default_folder(APP_NAME),
}
}
/// The window was started with `--control`, listening on `port` (none when it couldn't): that
/// channel serves the whole run, the link stays off and Preferences says the launch options
/// manage it.
pub fn launched_with_control(mut self, port: Option<u16>) -> Self {
self.link = None;
self.launch.port = port;
self.launch.launch_flags = true;
self
}
/// `default` replaces the default agent folder (tests).
pub fn with_default_folder(mut self, default: Option<PathBuf>) -> Self {
self.default_folder = default;
self
}
/// The saved agent settings.
pub fn settings(&self) -> &AgentSettings {
&self.settings
}
/// Where the link stands, for Preferences and `ui.inspect`.
pub fn status(&self) -> &AgentLinkStatus {
self.link.as_ref().map_or(&self.launch, AgentLink::status)
}
/// The suite's `AI-MCP` flag: the launcher's switch decides, and Preferences shows its state.
pub fn mcp_flag(&self) -> bool {
self.switch.mcp_flag()
}
/// Whether the launcher's switch lets agents use VectorCraft now.
pub fn allowed(&self) -> bool {
// VectorCraft had no agent consent of its own before the switch.
self.switch.allows(false)
}
/// Saves `settings`; the link applies them on the next pass.
fn set(&mut self, settings: AgentSettings) -> Result<(), String> {
(self.save)(&settings)?;
self.settings = settings;
Ok(())
}
}
/// What agent requests may open and save with `settings`: the agent folders (`default` for an empty
/// setting), or nothing. `Err` says why a folder can't be used.
fn roots_for(settings: &AgentSettings, default: Option<&std::path::Path>) -> Result<Arc<AutomationRoots>, String> {
let folders = settings.folders_with(default);
let read: Vec<&std::path::Path> = folders.read.as_deref().into_iter().collect();
let write: Vec<&std::path::Path> = folders.write.as_deref().into_iter().collect();
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
}
/// Once per pass: brings the link in line with the launcher's switch and the saved settings. The
/// control server starts, moves or stops; while it runs, its requests are the app's control channel
/// and run inside the agent folders ([`VectorcraftApp::run_control`]).
pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(agents) = app.agents.as_mut() else { return };
let allowed = agents.allowed();
let Some(link) = agents.link.as_mut() else { return };
let update = link.sync(allowed.then_some(&agents.settings), &WindowHost::of(ctx));
if update.stopped {
app.channel = None;
app.deferred_control = None;
}
if let Some(requests) = update.requests {
app.channel = Some(ControlChannel::new(requests));
}
if !update.changed {
return;
}
app.automation_roots = Some(if link.status().port.is_none() {
AutomationRoots::none()
} else {
// Opened only when something changed: the default folder is created on the way.
roots_for(&agents.settings, agents.default_folder.as_deref()).unwrap_or_else(|e| {
link.note(LinkProblem::App(format!("Agents can't open or save files: {e}")));
AutomationRoots::none()
})
});
}
/// The keys `prefs.agents` takes.
const KEYS: [&str; 4] = ["controlPort", "readRoot", "writeRoot", "whenAppClosed"];
/// `prefs.agents`: the agent settings of Preferences › AI Integrations, the link's status and the
/// launcher's switch. `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` changes and saves those
/// settings first. Agents can't change them: their requests run confined to the agent folders, and
/// widening those is the person's choice.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let Some(agents) = app.agents.as_mut() else {
return Err("agents can't use this window: it keeps no preferences (VECTORCRAFT_NO_PREFS), or it is a nightly".into());
};
let given = p.as_object().filter(|o| !o.is_empty());
if let Some(given) = given {
if let Some(unknown) = given.keys().find(|k| !KEYS.contains(&k.as_str())) {
return Err(format!("unknown agent setting `{unknown}` ({})", KEYS.join(", ")));
}
if file_access::current().is_some() {
return Err("agents can't change the agent settings: the person sets them in Preferences › AI Integrations".into());
}
let mut next = serde_json::to_value(agents.settings()).map_err(|e| e.to_string())?;
if let Some(next) = next.as_object_mut() {
next.extend(given.clone());
}
let next: AgentSettings = serde_json::from_value(next).map_err(|e| format!("bad agent setting: {e}"))?;
if next.control_port > u32::from(u16::MAX) {
return Err(format!("controlPort must be 0 to {}, not {}", u16::MAX, next.control_port));
}
agents.set(next)?;
}
Ok(json!({"settings": agents.settings(), "status": agents.status(), "allowed": agents.allowed(), "mcpFlag": agents.mcp_flag()}))
}
/// The agent settings as Preferences shows them: under [`PAGE`] in its draft.
pub(crate) fn draft_value(app: &VectorcraftApp) -> Option<Value> {
serde_json::to_value(app.agents.as_ref()?.settings()).ok()
}
/// What Preferences' Agents page needs each pass: the link's status and the suite's `AI-MCP` flag.
pub(crate) fn page_state(app: &VectorcraftApp) -> Option<(AgentLinkStatus, bool)> {
let agents = app.agents.as_ref()?;
Some((agents.status().clone(), agents.mcp_flag()))
}
#[cfg(test)]
mod tests;
+135
View File
@@ -0,0 +1,135 @@
//! Agents in the open window: the link follows the launcher's switch, agent requests stay inside
//! the agent folders, and agents can't change the agent settings.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use craft::automation::agents::{AgentSettings, AgentSwitch, CONNECTION_FILE, read_connection};
use craft::automation::client::ControlClient;
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_engine::file_access::{self, AutomationRoots};
use super::Agents;
use crate::{Services, VectorcraftApp};
/// A test's folder with `settings` (the app's settings folder), `in` (the read folder, with
/// `a.svg`), `out` (the write folder) and `outside` (with `b.svg`).
fn folders(tag: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-ui-agents-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
for d in ["settings", "in", "out", "outside"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30"><rect width="20" height="10"/></svg>"#;
std::fs::write(base.join("in/a.svg"), svg).unwrap();
std::fs::write(base.join("outside/b.svg"), svg).unwrap();
base
}
fn s(p: PathBuf) -> String {
p.to_string_lossy().into_owned()
}
/// An app with the desktop's file services whose agents link follows `switch`, with `in` and `out`
/// as the agent folders; the settings it saves land in the returned list.
fn app_with_agents(base: &Path, switch: AgentSwitch) -> (VectorcraftApp, Arc<Mutex<Vec<AgentSettings>>>) {
let services = Services {
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
write: Some(Box::new(|p: &str, b: &[u8]| vectorcraft_format::write_atomic(Path::new(p), b).map_err(|e| e.to_string()))),
..Default::default()
};
let mut settings = AgentSettings::default();
settings.read_root = s(base.join("in"));
settings.write_root = s(base.join("out"));
let saved = Arc::new(Mutex::new(Vec::new()));
let into = saved.clone();
let save: super::SaveFn = Box::new(move |settings| {
into.lock().unwrap().push(settings.clone());
Ok(())
});
let agents = Agents::new(Some(base.join("settings")), "VectorCraft test".into(), switch, settings, save).with_default_folder(None);
let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services).with_agents(agents));
(app, saved)
}
/// One request from an agent's client through the link's server, answered by the app's frames: the client
/// thread hands its reply back over a channel, and the app runs a pass while it waits.
fn agent_request(app: &mut VectorcraftApp, client: &mut Option<ControlClient>, method: &str, params: Value) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().unwrap_or_default();
let mut c = client.take().expect("a connected client");
let sent = method.to_owned();
let (done, reply) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let r = c.call(&sent, params);
let _ = done.send((c, r));
});
for _ in 0..2000 {
app.run_control(&ctx);
app.poll_input(&ctx);
if let Ok((c, r)) = reply.recv_timeout(std::time::Duration::from_millis(5)) {
*client = Some(c);
return r;
}
}
panic!("the app did not answer {method:?}")
}
// With the launcher's switch naming VectorCraft, the window serves agents on loopback and publishes
// where; their requests open and save only inside the agent folders, while the person is not confined.
#[test]
fn agents_reach_the_window_only_inside_the_agent_folders() {
let base = folders("on");
let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, true));
let ctx = app.ui_ctx.clone().unwrap_or_default();
super::sync(&mut app, &ctx);
let port = app.agents.as_ref().and_then(|a| a.status().port).expect("the link listens while the switch allows it");
let connection = read_connection(&base.join("settings")).unwrap().expect("the connection file is published");
assert_eq!(connection.port, port);
let token = std::fs::read_to_string(&connection.token_file).unwrap();
let mut client = Some(ControlClient::connect(([127, 0, 0, 1], port).into(), token.trim()).unwrap());
let inside = agent_request(&mut app, &mut client, "app.open", json!({"path": s(base.join("in/a.svg"))}));
assert!(inside.is_ok(), "{inside:?}");
let outside = agent_request(&mut app, &mut client, "app.open", json!({"path": s(base.join("outside/b.svg"))}));
assert!(outside.as_ref().is_err_and(|e| e.contains("outside the read root")), "{outside:?}");
let saved = agent_request(&mut app, &mut client, "app.export", json!({"path": s(base.join("outside/a.png")), "format": "png"}));
assert!(saved.as_ref().is_err_and(|e| e.contains("outside the write root")), "{saved:?}");
assert!(!base.join("outside/a.png").exists());
// The person at the keyboard opens what they like.
assert!(app.run("file.open", json!({"path": s(base.join("outside/b.svg"))})).is_ok());
let _ = std::fs::remove_dir_all(&base);
}
// With the switch off, nothing listens and no connection file is published.
#[test]
fn with_the_switch_off_nothing_listens() {
let base = folders("off");
let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, false));
let ctx = app.ui_ctx.clone().unwrap_or_default();
super::sync(&mut app, &ctx);
assert!(app.channel.is_none());
assert_eq!(app.agents.as_ref().and_then(|a| a.status().port), None);
assert!(!base.join("settings").join(CONNECTION_FILE).exists());
let _ = std::fs::remove_dir_all(&base);
}
// `prefs.agents` saves the person's settings, refuses unknown keys, and refuses every change from a
// confined request: agents can't widen their own folders.
#[test]
fn prefs_agents_saves_and_agents_cannot_change_it() {
let base = folders("prefs");
let (mut app, saved) = app_with_agents(&base, AgentSwitch::fixed(true, false));
let r = app.run("prefs.agents", json!({"whenAppClosed": "headless"})).unwrap();
assert_eq!(r["settings"]["whenAppClosed"], "headless");
assert_eq!(saved.lock().unwrap().len(), 1);
assert!(app.run("prefs.agents", json!({"port": 7})).is_err());
assert!(app.run("prefs.agents", json!({"controlPort": 70000})).is_err());
let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap();
let widened = file_access::confine(Some(&roots), || app.run("prefs.agents", json!({"readRoot": s(base.clone())})));
assert!(widened.is_err_and(|e| e.contains("can't change the agent settings")));
assert_eq!(saved.lock().unwrap().len(), 1, "nothing more was saved");
// Reading them is fine.
assert!(file_access::confine(Some(&roots), || app.run("prefs.agents", json!({}))).is_ok());
let _ = std::fs::remove_dir_all(&base);
}
+31 -3
View File
@@ -286,6 +286,8 @@ impl VectorcraftApp {
prefs_changed: false,
touch_screen: false,
automation_roots: None,
#[cfg(not(target_arch = "wasm32"))]
agents: None,
pending_plugin_install: None,
pending_profile_open: None,
queued_profile_opens: Default::default(),
@@ -315,6 +317,22 @@ impl VectorcraftApp {
pub fn with_automation_roots(mut self, roots: Option<Arc<AutomationRoots>>) -> Self {
let Some(roots) = roots else { return self };
self.automation_roots = Some(roots);
self.check_file_services();
self
}
/// Lets agents into this window while the ArtCraft Launcher's switch names VectorCraft
/// ([`crate::agents`]): their requests, the input they inject and the saves they start read and
/// write only inside the agent folders, as with [`Self::with_automation_roots`].
#[cfg(not(target_arch = "wasm32"))]
pub fn with_agents(mut self, agents: crate::agents::Agents) -> Self {
self.agents = Some(Box::new(agents));
self.check_file_services();
self
}
/// Has the host's file services check every path against the roots in force ([`file_access`]).
fn check_file_services(&mut self) {
let s = &mut self.services;
if let Some(read) = s.read.take() {
s.read = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| read(p))));
@@ -339,7 +357,6 @@ impl VectorcraftApp {
*service = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| open(p))));
}
}
self
}
/// The folders this pass may read and write: the automation roots while the pass carries
@@ -471,6 +488,9 @@ impl VectorcraftApp {
let lang = self.ui_language();
if self.host.lang() != lang {
self.host = Arc::new(self.host.with_lang(lang));
if let Some(ctx) = &self.ui_ctx {
crate::ui_fonts::follow_language(ctx, lang);
}
}
let native_ppp = self.ui_ctx.as_ref().map_or(1.0, |ctx| ctx.pixels_per_point() / ctx.zoom_factor());
// The canvas steps through the zoom stops of the current window's display.
@@ -611,6 +631,12 @@ impl VectorcraftApp {
}
#[cfg(not(target_arch = "wasm32"))]
self.tick_link_updates(ctx, now);
// The web app has no link watch worker and no files to read: View › Show Missing Links
// marks again here whenever the art changed, so artwork shown or restored is marked too.
#[cfg(target_arch = "wasm32")]
if self.session.mark_missing_links_in_place() {
ctx.request_repaint();
}
crate::addons::select::link_status::refresh(self, now);
if !self.background.jobs.is_empty()
|| !self.opening.pending.is_empty()
@@ -628,6 +654,8 @@ impl VectorcraftApp {
}
crate::keymap::note_os(ctx);
prefs_dialog::apply_runtime(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
crate::agents::sync(self, ctx);
self.run_control(ctx);
// Plug-ins loading on other threads since launch install as their loads finish; until then
// the host keeps coming back to look again, and once more when the last one installs, for
@@ -803,8 +831,8 @@ impl VectorcraftApp {
crate::place::window_files(app, ui);
});
// The shell shows the window's dialogs under these words. Temporary: removed once the craft-libs pin includes
// storytold/craft-libs#4891 (`dialogs::print::title_words`).
let words = dialogs::print::title_words(self).map(WordsOverride::Overlay);
// storytold/craft-libs#4891 and #5291 (`dialogs::shell_words`).
let words = dialogs::shell_words(self).map(WordsOverride::Overlay);
let shown = with_env(ui, |env| env.words = words, |ui| shell.show(ui, self));
chrome::set_control_bar_place(&mut self.ui, control_bar_place);
if shown.screen_mode != given {
+3 -1
View File
@@ -95,7 +95,9 @@ impl VectorcraftApp {
let last: f64 = ctx.data(|d| d.get_temp(last_key)).unwrap_or(f64::NEG_INFINITY);
// The active document as the last look saw it: its uid and revision.
let (seen_key, doc) = (egui::Id::unique("linkWatch.seen"), self.session.active().map(|d| (d.uid, d.revision)));
if now - last >= 2.0 || (focused && !was_focused) {
// View › Show Missing Links just turned on: its first scan runs on the worker now, and
// the canvas repaints from the result (the toggle itself never reads files).
if now - last >= 2.0 || (focused && !was_focused) || self.session.missing_link_scan_due() {
// Walking the document's links costs a pass over it: only when a look is due.
// `start_link_scan` starts none for a document without links, which then doesn't
// wake the app for looks of its own (any frame still looks once one is due).
+38
View File
@@ -66,6 +66,11 @@ const WAVE_MAX: usize = 4_000;
/// long story of unknown words costs one check's worth.
const MAX_UNDERLINED: usize = 1_000;
/// The radius of a missing link's badge and the size of its question mark, in screen points: the
/// same at every zoom.
const MISSING_BADGE_RADIUS: f32 = 7.0;
const MISSING_BADGE_TEXT: f32 = 11.0;
/// The marks Show Hidden Characters drew on each text object in the last pass
/// ([`crate::CanvasCache::hidden_chars`]). Each is kept with the node it was laid out from: an edited
/// object is a new `Arc` and is laid out again, and all type is laid out again when the fonts or the
@@ -158,6 +163,9 @@ pub(crate) struct Marks {
fade: Vec<[Pos2; 4]>,
bleed: Vec<BezPath>,
artboard_marks: Vec<BezPath>,
/// View › Show Missing Links: each visible missing linked image or placed document in view, as
/// its box on the screen and where its badge sits (the box's top left corner in the document).
pub(crate) missing: Vec<([Pos2; 4], Pos2)>,
}
/// Drops the hidden-character and spelling memos and the text nodes they hold.
@@ -194,6 +202,8 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks {
return m;
};
let key = (st.uid, st.revision);
// The link watcher's last scan: nothing here reads files.
m.missing = missing_links(st, view);
if fades && let Some(shown) = app.view() {
m.fade = artboards::fade_quads(view, &artboards::frames(app, st, shown, shown.outline));
}
@@ -310,6 +320,18 @@ fn text_nodes(layers: &[Arc<Node>]) -> Vec<Arc<Node>> {
out
}
/// The missing links [`DocState::marked_missing_links`] marks in view: each one's box on the screen
/// (following a turned view) and its badge's place.
fn missing_links(st: &DocState, view: &CanvasView) -> Vec<([Pos2; 4], Pos2)> {
st.marked_missing_links()
.into_iter()
.filter_map(|id| st.doc.node(id))
.filter(|n| in_view(n, view))
.filter_map(|n| n.geometric_bounds())
.map(|b| (view.quad(b), view.to_screen(Point::new(b.x0, b.y0))))
.collect()
}
/// Whether `n`'s box meets the part of the document the view shows (the box round the view's
/// corners, which a turned view makes larger than the canvas).
fn in_view(n: &Node, view: &CanvasView) -> bool {
@@ -549,6 +571,8 @@ pub(crate) struct ArtMarks<'a> {
arm_color: [u8; 3],
/// The print tiles.
tiles: &'a [Tile],
/// The missing links' boxes and badges.
missing: &'a [([Pos2; 4], Pos2)],
}
impl<'a> ArtMarks<'a> {
@@ -565,6 +589,7 @@ impl<'a> ArtMarks<'a> {
arms: &marks.arms,
arm_color: marks.arm_color,
tiles: &marks.tiles,
missing: &marks.missing,
}
.label(label)
}
@@ -625,6 +650,9 @@ impl Component for ArtMarks<'_> {
for tile in self.tiles {
paint_tile(&draw, tile);
}
for (quad, at) in self.missing {
paint_missing(&draw, quad, *at, style.bad);
}
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
@@ -655,6 +683,16 @@ fn paint_tile(draw: &Draw<'_>, tile: &Tile) {
draw.doc(room, &DocText::new(&run));
}
/// One missing link: a thick outline round its box and, at the box's corner, a filled badge with a
/// question mark, so the mark doesn't rely on its colour alone.
fn paint_missing(draw: &Draw<'_>, quad: &[Pos2; 4], at: Pos2, color: StyleColor) {
draw.stroke(&PaintShape::Path(ring(quad.to_vec(), true)), StrokeWidth::Thick, color);
draw.fill(&PaintShape::Circle(at, MISSING_BADGE_RADIUS), color);
let run = [DocRun::new("?", FontRef::proportional(), MISSING_BADGE_TEXT, DataColor::new(Color32::WHITE))];
let room = egui::Rect::from_min_size(at - Vec2::new(MISSING_BADGE_TEXT * 0.3, MISSING_BADGE_TEXT * 0.7), Vec2::splat(MISSING_BADGE_TEXT * 1.4));
draw.doc(room, &DocText::new(&run));
}
/// A wavy line from `a` to `b` on screen, waves 4 pixels long and 1.5 high, down the page from the
/// line whichever way the type runs; empty for a segment under a pixel long or not finite.
pub(crate) fn wave(a: Pos2, b: Pos2) -> Vec<Pos2> {
+44
View File
@@ -492,3 +492,47 @@ fn auto_spell_check_is_a_toggle_of_the_canvas_lines() {
assert_eq!(segments(&mut app), 0, "off");
assert!(app.canvas.spelling.lines.is_empty(), "no node is kept");
}
/// A document with a placed document whose file is gone, View › Show Missing Links on and its markers
/// inspected → (app, the placed object).
fn missing_placed(name: &str) -> (VectorcraftApp, NodeId) {
let dir = std::env::temp_dir().join(format!("vectorcraft-marks-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("placed.vectorcraft");
std::fs::write(&path, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(80.0, 40.0))).unwrap();
let mut app = app();
let r = app.session.execute("file.place", &json!({"path": path.to_string_lossy(), "at": [200, 150]})).unwrap();
let id = NodeId(r["ids"][0].as_u64().unwrap());
std::fs::remove_dir_all(&dir).unwrap();
app.run("view.showMissingLinks", json!({"on": true})).unwrap();
// The synchronous inspection stands in for the link watcher's scan.
app.run("links.marked", json!({})).unwrap();
(app, id)
}
/// A missing link is outlined round its box and badged at its corner in any view, turned or zoomed,
/// and nothing is marked once the toggle is off.
#[test]
fn missing_links_are_marked_round_their_box_in_any_view_until_turned_off() {
let (mut app, id) = missing_placed("follow");
let bounds = app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
for (zoom, rotation) in [(0.25, 0.0), (1.0, 37.0), (8.0, 90.0)] {
let view = CanvasView::new(view().rect, bounds.center(), zoom).rotation(rotation);
let m = marks_of(&mut app, &view);
assert_eq!(m.missing, vec![(view.quad(bounds), view.to_screen(Point::new(bounds.x0, bounds.y0)))], "zoom {zoom}, {rotation}°");
}
app.run("view.showMissingLinks", json!({"on": false})).unwrap();
assert!(marks_of(&mut app, &view()).missing.is_empty());
}
/// The menu item runs the engine's toggle, and its label follows it.
#[test]
fn the_missing_links_menu_item_uses_the_engine_toggle() {
let mut app = app();
assert_eq!(crate::menus::dynamic_label(&app, "view.showMissingLinks", ""), "Show Missing Links");
app.run("view.showMissingLinks", json!({"on": true})).unwrap();
assert!(app.session.active().unwrap().show_missing_links);
assert_eq!(crate::menus::dynamic_label(&app, "view.showMissingLinks", ""), "Hide Missing Links");
app.run("view.showMissingLinks", json!({"on": false})).unwrap();
assert!(!app.session.active().unwrap().show_missing_links);
}
+9
View File
@@ -189,6 +189,15 @@ pub(crate) use export_for_screens::{
};
pub(crate) use new_document::preset_name;
pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document};
/// The words the window's shell shows its dialogs under: the rows of the open dialogs whose framework words VectorCraft
/// changes for now (`print::title_words`, `new_document::name_words`), or `None` when no such dialog is open.
pub(crate) fn shell_words(app: &crate::VectorcraftApp) -> Option<craft::ui::runtime::env::WordRows> {
[print::title_words(app), new_document::name_words(app)]
.into_iter()
.flatten()
.reduce(|rows, more| more.iter().fold(rows, |rows, (word, text)| rows.row(word, text)))
}
pub use png_options::open as open_raster_options;
pub use save_pdf::{open as open_save_pdf, open_preset as open_pdf_preset};
pub use tools::open_tool_dialog;
+123 -13
View File
@@ -9,7 +9,8 @@
//! The dialog's fields, as `ui.dialog.set` reads and writes them, are `file.new`'s params
//! (`name` is the document's name, `width`, `height` (pt), `units`, `artboards`, `artboardLayout`,
//! `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`, `previewMode`,
//! `alignNewObjectsToPixelGrid`, `profile`), plus `basedOn`, the preset the fields were filled from.
//! `alignNewObjectsToPixelGrid`, `profile`), plus `basedOn`, the preset the fields were filled from, and
//! `basedOnUnits`, the units of that preset or Recent entry (null when the fields were edited).
//! The dialog opens in Preferences › Units › General, also on a Recent entry made in other units
//! (one in pixels, or a saved preset in the units it was saved in, keeps its units); units chosen in
//! the Units list or set with `ui.dialog.set` stay when a card is picked.
@@ -34,7 +35,7 @@ use craft::ui::patterns::form_dialogs::{
use craft::ui::patterns::presets::{GroupPath, NamedPresetEvent, PresetLibrary};
use craft::ui::pickers::Select;
use craft::ui::popover::Popover;
use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind};
use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind, WordRows};
use craft::ui::sections::Section;
use craft::ui::style::TypeRole;
use craft::ui::text::{LinkMode, LinkedWords, NumberField, follow_equal, link_toggle};
@@ -96,9 +97,14 @@ pub(crate) struct VcNewDocument {
/// The orientation automation set, which [`DocumentSettings::note_set`] turns the page to: read back from the
/// fields, the width and height carry the orientation, so the one listed with them is not applied.
turn: Option<Value>,
/// The units of the card or Recent entry the settings were filled from, which can differ from the units shown:
/// Recent keeps one entry per size and units, so these tell two entries of one size apart. None once a field
/// other than the units or the orientation was edited in Preset Details.
entry_units: Option<Unit>,
}
/// The same document whatever orientation a set asked for: `turn` is spent by the set that gave it.
/// The same document whatever orientation a set asked for: `turn` is spent by the set that gave it, and
/// `entry_units` only says which card the settings came from.
impl PartialEq for VcNewDocument {
fn eq(&self, other: &Self) -> bool {
(&self.title, &self.settings) == (&other.title, &other.settings)
@@ -108,7 +114,7 @@ impl PartialEq for VcNewDocument {
impl VcNewDocument {
/// `settings` as they are, with an empty document name (a card's value).
fn of(settings: DocSettings) -> Self {
Self { title: String::new(), settings, turn: None }
Self { title: String::new(), settings, turn: None, entry_units: None }
}
/// The fields as `ui.dialog.set` and `file.new` name them.
@@ -117,6 +123,7 @@ impl VcNewDocument {
if let Value::Object(m) = &mut v {
m.insert("name".into(), json!(self.title));
m.insert("basedOn".into(), json!(self.settings.name));
m.insert("basedOnUnits".into(), json!(self.entry_units.map(Unit::label)));
}
v
}
@@ -134,7 +141,11 @@ impl VcNewDocument {
let mut settings = read(&sizes)?;
settings.name = value.get("basedOn").and_then(Value::as_str).unwrap_or(CUSTOM).to_owned();
let title = value.get("name").and_then(Value::as_str).unwrap_or_default().to_owned();
Ok(Self { title, settings, turn })
let entry_units = match value.get("basedOnUnits") {
None | Some(Value::Null) => None,
Some(u) => Some(u.as_str().and_then(Unit::named).ok_or_else(|| format!("basedOnUnits: unknown units `{u}`"))?),
};
Ok(Self { title, settings, turn, entry_units })
}
}
@@ -245,8 +256,10 @@ impl DocumentSettings for VcNewDocument {
.map(|recent| {
let s = &recent.settings;
// The entry the fields were filled from shows the units chosen in Preset Details, which
// the new document will have (#2078); the others keep their own.
let chosen = (s.name.as_str(), s.width, s.height) == (now.name.as_str(), now.width, now.height);
// the new document will have (#2078); the others keep their own. Two entries of one size
// differ in their units, so only the one in the units the fields came from is that entry.
let from = cx.values.entry_units.unwrap_or(now.units);
let chosen = (s.name.as_str(), s.width, s.height, s.units) == (now.name.as_str(), now.width, now.height, from);
let shown = DocSettings { units: if chosen { now.units } else { s.units }, ..s.clone() };
DocumentCard::new(text(preset_name(&s.name)), shown.size_label(), recent.clone(), CardSource::Recent)
})
@@ -262,6 +275,7 @@ impl DocumentSettings for VcNewDocument {
fn apply_card(&mut self, card: &DocumentCard<Self>, _setup: &Setup, memory: &mut Memory) {
let units = self.settings.units;
self.settings = card.settings.settings.clone();
self.entry_units = Some(self.settings.units);
if memory.units_chosen {
self.settings.units = units;
}
@@ -377,6 +391,7 @@ impl DocumentSettings for VcNewDocument {
after.units = before.units;
if !turned && after != before {
values.settings.name = CUSTOM.into();
values.entry_units = None;
cx.drop_card();
}
if let Some(o) = picked {
@@ -401,7 +416,7 @@ fn built_in_card(preset: &DocSettings, values: &VcNewDocument, orientation: Opti
std::mem::swap(&mut s.width, &mut s.height);
}
let line = s.size_label();
let value = VcNewDocument { title: values.title.clone(), settings: s, turn: None };
let value = VcNewDocument { title: values.title.clone(), settings: s, turn: None, entry_units: None };
DocumentCard::new(text(preset_name(&preset.name)), line, value, CardSource::preset(None))
}
@@ -677,7 +692,8 @@ fn first_settings(app: &VectorcraftApp, category: &str) -> Option<VcNewDocument>
let as_saved = newdoc::find(&app.session, &first.name).is_some_and(|p| p.units == first.units);
let own = !category.eq_ignore_ascii_case("Recent") || first.units == Unit::Pixels || as_saved;
let units = if own { first.units } else { app.session.default_units() };
Some(VcNewDocument { title: app.session.peek_untitled().to_string(), settings: DocSettings { units, ..first }, turn: None })
let entry_units = Some(first.units);
Some(VcNewDocument { title: app.session.peek_untitled().to_string(), settings: DocSettings { units, ..first }, turn: None, entry_units })
}
/// The settings New Document opens on.
@@ -686,9 +702,18 @@ fn offered(app: &VectorcraftApp) -> VcNewDocument {
title: app.session.peek_untitled().to_string(),
settings: DocSettings { units: app.session.default_units(), ..DocSettings::default() },
turn: None,
entry_units: None,
})
}
/// The words that name New Document's name field "Document Name" while the dialog is open, for the window's shell to
/// show its dialogs under. The framework names the field "Name". Temporary: this is removed once the craft-libs pin
/// includes storytold/craft-libs#5291, which names the field and gives Save Document Preset its save icon.
pub(crate) fn name_words(app: &VectorcraftApp) -> Option<WordRows> {
let open = app.dialogs()?.with(|host| host.is_open::<HostedNewDocument<VcNewDocument>>());
open.then(|| WordRows::new().row(craft::i18n::Word::keyed("newDocument.name", "Name"), tl!("Document Name")))
}
/// Open New Document on the most recent settings (or Letter), named after the next untitled
/// document, in Preferences › Units › General.
pub fn open(app: &mut VectorcraftApp) {
@@ -705,11 +730,11 @@ pub fn open(app: &mut VectorcraftApp) {
let mut saved = PresetLibrary::new();
for preset in &app.session.prefs.new_doc_presets {
// The engine keeps names the library refuses (an empty one); such a preset is not offered here.
saved.add(&GroupPath::root(), &preset.name, VcNewDocument { title: preset.name.clone(), settings: preset.clone(), turn: None }).ok();
saved.add(&GroupPath::root(), &preset.name, VcNewDocument { title: preset.name.clone(), ..VcNewDocument::of(preset.clone()) }).ok();
}
let recent: Vec<VcNewDocument> = app.session.prefs.recent_new_docs.iter().cloned().map(VcNewDocument::of).collect();
let mut dialog = HostedNewDocument::<VcNewDocument>::new(&ctx, first, move |options| {
NewDocumentDialog::over(Bind::bound(options)).categories(categories.clone()).setup(setup.clone())
NewDocumentDialog::over(Bind::bound(options)).categories(categories.clone()).setup(setup.clone()).saved_after_recent(true).recent_items(true)
})
.saved(saved)
.recent(recent);
@@ -1254,6 +1279,38 @@ mod tests {
}
}
/// Recent is headed as the recent documents it lists, and Saved is the second tab, right after Recent; before,
/// Recent read "Blank Document Presets (n)" and Saved was the last tab.
#[test]
fn recent_heads_its_documents_and_saved_follows_it() {
use egui::accesskit::Role;
let mut app = app();
app.run("file.new", json!({"preset": "Letter"})).unwrap();
app.run("file.new", json!({"preset": "Web 1920×1080"})).unwrap();
open(&mut app);
let out = laid_out(&mut app);
let drawn: Vec<String> = crate::tests_labels::text_shapes(&out).into_iter().map(|(t, _)| t.galley.text().to_uppercase()).collect();
assert!(drawn.iter().any(|t| t == "YOUR RECENT ITEMS (2)"), "Recent counts its two documents: {drawn:?}");
assert!(!drawn.iter().any(|t| t.starts_with("BLANK DOCUMENT PRESETS")), "Recent is not headed as presets: {drawn:?}");
// The Home screen behind the dialog has tabs of its own: only the dialog's are read.
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect();
let mut stack: Vec<_> = nodes.iter().filter(|(_, n)| n.role() == Role::Dialog).map(|(id, _)| *id).collect();
let mut tabs = Vec::new();
while let Some(id) = stack.pop() {
if let Some(node) = by_id.get(&id) {
if let (Role::Tab, Some(label), Some(b)) = (node.role(), node.label(), node.bounds()) {
tabs.push((b.x0, label.to_owned()));
}
stack.extend(node.children().iter().copied());
}
}
tabs.sort_by(|a, b| a.0.total_cmp(&b.0));
let order: Vec<&str> = tabs.iter().map(|(_, label)| label.as_str()).collect();
assert!(order.len() > 2, "the dialog's tabs: {order:?}");
assert_eq!(order[..2], ["Recent", "Saved"], "Saved follows Recent: {order:?}");
}
#[test]
fn a_preset_fills_the_details_and_create_makes_the_document() {
let mut app = app();
@@ -1559,8 +1616,7 @@ mod tests {
let card = |units| DocumentCard::new("Card", "line", VcNewDocument::of(entry(units)), CardSource::Recent);
let setup = Setup::default();
let mut doc =
VcNewDocument { title: "Mine".into(), settings: DocSettings { units: Unit::Millimeters, ..DocSettings::default() }, turn: None };
let mut doc = VcNewDocument { title: "Mine".into(), ..VcNewDocument::of(DocSettings { units: Unit::Millimeters, ..DocSettings::default() }) };
let mut memory = Memory::default();
doc.apply_card(&card(Unit::Inches), &setup, &mut memory);
assert_eq!((doc.settings.units, doc.title.as_str()), (Unit::Inches, "Mine"), "a saved preset keeps its own units, the name stays");
@@ -1576,6 +1632,50 @@ mod tests {
assert_eq!(shown.settings.settings.units, Unit::Millimeters, "the cards follow the chosen units");
}
/// Recent keeps an A4 made in pixels and one made in millimeters as two entries. Only the card the fields came
/// from shows the units in Preset Details (the newest entry, opened in the general units unless it is in pixels);
/// the other card keeps its own units, also after the units are set from outside the dialog.
#[test]
fn recent_entries_of_one_size_in_two_units_show_two_sizes() {
let a4 = newdoc::find(&Session::new(), "A4").unwrap();
let entry = |units| DocSettings { units, ..a4.clone() };
let label = |units| entry(units).size_label();
let count = |panel: &Panel, units| panel.painted(&label(units)).len();
let opened = |newest, older| {
let mut app = app();
general_units(&mut app, "Points");
app.session.prefs.recent_new_docs = vec![entry(newest), entry(older)];
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open(&mut panel.app());
panel
};
for (newest, older, shown) in [(Unit::Pixels, Unit::Millimeters, Unit::Pixels), (Unit::Millimeters, Unit::Pixels, Unit::Points)] {
let mut panel = opened(newest, older);
panel.frame();
panel.frame();
assert_eq!(fields(&panel.app())["units"], json!(shown.label()));
assert_eq!(fields(&panel.app())["basedOnUnits"], json!(newest.label()));
assert_eq!(count(&panel, shown), 1, "the newest entry shows the units of the fields: {:?}", panel.texts());
assert_eq!(count(&panel, older), 1, "the older entry keeps its own units: {:?}", panel.texts());
set(&panel.app(), "units", json!("Inches")).unwrap();
panel.frame();
assert_eq!(count(&panel, Unit::Inches), 1, "the chosen units reach the newest entry only: {:?}", panel.texts());
assert_eq!(count(&panel, older), 1, "the older entry still keeps its own units: {:?}", panel.texts());
// The same set before the dialog's first frame.
let mut panel = opened(newest, older);
set(&panel.app(), "units", json!("Inches")).unwrap();
panel.frame();
panel.frame();
assert_eq!(count(&panel, Unit::Inches), 1, "a set before the first frame reaches the newest entry: {:?}", panel.texts());
assert_eq!(count(&panel, older), 1, "and leaves the older entry in its own units: {:?}", panel.texts());
}
let panel = opened(Unit::Pixels, Unit::Millimeters);
assert!(set(&panel.app(), "basedOnUnits", json!("Furlongs")).is_err(), "unknown units are refused");
}
/// Edit opens a profile as a document and closes the dialog, Reset does not; the rows list every
/// profile and say which were edited.
#[test]
@@ -1674,6 +1774,16 @@ mod tests {
nodes.iter().find(|(r, n, _)| *r == role && n == name).map(|(_, _, b)| *b).unwrap_or_else(|| panic!("no {role:?} {name}"))
}
/// The name field is named Document Name; before, screen readers read it as plain Name.
#[test]
fn new_document_names_its_name_field_document_name() {
use egui::accesskit::Role;
let nodes = dialog_nodes(1280.0, 900.0);
let field = |name: &str| nodes.iter().any(|(role, label, _)| *role == Role::TextInput && label == name);
assert!(field("Document Name"), "a text field named Document Name");
assert!(!field("Name"), "no text field named plain Name");
}
/// Every Preset Details label stands above its field, at the field's left edge; before, Width, Height,
/// Orientation, Artboards, the Bleed sides and Background Contents sat right-aligned beside their fields.
#[test]
+1
View File
@@ -30,6 +30,7 @@ pub const TOGGLES: &[&str] = &[
"view.rulers",
"view.boundingBox",
"view.transparencyGrid",
"view.showMissingLinks",
"view.guides",
"view.grid",
"view.slices.hide",
+7 -1
View File
@@ -24,6 +24,9 @@ macro_rules! tl {
}
pub mod addons;
/// Agents in the open window through the ArtCraft Launcher's switch (desktop).
#[cfg(not(target_arch = "wasm32"))]
pub mod agents;
pub mod background;
mod brand;
pub mod canvas;
@@ -131,7 +134,7 @@ pub use caches::{CacheKey, CanvasCache, LivePaintGapsCache, Perf, PlacedKey, Pri
#[cfg(test)]
pub(crate) use services::browsable_url;
pub use services::{DownloadFn, ExistsFn, Inbox, ReadFn, SaveStreamFn, SaveWriteFn, ScreenDensity, ScreenPpi, Services, WriteFn};
pub use ui_fonts::ui_fonts;
pub use ui_fonts::{configure_ui_fonts, ui_fonts};
pub struct VectorcraftApp {
pub session: Session,
@@ -343,6 +346,9 @@ pub struct VectorcraftApp {
/// (`--automation-read-root`, `--automation-write-root`); `None`: anywhere. See
/// [`Self::with_automation_roots`].
automation_roots: Option<Arc<AutomationRoots>>,
/// The agents link while the ArtCraft Launcher's switch may let agents in ([`Self::with_agents`]).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) agents: Option<Box<agents::Agents>>,
/// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which
/// `ui.dialog.set` writes.
pub(crate) pending_plugin_install: Option<dialogs::plugin::PendingInstall>,
+5
View File
@@ -52,6 +52,9 @@ fn window_toggle_label(app: &VectorcraftApp, id: &str) -> Option<String> {
"view.transparencyGrid" => {
if app.session.active().is_some_and(|d| d.transparency_grid) { "Hide Transparency Grid" } else { "Show Transparency Grid" }.into()
}
"view.showMissingLinks" => {
if app.session.active().is_some_and(|d| d.show_missing_links) { "Hide Missing Links" } else { "Show Missing Links" }.into()
}
"view.guides" => if v.guides { "Hide Guides" } else { "Show Guides" }.into(),
"view.grid" => if v.grid { "Hide Grid" } else { "Show Grid" }.into(),
"view.guides.lock" => if app.session.guides_locked() { "Unlock Guides" } else { "Lock Guides" }.into(),
@@ -371,6 +374,8 @@ pub const DYNAMIC_LABELS: &[&str] = &[
"Show Bounding Box",
"Hide Transparency Grid",
"Show Transparency Grid",
"Show Missing Links",
"Hide Missing Links",
"Hide Guides",
"Show Guides",
"Hide Grid",
+4
View File
@@ -299,6 +299,10 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
crate::prefs_dialog::open(app, s("category").as_deref());
Ok(Value::Null)
}
#[cfg(not(target_arch = "wasm32"))]
"prefs.agents" => crate::agents::command(app, p),
#[cfg(target_arch = "wasm32")]
"prefs.agents" => Err("agents in the open window need the desktop app".into()),
// Edit → Color Settings… / Assign Profile… (no params): show the colour-management panel
// wherever it is, as Window › Separations Preview does (it isn't in an icon column, so a
// flyout for it never opened: #4542), scrolled to its Color Settings section, which a short
+1
View File
@@ -674,6 +674,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
),
c("Hide Bounding Box", "view.boundingBox"),
c("Show Transparency Grid", "view.transparencyGrid"),
c("Show Missing Links", "view.showMissingLinks"),
c("Hide Text Threads", "view.textThreads"),
c("Hide Gradient Annotator", "view.gradientAnnotator"),
c("Hide Corner Widget", "view.cornerWidget"),
+6
View File
@@ -172,6 +172,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
),
("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"),
("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"),
(
"prefs.agents",
"AI Integrations",
"",
"{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences",
),
("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"),
(
"view.refreshMonitorProfile",
+7
View File
@@ -1073,6 +1073,12 @@ fn groups(app: &VectorcraftApp) -> [Vec<(CommandRef, CommandState)>; 6] {
let f = Facts::of(&cache.list, &selected);
let o = &app.ui.links.options;
let e = |id: &str, params: Value, a: Act, label: &str| entry(app, &f, id, params, a, label);
// View › Show Missing Links, also here: checked while the canvas marks them.
let marking = app.session.active().map(|st| st.show_missing_links);
let show_missing = (
CommandRef::with_params("view.showMissingLinks", json!({ "on": marking != Some(true) })),
CommandState::new().enabled(marking.is_some()).checked(marking == Some(true)).title(tl!("Show Missing Links")),
);
[
vec![
e("ui.relinkDialog", json!({ "ids": f.all() }), Act::Relink, "Relink…"),
@@ -1097,6 +1103,7 @@ fn groups(app: &VectorcraftApp) -> [Vec<(CommandRef, CommandState)>; 6] {
.chain([
option_entry("ui.links.linkInfo", Value::Null, o.info, "Show Link Info"),
option_entry("ui.links.dcs", Value::Null, o.dcs, "Show DCS Transparency Interactions"),
show_missing,
])
.collect(),
]
+31 -3
View File
@@ -173,6 +173,30 @@ impl PrefsWindow {
}
}
/// The English names of the window's pages: the preference categories, then AI Integrations where agents may use the
/// window (the desktop app with preferences).
fn categories(app: &VectorcraftApp) -> impl Iterator<Item = &'static str> {
#[cfg(not(target_arch = "wasm32"))]
let agents = app.agents.is_some().then_some(crate::agents::PAGE_TITLE);
#[cfg(target_arch = "wasm32")]
let agents = {
let _ = app;
None
};
PREF_CATEGORIES.iter().copied().chain(agents)
}
/// The agent settings as the AI Integrations page edits them; `None` where the window has no such page.
fn agent_settings(app: &VectorcraftApp) -> Option<Value> {
#[cfg(not(target_arch = "wasm32"))]
return crate::agents::draft_value(app);
#[cfg(target_arch = "wasm32")]
{
let _ = app;
None
}
}
/// Whether `key` is a row of the window: a UI-only field, a preference or a preference group.
fn is_known(key: &str) -> bool {
UI_FIELDS.iter().any(|f| f.0 == key) || spec(key).is_some() || PREF_GROUPS.contains(&key)
@@ -203,7 +227,10 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) {
draft.set("__smartGuides", &app.ui.view.smart_guides);
draft.set("__snapToGrid", &app.ui.view.snap_to_grid);
draft.set("__taskBar", &app.ui.task_bar);
let selected = category.and_then(|c| PREF_CATEGORIES.iter().find(|x| x.eq_ignore_ascii_case(c))).copied().unwrap_or(PREF_CATEGORIES[0]);
if let Some(agents) = agent_settings(app) {
draft.set(model::AGENTS_KEY, &agents);
}
let selected = category.and_then(|c| categories(app).find(|x| x.eq_ignore_ascii_case(c))).unwrap_or(PREF_CATEGORIES[0]);
// The saved delay, so OK writes the delay in use in its place.
let mut source = draft.clone();
if let Some(saved) = &saved_delay {
@@ -298,11 +325,12 @@ pub(crate) fn fields(app: &VectorcraftApp) -> Option<Map<String, Value>> {
/// Sets one field as the user editing it would (`ui.dialog.set`). `Err` while the window is closed, for an unknown
/// key or a value of the wrong kind.
pub(crate) fn set_field(app: &mut VectorcraftApp, key: &str, value: Value) -> Result<(), String> {
let category = (key == "__category").then(|| value.as_str().map(|name| (name, categories(app).find(|c| c.eq_ignore_ascii_case(name)))));
let w = app.prefs.as_mut().ok_or("no dialog open")?;
match key {
"__category" => {
let name = value.as_str().ok_or("`__category` takes text")?;
let category = PREF_CATEGORIES.iter().find(|c| c.eq_ignore_ascii_case(name)).ok_or_else(|| format!("no category `{name}`"))?;
let (name, category) = category.flatten().ok_or("`__category` takes text")?;
let category = category.ok_or_else(|| format!("no category `{name}`"))?;
w.state.selected = category.to_string();
Ok(())
}
+64 -5
View File
@@ -33,6 +33,28 @@ pub(super) const WARNING_DIALOGS: &[&str] = &["showExternalScriptWarning"];
/// The row key of the Reset All Warning Dialogs button.
const RESET_WARNINGS_KEY: &str = "resetWarningDialogs";
/// The draft key of the agent settings of Preferences › AI Integrations (`prefs.agents`).
pub(super) const AGENTS_KEY: &str = "integrations";
/// Preferences › AI Integrations: with the suite's `AI-MCP` flag, the framework's Agents page over the agent settings
/// in the draft (the ArtCraft Launcher's switch decides; the page has none of its own); without it, a line that says
/// so, as VectorCraft had no agent settings before the switch. Returns whether the draft changed.
#[cfg(not(target_arch = "wasm32"))]
fn agents_page(live: &mut Live<'_>, ui: &mut egui::Ui) -> bool {
use craft::ui::contract::Show as _;
use craft::ui::display::{Shade, Text};
let Some((status, mcp_flag)) = crate::agents::page_state(live.app) else { return false };
if !mcp_flag {
Text::new(tl!(
"Agents use VectorCraft without a window. The ArtCraft Launcher's Settings › AI agents switch lets them into the open window once the suite's AI-MCP flag is on."
))
.shade(Shade::Muted)
.show(ui);
return false;
}
craft::automation::ui::agents::AgentsPage::new(AGENTS_KEY, &mut live.w.draft, &status).mcp_flag(true).show(ui).changed
}
/// Turns the warning preferences `keys` back on in the draft, as Reset All Warning Dialogs does; OK or Apply writes
/// them.
pub(super) fn reset_warning_dialogs(w: &mut PrefsWindow, keys: &[&str]) {
@@ -358,7 +380,15 @@ impl Live<'_> {
impl PreferencesModel for Live<'_> {
fn pages(&self) -> Vec<PageSpec<'_>> {
PREF_CATEGORIES.iter().map(|&cat| self.page(cat)).collect()
let pages = PREF_CATEGORIES.iter().map(|&cat| self.page(cat));
// The agent settings, drawn whole by the framework's Agents page, on the desktop.
#[cfg(not(target_arch = "wasm32"))]
let pages = pages.chain(self.app.agents.is_some().then(|| {
use crate::agents::PAGE_TITLE;
let keywords = "agents AI MCP ArtCraft Launcher control port folders";
PageSpec::custom(PAGE_TITLE, tl!(PAGE_TITLE)).keywords(keywords).resettable(false)
}));
pages.collect()
}
fn set(&mut self, key: &str, value: PrefValue) {
@@ -429,7 +459,12 @@ impl PreferencesModel for Live<'_> {
}
}
fn custom_page(&mut self, _ui: &mut egui::Ui, _page: &str) -> bool {
fn custom_page(&mut self, ui: &mut egui::Ui, page: &str) -> bool {
#[cfg(not(target_arch = "wasm32"))]
if page == crate::agents::PAGE_TITLE {
return agents_page(self, ui);
}
let _ = (ui, page);
false
}
@@ -478,12 +513,33 @@ impl PreferencesDraft for Live<'_> {
|| current.get(k).and_then(Value::as_f64) == self.w.source.get::<Value>(k).as_ref().and_then(Value::as_f64))
})
.collect();
let values: Map<String, Value> = edited.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect();
let values: Map<String, Value> =
edited.iter().filter(|(k, _)| !k.starts_with("__") && *k != AGENTS_KEY).map(|(k, v)| (k.clone(), v.clone())).collect();
let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool);
let document_units = self.w.reset_units.as_deref().is_none_or(|u| values.get("unitsGeneral").and_then(Value::as_str) != Some(u));
// The agent settings are saved where `vectorcraft-cli mcp` reads them, not with the preferences: only the
// fields changed in the window, so one `prefs.agents` changed while it is open keeps its new value. First,
// so a refused agent setting leaves the preferences unapplied too.
if let Some(agents) = edited.get(AGENTS_KEY).and_then(Value::as_object) {
let read = self.w.source.get::<Map<String, Value>>(AGENTS_KEY).unwrap_or_default();
let given: Map<String, Value> =
agents.iter().filter(|(k, v)| *k != "allowAgentControl" && read.get(*k) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect();
if !given.is_empty() {
self.app.run("prefs.agents", Value::Object(given))?;
}
}
// A refused folder, typed or picked, comes back here as the engine's message.
if !values.is_empty() {
self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?;
if !values.is_empty()
&& let Err(e) = self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))
{
// The agent settings were saved: the window shows them as saved (its own edits among them, a change made
// outside it kept), and Apply doesn't send them again.
if let Some(agents) = super::agent_settings(self.app) {
self.w.draft.set(AGENTS_KEY, &agents);
self.w.source.set(AGENTS_KEY, &agents);
self.w.opened.set(AGENTS_KEY, &agents);
}
return Err(e);
}
let row = |key: &str| edited.get(key).and_then(Value::as_bool);
// When OK enters the Touch workspace, the task bar is set before the switch, so it goes to the workspace being
@@ -524,6 +580,9 @@ impl PreferencesDraft for Live<'_> {
self.w.draft.set("__smartGuides", &self.app.ui.view.smart_guides);
self.w.draft.set("__snapToGrid", &self.app.ui.view.snap_to_grid);
self.w.draft.set("__taskBar", &self.app.ui.task_bar);
if let Some(agents) = super::agent_settings(self.app) {
self.w.draft.set(AGENTS_KEY, &agents);
}
self.w.opened = self.w.draft.clone();
self.w.source = self.w.draft.clone();
self.w.touched.clear();
+51
View File
@@ -1589,3 +1589,54 @@ fn reset_all_warning_dialogs_turns_a_dismissed_warning_back_on() {
click_reset_warnings(&mut a);
assert!(!a.prefs.as_ref().unwrap().touched.contains("showExternalScriptWarning"), "a dimmed button changes nothing");
}
/// Preferences › AI Integrations (desktop): the page is there while the window has an agents link, it opens by
/// name, and OK saves an edited agent setting through `prefs.agents` instead of `prefs.set`.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn ai_integrations_page_saves_the_agent_settings_on_ok() {
use craft::automation::agents::{AgentSettings, AgentSwitch};
use std::sync::{Arc, Mutex};
let saved: Arc<Mutex<Vec<AgentSettings>>> = Arc::default();
let into = saved.clone();
let save: crate::agents::SaveFn = Box::new(move |s| {
into.lock().unwrap().push(s.clone());
Ok(())
});
let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save)
.with_default_folder(None);
let mut a = app().with_agents(agents);
open(&mut a, Some("ai integrations"));
assert_eq!(page(&a), Some(crate::agents::PAGE_TITLE));
assert!(with_pages(&mut a, |pages| pages.iter().any(|p| p.id == crate::agents::PAGE_TITLE && p.custom)));
a.prefs.as_mut().unwrap().draft.set("integrations.whenAppClosed", &"error");
confirm(&mut a).unwrap();
let saved = saved.lock().unwrap();
assert_eq!(saved.len(), 1);
assert_eq!(saved[0].when_app_closed, craft::automation::agents::WhenAppClosed::Error);
}
/// OK sends only the agent settings changed in the window: one changed through `prefs.agents` while Preferences is
/// open keeps its new value.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn ok_keeps_an_agent_setting_changed_while_preferences_is_open() {
use craft::automation::agents::{AgentSettings, AgentSwitch};
use std::sync::{Arc, Mutex};
let saved: Arc<Mutex<Vec<AgentSettings>>> = Arc::default();
let into = saved.clone();
let save: crate::agents::SaveFn = Box::new(move |s| {
into.lock().unwrap().push(s.clone());
Ok(())
});
let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save)
.with_default_folder(None);
let mut a = app().with_agents(agents);
open(&mut a, Some(crate::agents::PAGE_TITLE));
a.run("prefs.agents", json!({"readRoot": "/elsewhere"})).unwrap();
a.prefs.as_mut().unwrap().draft.set("integrations.whenAppClosed", &"error");
confirm(&mut a).unwrap();
let last = saved.lock().unwrap().last().cloned().unwrap();
assert_eq!(last.read_root, "/elsewhere", "the window did not send back the folder it opened with");
assert_eq!(last.when_app_closed, craft::automation::agents::WhenAppClosed::Error);
}
+78 -2
View File
@@ -1,10 +1,12 @@
//! The app's interface font stack: the craft faces it embeds (Japanese, Georgian, Devanagari,
//! Gujarati), JetBrains Mono for monospace, and the framework's loader for every other script.
//! The stack is installed once by the shell (`embed::install`).
//! The shell installs the stack at startup and refreshes it when the interface language changes.
use std::sync::Arc;
use craft::ui::fonts::{Family, I18nScripts, SEMIBOLD, UiFonts};
use craft::ui::fonts::{Family, FontFetcher, I18nScripts, SEMIBOLD, UiFonts};
use crate::i18n::{Lang, LangExt};
/// The interface fonts configuration. Characters no face covers are looked up in the installed
/// system fonts on native; the web build has the faces its server offers instead.
@@ -22,6 +24,49 @@ pub fn ui_fonts() -> UiFonts<'static> {
}
}
#[derive(Clone)]
struct FontSelection {
language: Lang,
fetcher: Option<Arc<dyn FontFetcher>>,
}
impl FontSelection {
fn fonts(&self) -> UiFonts<'static> {
let fonts = ui_fonts().ui_language(self.language.code());
match &self.fetcher {
Some(fetcher) => fonts.fetcher(Arc::clone(fetcher)),
None => fonts,
}
}
}
fn font_selection_id() -> egui::Id {
egui::Id::unique("vectorcraft-interface-font-selection")
}
/// Builds the shell's initial font configuration and keeps its language and font fetcher with
/// this context so they can be reused when the interface language changes.
pub fn configure_ui_fonts(ctx: &egui::Context, language: Lang, fetcher: Option<Arc<dyn FontFetcher>>) -> UiFonts<'static> {
let selection = FontSelection { language, fetcher };
let fonts = selection.fonts();
ctx.data_mut(|data| data.insert_temp(font_selection_id(), Some(selection)));
fonts
}
pub(crate) fn follow_language(ctx: &egui::Context, language: Lang) {
let changed = ctx.data_mut(|data| {
let selection = data.get_temp_mut_or_default::<Option<FontSelection>>(font_selection_id()).as_mut()?;
if selection.language == language {
return None;
}
selection.language = language;
Some(selection.clone())
});
if let Some(selection) = changed {
selection.fonts().install(ctx);
}
}
#[cfg(test)]
mod tests {
use craft::ui::fonts::{FontRef, Sample, UiFonts, assert_covers, missing_glyphs};
@@ -75,6 +120,37 @@ mod tests {
assert_covers(&ui_fonts().stack(), [Sample::new("ja", "japanese", JAPANESE)]);
}
#[test]
fn han_fonts_follow_the_interface_language() {
if !embeds("Hans") || !embeds("Jpan") {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
}
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let ctx = crate::testing::ui_context();
app.session.prefs.interface_language = "zh-hans".into();
configure_ui_fonts(&ctx, app.ui_language(), None).install(&ctx);
for (language, preferred, alternate) in [
(None, "Noto Sans CJK SC", "BIZ UDPGothic"),
(Some("ja"), "BIZ UDPGothic", "Noto Sans CJK SC"),
(Some("zh-hans"), "Noto Sans CJK SC", "BIZ UDPGothic"),
] {
if let Some(language) = language {
crate::menus::run_ui_command(&mut app, "app.language", &serde_json::json!({"lang": language})).unwrap().unwrap();
}
crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |_, ui| {
ui.ctx().fonts(|fonts| {
let chain = &fonts.definitions().families[&egui::FontFamily::Proportional];
let index = |family: &str| {
chain.iter().position(|face| face.starts_with(family)).unwrap_or_else(|| panic!("missing {family} in {chain:?}"))
};
assert!(index(preferred) < index(alternate), "expected {preferred} before {alternate} in {chain:?}");
});
});
}
}
#[test]
fn the_ui_works_without_the_craft_fonts() {
let stack = UiFonts::new(&I18nScripts).stack();
+13 -1
View File
@@ -1,6 +1,6 @@
# Control protocol
> **Last updated:** 2026-11-19 · **Change:** #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726).
> **Last updated:** 2026-12-03 · **Change:** the window serves agents while the ArtCraft Launcher's AI agents switch names VectorCraft ([Agents in the open window](#agents-in-the-open-window)); previously: #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726).
`vectorcraft --control <port>` listens on `127.0.0.1:<port>` (loopback only). The port must be a number
from 1 to 65535 (`--control=<port>` works too), given once; otherwise the app prints an error and exits
@@ -33,6 +33,18 @@ persistent clients can send further requests within these bounds, or reconnect a
These transport budgets are separate from the existing 60-second command-processing wait.
Transport: `apps/vectorcraft/src/control_server.rs`.
## Agents in the open window
While the ArtCraft Launcher's *Settings › AI agents* switch names VectorCraft, the window serves this protocol
without `--control`, on a loopback port of its own (*Edit › Preferences › AI Integrations › Control Port*; 0
picks a free one), and publishes the port, its process id and the token file in `agent-connection.json` in
the settings folder. It stops and removes the file when the switch turns off. Each connection must
authenticate before anything else is answered, with the token in `agent-control.token` there (readable by
the user only): `auth.challenge {clientNonce}` and then `auth {proof}`, which `vectorcraft-cli mcp` uses so the
token never crosses the wire, or `auth {token}`. Every request on it runs inside the agent folders of
Preferences › AI Integrations, as with `--automation-read-root` and `--automation-write-root`, and
`prefs.agents` refuses to change them from there. See [Agents in the open window](mcp.md#agents-in-the-open-window).
## Synthetic input budgets
`ui.drag` accepts at most **256** `steps`; `ui.click` and `ui.drag` accept at most **16** `count`.
+1
View File
@@ -83,6 +83,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
|---|---|---|
| 2026-12-02 | minor | G12: Retype panel font rows have an item context menu: a secondary click or Shift+F10 selects the row and offers Apply Font (what a click on the row does; off without live text selected), the panel menu's Small, Medium and Large sample sizes and Reset Retype Panel; the menu closes when the list or the document changes. Headless regressions: `panels::retype::tests`. Scores and estimates unchanged. |
| 2026-12-02 | minor | G12: SVG Interactivity event rows have an item menu: a right-click (or Shift+F10 on the focused row) picks that event and offers Remove Event (`svgInteractivity.removeEvent` for that row, one undo step), Clear Events (`svgInteractivity.clearEvents`, enabled like the panel menu row) and Link JavaScript Files… (`ui.javascriptFilesDialog`). Headless regressions: `panels::svg_interactivity::tests`. Scores and estimates unchanged. |
| 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-25 | minor | Document Info › Objects: total enclosed area (`pathArea` in pt²) for closed and compound paths (holes subtracted per fill rule; guides and open paths left out) and formatted Path Area in document units, beyond reference panel (#6965). Worked out only when the request covers Objects (`pathArea` null otherwise or with `pathArea: false`); the panel asks for it only while Objects or All Categories is shown. Tests: `info_gives_the_paths_total_area`, `info_works_out_the_path_area_only_for_the_objects_category`, `the_path_area_is_worked_out_only_while_objects_is_shown`, `format_area_formats_and_trims_cleanly`. Scores and estimates unchanged. |
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
| 2026-11-21 | minor | G12: Document Info › Selection Only (`ui.docInfo.selectionOnly`) counts objects in the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. |
+96 -33
View File
@@ -1,6 +1,6 @@
# VectorCraft MCP server
> **Last updated:** 2026-11-27 · **Change:** Anchor Inspector: canceled Corner and Shared Edge option edits restore their opening values; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained.
> **Last updated:** 2026-12-03 · **Change:** plain `vectorcraft-cli mcp` finds the open window through the ArtCraft Launcher's AI agents switch (no port or token to configure), `--when-closed`, the `agent_folders` tool, Preferences › AI Integrations and `prefs.agents`; `--connect` is deprecated. Previously: Anchor Inspector: canceled Corner and Shared Edge option edits restore their opening values; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained.
>
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
@@ -8,21 +8,53 @@
(newline-delimited JSON-RPC 2.0; see [Protocol](#protocol) for version negotiation). Agents use it to
draw, inspect and look at VectorCraft documents.
It has two backends:
It has three ways to run:
| Mode | How | What works |
|---|---|---|
| **Remote** | `vectorcraft-cli mcp --connect 127.0.0.1:7979` (the app must run with `vectorcraft --control 7979`) | Everything. Tool calls are forwarded over the [control protocol](control-protocol.md), so you watch the app change live. |
| **Headless** | `vectorcraft-cli mcp --headless` | An in-process engine session with a CPU renderer. Everything except the UI-only tools (`inspect_ui` or `ui_inspect`, `type_text`, `answer_dialog`, `open_panel`, `screenshot {window:true}` or `ui_screenshot`). |
| **Open window** | `vectorcraft-cli mcp` while the ArtCraft Launcher's *Settings › AI agents* switch lets agents use VectorCraft (see [Agents in the open window](#agents-in-the-open-window)); `--automation-read-root` or `--automation-write-root` make it headless instead | Everything. Each tool call goes to the open VectorCraft window, so you watch the app change live. |
| **Headless** | `vectorcraft-cli mcp --headless` or with automation roots, or plain `mcp` while agents may not use the open window | An in-process engine session with a CPU renderer. Everything except the UI-only tools (`inspect_ui` or `ui_inspect`, `type_text`, `answer_dialog`, `open_panel`, `screenshot {window:true}` or `ui_screenshot`). |
| **Remote** (deprecated) | `vectorcraft-cli mcp --connect 127.0.0.1:7979` (the app must run with `vectorcraft --control 7979` and `VECTORCRAFT_CONTROL_TOKEN`) | Everything, over the [control protocol](control-protocol.md). `--connect` prints a deprecation line and goes away in a later release. |
With no flag, the server tries `127.0.0.1:7979` and falls back to headless. Logs go to stderr; stdout carries
only protocol messages.
Logs go to stderr; stdout carries only protocol messages.
## Agents in the open window
One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents use Craft
apps* (behind the suite's `AI-MCP` flag). The launcher also adds one `ArtCraft` entry to the MCP clients it
knows; VectorCraft writes no client configuration of its own.
While the switch names VectorCraft, the open window serves its control channel on loopback and publishes
`agent-connection.json` (port, process id, token file) in its settings folder; the token stays in
`agent-control.token` there, readable by the user only. Plain `vectorcraft-cli mcp` reads that file before every tool
call and authenticates with the challenge handshake (the window proves it holds the token first; the token
itself never crosses the wire). So no port or token goes into a client's configuration, the app may be
opened after the MCP session started, and it may quit or restart while the session goes on. When the switch
turns off, the window stops listening and removes the file.
Every file an agent's request opens or saves in the window stays inside the agent folders: those set in
*Edit › Preferences › AI Integrations*, or `Documents/ArtCraft/Agents/VectorCraft` when none is set (made when
first used). A request outside them is refused, as with `--automation-read-root`. The person at the keyboard
is not confined. The `agent_folders` tool tells the agent which folders it may use.
While agents may use VectorCraft but it is closed, Preferences › AI Integrations chooses what plain `mcp`
does: open VectorCraft and wait for it (the default), run the call in a session without a window confined to
the agent folders, or answer with an error that asks to open VectorCraft. `--when-closed
launch|headless|error` overrides the choice for one server. A session that went headless stays headless, so
documents don't move under the agent. While agents may not use VectorCraft, plain `mcp` runs headless with
only the folders given on its command line, as before.
Preferences › AI Integrations shows the switch's state, the port agents connect on, Control Port (0: any free
port), the two folders and the closed-app choice. Without the `AI-MCP` flag it only says that agents use
VectorCraft without a window. The same settings are the UI command `prefs.agents {controlPort?, readRoot?,
writeRoot?, whenAppClosed?}`, which agents' own requests can read but not change. Started with `--control`,
the window serves that channel for the whole run instead, and the page says so.
### Command catalogue (headless vs remote)
`command_list` / `list_commands` / `vectorcraft://commands` return the live catalogue for the backend in use:
- **Headless:** engine and plug-in commands, plus the desktop menu catalogue (`UI_COMMANDS`) marked `"ui": true` so agents can discover ids such as `view.fitArtboard`, `file.newDialog` and `window.*`. Running a UI-only command that the headless host does not implement returns an error that points at `--connect`.
- **Headless:** engine and plug-in commands, plus the desktop menu catalogue (`UI_COMMANDS`) marked `"ui": true` so agents can discover ids such as `view.fitArtboard`, `file.newDialog` and `window.*`. Running a UI-only command that the headless host does not implement returns an error that asks for the open window.
The catalogue is mirrored in `crates/mcp/src/ui_catalog.rs` (mcp does not depend on ui-egui). Regenerate with `cargo xtask ui-commands`; `cargo xtask ci` runs `ui-commands --check` so the mirror cannot drift.
- **Remote:** the same lists, with each UI entry's `enabled` taken from the live app. Run UI commands with `command_run` / `run_command` or `invoke_menu`.
@@ -30,6 +62,28 @@ Effect ids from `effect.list` / `apply_effect` / `vectorcraft://effect/{id}` (fo
A release `vectorcraft-cli` on `PATH` can lag the checkout. Prefer `cargo install --path apps/vectorcraft-cli --locked` and put `$CARGO_HOME/bin` first in the MCP client's environment, or set the client's `command` to that binary's absolute path (#6460).
## Missing-link canvas markers
Use `run_command` with these engine commands (the `command_run` alias takes the same calls with `id` in place of `command`):
```json
{"command":"view.showMissingLinks","params":{"on":true}}
{"command":"links.marked","params":{}}
{"command":"view.showMissingLinks","params":{"on":false}}
```
`links.marked` refreshes file status and returns `{on, images: [{id, bounds: [x0, y0,
x1, y1]}]}` for visible missing linked images and placed documents in the active document.
When the toggle is off, `images` is empty; `links.list {show: "missing"}` still lists missing
links independently. Neither command changes selection or undo history. `view.showMissingLinks`
never reads linked files, so it returns at once even for a large or slow file; `links.marked` is
the explicit, synchronous inspection. The desktop canvas draws a red outline and badge, scans
files in the background as soon as the toggle turns on and then about every two seconds even
with the Links panel closed, and removes markers after repair. The toggle is per open
document and starts off on reopen. Markers are never saved as artwork, rendered into exports
or printing, or exposed as selectable objects. Headless mode exposes the same state and
queries; it has no canvas on which to draw decorations.
## Install and register
From the repository root, with Rust 1.95+ and the platform's source-build prerequisites installed:
@@ -40,11 +94,13 @@ cargo install --path apps/vectorcraft-cli --locked
export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"
vectorcraft-cli --help
claude mcp add vectorcraft -- vectorcraft-cli mcp
# or pin a mode:
# or always without a window:
claude mcp add vectorcraft-headless -- vectorcraft-cli mcp --headless
claude mcp add vectorcraft-app -- vectorcraft-cli mcp --connect 127.0.0.1:7979
```
With the ArtCraft Launcher, its AI agents switch adds the `ArtCraft` entry for you, and these commands are only
needed for a build of your own.
Cargo installs a binary, not a symlink into `target/`, so it survives `cargo clean`.
Re-run the install command after updating the checkout.
By default the executable goes in `$CARGO_HOME/bin` (`~/.cargo/bin` when unset), or
@@ -66,7 +122,7 @@ installed binary path, not a literal `~` or `$HOME` expression. Avoid symlinks i
`target/release`: cleaning the build directory breaks them. A source build alone does
not put the CLI on `PATH`.
For a live session, start the app first: `cargo run --release -p vectorcraft -- --control 7979`.
For a live session, turn on the launcher's AI agents switch (for a build of your own, set the `AI-MCP` flag and name `vectorcraft` in the launcher's app list) and open the app: `cargo run --release -p vectorcraft`.
### From an installed release
@@ -76,33 +132,21 @@ The release packages ship `vectorcraft-cli` alongside the desktop app, so no bui
|---|---|
| Windows (MSI) | `%LOCALAPPDATA%\Programs\ArtCraft\VectorCraft\vectorcraft-cli.exe` by default (`C:\Program Files\ArtCraft\VectorCraft\vectorcraft-cli.exe` for an all-users install, under `Program Files (x86)` instead for the 32-bit build, or wherever you installed it otherwise), not on `PATH` |
| Linux (deb, rpm) | `/usr/bin/vectorcraft-cli` |
| macOS | the separate `vectorcraft-cli-<version>-macos-<arch>.zip` release asset (the `.app` holds only the desktop app) |
| macOS | `VectorCraft.app/Contents/MacOS/vectorcraft-cli`, beside the app, where the ArtCraft Launcher finds it (`/Applications/VectorCraft.app` by default), or the separate `vectorcraft-cli-<version>-macos-<arch>.zip` release asset |
```sh
# Windows (PowerShell), default install folder
claude mcp add vectorcraft -- "$env:LOCALAPPDATA\Programs\ArtCraft\VectorCraft\vectorcraft-cli.exe" mcp
# macOS, VectorCraft in /Applications (the default; put your own path to VectorCraft.app otherwise)
claude mcp add vectorcraft -- "/Applications/VectorCraft.app/Contents/MacOS/vectorcraft-cli" mcp
# Linux, or macOS with the CLI unzipped onto PATH
claude mcp add vectorcraft -- vectorcraft-cli mcp
```
For a live session, start the installed app with the control port before the MCP client starts the server:
```sh
# macOS: quit VectorCraft first, since `open -a` passes no arguments to an app that is already running
open -a VectorCraft --args --control 7979
# Windows (PowerShell), default install folder
& "$env:LOCALAPPDATA\Programs\ArtCraft\VectorCraft\vectorcraft.exe" --control 7979
# Linux (deb, rpm)
vectorcraft --control 7979
```
The Dock, Start menu and desktop launchers start the app without `--control`, so the app opens no control
port unless `VECTORCRAFT_CONTROL_PORT` is set. `vectorcraft-cli mcp` with no flag tries `127.0.0.1:7979`
once, when it starts: a server that started before the app stays headless until the MCP client restarts
it. `open -a` and PowerShell's `&` return before the app opens the port, so wait until the VectorCraft
window is open before you start the MCP client. With `--connect`, a server that finds no app stops and
prints `vectorcraft-cli: cannot connect to 127.0.0.1:7979: ` followed by the system's connection error, for
example `connection timed out`.
For a live session, turn on *Settings › AI agents* in the ArtCraft Launcher and open VectorCraft as usual (Dock,
Start menu, desktop launcher). The server finds the window whenever it opens, unless the session already went headless
(a call made while VectorCraft was closed, with the headless closed-app choice); such a session needs a new
MCP session to use the window. See [Agents in the open window](#agents-in-the-open-window).
## Confining file access
@@ -832,6 +876,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
| `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. |
| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. |
| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. |
| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. |
For example, create editable Japanese area type with the engine's vertical writing mode:
@@ -3252,7 +3297,8 @@ through `$`:
reverted document.
`removeAll()` on any `pathItems`, on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's
`groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group
or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that
or layer that keeps other objects that are not ruler guides. `removeAll()` on the `pathItems` of a compound path that is such a clipping
path throws the same way, since it would leave the clipping path empty. The document's `pathItems.removeAll()` still deletes the paths of a group that
is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then
clips. Text beside the clipping path in the clipping group does not count. Hidden text, text
in a hidden group, blank text without a list marker, area text too short for its first line, and text that a clipping group nested in
@@ -3691,7 +3737,11 @@ through `$`:
radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`,
`shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new
art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing
mode, which stays as it was. These creation commands take `onLayer: layerId` to draw normally on that layer and
mode, which stays as it was. For ordinary layer placement, when the active layer is locked or hidden, the new
path goes on the topmost shown, unlocked layer. While an opacity mask, pattern or symbol is being edited, the
new path goes on that editing layer, and the call throws and makes no path when that layer is locked or hidden.
The call also throws and makes no path when the document has layers and every one is locked or hidden.
These creation commands take `onLayer: layerId` to draw normally on that layer and
record this placement for replay. A null `onLayer` draws normally on the active layer. A layer's and a group's `pathItems`
(https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/)
have the same members, and their `parent` is that layer or group. Their `add()` and shape creators put the new path
@@ -9205,6 +9255,17 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a
an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded.
`path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that
keeps its kind, leave the document as it is and record no undo step.
On a path with rounded Live Corners, `path.moveAnchor` and `path.moveAnchors` (and the arrow keys) move the uncut corner
each moved anchor belongs to by the drag delta and cut the corners again at their radii. The corners stay live; a live
rectangle or polygon becomes a path with live corners. The delta is measured from the drawn anchor, but the recut can
move that anchor again: a grabbed arc end can finish away from a snap target, and `path.moveAnchor` can leave the drawn
anchor away from `(x, y)`. When the recut changes the anchor layout, all selected anchors of that path are remapped
through their uncut outline anchors and its selected segments are cleared. An unchanged layout keeps the selection.
Anchor edits instead make the shape a plain path when it has no rounded corner, when a live rectangle is sheared or
unevenly scaled, when an arrow-key nudge's selected curved segments bend or hold their anchors, or when a transform of
direct-selected anchors is other than a move. A nudge that changes nothing, including one that the pixel-grid snap of a
pixel-aligned path takes back (objects selected whole beside the anchors included), records no undo step and leaves Live Corners as they are: a live rectangle stays a live
rectangle. These fallbacks edit the drawn anchors rather than recutting the uncut outline.
`path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same
length, and the anchor keeps its kind. At an open end, where no segment leaves the anchor on the other side,
`symmetric` has no effect and the handle moves as it would without it. Both `symmetric` and `independent` default to false, and a call with both true is
@@ -10292,7 +10353,9 @@ the corners holding a Direct-Selected anchor, or every corner of a path selected
hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the
rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the
paths differ). A path without Live Corners is Absolute: Relative leaves it, an ellipse or a line as it is, with no
undo step. Editing a path's anchors (for example `path.moveAnchors`) ends its Live Corners, so it is Absolute again.
undo step. Moving a path's anchors with `path.moveAnchor`, `path.moveAnchors` or the arrow keys keeps Live Corners and
the radius mode under the rules above. An anchor edit that makes the shape a plain path ends Live Corners and resets
the radius mode to Absolute.
With Relative rounding, a radius is
compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius
shown again adds no undo step. The Corner Radius field beside the link sets the same corners. Each change runs one
@@ -10886,7 +10949,7 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture
{"name":"pointer_gesture","arguments":{"tool":"selection","mods":{"cmd":true},"events":[{"kind":"down","x":175,"y":125},{"kind":"up","x":175,"y":125}]}}
```
The preferences for the view need the desktop app (`vectorcraft-cli mcp --connect`): `zoomWithMouseWheel` (the
The preferences for the view need the open window (see [Agents in the open window](#agents-in-the-open-window)): `zoomWithMouseWheel` (the
wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; the control channel's
`ui.wheel` turns the wheel), `trackpadRotateView` (on by default: a two-finger rotation on a Mac trackpad, in the
macOS app or in Safari, turns the view about the pointer once it reaches 5°; with it off, the gesture does not turn
+2 -1
View File
File diff suppressed because one or more lines are too long
+6 -4
View File
@@ -132,6 +132,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
| 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-25 | minor | Document Info › Objects: total enclosed area (`pathArea` in pt²) for closed and compound paths (holes subtracted per fill rule; guides and open paths left out) and formatted Path Area in document units (#6965). Worked out only when the request covers Objects (`pathArea` null otherwise or with `pathArea: false`); the panel asks for it only while Objects or All Categories is shown. Tests: `info_gives_the_paths_total_area`, `info_works_out_the_path_area_only_for_the_objects_category`, `the_path_area_is_worked_out_only_while_objects_is_shown`, `format_area_formats_and_trims_cleanly`. Scores and estimates unchanged. |
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
@@ -373,7 +374,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de
| Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated |
| Automation (Actions, Variables, scripting, batch) | 3 | 80% | script DOM classes for layers, artboards and gradient stops, `#engine` (#1183), Batch option depth (scripting, #9019, Batch, #1938, and image and graph variables are done) | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged |
| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show (`panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`); Properties Quick Actions offer Ungroup for any selected group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`); Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score and hours unchanged; Layers appearance marker uses a hollow diamond and tooltip separate from targeting and selected art (#8710), based on Hassan1305's #8757; focused Layers coverage, runtime validation pending; scores and hours unchanged; Tools toolbar Search entry and retained customization covered in `crates/ui-egui/src/toolbar/tests.rs` (#8758), scores and hours unchanged |
| Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) |
| Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged); #5547: missing-link canvas outlines and badges, View/Links toggles and command API (score and hours unchanged) |
| Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) |
| **Feature depth** | **105** | **~79%** | | **~250–420** | |
| Interaction-fidelity pass (every tool's modifiers, cursors, Properties per context) | | | [ui-parity.md](ui-parity.md) | 60–90 | estimated |
@@ -863,6 +864,7 @@ since 2026-10-01.
- **A Shift-click inside a selected group** (VectorCraft's own rule): with Direct Selection, a Shift-click on the fill of a path inside a selected group deselects that path, and the group's other objects stay selected (`select.remove`); a Shift-drag from there moves nothing. A Shift-click on one of the path's anchors deselects only that anchor, and the path's other anchors and the group's other objects stay selected. Tests: `direct::tests::a_shift_press_inside_a_selected_group_deselects_the_path`, `selection_commands::remove_and_anchor_toggle_open_a_selected_group`, `selection::tests::expand_to_selects_a_member_in_place_of_its_selected_group`.
- **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of every selected path is selected (the paths selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. When another selected path has only some corners picked, a Shift-click on a widget of a path selected whole deselects that corner and keeps the other picks. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`.
- **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks (while every corner of every selected path is picked, it picks that corner alone, and a double-click then opens Corners for that corner), a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `corners::tests::a_path_with_hidden_widgets_keeps_its_picks`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`.
- **Anchor edits keep Live Corners (#10545):** moving an anchor of a path with rounded corners (Direct Selection drag, arrow keys, `path.moveAnchor`) moves its uncut corner by the drag delta and recuts it at its radius. A grabbed arc end can finish away from a snap target. A live rectangle or polygon becomes a path with live corners. When the anchor layout changes, the path's whole anchor selection is remapped and its segment selection is cleared. An anchor edit makes the shape a plain path when there is no rounded corner, a live rectangle is sheared or unevenly scaled, an arrow-key nudge bends selected curved segments or holds their anchors, or direct-selected anchors receive a transform other than a move. A nudge that changes nothing, including one that the pixel-grid snap of pixel-aligned paths takes back (with objects selected whole too), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These are VectorCraft's own rules. Tests: `tests::livecorners::moving_an_anchor_keeps_the_corners_live`, `tests::livecorners::dragging_selected_anchors_keeps_the_corners_live`, `tests::livecorners::moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path`, `tests::livecorners::a_recut_remaps_the_whole_anchor_selection`, `tests::livecorners::a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same`, `tests::livecorners::an_unchanged_corner_layout_keeps_the_selection`.
- **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF.
- **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`).
- **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html).
@@ -1116,7 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`.
- Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`.
- Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`.
- Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`.
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`.
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
@@ -1127,7 +1129,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
@@ -1190,7 +1192,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`.
- Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse.
- Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).
- MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172).
- MCP server with 34 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command, agent folders), attached to the open window through the ArtCraft Launcher's AI agents switch or headless (#10621). Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id needs the open window to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (headless, `notifications/cancelled` stops it at the next page or group and writes nothing; in the open window it only stops the call waiting, and the app may still finish and write the export), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172).
- MCP window captures from an app that does not send the image back go through a file in a new folder inside the system's temporary folder, which only the user can open on Unix, instead of a fixed name in the shared folder; the folder is removed after the read, also when the capture or the read fails (`tests::conventions::an_old_app_captures_the_window_in_a_new_private_folder`).
- MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads).
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`).
+4 -2
View File
@@ -114,6 +114,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
| 2026-11-06 | minor | Drop Shadow, Outer Glow and Inner Glow: spinner arrows beside Opacity, the offsets, Blur and Darkness (#5367, #5368); scores and estimates unchanged |
| 2026-11-06 | minor | Rename (`ui.rename`, no default key) opens the Layers panel's name field on the selected layer, group or object's row, as double-clicking its name does; a key can be assigned in Keyboard Shortcuts (#5324, a VectorCraft addition); scores and estimates unchanged |
| 2026-11-06 | minor | Properties panel in Edit Artboards (Shift+O): a Transform section with the shared reference point, X, Y, W and H, the preset and orientation, and Move and Scale Artwork with Artboard, above the Artboards section with the name, Artboard Options and Fill (#5219); scores and estimates unchanged |
| 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-06 | minor | Shape tools: a press on the selection's centre point (Show Center) moves the selection, also where no art is painted, and a press in the rotate zone just outside a bounding-box corner turns it about the centre, both as the Selection tool's do (#5477); the Selection tool takes its centre point too, so an unfilled shape moves instead of starting a marquee; scores and estimates unchanged |
| 2026-11-06 | minor | Transform fields: one Tab moves from one numeric field to the next in the Transform panel, the Properties panel's Transform section and the Control bar — a field's scrub label was a second, invisible tab stop, and the W/H link between W and H is now made after the fields, so it stays a tab stop after them; scores and estimates unchanged |
| 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: and the Properties panel's Stroke, links to their panels, scrub the field after them as other labels do; a click still opens the panel (#4088); scores and estimates unchanged |
@@ -195,9 +196,9 @@ tools, never checked side by side) isn't captured row by row.
## Headless (RFC-0052)
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 366 unknown.**
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 368 unknown.**
Every parity table on this page has a Headless column: the Summary table (12 area rows, including the overall row) and the behaviour tables (353 rows). Every row is `unknown` until it is checked. A checked row may be marked `no (<reach>)` or `partial (<reach>)` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the row cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:<id>` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows.
Every parity table on this page has a Headless column: the Summary table (12 area rows, including the overall row) and the behaviour tables (356 rows). Every row is `unknown` until it is checked. A checked row may be marked `no (<reach>)` or `partial (<reach>)` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the row cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:<id>` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows.
## Pen, Curvature and anchor tools
@@ -620,6 +621,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | unknown |
| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | unknown |
| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Randomize Fill Colors… picks Colors (Any Color, Tints of a Swatch or Grays), a Swatch among the document's global and spot swatches, Minimum and Maximum (%) and a Seed, with Preview, and gives each selected filled path and compound path, inside groups too, its own fill color at random, one undo step | done | `addon.color.randomFill`, `crates/engine/src/cmd/addons/color/random_fill.rs`, `crates/ui-egui/src/addons/color/random_fill.rs` and their tests; a VectorCraft addition, so it is not scored | unknown |
| Missing linked images and placed documents can show red canvas bounds and a badge; View and Links panel toggles share transient per-document state; command API can set and list markers | done | #5547; `cmd/links.rs`, `link_watch.rs`, `canvas/missing_links.rs`; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass | unknown |
| Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | unknown |
| Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | unknown |
| Style panels: a double-click on a user character style's row opens its Character Style Options, and on a paragraph style's row opens the same Paragraph Style Options as the panel menu, with General, Basic Paragraph Formats, Tabs, Composition, Hyphenation, Justification and East Asian Composition Settings; the Character Style Options dialog keeps a fixed width, its sections scrolling when the window is shorter so OK and Cancel stay on screen | done | `ui.charStyleOptions`, `ui.paraStyleOptions` (`paraStyle.edit`); `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`, `dialogs::para_style_options::tests::every_section_draws_its_fields`, `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` | unknown |
+5 -1
View File
@@ -117,6 +117,9 @@ echo "==> assembling $APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).
cp "$WORK/bin/vectorcraft" "$APP/Contents/MacOS/VectorCraft"
# The CLI too, beside the app: the ArtCraft Launcher finds `vectorcraft-cli` next to the app's
# executable and registers `vectorcraft-cli mcp` for agents.
cp "$WORK/bin/vectorcraft-cli" "$APP/Contents/MacOS/vectorcraft-cli"
cp "$ROOT/assets/app-icon/vectorcraft.icns" "$APP/Contents/Resources/VectorCraft.icns"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@SHORT_VERSION@/$SHORT_VERSION/g" \
-e "s/@BUILD_SHA@/${VECTORCRAFT_BUILD_SHA:-unknown}/g" \
@@ -127,7 +130,8 @@ printf 'APPL????' >"$APP/Contents/PkgInfo"
copy_docs "$APP/Contents/Resources"
# Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature).
# Today the only nested code is the main executable; frameworks/helpers would be signed here too.
# The bundled CLI is nested executable code; sign it before sealing the app bundle.
sign --options runtime --identifier ai.storyteller.vectorcraft-cli "$APP/Contents/MacOS/vectorcraft-cli"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/VectorCraft"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
codesign --verify --strict --deep --verbose=2 "$APP"
+2460 -163
View File
File diff suppressed because it is too large Load Diff