mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
Merge main into fix/trace-preset-bracket-names
This commit is contained in:
Generated
+27
@@ -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",
|
||||
|
||||
@@ -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). |
|
||||
|
||||
@@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`).
|
||||
craft = { workspace = true, features = ["automation-agents"] }
|
||||
|
||||
# `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this
|
||||
# process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT),
|
||||
@@ -52,6 +54,7 @@ serde_json = { workspace = true }
|
||||
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = [
|
||||
"apps/vectorcraft/src/agent_settings.rs",
|
||||
"apps/vectorcraft/src/mac_fonts.rs",
|
||||
"apps/vectorcraft/src/prefs_dir.rs",
|
||||
"apps/vectorcraft/src/profile.rs",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! ```text
|
||||
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent]
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
@@ -39,6 +39,10 @@ macro_rules! out {
|
||||
}};
|
||||
}
|
||||
|
||||
/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the
|
||||
/// closed-app choice and the agent folders the app saved.
|
||||
#[path = "../../vectorcraft/src/agent_settings.rs"]
|
||||
mod agent_settings;
|
||||
/// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "../../vectorcraft/src/mac_fonts.rs"]
|
||||
@@ -56,9 +60,11 @@ mod system_fonts;
|
||||
#[path = "../../vectorcraft/src/windows_cores.rs"]
|
||||
mod windows_cores;
|
||||
|
||||
use craft::automation::agents::WhenAppClosed;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server};
|
||||
use vectorcraft_mcp::agents::{LiveBackend, LiveConfig};
|
||||
use vectorcraft_mcp::{Backend, Headless, Remote, Server};
|
||||
|
||||
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as
|
||||
/// ripgrep does; any other write error is reported.
|
||||
@@ -79,9 +85,18 @@ USAGE:
|
||||
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
|
||||
does not take --connect.
|
||||
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
|
||||
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
|
||||
(vectorcraft --control 7979), falling back to a headless in-process session.
|
||||
vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
|
||||
Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI
|
||||
agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection
|
||||
file the window publishes in the settings folder: no port or token to configure, and an app
|
||||
opened after the session started is found too. Otherwise the call runs in a session without
|
||||
a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI
|
||||
Integrations applies (open VectorCraft, a session without a window in the agent folders, or
|
||||
an error); --when-closed overrides it. Files of the open window's agent requests stay in the
|
||||
agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the
|
||||
agent_folders tool names them. --headless always runs without a window.
|
||||
--connect ADDR (deprecated, removed in a later release) drives an app started with
|
||||
vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN.
|
||||
--automation-read-root / --automation-write-root confine the files the agent's commands read
|
||||
(open, place, relink, library loads…) and write (save, export, package, library saves…) to
|
||||
DIR, links followed; each may be given more than once, a path inside any of its folders being
|
||||
@@ -280,6 +295,20 @@ fn with_stores(mut h: Headless) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed`
|
||||
/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with
|
||||
/// the user's stores, or confined to the agent folders without them.
|
||||
fn live_config(dir: std::path::PathBuf, when_closed: Option<WhenAppClosed>) -> LiveConfig {
|
||||
let mut cfg = LiveConfig::new(dir, agent_settings::read_settings);
|
||||
cfg.when_closed = when_closed;
|
||||
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE));
|
||||
cfg.headless = Box::new(|roots| match roots {
|
||||
Some(roots) => Headless::with_document().with_automation_roots(Some(roots)),
|
||||
None => with_stores(Headless::with_document()),
|
||||
});
|
||||
cfg
|
||||
}
|
||||
|
||||
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
|
||||
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
|
||||
if allow {
|
||||
@@ -288,26 +317,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
|
||||
/// plug-ins, so `--connect` is refused and the default does not connect.
|
||||
/// The stderr line `mcp --connect` prints: the flag works for one more release.
|
||||
const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
|
||||
|
||||
/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's
|
||||
/// switch), found through its connection file on every tool call, otherwise a headless session
|
||||
/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and
|
||||
/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless.
|
||||
/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated).
|
||||
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
|
||||
if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) {
|
||||
return help();
|
||||
}
|
||||
let mut connect: Option<String> = None;
|
||||
let mut headless = false;
|
||||
let mut when_closed: Option<String> = None;
|
||||
let mut allow_grants = false;
|
||||
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
// The roots also come as `--flag=DIR`, as the other Craft apps take them.
|
||||
let (flag, inline) = match a.split_once('=') {
|
||||
Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())),
|
||||
Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())),
|
||||
_ => (a.as_str(), None),
|
||||
};
|
||||
match flag {
|
||||
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
|
||||
"--headless" => headless = true,
|
||||
"--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?),
|
||||
"--allow-plugin-grants" => allow_grants = true,
|
||||
"--automation-read-root" | "--automation-write-root" => {
|
||||
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
@@ -328,6 +365,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if safe_mode && connect.is_some() {
|
||||
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
|
||||
}
|
||||
let when_closed = match when_closed.as_deref() {
|
||||
None => None,
|
||||
Some(choice) => {
|
||||
let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?;
|
||||
if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) {
|
||||
return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into());
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
};
|
||||
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
|
||||
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?;
|
||||
@@ -343,13 +390,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
} else if headless || safe_mode || allow_grants {
|
||||
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
|
||||
} else if let Some(addr) = connect {
|
||||
eprintln!("{CONNECT_DEPRECATED}");
|
||||
// Explicit address: fail loudly if the app isn't there.
|
||||
let token = vectorcraft_mcp::control_token()?;
|
||||
Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
|
||||
} else {
|
||||
// No token or no app listening: the headless session answers instead.
|
||||
match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) {
|
||||
Some(r) => Box::new(r),
|
||||
match prefs_dir::prefs_dir() {
|
||||
Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))),
|
||||
// No settings folder (no home folder): no window can be found either, so `--when-closed error`
|
||||
// refuses rather than answering from a session the agent didn't ask for.
|
||||
None if when_closed == Some(WhenAppClosed::Error) => {
|
||||
return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into());
|
||||
}
|
||||
None => Box::new(with_stores(Headless::with_document())),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() {
|
||||
let r = run_in(&config, &[("pdf.preset.list", json!({}))]);
|
||||
assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true));
|
||||
}
|
||||
|
||||
/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one
|
||||
/// release but says it is deprecated before it connects.
|
||||
#[test]
|
||||
fn mcp_when_closed_and_the_deprecated_connect() {
|
||||
let fails = |args: &[&str], why: &str| {
|
||||
let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
|
||||
err.into_owned()
|
||||
};
|
||||
fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error");
|
||||
fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window");
|
||||
fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window");
|
||||
let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated");
|
||||
assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}");
|
||||
}
|
||||
|
||||
@@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
let pen = host.pointers.borrow().pen();
|
||||
let spec = InstallSpec::new(ShellInfo::current(), Arc::new(SystemWindows)).pen(pen);
|
||||
// The interface faces the page serves are fetched by the stack as text needs them.
|
||||
let fonts = vectorcraft_ui_egui::ui_fonts().fetcher(Arc::new(crate::fonts::BrowserFetcher));
|
||||
let language = taken.borrow().as_ref().map_or_else(i18n::system_lang, VectorcraftApp::ui_language);
|
||||
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, language, Some(Arc::new(crate::fonts::BrowserFetcher)));
|
||||
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
let files = {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder
|
||||
//! (`prefs_dir.rs`). The desktop app writes them when they change (`prefs.agents`); `vectorcraft-cli`
|
||||
//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice
|
||||
//! and the agent folders.
|
||||
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
use craft::automation::agents::AgentSettings;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed",
|
||||
/// "allowAgentControl"}`, the framework's `AgentSettings`.
|
||||
pub const SETTINGS_FILE: &str = "agents.json";
|
||||
|
||||
/// The largest settings file read; the settings are a few short strings.
|
||||
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
|
||||
|
||||
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read,
|
||||
/// so neither the app nor the CLI fails over them. One bad value resets only itself.
|
||||
pub fn read_settings(dir: &Path) -> AgentSettings {
|
||||
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
|
||||
let mut text = String::new();
|
||||
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
|
||||
return AgentSettings::default();
|
||||
}
|
||||
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
|
||||
let mut settings = AgentSettings::default();
|
||||
for (key, value) in saved {
|
||||
let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue };
|
||||
if one.contains_key(&key) {
|
||||
one.insert(key, value);
|
||||
if let Ok(next) = serde_json::from_value(Value::Object(one)) {
|
||||
settings = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a
|
||||
/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
|
||||
// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them.
|
||||
#[allow(dead_code)]
|
||||
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
|
||||
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
|
||||
std::fs::write(&partial, text)?;
|
||||
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&partial);
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft::automation::agents::WhenAppClosed;
|
||||
|
||||
// Settings saved by the app read back in the CLI, and a damaged file or value never fails it.
|
||||
#[test]
|
||||
fn saved_settings_read_back_and_bad_values_reset_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(read_settings(dir.path()), AgentSettings::default());
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.read_root = "/in".into();
|
||||
settings.when_app_closed = WhenAppClosed::Headless;
|
||||
write_settings(dir.path(), &settings).unwrap();
|
||||
assert_eq!(read_settings(dir.path()), settings);
|
||||
std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap();
|
||||
assert_eq!(read_settings(dir.path()), AgentSettings::default());
|
||||
std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap();
|
||||
let read = read_settings(dir.path());
|
||||
assert_eq!(read.when_app_closed, WhenAppClosed::Error);
|
||||
assert_eq!(read.read_root, "");
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
//! how the window's frames reach the display (`presentation`).
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod agent_settings;
|
||||
mod automation_args;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
@@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<Stri
|
||||
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
|
||||
}
|
||||
|
||||
/// Agents in the open window (`vectorcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
|
||||
/// names VectorCraft, the window serves agents on loopback and publishes the connection in its
|
||||
/// settings folder, where `vectorcraft-cli mcp` finds it. A connection file a crashed run left is
|
||||
/// removed first. With `--control` (`control_port`, served by `launched`) that channel serves the
|
||||
/// whole run and the link stays off. A nightly and a run without preferences have no link.
|
||||
fn agents_link(ctx: &egui::Context, control_port: Option<u16>, launched: Option<&Listening>) -> Option<vectorcraft_ui_egui::agents::Agents> {
|
||||
use craft::automation::agents::{AgentSwitch, remove_stale_connection};
|
||||
use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn};
|
||||
let dir = prefs_dir::prefs_dir()?;
|
||||
remove_stale_connection(&dir);
|
||||
let switch = AgentSwitch::watch(LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
});
|
||||
let save_dir = dir.clone();
|
||||
let save: SaveFn = Box::new(move |settings| {
|
||||
agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display()))
|
||||
});
|
||||
let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION"));
|
||||
let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save);
|
||||
// The port it listens on (the one the system picked for `--control 0`), none when it couldn't.
|
||||
Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents })
|
||||
}
|
||||
|
||||
/// The control channel's port, and the token's notice with the token itself.
|
||||
type ControlChannel = (Option<u16>, Option<(String, String)>);
|
||||
|
||||
@@ -857,8 +882,6 @@ fn main() -> std::process::ExitCode {
|
||||
Some(pen) => spec.pen(pen),
|
||||
None => spec,
|
||||
};
|
||||
embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
let folders = settings.lock().get().ui.last_folders.clone();
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
@@ -875,7 +898,6 @@ fn main() -> std::process::ExitCode {
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.files(files.clone())
|
||||
.build();
|
||||
host.clone().install(ctx);
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
@@ -900,12 +922,16 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_proof_setups(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
|
||||
load_prefs(&mut app, &settings);
|
||||
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None);
|
||||
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
host.clone().install(ctx);
|
||||
app.host = Arc::new(host);
|
||||
app.adopt_context(&cc.egui_ctx);
|
||||
// A nightly is updated by the Launcher: it never checks for a stable release, which
|
||||
// would install this program's own updater over the nightly build.
|
||||
app.set_startup_update_check(!nightly);
|
||||
load_prefs(&mut app, &settings);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// Loads started later (a preference change, the end of Safe Mode) are waited for,
|
||||
// after the launch's own.
|
||||
@@ -1048,6 +1074,12 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !nightly
|
||||
&& prefs_enabled()
|
||||
&& let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref())
|
||||
{
|
||||
app = app.with_agents(agents);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
open_documents::set_ui(&cc.egui_ctx);
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -903,7 +903,7 @@ pub struct SymbolOptions {
|
||||
|
||||
impl SymbolOptions {
|
||||
/// The options `d` keeps for symbol `name`.
|
||||
fn of(d: &Document, name: &str) -> Self {
|
||||
pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self {
|
||||
Self {
|
||||
size: stored_natural_size(d, name),
|
||||
registration: d.symbol_registration(name),
|
||||
@@ -914,7 +914,7 @@ impl SymbolOptions {
|
||||
}
|
||||
|
||||
/// Make them the options of `d`'s symbol `name`.
|
||||
fn give(&self, d: &mut Document, name: &str) {
|
||||
pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) {
|
||||
set_natural_size(d, name, self.size);
|
||||
d.set_symbol_registration(name, self.registration);
|
||||
d.set_symbol_export_type(name, self.export_type);
|
||||
|
||||
@@ -10,9 +10,12 @@
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::fileio::{read_file_head, write_file};
|
||||
@@ -77,6 +80,166 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Every stored family name, including regeneration settings and retained style defaults.
|
||||
/// Planning reads a private clone so gathering names never changes the destination.
|
||||
fn family_names(d: &Document) -> Result<BTreeSet<String>> {
|
||||
let mut view = d.clone();
|
||||
let mut names = BTreeSet::new();
|
||||
let mut note = |family: &mut String| {
|
||||
names.insert(family.to_lowercase());
|
||||
};
|
||||
super::textstyles::each_text_mut(&mut view, &mut |text| {
|
||||
for run in &mut text.runs {
|
||||
note(&mut run.style.font_family);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) {
|
||||
if let Some(Value::String(family)) = style.attrs.get_mut("font_family") {
|
||||
note(family);
|
||||
}
|
||||
}
|
||||
let mut graphs = Vec::new();
|
||||
view.visit_stored(|node, _| {
|
||||
if node.extras().graph.is_some() {
|
||||
graphs.push(node.id);
|
||||
}
|
||||
});
|
||||
for id in graphs {
|
||||
if let Some(node) = view.stored_node_mut(id) {
|
||||
graph_families(node, &mut note);
|
||||
}
|
||||
}
|
||||
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
|
||||
graph_families(node, note);
|
||||
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
|
||||
brush_graphs(Arc::make_mut(&mut mask.art), note);
|
||||
}
|
||||
for child in node.children_mut().into_iter().flatten() {
|
||||
brush_graphs(Arc::make_mut(child), note);
|
||||
}
|
||||
}
|
||||
for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) {
|
||||
brush_graphs(art, &mut note);
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) {
|
||||
let labels = &mut graph.label_styles;
|
||||
for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() {
|
||||
visit(&mut style.font_family);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Family fields held directly by one node; the adoption walker owns tree/resource traversal.
|
||||
pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
for run in &mut text.runs {
|
||||
visit(&mut run.style.font_family);
|
||||
}
|
||||
}
|
||||
graph_families(node, visit);
|
||||
}
|
||||
|
||||
/// A fully checked incoming-only rename map and the destination's prospective definitions.
|
||||
pub(super) struct CompositeImport {
|
||||
names: BTreeMap<String, String>,
|
||||
pub(super) combined: Vec<CompositeFont>,
|
||||
}
|
||||
|
||||
impl CompositeImport {
|
||||
pub(super) fn rename(&self, family: &mut String) -> bool {
|
||||
if let Some(name) = self.names.get(&family.to_lowercase()) {
|
||||
let changed = family.as_str() != name.as_str();
|
||||
*family = name.clone();
|
||||
changed
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
|
||||
let db = FontDb::global();
|
||||
let mut number = 2_u64;
|
||||
loop {
|
||||
let suffix = format!(" {number}");
|
||||
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
|
||||
let name = format!("{}{suffix}", stem.trim_end());
|
||||
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
|
||||
&& !reserved.contains(&name.to_lowercase())
|
||||
&& !db.has_installed_family(&name)
|
||||
{
|
||||
return Ok(name);
|
||||
}
|
||||
number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Plan used incoming definitions before changing either document or the font database.
|
||||
/// Keep existing meanings even for an uninstalled family that destination art still names.
|
||||
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
|
||||
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
let mut source_names = BTreeSet::new();
|
||||
for font in &source {
|
||||
font.check().map_err(|why| bad(cmd, why))?;
|
||||
if !source_names.insert(font.name.to_lowercase()) {
|
||||
return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name)));
|
||||
}
|
||||
}
|
||||
let target_families = family_names(target)?;
|
||||
let mut target_taken = target_families.clone();
|
||||
for font in target.composite_fonts.iter() {
|
||||
target_taken.insert(font.name.to_lowercase());
|
||||
target_taken.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let mut reserved = source_families;
|
||||
reserved.extend(target_families);
|
||||
for font in source.iter().chain(target.composite_fonts.iter()) {
|
||||
reserved.insert(font.name.to_lowercase());
|
||||
reserved.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let db = FontDb::global();
|
||||
let mut names = BTreeMap::new();
|
||||
let mut combined = target.composite_fonts.to_vec();
|
||||
for font in source {
|
||||
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
|
||||
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
|
||||
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
|
||||
if needs_alias {
|
||||
// A repeated import reuses its already-installed equal alias.
|
||||
reused = target.composite_fonts.iter().find(equivalent);
|
||||
}
|
||||
let name = match reused {
|
||||
Some(other) => other.name.clone(),
|
||||
None if needs_alias => composite_alias(&font.name, &reserved, cmd)?,
|
||||
None => font.name.clone(),
|
||||
};
|
||||
reserved.insert(name.to_lowercase());
|
||||
names.insert(font.name.to_lowercase(), name.clone());
|
||||
if reused.is_none() {
|
||||
combined.push(CompositeFont { name, ..font });
|
||||
}
|
||||
}
|
||||
// A source document may currently lend fonts to the database. Validate the prospective
|
||||
// document, not composite names temporarily registered by a different document.
|
||||
if combined.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) {
|
||||
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
|
||||
}
|
||||
if CompositeFont::usable(&combined).is_some() {
|
||||
return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together"));
|
||||
}
|
||||
Ok(CompositeImport { names, combined })
|
||||
}
|
||||
|
||||
/// Register the active document's composite fonts in the font database, and remove the ones the
|
||||
/// other open documents (or an earlier active document) defined. Run after each command and when
|
||||
/// another document takes the front, so an undo, a revert, an opened or closed file or a document
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy (a move by 0 changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with rounded Live Corners, each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target; refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it",
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with rounded Live Corners, the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y)",
|
||||
has_doc,
|
||||
move_anchor
|
||||
),
|
||||
@@ -176,6 +176,118 @@ pub(super) fn path_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
/// Transform `anchors` of path `id` by `xf` when the path has cut Live Corners: the anchors of its
|
||||
/// uncut outline move (with `interpolate` and a move, as [`move_interpolating_handles`] moves
|
||||
/// them) and the corners are cut again with the same radii, so they stay live
|
||||
/// ([`vectorcraft_doc::edit_corner_anchors`]). Returns `None`, changing nothing, for a path
|
||||
/// without cut corners.
|
||||
fn transform_live_corner_anchors(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
id: NodeId,
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
interpolate: bool,
|
||||
) -> Option<()> {
|
||||
let NodeKind::Path { path, live, .. } = &mut d.node_mut(id)?.kind else { return None };
|
||||
let c = xf.as_coeffs();
|
||||
vectorcraft_doc::edit_corner_anchors(path, live, anchors, |base, set| {
|
||||
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
move_interpolating_handles(base, set, Vec2::new(c[4], c[5]));
|
||||
} else {
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = base.anchor_mut(si, ai) {
|
||||
*a = a.transform(xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// For each anchor of path `id` as drawn (per subpath), the anchor of its uncut outline it comes
|
||||
/// from ([`vectorcraft_doc::LiveCorners::sources`]), or `None` when `id` is not a path.
|
||||
fn corner_sources(d: &Document, id: NodeId) -> Option<Vec<Vec<usize>>> {
|
||||
let NodeKind::Path { path, live, .. } = &d.node(id)?.kind else { return None };
|
||||
Some(vectorcraft_doc::LiveCorners::new(path, live.as_deref())?.sources().to_vec())
|
||||
}
|
||||
|
||||
/// After the anchors of path `id` as drawn changed from `before` to `after` (each listing the
|
||||
/// corners they come from, as [`corner_sources`] gives them), point the selected anchors and the
|
||||
/// key anchor of `sel` on that path at the anchors of the same corners, and drop the path's
|
||||
/// selected segments. An unchanged layout leaves `sel` as it is.
|
||||
fn remap_corner_anchors(sel: &mut Selection, id: NodeId, before: &[Vec<usize>], after: &[Vec<usize>]) {
|
||||
if before == after {
|
||||
return;
|
||||
}
|
||||
let source = |(si, ai): AnchorRef| before.get(si).and_then(|v| v.get(ai)).copied();
|
||||
let drawn =
|
||||
|k: usize| after.iter().enumerate().flat_map(move |(si, v)| v.iter().enumerate().filter(move |(_, s)| **s == k).map(move |(ai, _)| (si, ai)));
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
let corners: BTreeSet<usize> = set.iter().filter_map(|r| source(*r)).collect();
|
||||
*set = corners.into_iter().flat_map(drawn).collect();
|
||||
}
|
||||
if let Some((key, r)) = sel.key_anchor
|
||||
&& key == id
|
||||
{
|
||||
sel.key_anchor = source(r).and_then(|k| drawn(k).next()).map(|r| (id, r));
|
||||
}
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
|
||||
/// Snap pixel-aligned path `id`, or the pixel-aligned compound path that holds it, to the pixel
|
||||
/// grid again, with `sel` following its anchors when the snap cuts its Live Corners again with a
|
||||
/// different layout ([`remap_corner_anchors`]).
|
||||
fn snap_keeping_selection(d: &mut Document, id: NodeId, sel: &mut Selection, before: Option<&[Vec<usize>]>) {
|
||||
let top = compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
if let (Some(before), Some(after)) = (before, corner_sources(d, id)) {
|
||||
remap_corner_anchors(sel, id, before, &after);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `apply` on a copy of the active document, followed by the pixel-grid snap that
|
||||
/// [`Session::edit`] makes, leaves the document as it was (a nudge that the snap of a
|
||||
/// pixel-aligned path takes back). Without a pixel-aligned path among `ids` (or a compound path
|
||||
/// holding one) the answer is `false` without trying. An anchor edit turns a live rectangle or
|
||||
/// polygon into a live path with the same outline, radii and kinds; that conversion alone counts
|
||||
/// as no change, while any change to the uncut outline or the corner settings still counts.
|
||||
fn snap_undoes(s: &Session, ids: impl IntoIterator<Item = NodeId>, apply: impl FnOnce(&mut Document, &mut Selection) -> Result<()>) -> Result<bool> {
|
||||
let st = s.doc()?;
|
||||
let ids: Vec<NodeId> = ids.into_iter().collect();
|
||||
if !ids.iter().any(|&id| st.doc.node(compound_or_self(&st.doc, id)).is_some_and(|n| n.extras().pixel_aligned)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut doc = (*st.doc).clone();
|
||||
let mut sel = st.selection.clone();
|
||||
apply(&mut doc, &mut sel)?;
|
||||
super::refresh_pixel_aligned(&st.doc, &mut doc);
|
||||
for &id in &ids {
|
||||
let (Some(NodeKind::Path { path, live, .. }), Some(anchors)) = (st.doc.node(id).map(|n| &n.kind), st.selection.anchors.get(&id)) else {
|
||||
continue;
|
||||
};
|
||||
// A live path keeps its variant through an anchor edit, so only a rectangle or polygon
|
||||
// needs the comparison below.
|
||||
if !matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Rectangle { .. } | vectorcraft_doc::LiveShape::Polygon { .. })) {
|
||||
continue;
|
||||
}
|
||||
// The path and live shape the same anchors, left where they are, would turn this path
|
||||
// into. The drawn path is cut from the live shape, and a recut can differ from the stored
|
||||
// path by rounding, so the live shapes are compared and both fields are restored.
|
||||
let (mut converted_path, mut converted) = (path.clone(), live.clone());
|
||||
if vectorcraft_doc::edit_corner_anchors(&mut converted_path, &mut converted, anchors, |_, _| {}).is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some(NodeKind::Path { path: after_path, live: after, .. }) = doc.node_mut(id).map(|n| &mut n.kind)
|
||||
&& *after == converted
|
||||
{
|
||||
after.clone_from(live);
|
||||
after_path.clone_from(path);
|
||||
}
|
||||
}
|
||||
Ok(doc == *st.doc)
|
||||
}
|
||||
|
||||
fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "path.appendAnchor")?.ok_or_else(|| bad("path.appendAnchor", "missing id"))?;
|
||||
let a = anchor_from_json(p, "path.appendAnchor")?;
|
||||
@@ -278,6 +390,13 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut sel = st.selection.clone();
|
||||
let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) };
|
||||
// A path with a curved segment that bends or holds its anchors is edited anchor by anchor, so
|
||||
// the segment indices found above stay valid.
|
||||
let plain: BTreeSet<NodeId> = bends
|
||||
.iter()
|
||||
.map(|b| b.0)
|
||||
.chain(sel.anchors.iter().filter(|(id, set)| st.selection.anchors.get(id) != Some(*set)).map(|(id, _)| *id))
|
||||
.collect();
|
||||
// Segments that hold their anchors and don't bend, with nothing else to move, change nothing.
|
||||
if held && bends.is_empty() && sel.whole().is_empty() && sel.guides.is_empty() && sel.anchors.values().all(BTreeSet::is_empty) {
|
||||
return ok();
|
||||
@@ -286,15 +405,21 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
|
||||
// `patterns` (default: General › Transform Pattern Tiles) is on.
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &sel.whole())?, ..Scaling::default() };
|
||||
let interpolate = interpolates_handles(s, p, C)?;
|
||||
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, |doc, _| {
|
||||
transform_selected(doc, &sel, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
let apply = |doc: &mut Document, live: &mut Selection| -> Result<()> {
|
||||
transform_selected(doc, &sel, live, &plain, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
for &(id, si, seg) in &bends {
|
||||
if let Some(sp) = path_mut(doc, id)?.subpaths.get_mut(si) {
|
||||
sp.nudge_segment(seg, d);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
};
|
||||
// Anchors and objects selected whole that the pixel-grid snap puts back where they were change
|
||||
// nothing, and record no undo step.
|
||||
if sel.guides.is_empty() && snap_undoes(s, sel.anchors.keys().copied().chain(sel.whole()), apply)? {
|
||||
return ok();
|
||||
}
|
||||
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, apply)?;
|
||||
// Transform Again repeats a move that moved something; a drag records it when it commits. A
|
||||
// move that held segments' anchors is not one move of the selection.
|
||||
let st = s.doc_mut()?;
|
||||
@@ -350,7 +475,7 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
s.edit(label, |doc, live| {
|
||||
transform_selected(doc, &sel, xf, sc, interpolate)?;
|
||||
transform_selected(doc, &sel, live, &BTreeSet::new(), xf, sc, interpolate)?;
|
||||
Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) })
|
||||
})
|
||||
}
|
||||
@@ -359,14 +484,32 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
/// objects selected whole (those with no entry in `sel`'s `anchors`). An object inside
|
||||
/// another selected object, such as a path in a selected group, moves once, with that object.
|
||||
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
|
||||
/// are re-mapped ([`move_interpolating_handles`]).
|
||||
fn transform_selected(doc: &mut Document, sel: &Selection, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
/// are re-mapped ([`move_interpolating_handles`]). A path with rounded Live Corners keeps them
|
||||
/// ([`transform_live_corner_anchors`]), and `live_sel` follows its anchors when the recut changes
|
||||
/// them, except for the paths in `plain`, which are edited anchor by anchor.
|
||||
fn transform_selected(
|
||||
doc: &mut Document,
|
||||
sel: &Selection,
|
||||
live_sel: &mut Selection,
|
||||
plain: &BTreeSet<NodeId>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
sc: Scaling,
|
||||
interpolate: bool,
|
||||
) -> Result<()> {
|
||||
let ids = super::edit::outermost(doc, sel.objects.clone());
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
let delta = vectorcraft_geom::Vec2::new(c[4], c[5]);
|
||||
for id in &ids {
|
||||
match sel.anchors.get(id) {
|
||||
Some(set)
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0]
|
||||
&& !plain.contains(id)
|
||||
&& let Some(before) = corner_sources(doc, *id)
|
||||
&& transform_live_corner_anchors(doc, *id, set, xf, interpolate).is_some() =>
|
||||
{
|
||||
snap_keeping_selection(doc, *id, live_sel, Some(&before));
|
||||
}
|
||||
Some(set) => {
|
||||
let path = path_mut(doc, *id)?;
|
||||
// Only an exact move takes the interpolating path: a near-identity scale or
|
||||
@@ -798,16 +941,19 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return ok();
|
||||
}
|
||||
s.edit("Move", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps to the
|
||||
// pixel grid again.
|
||||
let top = compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
s.edit("Move", |d, sel| {
|
||||
let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p);
|
||||
let before = corner_sources(d, id);
|
||||
let moved = BTreeSet::from([(si, ai)]);
|
||||
let kept = old.and_then(|p0| transform_live_corner_anchors(d, id, &moved, vectorcraft_geom::Affine::translate(pos - p0), false));
|
||||
if kept.is_none() {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
}
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps to the
|
||||
// pixel grid again, and the selection follows a path whose corners were cut again.
|
||||
snap_keeping_selection(d, id, sel, kept.and(before.as_deref()));
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -578,7 +578,7 @@ fn art_of<'a>(nodes: impl Iterator<Item = &'a Arc<Node>>) -> Vec<Node> {
|
||||
}
|
||||
|
||||
/// The art as one object of `d` (its resources added), at its natural size and position.
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Result<Node> {
|
||||
let mut node = match l.art {
|
||||
Art::Image(img, clip) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
@@ -613,7 +613,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))),
|
||||
Art::Document(s, link, bounding) => document::node(d, &s, link, bounding),
|
||||
Art::Vector { src, mut nodes, clip } => {
|
||||
adopt::adopt(d, &src, &mut nodes);
|
||||
adopt::adopt(d, &src, &mut nodes, PLACE)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = clip {
|
||||
children.insert(0, Arc::new(clip_path(d.alloc_id(), r)));
|
||||
@@ -622,7 +622,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
}
|
||||
};
|
||||
node.name = Some(l.name);
|
||||
node
|
||||
Ok(node)
|
||||
}
|
||||
|
||||
/// `node` moved and scaled by `m` as a whole: strokes, effects and pattern tiles go along.
|
||||
@@ -817,22 +817,86 @@ impl Session {
|
||||
if self.doc()?.uid != read.job.doc {
|
||||
return Err(bad(PLACE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
// Deleted, changed, or another object with its id: an undo that removes the object frees
|
||||
// its id for the next object made.
|
||||
if st.doc.node(old) != read.job.replaced.as_ref() {
|
||||
// Keep the asynchronous target check against the drawing currently on show.
|
||||
if self.doc()?.doc.node(old) != read.job.replaced.as_ref() {
|
||||
return Err(bad(PLACE, "replace: the object to replace was changed or deleted"));
|
||||
}
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
// Provisional reselection and placement are one outside command. Deferring their
|
||||
// notifications must not make an asynchronous handoff part of an unrelated tool drag.
|
||||
if self.depth == 0 && !self.previewing && !self.in_tool_actions {
|
||||
self.command_with_settled_warnings(|s| s.outside_interaction(PLACE, ¶ms, |s| s.place_read_handoff(read, ¶ms)))
|
||||
} else {
|
||||
self.place_read_handoff(read, ¶ms)
|
||||
}
|
||||
}
|
||||
|
||||
fn place_read_handoff(&mut self, read: PlaceRead, params: &Value) -> Result<Value> {
|
||||
let mut rollback = None;
|
||||
let mut reselect = None;
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
if st.selection.objects != [old] || st.selection.symbol_part.is_some() {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
// Adoption may now fail. Its provisional selection must not escape that error.
|
||||
rollback = Some((
|
||||
self.active,
|
||||
st.clone(),
|
||||
self.paint.clone(),
|
||||
self.fill_active,
|
||||
self.pending_paint.clone(),
|
||||
self.active_appearance_item.clone(),
|
||||
self.batch_paint_docs.clone(),
|
||||
self.journal.len(),
|
||||
self.journal.held(),
|
||||
));
|
||||
self.journal.hold(Some(self.journal.first_kept()));
|
||||
reselect = Some(old);
|
||||
}
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
let r = self.execute(PLACE, ¶ms);
|
||||
let outer_tool_actions = self.in_tool_actions;
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = true;
|
||||
}
|
||||
let result = (|| {
|
||||
if let Some(old) = reselect {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
self.execute(PLACE, params)
|
||||
})();
|
||||
self.place_hand_off = None;
|
||||
r
|
||||
if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback {
|
||||
if result.is_err() {
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == before.uid) {
|
||||
let revision = st.revision.max(before.revision);
|
||||
*st = before;
|
||||
st.revision = revision + 1;
|
||||
}
|
||||
self.active = active;
|
||||
self.paint = paint;
|
||||
self.fill_active = fill_active;
|
||||
self.pending_paint = pending;
|
||||
self.active_appearance_item = appearance;
|
||||
self.batch_paint_docs = paint_docs;
|
||||
self.journal.truncate(journal);
|
||||
for group in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) {
|
||||
group.journal.retain(|&(n, _)| n < journal);
|
||||
group.steps.retain(|&(n, _)| n < journal);
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
self.sync_front_profiles();
|
||||
super::compositefonts::sync(self);
|
||||
}
|
||||
self.journal.hold(held);
|
||||
}
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = outer_tool_actions;
|
||||
self.after_command(result.is_ok().then_some(PLACE));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,7 +1062,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let mut node = transformed(build(d, loaded, link), m);
|
||||
let mut node = transformed(build(d, loaded, link)?, m);
|
||||
if let Some((old_image, (_, q, _))) = distorted {
|
||||
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
|
||||
}
|
||||
@@ -1266,7 +1330,7 @@ fn thumbnail_png(l: Loaded, px: f64) -> Result<String> {
|
||||
let natural = l.natural;
|
||||
let mut d = Document::new(natural.width().max(1.0), natural.height().max(1.0));
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
let node = build(&mut d, l, None);
|
||||
let node = build(&mut d, l, None)?;
|
||||
d.insert(layer, 0, node)?;
|
||||
let k = px.clamp(1.0, MAX_THUMBNAIL) / natural.width().max(natural.height()).max(1e-9);
|
||||
let png = vectorcraft_render::Renderer::new().render_region(&d, natural, k, false).to_png().map_err(EngineError::Other)?;
|
||||
|
||||
@@ -5,13 +5,16 @@
|
||||
//! defines differently keeps its colour, unlinked. Text styles are left as they are: the art carries
|
||||
//! its own formatting.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::super::Result;
|
||||
use super::super::clipboard::SymbolOptions;
|
||||
use super::super::compositefonts::{CompositeImport, node_families, plan_import};
|
||||
use super::unique_name;
|
||||
|
||||
/// Visit `n` and every descendant (children and opacity-mask art) mutably.
|
||||
@@ -52,9 +55,56 @@ fn paint_refs(p: &mut Paint, f: &mut impl FnMut(Ref)) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Visit only the records the shared reader accepted, in their original order. Consuming
|
||||
/// each accepted record once also leaves ignored duplicate surfaces and capped records alone.
|
||||
fn accepted_graphic_refs<T: PartialEq>(
|
||||
list: &mut serde_json::Value,
|
||||
accepted: Vec<T>,
|
||||
parse: impl Fn(&serde_json::Value) -> Option<T>,
|
||||
f: &mut impl FnMut(Ref),
|
||||
) {
|
||||
let Some(list) = list.as_array_mut() else { return };
|
||||
let mut accepted = accepted.into_iter().peekable();
|
||||
for value in list {
|
||||
let Some(next) = accepted.peek() else { break };
|
||||
if parse(value).as_ref() != Some(next) {
|
||||
continue;
|
||||
}
|
||||
let _ = accepted.next();
|
||||
if let Some(serde_json::Value::String(symbol)) = value.get_mut("symbol") {
|
||||
f(Ref::Symbol(symbol));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol references in accepted Graphics and Map Art records, including fill/stroke effects.
|
||||
/// Each stored name is visited once, so a rename cannot feed a second rename in the same map.
|
||||
fn appearance_graphic_refs(appearance: &mut vectorcraft_doc::Appearance, f: &mut impl FnMut(Ref)) {
|
||||
use vectorcraft_render::effects as fx;
|
||||
|
||||
if fx::appearance_graphic_symbols(appearance).is_empty() {
|
||||
return;
|
||||
}
|
||||
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
|
||||
for effect in effects.iter_mut().chain(items.iter_mut().flat_map(|item| item.effects_mut())) {
|
||||
if fx::takes_graphics(&effect.id) {
|
||||
let accepted = fx::mapped_graphics(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::GRAPHICS) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::MappedGraphic::from_value(value).ok(), f);
|
||||
}
|
||||
} else if fx::takes_map_art(&effect.id) {
|
||||
let accepted = fx::surface_maps(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::MAP_ART) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::SurfaceMap::from_value(value).ok(), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every resource reference in `n` and its descendants.
|
||||
fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
each_mut(n, &mut |n| {
|
||||
appearance_graphic_refs(&mut n.appearance, f);
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(fl) => paint_refs(&mut fl.paint, f),
|
||||
@@ -71,6 +121,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
for r in &mut t.runs {
|
||||
paint_refs(&mut r.style.fill, f);
|
||||
paint_refs(&mut r.style.stroke, f);
|
||||
if let Some(inline) = &mut r.inline {
|
||||
f(Ref::Symbol(&mut inline.symbol));
|
||||
}
|
||||
}
|
||||
if let Some(fonts) = &mut t.file_fonts {
|
||||
fonts.map_keys(|key| f(Ref::Image(key)));
|
||||
@@ -81,6 +134,14 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(extras) = n.extras_if_any() {
|
||||
extras
|
||||
.symbol_overrides
|
||||
.iter_mut()
|
||||
.flat_map(|override_| [&mut override_.fill, &mut override_.stroke])
|
||||
.flatten()
|
||||
.for_each(|paint| paint_refs(paint, f));
|
||||
}
|
||||
// A color-masked image's masked pixels come along, and the key they were made from
|
||||
// follows the image's.
|
||||
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
|
||||
@@ -162,7 +223,16 @@ fn canon(dst: &Document, n: &Node) -> Node {
|
||||
own.images.insert(k.clone(), blob.clone());
|
||||
}
|
||||
}
|
||||
own.reid(n)
|
||||
let mut canonical = own.reid(n);
|
||||
// Derived layout caches do not define the stored art's resource identity.
|
||||
each_mut(&mut canonical, &mut |node| {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
text.cached_bounds = None;
|
||||
text.cached_baselines.clear();
|
||||
text.cached_ink = None;
|
||||
}
|
||||
});
|
||||
canonical
|
||||
}
|
||||
|
||||
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
@@ -220,12 +290,273 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
/// Apply the final resource-name plan to one incoming reference.
|
||||
fn rename_ref(r: Ref<'_>, maps: [&Renames; 5]) {
|
||||
let (map, key) = match r {
|
||||
Ref::Image(key) => (maps[0], key),
|
||||
Ref::Symbol(key) => (maps[1], key),
|
||||
Ref::Pattern(key) => (maps[2], key),
|
||||
Ref::Brush(key) => (maps[3], key),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|key| maps[4].get(key)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(key.as_str()) {
|
||||
*key = new.clone();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum ResourceKind {
|
||||
Symbol,
|
||||
Pattern,
|
||||
Brush,
|
||||
}
|
||||
|
||||
type ResourceKey = (ResourceKind, String);
|
||||
|
||||
/// A source definition's dependencies whose planned names have not been finalized yet.
|
||||
fn pending_dependencies(key: &ResourceKey, src: &Document, brushes: &[Brush], pending: &BTreeSet<ResourceKey>) -> BTreeSet<ResourceKey> {
|
||||
let mut dependencies = BTreeSet::new();
|
||||
let mut note = |r: Ref<'_>| {
|
||||
let key = match r {
|
||||
Ref::Symbol(name) => (ResourceKind::Symbol, name.clone()),
|
||||
Ref::Pattern(name) => (ResourceKind::Pattern, name.clone()),
|
||||
Ref::Brush(name) => (ResourceKind::Brush, name.clone()),
|
||||
Ref::Image(_) | Ref::Swatch(_) => return,
|
||||
};
|
||||
if pending.contains(&key) {
|
||||
dependencies.insert(key);
|
||||
}
|
||||
};
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
if let Some(symbol) = src.symbols.iter().find(|symbol| symbol.name == key.1) {
|
||||
refs(&mut (*symbol.art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
if let Some(pattern) = src.pattern(&key.1) {
|
||||
for art in &pattern.art {
|
||||
refs(&mut (**art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
if let Some(mut brush) = brushes.iter().find(|brush| brush.name == key.1).cloned() {
|
||||
for art in brush_art(&mut brush) {
|
||||
refs(art, &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dependencies
|
||||
}
|
||||
|
||||
/// Prefer the original name, then only canonical numbered variants from `unique_name`.
|
||||
/// A free original name keeps its planned copy; another incoming name is never stolen.
|
||||
fn matching_name<T>(base: &str, definitions: &[T], used: &[String], name: impl Fn(&T) -> &str, same: impl Fn(&T) -> bool) -> Option<String> {
|
||||
let original = definitions.iter().find(|definition| name(definition) == base)?;
|
||||
if same(original) {
|
||||
return Some(base.to_string());
|
||||
}
|
||||
let prefix = format!("{base} ");
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut aliases: Vec<_> = definitions
|
||||
.iter()
|
||||
.filter_map(|definition| {
|
||||
let candidate = name(definition);
|
||||
// Match the first definition, as the document name lookups do.
|
||||
if !seen.insert(candidate.to_string()) {
|
||||
return None;
|
||||
}
|
||||
let suffix = candidate.strip_prefix(&prefix)?;
|
||||
if suffix.starts_with('0') || !suffix.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let number = suffix.parse::<u64>().ok()?;
|
||||
(number >= 2 && !used.iter().any(|used| used == candidate)).then_some((number, definition))
|
||||
})
|
||||
.collect();
|
||||
aliases.sort_unstable_by_key(|(number, _)| *number);
|
||||
aliases.into_iter().find_map(|(_, definition)| same(definition).then(|| name(definition).to_string()))
|
||||
}
|
||||
|
||||
/// Compare final incoming content, not the original references or destination's resource name.
|
||||
fn reusable_name(
|
||||
key: &ResourceKey,
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
maps: [&Renames; 5],
|
||||
) -> Option<String> {
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?;
|
||||
let mut incoming = source.clone();
|
||||
refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps));
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.symbols,
|
||||
&used.symbols,
|
||||
|symbol| &symbol.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_symbol(dst, &normalized, &incoming) && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
let mut incoming = src.pattern(&key.1)?.clone();
|
||||
for art in &mut incoming.art {
|
||||
refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps));
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.patterns,
|
||||
&used.patterns,
|
||||
|pattern| &pattern.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_pattern(dst, &normalized, &incoming)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone();
|
||||
for art in brush_art(&mut incoming) {
|
||||
refs(art, &mut |r| rename_ref(r, maps));
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
dst_brushes,
|
||||
&used.brushes,
|
||||
|brush| &brush.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
for art in brush_art(&mut normalized) {
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
normalized == incoming
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalize each copied definition only after its copied dependencies. Each key/edge is
|
||||
/// processed once; a cycle (and its unresolved parents) conservatively keeps the planned copies.
|
||||
fn reuse_remapped_resources(
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
fixed: [&Renames; 2],
|
||||
changing: [&mut Renames; 3],
|
||||
) {
|
||||
let [symbols, patterns, brushes] = changing;
|
||||
let mut pending = BTreeSet::new();
|
||||
for (kind, map) in [(ResourceKind::Symbol, &*symbols), (ResourceKind::Pattern, &*patterns), (ResourceKind::Brush, &*brushes)] {
|
||||
pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone())));
|
||||
}
|
||||
let mut waiting = BTreeMap::new();
|
||||
let mut parents: BTreeMap<ResourceKey, Vec<ResourceKey>> = BTreeMap::new();
|
||||
let mut ready = BTreeSet::new();
|
||||
for key in &pending {
|
||||
let dependencies = pending_dependencies(key, src, src_brushes, &pending);
|
||||
if dependencies.is_empty() {
|
||||
ready.insert(key.clone());
|
||||
}
|
||||
waiting.insert(key.clone(), dependencies.len());
|
||||
for dependency in dependencies {
|
||||
parents.entry(dependency).or_default().push(key.clone());
|
||||
}
|
||||
}
|
||||
while let Some(key) = ready.pop_first() {
|
||||
let maps = [fixed[0], &*symbols, &*patterns, &*brushes, fixed[1]];
|
||||
if let Some(name) = reusable_name(&key, dst, src, src_brushes, dst_brushes, used, maps) {
|
||||
let map = match key.0 {
|
||||
ResourceKind::Symbol => &mut *symbols,
|
||||
ResourceKind::Pattern => &mut *patterns,
|
||||
ResourceKind::Brush => &mut *brushes,
|
||||
};
|
||||
map.insert(key.1.clone(), (Some(name), false));
|
||||
}
|
||||
for parent in parents.remove(&key).into_iter().flatten() {
|
||||
if let Some(count) = waiting.get_mut(&parent) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
ready.insert(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap only incoming users before resource equality decides whether to share or copy.
|
||||
/// Report actual family renaming for the final copied-resource reuse phase.
|
||||
fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) {
|
||||
let mut staged = src.clone();
|
||||
let mut aliased = false;
|
||||
for node in nodes.iter_mut() {
|
||||
each_mut(node, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) {
|
||||
each_mut(Arc::make_mut(&mut symbol.art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) {
|
||||
for art in &mut pattern.art {
|
||||
each_mut(Arc::make_mut(art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) {
|
||||
for art in brush_art(brush) {
|
||||
each_mut(art, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
(staged, aliased)
|
||||
}
|
||||
|
||||
/// Discover the incoming resource frontier and its composite-font users before planning
|
||||
/// names or changing either document. Resource order and the no-composite fast path stay shared.
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, BTreeSet<String>) {
|
||||
let mut used = Used::default();
|
||||
let composites = !src.composite_fonts.is_empty();
|
||||
let mut families = BTreeSet::new();
|
||||
let mut note_family = |name: &mut String| {
|
||||
families.insert(name.to_lowercase());
|
||||
};
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(n, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
let src_brushes = vectorcraft_brush::library(src);
|
||||
// Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while
|
||||
@@ -254,8 +585,29 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
}
|
||||
for mut a in art {
|
||||
refs(&mut a, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
}
|
||||
(used, src_brushes, families)
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes);
|
||||
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
|
||||
// All representability/validation errors precede incoming or destination mutation.
|
||||
let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
|
||||
let staged;
|
||||
let mut aliased = false;
|
||||
let src = if let Some(plan) = &plan {
|
||||
(staged, aliased) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan);
|
||||
&staged
|
||||
} else {
|
||||
src
|
||||
};
|
||||
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
|
||||
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
|
||||
@@ -264,7 +616,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
&used.symbols,
|
||||
|n| src.symbols.iter().find(|s| s.name == n),
|
||||
|n| dst.symbols.iter().find(|s| s.name == n),
|
||||
|a, b| same_symbol(dst, a, b),
|
||||
|a, b| same_symbol(dst, a, b) && SymbolOptions::of(dst, &a.name) == SymbolOptions::of(src, &b.name),
|
||||
|c| dst.symbols.iter().any(|s| s.name == c),
|
||||
);
|
||||
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
|
||||
@@ -330,23 +682,14 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
|
||||
}
|
||||
|
||||
let mut rename = |r: Ref| {
|
||||
let (map, k) = match r {
|
||||
Ref::Image(k) => (&images, k),
|
||||
Ref::Symbol(k) => (&symbols, k),
|
||||
Ref::Pattern(k) => (&patterns, k),
|
||||
Ref::Brush(k) => (&brushes, k),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|k| swatches.get(k)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(k.as_str()) {
|
||||
*k = new.clone();
|
||||
}
|
||||
};
|
||||
if aliased || symbols.values().any(|(_, copy)| *copy) {
|
||||
reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]);
|
||||
}
|
||||
|
||||
if let Some(plan) = plan {
|
||||
dst.composite_fonts = plan.combined.into();
|
||||
}
|
||||
let mut rename = |r: Ref| rename_ref(r, [&images, &symbols, &patterns, &brushes, &swatches]);
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut rename);
|
||||
}
|
||||
@@ -375,6 +718,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
|
||||
def.art = Arc::new(dst.reid(&def.art));
|
||||
dst.symbols.push(def);
|
||||
SymbolOptions::of(src, old).give(dst, new);
|
||||
}
|
||||
}
|
||||
for (old, new) in copies(&patterns) {
|
||||
@@ -406,4 +750,5 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
dst.swatches.push(w);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -178,6 +178,10 @@ fn opened_document_art(
|
||||
super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false);
|
||||
}
|
||||
l.doc.drop_edit_modes();
|
||||
// Measure and crop in this source's composite fonts, not those of the front document.
|
||||
// The existing thread-local loan restores its caller's context on every return or unwind.
|
||||
let source_fonts = l.doc.composite_fonts.clone();
|
||||
let _source_fonts = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts);
|
||||
// The native file does not store type's layout bounds. Measure them before cropping or
|
||||
// copying the art, so the placed group keeps the positions of aligned point type.
|
||||
for warning in crate::Session::refresh_text_bounds(&mut l.doc) {
|
||||
@@ -544,7 +548,7 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, cmd)?;
|
||||
let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?;
|
||||
let mut nodes = a.nodes;
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes);
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes, cmd)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = a.clip {
|
||||
children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r)));
|
||||
|
||||
@@ -750,6 +750,7 @@ pub const SWITCHING_LABELS: &[&str] = &[
|
||||
"Lock Guides",
|
||||
"Hide Slices",
|
||||
"Show Print Tiling",
|
||||
"Show Missing Links",
|
||||
"Lock Grid",
|
||||
"Edit Envelope",
|
||||
"Edit Contents",
|
||||
|
||||
@@ -132,6 +132,10 @@ pub struct DocState {
|
||||
pub spelling_ignored: std::collections::BTreeSet<String>,
|
||||
/// View → Show Transparency Grid, per document (saved view state, not undoable).
|
||||
pub transparency_grid: bool,
|
||||
/// View → Show Missing Links: transient canvas decoration, never document artwork.
|
||||
pub show_missing_links: bool,
|
||||
/// Last worker scan, tied to the exact document snapshot it inspected.
|
||||
pub missing_link_markers: Option<(Arc<Document>, Vec<NodeId>)>,
|
||||
/// The format Save writes ([`cmd::fileio::SAVE_FORMATS`]): the one the document was opened
|
||||
/// from or last saved as.
|
||||
pub format: &'static str,
|
||||
@@ -491,6 +495,30 @@ impl SameContent {
|
||||
}
|
||||
|
||||
impl DocState {
|
||||
/// Cached missing links still present and visible in the current art. Geometry-only edits
|
||||
/// keep their markers moving with the objects; relinking or embedding drops them immediately.
|
||||
pub fn marked_missing_links(&self) -> Vec<NodeId> {
|
||||
if !self.show_missing_links {
|
||||
return vec![];
|
||||
}
|
||||
let Some((before, ids)) = &self.missing_link_markers else { return vec![] };
|
||||
fn link(n: &vectorcraft_doc::Node) -> Option<&vectorcraft_doc::LinkInfo> {
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) => im.link.as_ref(),
|
||||
NodeKind::PlacedDocument(p) => Some(&p.link),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
ids.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
let old = before.node(*id).and_then(link);
|
||||
let now = self.doc.node(*id).and_then(link);
|
||||
now.is_some() && now == old && self.doc.is_visible(*id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn new(mut doc: Document, path: Option<String>) -> Self {
|
||||
let active_layer = doc.default_layer();
|
||||
// Saved view state lives here while the document is open (saves write it back).
|
||||
@@ -532,6 +560,8 @@ impl DocState {
|
||||
mask_view: None,
|
||||
spelling_ignored: Default::default(),
|
||||
transparency_grid,
|
||||
show_missing_links: false,
|
||||
missing_link_markers: None,
|
||||
format: "vectorcraft",
|
||||
save_options: Default::default(),
|
||||
save_artboards: vec![],
|
||||
|
||||
@@ -93,7 +93,7 @@ impl AutomationRoots {
|
||||
|
||||
/// Roots that grant no access of either kind: inside [`confine`] with them, every path a
|
||||
/// command reads or writes is refused.
|
||||
pub(crate) fn none() -> Arc<Self> {
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: Vec::new(), write: Vec::new() })
|
||||
}
|
||||
|
||||
@@ -124,6 +124,11 @@ impl AutomationRoots {
|
||||
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
|
||||
}
|
||||
|
||||
/// The folders of the kind `access`, as people read them.
|
||||
pub fn folders(&self, access: Access) -> impl Iterator<Item = &Path> {
|
||||
self.of(access).iter().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// The roots of the kind `access`.
|
||||
fn of(&self, access: Access) -> &[Root] {
|
||||
match access {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -853,9 +853,24 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
|
||||
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
// Deleting every path of a compound path would leave it empty, so a compound path that
|
||||
// clips counts as deleted too.
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
let masks: Vec<u64> = ids
|
||||
.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
|
||||
@@ -394,6 +394,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();
|
||||
@@ -679,7 +692,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
@@ -845,7 +858,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}))?;
|
||||
|
||||
@@ -661,6 +661,7 @@ impl Session {
|
||||
self.pending_paint = None;
|
||||
// The previous preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
|
||||
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
|
||||
// A selected object's converted appearance must not replace the current paints while
|
||||
@@ -877,6 +878,7 @@ impl Session {
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// A canceled preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
|
||||
// the document has it again, not as a preview left it. An interaction that changed only the
|
||||
// defaults (`defaultsOnly: true`) leaves the defaults it began with.
|
||||
|
||||
@@ -25,6 +25,12 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run a command callback and keep warnings from every preview it settles or restores.
|
||||
pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
let (r, settled) = self.collect_settled_warnings(f);
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
}
|
||||
|
||||
/// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
|
||||
fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
|
||||
let Some(d) = self.active_mut() else { return (spec.enabled)(self) };
|
||||
@@ -121,10 +127,9 @@ impl Session {
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
let r = if self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| {
|
||||
self.command_with_settled_warnings(|s| {
|
||||
if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) }
|
||||
});
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
})
|
||||
} else {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
@@ -253,6 +258,10 @@ impl Session {
|
||||
// after an undone or redone Assign Profile, a failed or panicked command's documents put
|
||||
// back, and a batch step, before the next step converts through them.
|
||||
self.sync_front_profiles();
|
||||
if self.depth != 0 {
|
||||
// The next batch step can measure/outline definitions this step adopted.
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
if r.is_err() && self.depth == 0 {
|
||||
self.batch_paint_docs.clear();
|
||||
// A failed or panicked command's documents are put back: type is drawn in their
|
||||
|
||||
@@ -118,6 +118,7 @@ mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod missing_links;
|
||||
mod moved;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
|
||||
@@ -152,7 +152,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
// The worker takes its turn after the slot is read and before the flag is, if the slot is free.
|
||||
let ended = link_watch::ended_without_stamps(&scan, |flag| {
|
||||
if let Ok(mut slot) = scan.0.try_lock() {
|
||||
*slot = Some((uid, stamps.clone()));
|
||||
*slot = Some(link_watch::LinkScanResult::stamps(uid, stamps.clone()));
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
}
|
||||
flag.load(Ordering::SeqCst)
|
||||
@@ -163,7 +163,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
let scan = scan.clone();
|
||||
move || {
|
||||
let _ended = link_watch::Ended(scan.clone());
|
||||
*scan.0.lock().unwrap() = Some((uid, stamps));
|
||||
*scan.0.lock().unwrap() = Some(link_watch::LinkScanResult::stamps(uid, stamps));
|
||||
}
|
||||
});
|
||||
worker.join().unwrap();
|
||||
|
||||
@@ -1241,3 +1241,258 @@ fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transf
|
||||
let asked = double_click(&mut s, "directSelection");
|
||||
assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}");
|
||||
}
|
||||
|
||||
/// Live radii of every corner of path `id`, or `None` when it has no Live Corners left.
|
||||
fn live_radii(s: &Session, id: NodeId) -> Option<Vec<f64>> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n)?;
|
||||
let all = lc.all();
|
||||
Some(all.iter().map(|k| lc.drawn_radius(*k)).collect())
|
||||
}
|
||||
|
||||
/// #10545: moving an anchor of a rounded rectangle moves its corner and keeps every corner live
|
||||
/// at its radius, in one undo step.
|
||||
#[test]
|
||||
fn moving_an_anchor_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 0, "y": 25})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert_eq!(n.path_data().unwrap().anchor_count(), 8);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(corners(&s, id), ([10.0; 4], [CornerKind::Round; 4], 8));
|
||||
}
|
||||
|
||||
/// #10545: dragging direct-selected anchors of a rounded rectangle keeps its corners live, and
|
||||
/// the corner they belong to moves by the drag.
|
||||
#[test]
|
||||
fn dragging_selected_anchors_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let before = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
// The two ends of the top-left corner's arc.
|
||||
let arc: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(arc.len(), 2);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": arc, "mode": "set"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": -20, "dy": 0})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
let after = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
assert!(after.x0 < before.x0 - 10.0 && (after.x1 - before.x1).abs() < 1e-6, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path() {
|
||||
for xf in [Affine::scale_non_uniform(2.0, 1.0), Affine::new([1.0, 0.0, 0.5, 1.0, 10.0, 10.0])] {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
let live = LiveShape::Rectangle { w: 50.0, h: 60.0, radii: [10.0; 4], kinds: Default::default(), radii_relative: false, xf };
|
||||
let mut expected = live.to_path();
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let NodeKind::Path { path, live: slot, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not a path") };
|
||||
*path = expected.clone();
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
let delta = vectorcraft_geom::Vec2::new(-20.0, 5.0);
|
||||
let a = expected.anchor_mut(0, 0).unwrap();
|
||||
*a = a.transform(Affine::translate(delta));
|
||||
let target = a.p;
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 0, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": delta.x, "dy": delta.y, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(n.live_shape().is_none(), "{command}: {xf:?}");
|
||||
assert_eq!(n.path_data().unwrap(), &expected, "{command}: {xf:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_remaps_the_whole_anchor_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected: BTreeSet<_> = [0, 2].into_iter().map(|k| *lc.anchors_of(&BTreeSet::from([k])).first().unwrap()).collect();
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([0])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(50.0, 30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected);
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 0)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": 50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
assert_eq!(selected_anchors(&s, id), Some(lc.anchors_of(&BTreeSet::from([0, 2]))), "{command}");
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id), "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected = lc.anchors_of(&BTreeSet::from([1]));
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([2])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, -30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected.clone());
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": moved.1, "x": target.x, "y": target.y})).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources);
|
||||
assert_eq!(lc.anchors_of(&BTreeSet::from([1])), selected);
|
||||
assert_eq!(selected_anchors(&s, id), Some(selected));
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_corner_layout_keeps_the_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, anchors(&[0, 1, 2]));
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let sources = LiveCorners::of(n).unwrap().sources().to_vec();
|
||||
let target = n.path_data().unwrap().subpaths[0].anchors[4].p + vectorcraft_geom::Vec2::new(-20.0, 0.0);
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 4, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -20, "dy": 0, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().sources(), sources);
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_keeps_the_key_anchor_on_its_corner() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, key, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
// The top right corner moves to the middle of the rectangle.
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([1])).first().unwrap();
|
||||
let key = *lc.anchors_of(&BTreeSet::from([3])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, 30.0);
|
||||
(BTreeSet::from([moved, key]), moved, key, target, lc.sources().to_vec())
|
||||
};
|
||||
let sel = &mut s.doc_mut().unwrap().selection;
|
||||
sel.anchors.insert(id, selected);
|
||||
sel.key_anchor = Some((id, key));
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
let now = s.doc().unwrap().selection.key_anchor;
|
||||
assert_eq!(now, lc.anchors_of(&BTreeSet::from([3])).first().map(|r| (id, *r)), "{command}");
|
||||
assert_ne!(now, Some((id, key)), "{command}: the key anchor's index changed with the recut");
|
||||
}
|
||||
}
|
||||
|
||||
/// A nudge of a pixel-aligned rounded rectangle's edge that the pixel-grid snap takes back
|
||||
/// changes nothing and records no undo step.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_records_no_undo_step() {
|
||||
let (mut s, id) = session();
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(left.len(), 4);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
// A first move by a whole point makes the rectangle a live path; the snap keeps that move.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// The same nudge on a rounded rectangle that no anchor edit has touched yet records no undo
|
||||
/// step and leaves it a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_keeps_a_live_rectangle() {
|
||||
for x in [10, 50, 137] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "x = {x}");
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })), "x = {x}");
|
||||
assert_eq!(s.doc().unwrap().doc, doc, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same nudge with a second pixel-aligned rectangle selected whole, which the snap also takes
|
||||
/// back, records no undo step and leaves the rounded rectangle a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_with_an_object_selected_whole_records_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let whole = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [whole.0]})).unwrap();
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [whole.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.whole(), vec![whole]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })));
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Canvas marker state and command API, independent of artwork and link update preferences.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::tests_links::{Folder, RED, place, png, session, write};
|
||||
use crate::*;
|
||||
|
||||
fn marked(s: &mut Session) -> Vec<u64> {
|
||||
s.execute("links.marked", &json!({})).unwrap()["images"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_toggle_is_transient_per_document_and_validated() {
|
||||
let mut s = session();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
for p in [json!({"on": "false"}), json!({"on": 1}), json!({"on": []})] {
|
||||
assert!(s.execute("view.showMissingLinks", &p).is_err());
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().show_missing_links);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({})).unwrap(), json!({"on": false}));
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_follow_files_relink_update_and_embed() {
|
||||
let dir = Folder::new("marker-lifecycle");
|
||||
let path = dir.file("art.png");
|
||||
let replacement = dir.file("replacement.png");
|
||||
let bytes = png(40, 40, RED);
|
||||
write(&path, &bytes);
|
||||
write(&replacement, &bytes);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let saved = vectorcraft_format::save_file(&doc);
|
||||
let pixels = vectorcraft_render::Renderer::new().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels;
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection, selection);
|
||||
assert_eq!(st.history.undo.len(), undo);
|
||||
assert_eq!(vectorcraft_format::save_file(&st.doc), saved);
|
||||
assert_eq!(
|
||||
vectorcraft_render::Renderer::new().render_region(&st.doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels,
|
||||
pixels
|
||||
);
|
||||
s.execute("links.relink", &json!({"ids": [id.0], "path": replacement})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
write(&replacement, &bytes);
|
||||
s.execute("links.update", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() {
|
||||
for mode in ["automatically", "askWhenModified", "manually"] {
|
||||
let dir = Folder::new(&format!("marker-watch-{mode}"));
|
||||
let path = dir.file("art.png");
|
||||
let bytes = png(20, 20, RED);
|
||||
write(&path, &bytes);
|
||||
let mut s = session();
|
||||
s.prefs.update_links = mode.into();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert_eq!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1, vec![id]);
|
||||
write(&path, &bytes);
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
let seen = s.doc().unwrap().missing_link_markers.as_ref().unwrap().0.clone();
|
||||
s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 3, "height": 4})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&seen, &s.doc().unwrap().missing_link_markers.as_ref().unwrap().0));
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
// Switching the toggle off while a look is pending must not resurrect its markers.
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_missing_links_on_returns_before_the_file_probe_and_scans_on_the_link_watcher() {
|
||||
use crate::cmd::links::probe_gate::{self, Gate};
|
||||
use std::time::Duration;
|
||||
let dir = Folder::new("marker-toggle-nonblocking");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let stored = crate::tests_links::image(&s, id).link.unwrap().path;
|
||||
let gate = Gate::close(&stored);
|
||||
// The toggle returns while the probe of the (slow) linked file is held closed.
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
assert!(!gate.finished(), "the toggle waited for the file probe");
|
||||
assert_eq!(gate.entered(Duration::ZERO), None, "the toggle probed the file on the calling thread");
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
// The desktop app starts the watcher's look at once, and the probe runs there.
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
assert_eq!(gate.entered(Duration::from_secs(10)).as_deref(), Some("link-watch"));
|
||||
assert!(s.poll_link_scan().is_none(), "the look ended before its probe was released");
|
||||
gate.open();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
probe_gate::remove(&stored);
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.missing_link_scan_due());
|
||||
// Turning it on again while on keeps the markers; off clears them.
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_scan_for_a_document_without_links_ends_without_a_worker() {
|
||||
let mut s = session();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(s.link_scan.is_none());
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_hidden_when_the_overlay_turns_on_is_marked_once_shown() {
|
||||
let dir = Folder::new("marker-hidden-then-shown");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
// Found by the desktop's link watch worker, and in place as the web app does.
|
||||
for in_place in [false, true] {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let mark = |s: &mut Session| {
|
||||
if in_place {
|
||||
s.mark_missing_links_in_place();
|
||||
} else {
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
}
|
||||
};
|
||||
mark(&mut s);
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty(), "hidden art is not marked");
|
||||
s.execute("object.showAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id], "shown art is marked without another scan");
|
||||
if in_place {
|
||||
// Artwork restored while the overlay is on is marked again.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.mark_missing_links_in_place());
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.mark_missing_links_in_place(), "unchanged art is not looked at again");
|
||||
}
|
||||
write(&path, &png(20, 20, RED));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_include_placed_documents_and_exclude_hidden_art() {
|
||||
let dir = Folder::new("marker-placed");
|
||||
let path = dir.file("placed.vectorcraft");
|
||||
write(&path, &vectorcraft_format::save_file(&vectorcraft_doc::Document::new(40.0, 20.0)));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::PlacedDocument(_)));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
s.execute("object.move", &json!({"ids": [id.0], "dx": 15, "dy": 10})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
@@ -2713,6 +2713,32 @@ fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() {
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// `removeAll()` on the `pathItems` of a compound path that clips a group keeping other art
|
||||
/// would leave an empty clipping path, so it throws and deletes nothing, as deleting the clipping
|
||||
/// path itself does. Removing some of its paths still works.
|
||||
#[test]
|
||||
fn removing_all_the_paths_of_a_clipping_compound_path_is_refused() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [compound.0, other.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
run(&mut s, "var g = app.activeDocument.groupItems[0]; g.compoundPathItems[0].zOrder(ZOrderMethod.BRINGTOFRONT); g.clipped = true;").unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound));
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete a clipping path"), "{e}");
|
||||
assert!(e.contains(&compound.0.to_string()), "{e}");
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
run(&mut s, "app.activeDocument.compoundPathItems[0].pathItems[0].remove();").unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.node(compound).and_then(|n| n.children()).map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it
|
||||
/// is runs no command, also in a layer whose ruler guides are above its art.
|
||||
#[test]
|
||||
|
||||
@@ -680,6 +680,68 @@ fn document_path_creators_use_the_active_layer_during_isolation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A locked or hidden active layer does not take a script's new path: the path goes on the
|
||||
/// topmost shown, unlocked layer, where the app's own creation commands put new art.
|
||||
#[test]
|
||||
fn document_path_creators_skip_a_locked_or_hidden_active_layer() {
|
||||
for (prop, value) in [("locked", true), ("visible", false)] {
|
||||
for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] {
|
||||
let (mut s, _, _) = doc();
|
||||
let editable = s.active().unwrap().active_layer.unwrap();
|
||||
let top = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(top));
|
||||
s.execute("layer.setProps", &json!({"id": top.0, prop: value})).unwrap();
|
||||
let before = node(&s, editable).children().unwrap().len();
|
||||
log(&mut s, &format!("app.activeDocument.pathItems.{create};"));
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.node(top).unwrap().children().unwrap().is_empty(), "{prop} {create}");
|
||||
let children = st.doc.node(editable).unwrap().children().unwrap();
|
||||
assert_eq!(children.len(), before + 1, "{prop} {create}");
|
||||
let made = children.last().unwrap();
|
||||
assert!(matches!(made.kind, NodeKind::Path { .. }), "{prop} {create}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// While an opacity mask is being edited, a locked mask layer refuses a script's new path instead
|
||||
/// of the path going on an ordinary layer outside the mask.
|
||||
#[test]
|
||||
fn document_path_creators_refuse_a_locked_mask_editing_layer() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let layer = s.active().unwrap().doc.mask_edit.unwrap().layer;
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(layer));
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
let before = art(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.add();");
|
||||
assert!(e.contains("onLayer must name an editable layer"), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_creators_use_the_mask_editing_layer_after_the_active_layer_changes() {
|
||||
let (mut s, a, _) = doc();
|
||||
let ordinary = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let layer = s.active().unwrap().doc.mask_edit.unwrap().layer;
|
||||
s.execute("layer.setCurrent", &json!({"id": ordinary.0})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": ordinary.0, "locked": true})).unwrap();
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(ordinary));
|
||||
let before = node(&s, layer).children().unwrap().len();
|
||||
let ordinary_before = node(&s, ordinary).children().unwrap().len();
|
||||
log(&mut s, "app.activeDocument.pathItems.add();");
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.mask_edit.unwrap().layer, layer);
|
||||
let children = st.doc.node(layer).unwrap().children().unwrap();
|
||||
assert_eq!(children.len(), before + 1);
|
||||
assert!(matches!(children.last().unwrap().kind, NodeKind::Path { .. }));
|
||||
// The mask's art is stored on its object, which stays on the ordinary layer; that layer gains
|
||||
// no path of its own.
|
||||
assert_eq!(node(&s, ordinary).children().unwrap().len(), ordinary_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_writes_refuse_generated_graph_design_paths() {
|
||||
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
|
||||
|
||||
@@ -409,11 +409,14 @@ impl Session {
|
||||
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
|
||||
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
|
||||
/// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd
|
||||
/// press armed ([`Self::behind_armed`]).
|
||||
/// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press
|
||||
/// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown
|
||||
/// direction handle to mirror the opposite handle.
|
||||
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
|
||||
let id = self.lent_tool(self.tool.id(), mods)?;
|
||||
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
|
||||
(!behind).then_some(id)
|
||||
let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods));
|
||||
(!behind && !kept).then_some(id)
|
||||
}
|
||||
|
||||
/// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks
|
||||
|
||||
@@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let end = Point::new(180.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Down, end, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let p = anchor(&s, id).p;
|
||||
let shifted = Mods { shift: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let raw = Point::new(180.0, 150.0);
|
||||
pointer(&mut s, PointerKind::Drag, raw, shifted);
|
||||
assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, raw, shifted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
// A second object widens the selection's bounding box so its top-middle handle lands on the
|
||||
// curve's outgoing handle end at (180, 100).
|
||||
let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]}));
|
||||
let boxed = ViewInfo { show_bbox: true, ..view() };
|
||||
let end = Point::new(180.0, 100.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let a = anchor(&s, id);
|
||||
let both = Mods { alt: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle");
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
assert_eq!(anchor(&s, id), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() {
|
||||
let mut s = session();
|
||||
@@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() {
|
||||
assert_content(&s, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() {
|
||||
let mut s = session();
|
||||
let id = blend(&mut s);
|
||||
let (a, keys, _) = blend_state(&s, id);
|
||||
pointer(&mut s, PointerKind::Down, a.h_out, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
let (after, after_keys, _) = blend_state(&s, id);
|
||||
near(after.p, a.p);
|
||||
assert_mirrored(after, q, AnchorKind::Smooth);
|
||||
assert_eq!(after_keys, keys, "the key objects did not move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -119,6 +119,78 @@ fn picked_handles_stay_picked_after_they_are_dragged() {
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0));
|
||||
}
|
||||
|
||||
/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone
|
||||
/// and mirrors its opposite handle; the other picked handle stays where it is.
|
||||
#[test]
|
||||
fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let a = anchor(&s, id, 1);
|
||||
near(a.h_out, Point::new(180.0, 160.0));
|
||||
near(a.h_in, Point::new(20.0, 40.0));
|
||||
assert_eq!(a.kind, AnchorKind::Smooth);
|
||||
near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without
|
||||
/// Cmd/Ctrl then moves both.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during
|
||||
/// one.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() {
|
||||
for escape in [false, true] {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift);
|
||||
if escape {
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
}
|
||||
pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift);
|
||||
let x = if escape { 180.0 } else { 220.0 };
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both
|
||||
/// picked.
|
||||
#[test]
|
||||
fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd);
|
||||
near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag
|
||||
/// then moves only the handle pressed.
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@ use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind,
|
||||
OpacityMask, StrokeLayer, Symbol,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -1020,6 +1020,167 @@ fn hidden_layers_open_hidden() {
|
||||
assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}");
|
||||
}
|
||||
|
||||
fn dash_painted_nodes(nodes: &[Arc<Node>], out: &mut Vec<Node>) {
|
||||
for n in nodes {
|
||||
match &n.kind {
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push((**n).clone()),
|
||||
_ => {
|
||||
if let Some(children) = n.children() {
|
||||
dash_painted_nodes(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Original synthetic rectangle, independent of the artwork in #10476.
|
||||
fn dash_compat_document(pattern: Vec<f64>) -> Document {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let mut stroke = StrokeLayer::new(solid(Color::BLACK), 4.0);
|
||||
stroke.dash = Some(Dash { pattern, offset: 2.5, align_corners: false });
|
||||
stroke.overprint = true;
|
||||
let ap = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))), AppearanceItem::Stroke(stroke)],
|
||||
..Appearance::default()
|
||||
};
|
||||
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 180.0, 80.0)), ap);
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
fn ai_dash_outputs(doc: &Document) -> Vec<(String, Vec<String>, Document)> {
|
||||
let out = export_ai_editing(doc, &opts()).unwrap();
|
||||
let legacy = crate::export_legacy_ai(doc, &crate::LegacyAiOptions::default()).unwrap();
|
||||
let legacy_back = crate::import(&legacy.bytes).unwrap().document;
|
||||
vec![
|
||||
(String::from_utf8(out.program).unwrap().replace("\r\n", "\n"), out.warnings, read_back(doc)),
|
||||
(String::from_utf8(legacy.bytes).unwrap().replace("\r\n", "\n"), legacy.warnings, legacy_back),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_reduce_repetitions_and_keep_small_patterns_editable() {
|
||||
for (pattern, emitted) in [
|
||||
(vec![33.5673; 5], "[33.5673] 2.5 d"),
|
||||
(vec![33.5673; 10], "[33.5673] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0, 3.0, 2.0, 1.0, 3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
|
||||
(vec![0.25], "[0.25] 2.5 d"),
|
||||
(vec![0.25, 0.5], "[0.25 0.5] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0], "[3 2 1 2 3 4] 2.5 d"),
|
||||
] {
|
||||
let doc = dash_compat_document(pattern.clone());
|
||||
for (text, warnings, back) in ai_dash_outputs(&doc) {
|
||||
assert!(text.contains(emitted), "{pattern:?}: missing {emitted}: {text}");
|
||||
assert!(warnings.is_empty(), "{pattern:?}: {warnings:?}");
|
||||
let mut art = vec![];
|
||||
dash_painted_nodes(&back.layers, &mut art);
|
||||
assert_eq!(art.len(), 1);
|
||||
let st = art[0].appearance.stroke().unwrap();
|
||||
assert_eq!(st.width, 4.0);
|
||||
assert!(st.overprint);
|
||||
assert_eq!(st.dash.as_ref().unwrap().offset, 2.5);
|
||||
let got = &st.dash.as_ref().unwrap().pattern;
|
||||
for i in 0..pattern.len() * got.len() * 2 {
|
||||
assert_eq!(pattern[i % pattern.len()], got[i % got.len()]);
|
||||
}
|
||||
assert!(art[0].appearance.fill().is_some());
|
||||
}
|
||||
assert_eq!(doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap().dash.as_ref().unwrap().pattern, pattern);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_that_exceed_six_effective_lengths_are_outlined_with_a_warning() {
|
||||
for pattern in [vec![3.0, 2.0, 1.0, 2.0, 3.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]] {
|
||||
let doc = dash_compat_document(pattern);
|
||||
let original = &doc.layers[0].children().unwrap()[0];
|
||||
let path = original.path_data().unwrap();
|
||||
let expected = vectorcraft_effects::stroke::outline_region(path, FillRule::NonZero, original.appearance.stroke().unwrap()).to_bezpath();
|
||||
for (text, warnings, back) in ai_dash_outputs(&doc) {
|
||||
assert!(warnings.iter().any(|w| w.contains("filled outlines")), "{warnings:?}");
|
||||
assert!(
|
||||
!text.lines().filter(|l| l.ends_with(" d")).any(|l| {
|
||||
let array = l.rsplit_once('[').unwrap().1.split(']').next().unwrap();
|
||||
let n = array.split_whitespace().count();
|
||||
n > 6 || (n % 2 == 1 && n * 2 > 6)
|
||||
}),
|
||||
"{text}"
|
||||
);
|
||||
let mut art = vec![];
|
||||
dash_painted_nodes(&back.layers, &mut art);
|
||||
assert!(art.iter().all(|n| n.appearance.stroke().is_none()), "{art:?}");
|
||||
assert_eq!(art.len(), 2, "fill and outlined stroke keep their paint order");
|
||||
assert_eq!(art[0].appearance.fill().unwrap().paint, solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
let fill = art[1].appearance.fill().unwrap();
|
||||
assert_eq!(fill.paint, solid(Color::BLACK));
|
||||
assert!(fill.overprint);
|
||||
let got = art[1].stroke_path().unwrap();
|
||||
for y in 5..85 {
|
||||
for x in 5..185 {
|
||||
let p = vectorcraft_geom::Point::new(f64::from(x) + 0.123, f64::from(y) + 0.123);
|
||||
assert_eq!(got.winding(p) != 0, expected.winding(p) != 0, "at {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_in_linked_styles_also_respect_the_reader_limit() {
|
||||
for (pattern, live) in [(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false), (vec![33.5673; 5], true)] {
|
||||
let mut doc = dash_compat_document(pattern);
|
||||
let n = Arc::make_mut(&mut Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap()[0]);
|
||||
n.appearance.stroke_mut().unwrap().overprint = false;
|
||||
n.extras_mut().graphic_style = Some(7);
|
||||
let mut style = vectorcraft_doc::GraphicStyle::new("Dashed", (*n.appearance).clone());
|
||||
style.id = 7;
|
||||
doc.graphic_styles.push(style);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let text = String::from_utf8(out.program).unwrap();
|
||||
assert!(!text.contains("[3 2 1 2 3 4 5 6]"), "a style dictionary must not keep an incompatible dash list");
|
||||
if live {
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert!(text.contains("1 (Dashed) XW"), "an equivalent dash representation keeps the style link");
|
||||
assert!(text.contains("[33.5673] 2.5 d"));
|
||||
} else {
|
||||
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_in_legacy_text_reduce_or_outline_without_becoming_solid() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
|
||||
// Existing licensed test face, with original single-letter artwork.
|
||||
vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
|
||||
for (pattern, live) in [(vec![33.5673; 5], true), (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false)] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let st = CharStyle {
|
||||
font_family: HEIGHT_FAMILY.into(),
|
||||
size: 48.0,
|
||||
fill: solid(Color::rgb(0.0, 1.0, 0.0)),
|
||||
stroke: solid(Color::BLACK),
|
||||
stroke_width: 2.0,
|
||||
stroke_dash: Some(Dash { pattern, offset: 2.5, align_corners: false }),
|
||||
..CharStyle::default()
|
||||
};
|
||||
let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "T", st);
|
||||
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
|
||||
let out = crate::export_legacy_ai(&doc, &crate::LegacyAiOptions::default()).unwrap();
|
||||
let text = String::from_utf8(out.bytes).unwrap().replace("\r\n", "\n");
|
||||
assert_eq!(text.contains("0 To\n"), live, "irreducible type strokes must take the outline fallback");
|
||||
if live {
|
||||
assert!(text.contains("[33.5673] 2.5 d"));
|
||||
} else {
|
||||
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
|
||||
assert!(text.matches("\nf\n").count() >= 2, "the glyph's fill and dashed stroke are both painted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A 200 × 100 document of a gradient fill, a compound path, an image and a symbol instance, and
|
||||
/// what the data holds as plain paths: type.
|
||||
fn unsupported() -> Document {
|
||||
|
||||
@@ -71,7 +71,7 @@ pub(super) const LIVE: &str =
|
||||
"repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps";
|
||||
pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps";
|
||||
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
|
||||
pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps";
|
||||
|
||||
@@ -364,7 +364,7 @@ fn plain_key(k: &Node) -> bool {
|
||||
&& i.effects().is_empty()
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s))
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s) || !dash_read_back(s))
|
||||
});
|
||||
plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none();
|
||||
});
|
||||
|
||||
@@ -258,7 +258,7 @@ fn plain_within(art: &Node, masks: u32) -> bool {
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& matches!(i.paint(), Paint::Solid { .. } | Paint::None)
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s))
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s))
|
||||
});
|
||||
// A group's own fills and strokes aren't written.
|
||||
let group_paint = matches!(n.kind, NodeKind::Group { .. }) && items.iter().any(|i| !i.paint().is_none());
|
||||
@@ -519,7 +519,7 @@ impl Writer<'_> {
|
||||
let name = st.brush.as_deref()?;
|
||||
self.brush_set();
|
||||
let (plugin, kind) = self.live_brush(name).map(|b| (b.plugin, b.brush.kind.clone()))?;
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
|
||||
return None;
|
||||
}
|
||||
let ops = self.color_ops(&st.paint, true);
|
||||
|
||||
@@ -8,7 +8,6 @@ use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType};
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2};
|
||||
|
||||
use super::{MAX_NEST, Writer, Xy};
|
||||
@@ -367,7 +366,7 @@ impl Writer<'_> {
|
||||
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
|
||||
/// write it)?
|
||||
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
|
||||
self.direct(&s.paint) && stroke::is_plain(s)
|
||||
self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
|
||||
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
|
||||
|
||||
@@ -404,7 +404,7 @@ impl Writer<'_> {
|
||||
if st.brush.is_some() {
|
||||
return self.brush_filter(s, st, visible);
|
||||
}
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
|
||||
return None;
|
||||
}
|
||||
let ops = self.color_ops(&st.paint, true);
|
||||
@@ -1077,6 +1077,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) ->
|
||||
let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count();
|
||||
ap.items.retain(|i| !i.paint().is_none());
|
||||
ap.contents_index = (below > 0).then_some(below);
|
||||
// The writer shortens repeated dash lists without changing their painted period.
|
||||
// Compare those representations equally so a linked style can stay live.
|
||||
for i in &mut ap.items {
|
||||
if let AppearanceItem::Stroke(st) = i
|
||||
&& let Some(d) = st.dash.as_mut().filter(|d| d.is_dashed())
|
||||
&& let Some(pattern) = ai_ops::dash_pattern(&d.pattern)
|
||||
{
|
||||
d.pattern = pattern.to_vec();
|
||||
}
|
||||
}
|
||||
for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
|
||||
e.params = normalized_params(e);
|
||||
}
|
||||
|
||||
@@ -425,8 +425,8 @@ fn plain_wrap_art(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
|
||||
let painted = || match super::visible_items(n).as_slice() {
|
||||
[] => true,
|
||||
[AppearanceItem::Fill(f)] => solid(&f.paint),
|
||||
[AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
[AppearanceItem::Stroke(s)] => solid(&s.paint) && crate::ai_ops::plain_stroke(s),
|
||||
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && crate::ai_ops::plain_stroke(s),
|
||||
_ => false,
|
||||
};
|
||||
let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2);
|
||||
|
||||
@@ -179,7 +179,28 @@ pub(crate) fn window_samples(samples: &[u8], w: u32, channels: usize, [x0, y0, x
|
||||
out
|
||||
}
|
||||
|
||||
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`.
|
||||
/// The shortest equivalent dash list the AI reader can hold. Odd lists repeat twice before
|
||||
/// dash/gap parity repeats. Keep at most six effective lengths: longer lists can make the
|
||||
/// reader reject the entire file (#10476). Compare exactly, so no dash or gap changes length.
|
||||
pub(crate) fn dash_pattern(pattern: &[f64]) -> Option<&[f64]> {
|
||||
(1..=pattern.len().min(6))
|
||||
.filter(|n| n % 2 == 0 || *n <= 3)
|
||||
.find(|n| pattern.len().is_multiple_of(*n) && pattern.iter().enumerate().all(|(i, v)| *v == pattern[i % n]))
|
||||
.map(|n| &pattern[..n])
|
||||
}
|
||||
|
||||
/// Invalid or empty dashes already draw solid; valid dashes need an exact short representation.
|
||||
pub(crate) fn dash_fits(st: &StrokeLayer) -> bool {
|
||||
st.dash.as_ref().filter(|d| d.is_dashed()).is_none_or(|d| dash_pattern(&d.pattern).is_some())
|
||||
}
|
||||
|
||||
/// A plain AI stroke, including the reader's dash-list limit. Other strokes use filled outlines.
|
||||
pub(crate) fn plain_stroke(st: &StrokeLayer) -> bool {
|
||||
vectorcraft_effects::stroke::is_plain(st) && dash_fits(st)
|
||||
}
|
||||
|
||||
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. Callers check
|
||||
/// [`dash_fits`] first; irreducible longer patterns belong in their outline fallback.
|
||||
pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
|
||||
let cap = match st.cap {
|
||||
LineCap::Butt => ps::LineCap::Butt,
|
||||
@@ -191,6 +212,6 @@ pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
|
||||
LineJoin::Round => ps::LineJoin::Round,
|
||||
LineJoin::Bevel => ps::LineJoin::Bevel,
|
||||
};
|
||||
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| (d.pattern.as_slice(), d.offset));
|
||||
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).and_then(|d| dash_pattern(&d.pattern).map(|p| (p, d.offset)));
|
||||
ps::push_line_style(s, st.width, cap, join, st.miter_limit, dash);
|
||||
}
|
||||
|
||||
@@ -125,8 +125,7 @@ const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in pro
|
||||
const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
|
||||
/// Wedges a conic gradient is written as: one a degree.
|
||||
const CONIC_WEDGES: usize = 360;
|
||||
const STROKES: &str =
|
||||
"strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines";
|
||||
const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, gradients, brushes, arrowheads) are written as filled outlines";
|
||||
const IMAGE_ALPHA: &str = "transparent image pixels are written over white";
|
||||
const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art";
|
||||
const DEEP_DISTORTED: &str =
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::writer::Writer;
|
||||
use super::{
|
||||
Affine, AreaOptions, BezPath, CharPosition, CharStyle, CompositeFont, Document, Gradient, GradientKind, Paint, ParaStyle, PathAlign, PathEffect,
|
||||
StrokeLayer, TextKind, TextObject, Write, latin, ps, stroke,
|
||||
StrokeLayer, TextKind, TextObject, Write, latin, ps,
|
||||
};
|
||||
|
||||
/// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd`, `[`, the stops
|
||||
@@ -111,6 +111,9 @@ pub(super) fn holds_as_text(t: &TextObject) -> bool {
|
||||
r.inline.is_none()
|
||||
&& solid(&r.style.fill)
|
||||
&& solid(&r.style.stroke)
|
||||
// Long dash lists can reject the entire AI file. Keep their glyph paint by
|
||||
// taking the existing type-outline path instead of writing a solid stroke.
|
||||
&& (!r.style.has_stroke() || crate::ai_ops::dash_fits(&r.style.stroke_layer()))
|
||||
&& (if r.style.all_caps { r.text.to_uppercase() } else { r.text.clone() }).chars().all(|c| latin::encode(c).is_some())
|
||||
})
|
||||
}
|
||||
@@ -221,5 +224,5 @@ pub(super) fn direct_fill(p: &Paint) -> bool {
|
||||
|
||||
/// Can stroke `s` be written as the stroke of a path object (a plain line of a colour)?
|
||||
pub(super) fn direct_stroke(s: &StrokeLayer) -> bool {
|
||||
matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s)
|
||||
matches!(s.paint, Paint::Solid { .. }) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
|
||||
@@ -22,7 +22,9 @@ vectorcraft-format = { workspace = true }
|
||||
vectorcraft-tools = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
craft = { workspace = true, features = ["automation"] }
|
||||
# `automation-agents` and `control-agents`: plain `mcp` finds the open window through the ArtCraft
|
||||
# Launcher's switch and the connection file, with the shared live client and the agent folders.
|
||||
craft = { workspace = true, features = ["automation", "automation-agents", "control-agents"] }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//! Agents in the open window: the CLI's side of the ArtCraft Launcher's switch.
|
||||
//!
|
||||
//! While the launcher's *Settings › AI agents* switch names VectorCraft (behind the suite's `AI-MCP`
|
||||
//! flag), the desktop app serves its control channel on loopback and publishes where in its
|
||||
//! settings folder (`craft::automation::agents::AgentLink`, `vectorcraft_ui_egui::agents`). Plain
|
||||
//! `vectorcraft-cli mcp` reads that file on every tool call ([`LiveBackend`], over the shared
|
||||
//! `craft::automation::agents::Live`), so an MCP client's configuration holds no port and no token,
|
||||
//! and the app may start, quit or move to another port while the client stays connected. Adding
|
||||
//! VectorCraft to MCP clients is the launcher's job (one entry for every Craft app); VectorCraft
|
||||
//! writes no client configuration.
|
||||
//!
|
||||
//! What is VectorCraft's here: its launcher id, its window client ([`Window`], which makes the app
|
||||
//! prove it holds the token before it proves it holds it too) and its headless session
|
||||
//! ([`Headless`] with the agent folders as automation roots).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft::automation::agents::{self as shared, AgentSettings, Consent, HeadlessFolders, Route, WhenAppClosed};
|
||||
use craft::automation::client::{CALL_TIMEOUT, CONNECT_TIMEOUT, MAX_REPLY_BYTES};
|
||||
use craft::automation::security::{self, ProofRole};
|
||||
use craft::control::agents::{AgentFolders, folders_answer};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::file_access::{Access, AutomationRoots};
|
||||
|
||||
use crate::backend::Backend;
|
||||
use crate::headless::Headless;
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names VectorCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "vectorcraft";
|
||||
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/VectorCraft`).
|
||||
pub const APP_NAME: &str = "VectorCraft";
|
||||
/// The desktop app's file name beside the CLI (without `.exe`).
|
||||
pub const APP_EXE: &str = "vectorcraft";
|
||||
/// The method the `agent_folders` tool calls: the folders this session's file commands may use.
|
||||
pub const FOLDERS_METHOD: &str = "agent.folders";
|
||||
/// What a tool that needs the window says in a session without one.
|
||||
pub const NEEDS_WINDOW: &str = "needs the open VectorCraft window: open VectorCraft with AI agents on (ArtCraft Launcher › Settings › AI agents) and run `vectorcraft-cli mcp` without --headless";
|
||||
|
||||
/// Whether the person lets agents use VectorCraft now: with the suite's `AI-MCP` flag, the
|
||||
/// launcher's switch. VectorCraft had no agent consent of its own before the switch, so without
|
||||
/// the flag agents get a session without a window.
|
||||
pub fn allowed_now() -> bool {
|
||||
shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
/// The automation roots for `folders`: what a session with these folders may open and save. A kind
|
||||
/// without a folder is refused, and so is everything when there is no folder at all.
|
||||
pub fn roots_for(folders: &AgentFolders) -> Result<Arc<AutomationRoots>, String> {
|
||||
let read: Vec<&Path> = folders.read.as_deref().into_iter().collect();
|
||||
let write: Vec<&Path> = folders.write.as_deref().into_iter().collect();
|
||||
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
|
||||
}
|
||||
|
||||
/// The `agent_folders` answer of a headless session confined to `roots` (`None`: not confined).
|
||||
/// With more than one folder of a kind (`--automation-read-root` given twice), `read_folders` /
|
||||
/// `write_folders` list them all.
|
||||
pub(crate) fn headless_folders(roots: Option<&AutomationRoots>) -> Value {
|
||||
let Some(roots) = roots else {
|
||||
// A session started without automation roots (`--headless` without them, or with the
|
||||
// agents switch off) isn't confined: say so rather than claim it has no folders.
|
||||
return json!({
|
||||
"read_folder": null,
|
||||
"write_folder": null,
|
||||
"unrestricted": true,
|
||||
"note": "This session was started without automation roots: its file commands open and save wherever the user can.",
|
||||
});
|
||||
};
|
||||
let (read, write): (Vec<&Path>, Vec<&Path>) = (roots.folders(Access::Read).collect(), roots.folders(Access::Write).collect());
|
||||
let mut folders = AgentFolders::default();
|
||||
folders.read = read.first().map(|p| p.to_path_buf());
|
||||
folders.write = write.first().map(|p| p.to_path_buf());
|
||||
let mut answer = folders_answer(&folders);
|
||||
for (key, all) in [("read_folders", &read), ("write_folders", &write)] {
|
||||
if all.len() > 1
|
||||
&& let Some(o) = answer.as_object_mut()
|
||||
{
|
||||
o.insert(key.into(), json!(all.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>()));
|
||||
}
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
// ---- The open window ---------------------------------------------------------------------------
|
||||
|
||||
/// How often a call waiting for its reply looks whether it was cancelled.
|
||||
const CANCEL_POLL: Duration = Duration::from_millis(100);
|
||||
|
||||
/// One authenticated connection to the open window. The app proves it holds the token first
|
||||
/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the
|
||||
/// wire, and a program that took a stale port learns nothing derived from it.
|
||||
pub struct Window {
|
||||
addr: SocketAddr,
|
||||
token: String,
|
||||
conn: Option<(BufReader<TcpStream>, TcpStream)>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
/// A client for the window on `127.0.0.1:port` with `token`; connects on the first call.
|
||||
pub fn new(port: u16, token: String) -> Self {
|
||||
Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 }
|
||||
}
|
||||
|
||||
/// Connects and runs the challenge handshake.
|
||||
pub fn connect(&mut self) -> Result<(), String> {
|
||||
self.conn = None;
|
||||
let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?;
|
||||
stream.set_nodelay(true).ok();
|
||||
stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
|
||||
let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream);
|
||||
let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?;
|
||||
let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}), false)?
|
||||
.map_err(|e| format!("{} refused challenge authentication ({e}); the agent token was not used", self.addr))?;
|
||||
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned);
|
||||
let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else {
|
||||
return Err(format!("{} answered the challenge without a proof; the agent token was not used", self.addr));
|
||||
};
|
||||
if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
|
||||
return Err(format!("{} could not prove it holds VectorCraft's agent token; nothing was sent to it", self.addr));
|
||||
}
|
||||
let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?;
|
||||
round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}), false)?
|
||||
.map_err(|e| format!("VectorCraft refused the agent token: {e}"))?;
|
||||
self.conn = Some(conn);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends one request and reads the reply with its `id` (lines for other ids are skipped): `Err`
|
||||
/// when the connection failed or the call was cancelled while it waited, `Ok(Err)` when the app
|
||||
/// answered with an error. With `cancellable`, a cancelled MCP call stops waiting.
|
||||
fn round_trip(
|
||||
conn: &mut (BufReader<TcpStream>, TcpStream),
|
||||
id: u64,
|
||||
method: &str,
|
||||
params: Value,
|
||||
cancellable: bool,
|
||||
) -> Result<Result<Value, String>, String> {
|
||||
let (reader, writer) = conn;
|
||||
let line = json!({"id": id, "method": method, "params": params}).to_string();
|
||||
writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?;
|
||||
let deadline = Instant::now() + CALL_TIMEOUT;
|
||||
loop {
|
||||
let reply = read_line(reader, deadline, cancellable)?;
|
||||
let v: Value = serde_json::from_slice(&reply).map_err(|e| format!("bad reply from the window: {e}"))?;
|
||||
if v.get("id").and_then(Value::as_u64) != Some(id) {
|
||||
continue;
|
||||
}
|
||||
return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(v.get("result").cloned().unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// One reply line, at most [`MAX_REPLY_BYTES`], read by `deadline`.
|
||||
fn read_line(reader: &mut BufReader<TcpStream>, deadline: Instant, cancellable: bool) -> Result<Vec<u8>, String> {
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err("the window did not answer in time".into());
|
||||
}
|
||||
reader.get_ref().set_read_timeout(Some(left.min(CANCEL_POLL))).map_err(|e| e.to_string())?;
|
||||
let room = (MAX_REPLY_BYTES + 1).saturating_sub(line.len() as u64);
|
||||
// `read_until` keeps what it read before a timeout, so the line goes on where it stopped.
|
||||
match reader.by_ref().take(room).read_until(b'\n', &mut line) {
|
||||
Ok(0) => return Err("the window closed the connection".into()),
|
||||
Ok(_) if line.ends_with(b"\n") => return Ok(line),
|
||||
Ok(_) if line.len() as u64 > MAX_REPLY_BYTES => return Err("the window's reply is too long".into()),
|
||||
Ok(_) => return Err("the window closed the connection".into()),
|
||||
Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
|
||||
if cancellable && vectorcraft_engine::cancel::is_cancelled() {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == ErrorKind::Interrupted => {}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for Window {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
if self.conn.is_none() {
|
||||
self.connect().map_err(|e| format!("the VectorCraft window is not reachable: {e}; `{method}`: nothing was sent"))?;
|
||||
}
|
||||
let id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1).max(1);
|
||||
let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) };
|
||||
let cancellable = vectorcraft_engine::cancel::is_cancellable();
|
||||
match round_trip(conn, id, method, params, cancellable) {
|
||||
Ok(answer) => answer,
|
||||
// Never sent again: the request may have run. The next call reconnects.
|
||||
Err(e) => {
|
||||
self.conn = None;
|
||||
if e == "cancelled" {
|
||||
return Err(format!(
|
||||
"the VectorCraft window: `{method}` cancelled; the app may still finish what it was asked, which can't be stopped from here"
|
||||
));
|
||||
}
|
||||
Err(format!("lost the connection to the VectorCraft window ({e}); `{method}` may or may not have run: inspect state before retrying"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
format!("the open VectorCraft window ({})", self.addr)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- The live backend --------------------------------------------------------------------------
|
||||
|
||||
type SharedWindow = Arc<Mutex<Window>>;
|
||||
/// The headless session stays on the server's thread, as the backend does.
|
||||
type SharedHeadless = Rc<RefCell<Headless>>;
|
||||
|
||||
/// Makes each new headless session (the CLI attaches the user's stores) from its automation roots.
|
||||
pub type HeadlessMaker = Box<dyn Fn(Option<Arc<AutomationRoots>>) -> Headless + Send + Sync>;
|
||||
|
||||
/// What plain `vectorcraft-cli mcp` needs to find the window.
|
||||
pub struct LiveConfig {
|
||||
/// The app's settings folder: connection file, token file and agent settings.
|
||||
pub config_dir: PathBuf,
|
||||
/// Reads the agent settings saved in a settings folder (`agents.json`).
|
||||
pub read_settings: fn(&Path) -> AgentSettings,
|
||||
/// Overrides the app's closed-app choice (`--when-closed`).
|
||||
pub when_closed: Option<WhenAppClosed>,
|
||||
/// The command's folders (`--automation-read-root`, `--automation-write-root`).
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't.
|
||||
pub launch: Option<shared::LaunchFn>,
|
||||
pub launch_timeout: Duration,
|
||||
/// Whether agents may use the app now ([`allowed_now`]); tests replace it.
|
||||
pub allowed: fn() -> bool,
|
||||
/// The default agent folder for an empty folder setting; tests replace it.
|
||||
pub default_folder: Option<PathBuf>,
|
||||
/// Makes each new headless session.
|
||||
pub headless: HeadlessMaker,
|
||||
}
|
||||
|
||||
impl LiveConfig {
|
||||
/// The settings in `config_dir` as `read_settings` reads them, the launcher's switch, the
|
||||
/// default agent folder, and a plain headless session with a document.
|
||||
pub fn new(config_dir: PathBuf, read_settings: fn(&Path) -> AgentSettings) -> Self {
|
||||
Self {
|
||||
config_dir,
|
||||
read_settings,
|
||||
when_closed: None,
|
||||
read_roots: Vec::new(),
|
||||
write_root: None,
|
||||
launch: None,
|
||||
launch_timeout: shared::LAUNCH_TIMEOUT,
|
||||
allowed: allowed_now,
|
||||
default_folder: craft::control::agents::default_folder(APP_NAME),
|
||||
headless: Box::new(|roots| Headless::with_document().with_automation_roots(roots)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain `vectorcraft-cli mcp`: every call goes to the open window while the person lets agents
|
||||
/// use it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup
|
||||
/// is the shared `craft::automation::agents::Live`; a session that went headless stays headless.
|
||||
pub struct LiveBackend {
|
||||
live: shared::Live<SharedWindow, SharedHeadless>,
|
||||
config_dir: PathBuf,
|
||||
read_settings: fn(&Path) -> AgentSettings,
|
||||
default_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LiveBackend {
|
||||
pub fn new(cfg: LiveConfig) -> Self {
|
||||
let LiveConfig { config_dir, read_settings, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } =
|
||||
cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
|
||||
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
|
||||
let mut window = Window::new(w.port, w.token.clone());
|
||||
window.connect()?;
|
||||
Ok(Arc::new(Mutex::new(window)))
|
||||
};
|
||||
let make_headless = move |wanted: &HeadlessFolders| -> Result<SharedHeadless, String> {
|
||||
let roots = if wanted.read.is_empty() && wanted.write.is_none() {
|
||||
None
|
||||
} else {
|
||||
let read: Vec<&Path> = wanted.read.iter().map(PathBuf::as_path).collect();
|
||||
let write: Vec<&Path> = wanted.write.as_deref().into_iter().collect();
|
||||
Some(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
|
||||
};
|
||||
Ok(Rc::new(RefCell::new(headless(roots))))
|
||||
};
|
||||
let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, make_headless);
|
||||
shared_cfg.when_closed = when_closed;
|
||||
shared_cfg.read_roots = read_roots;
|
||||
shared_cfg.write_root = write_root;
|
||||
shared_cfg.launch = launch;
|
||||
shared_cfg.launch_timeout = launch_timeout;
|
||||
shared_cfg.default_folder = default_folder.clone();
|
||||
Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder }
|
||||
}
|
||||
|
||||
/// The folders the open window lets agents use, as the window opens them.
|
||||
fn window_folders(&self) -> Value {
|
||||
folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for LiveBackend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.live.resolve()? {
|
||||
Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()),
|
||||
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(h) => h.borrow_mut().call(method, params),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
matches!(self.live.resolve(), Ok(Route::Window(_)))
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"the open VectorCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window"
|
||||
.into()
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,12 @@ impl Remote {
|
||||
|
||||
impl Backend for Remote {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
if method == crate::agents::FOLDERS_METHOD {
|
||||
return Err(format!(
|
||||
"the app at {} was started with --control, so agent folders don't apply: its own --automation-read-root and --automation-write-root, if given, confine it",
|
||||
self.addr
|
||||
));
|
||||
}
|
||||
let addr = self.addr.clone();
|
||||
let client = self.open_client(method)?;
|
||||
// The app can't stop what it runs, but a cancelled call stops waiting for it.
|
||||
|
||||
@@ -163,13 +163,11 @@ impl Headless {
|
||||
}
|
||||
None if KEYBOARD_ONLY.contains(&id) => {
|
||||
return Err(format!(
|
||||
"`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, `--connect` included"
|
||||
"`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, in the open window too"
|
||||
));
|
||||
}
|
||||
None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => {
|
||||
return Err(format!(
|
||||
"`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`"
|
||||
));
|
||||
return Err(format!("`{id}` is a desktop UI command (`ui: true`): it {}", crate::agents::NEEDS_WINDOW));
|
||||
}
|
||||
None => self.session.check_params(id, params).map_err(|e| e.to_string())?,
|
||||
}
|
||||
@@ -451,9 +449,8 @@ impl Headless {
|
||||
"app.save" => self.save(p),
|
||||
"app.export" => self.export(p),
|
||||
"app.quit" => Ok(Value::Null),
|
||||
m if m.starts_with("ui.") => {
|
||||
Err(format!("`{m}` needs the desktop app (start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`)"))
|
||||
}
|
||||
crate::agents::FOLDERS_METHOD => Ok(crate::agents::headless_folders(self.roots.as_deref())),
|
||||
m if m.starts_with("ui.") => Err(format!("`{m}` {}", crate::agents::NEEDS_WINDOW)),
|
||||
other => Err(format!("unknown method `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,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;
|
||||
|
||||
@@ -405,7 +405,7 @@ Method:
|
||||
removeWord / dictionary; for this document only, text.spelling.ignoreAll.
|
||||
4. Prefer those commands over inventing replacements. screenshot if the layout may reflow.
|
||||
|
||||
Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); use --connect for the underlines.",
|
||||
Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); the underlines need the open window.",
|
||||
},
|
||||
PromptDef {
|
||||
name: "variables-bind",
|
||||
|
||||
@@ -4,6 +4,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::{Backend, Headless, PROTOCOL_VERSION, Remote, Server, tool_definitions};
|
||||
|
||||
mod agents;
|
||||
mod batchdraw;
|
||||
mod concurrency;
|
||||
mod conventions;
|
||||
@@ -279,10 +280,11 @@ fn tool_schemas_are_valid() {
|
||||
"transform",
|
||||
"create_graph",
|
||||
"text_wrap",
|
||||
"agent_folders",
|
||||
] {
|
||||
assert!(names.contains(want), "missing tool {want}");
|
||||
}
|
||||
assert_eq!(tools.len(), 33, "parity docs and #6460 expect 33 MCP tools");
|
||||
assert_eq!(tools.len(), 34, "parity docs and #6460 expect 34 MCP tools (agent_folders: #10621)");
|
||||
}
|
||||
|
||||
/// Headless `command_list` must expose engine commands that a stale release CLI used to omit (#6460).
|
||||
@@ -335,7 +337,7 @@ fn headless_command_list_includes_ui_commands() {
|
||||
}
|
||||
let r = call(&mut s, 40, "command_run", json!({"id": "view.fitArtboard", "params": {}}));
|
||||
assert_eq!(r["isError"], true, "{r}");
|
||||
assert!(text_of(&r).contains("--connect"), "{r}");
|
||||
assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}");
|
||||
}
|
||||
|
||||
/// Desktop commands that the app refuses for every automated request are not offered through
|
||||
@@ -1102,7 +1104,7 @@ fn answer_dialog_needs_the_desktop_app() {
|
||||
let mut s = server();
|
||||
let r = call(&mut s, 1, "answer_dialog", json!({"action": "confirm"}));
|
||||
assert_eq!(r["isError"], true, "{r}");
|
||||
assert!(text_of(&r).contains("needs the desktop app"), "{r}");
|
||||
assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}");
|
||||
}
|
||||
|
||||
/// How long a fake app waits for [`Remote`] to connect or to send, and how long a test waits for
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Plain `mcp` in front of the open window (`crate::agents`): the window gets the calls only while
|
||||
//! agents are allowed and it proves it holds the token; otherwise the closed-app choice applies.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use craft::automation::agents::{AgentSettings, Connection, TOKEN_FILE, WhenAppClosed, write_connection};
|
||||
use craft::automation::security::{AuthStep, ServerHandshake};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::TempFolder;
|
||||
use crate::Backend;
|
||||
use crate::agents::{FOLDERS_METHOD, LiveBackend, LiveConfig};
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// A stand-in for the window's control server holding `token`: it authenticates as the shared
|
||||
/// server does and answers every request with `{"window": true, "method"}`. The count is of the
|
||||
/// requests it got after authentication.
|
||||
fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let served = Arc::new(AtomicUsize::new(0));
|
||||
let count = served.clone();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { return };
|
||||
let count = count.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut writer = stream.try_clone().unwrap();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut signed_in = false;
|
||||
for line in BufReader::new(stream).lines() {
|
||||
let Ok(line) = line else { return };
|
||||
let reply = if signed_in {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}})
|
||||
} else {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
signed_in = matches!(step, AuthStep::Authenticated);
|
||||
reply
|
||||
};
|
||||
if writeln!(writer, "{reply}").is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
(port, served)
|
||||
}
|
||||
|
||||
/// Publishes a window on `port` in the settings folder `dir`, as the app's agents link does, with
|
||||
/// [`TOKEN`] in its token file.
|
||||
fn publish(dir: &Path, port: u16) {
|
||||
let token_file = dir.join(TOKEN_FILE);
|
||||
std::fs::write(&token_file, TOKEN).unwrap();
|
||||
// The client reads only a token its owner alone can read, as the app writes it.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
write_connection(dir, &Connection::new(port, token_file, "VectorCraft test")).unwrap();
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn closed_port() -> u16 {
|
||||
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
fn settings_headless(_: &Path) -> AgentSettings {
|
||||
let mut s = AgentSettings::default();
|
||||
s.when_app_closed = WhenAppClosed::Headless;
|
||||
s
|
||||
}
|
||||
|
||||
fn settings_error(_: &Path) -> AgentSettings {
|
||||
let mut s = AgentSettings::default();
|
||||
s.when_app_closed = WhenAppClosed::Error;
|
||||
s
|
||||
}
|
||||
|
||||
fn live(dir: &Path, allowed: fn() -> bool, read_settings: fn(&Path) -> AgentSettings, default_folder: PathBuf) -> LiveBackend {
|
||||
let mut cfg = LiveConfig::new(dir.to_path_buf(), read_settings);
|
||||
cfg.allowed = allowed;
|
||||
cfg.default_folder = Some(default_folder);
|
||||
LiveBackend::new(cfg)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_mcp_reaches_the_window_while_agents_are_allowed() {
|
||||
let dir = TempFolder::new("agents-window");
|
||||
let (port, served) = fake_window(TOKEN);
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
assert!(b.has_ui());
|
||||
let r = b.call("document.inspect", json!({})).unwrap();
|
||||
assert_eq!(r["window"], true, "{r}");
|
||||
assert!(served.load(Ordering::SeqCst) >= 1);
|
||||
// The window's folders are the agent folders as the window opens them: the default one here.
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy()));
|
||||
assert_eq!(folders["write_folder"], folders["read_folder"]);
|
||||
}
|
||||
|
||||
// With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with
|
||||
// only the command's folders: the closed-app choice (an error here) is for agents the person let in.
|
||||
#[test]
|
||||
fn with_agents_off_plain_mcp_runs_headless() {
|
||||
let dir = TempFolder::new("agents-off");
|
||||
let mut b = live(&dir, || false, settings_error, dir.file("Agents"));
|
||||
assert!(!b.has_ui());
|
||||
let r = b.call("document.inspect", json!({}));
|
||||
assert!(r.as_ref().is_ok_and(|r| r["window"] != true), "{r:?}");
|
||||
assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true);
|
||||
assert!(!dir.file("Agents").exists(), "the agent folder is made only for agents the person let in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_cannot_prove_the_token_gets_nothing() {
|
||||
let dir = TempFolder::new("agents-bad-token");
|
||||
let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
let e = b.call("document.inspect", json!({})).unwrap_err();
|
||||
assert!(e.contains("could not prove"), "{e}");
|
||||
assert_eq!(served.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
|
||||
let dir = TempFolder::new("agents-stale");
|
||||
publish(&dir, closed_port());
|
||||
let mut b = live(&dir, || true, settings_error, dir.file("Agents"));
|
||||
let e = b.call("document.inspect", json!({})).unwrap_err();
|
||||
assert!(e.contains("isn't running"), "{e}");
|
||||
|
||||
// Headless: a session without a window, confined to the agent folders.
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
assert!(!b.has_ui());
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders["read_folder"], json!(std::fs::canonicalize(dir.file("Agents")).map(shown).unwrap()));
|
||||
let outside = dir.file("outside.svg");
|
||||
std::fs::write(&outside, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="3"/>"#).unwrap();
|
||||
let e = b.call("app.open", json!({"path": outside.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
}
|
||||
|
||||
/// A canonical path as the automation roots show it: without Windows' `\\?\` prefix.
|
||||
fn shown(p: PathBuf) -> String {
|
||||
let s = p.to_string_lossy().into_owned();
|
||||
s.strip_prefix(r"\\?\").map_or(s.clone(), str::to_owned)
|
||||
}
|
||||
@@ -27,7 +27,16 @@ fn headless_links_report_missing_files_and_relink() {
|
||||
let r = run(&mut h, "document.open", json!({"path": file("doc.vectorcraft")}));
|
||||
assert_eq!(r["missingLinks"][0]["ids"], json!([id]), "{r}");
|
||||
assert_eq!(run(&mut h, "links.check", json!({}))["missing"], 1);
|
||||
assert_eq!(run(&mut h, "links.marked", json!({})), json!({"on": false, "images": []}));
|
||||
assert_eq!(run(&mut h, "view.showMissingLinks", json!({"on": true})), json!({"on": true}));
|
||||
let markers = run(&mut h, "links.marked", json!({}));
|
||||
assert_eq!(markers["images"][0]["id"], id);
|
||||
assert_eq!(markers["images"][0]["bounds"].as_array().unwrap().len(), 4);
|
||||
run(&mut h, "view.showMissingLinks", json!({"on": false}));
|
||||
assert_eq!(run(&mut h, "links.marked", json!({}))["images"], json!([]));
|
||||
run(&mut h, "view.showMissingLinks", json!({"on": true}));
|
||||
let r = run(&mut h, "links.relink", json!({"ids": [id], "path": file("b.png")}));
|
||||
assert_eq!(r["relinked"], json!([id]));
|
||||
assert_eq!(run(&mut h, "links.check", json!({}))["links"][0]["status"], "ok");
|
||||
assert_eq!(run(&mut h, "links.marked", json!({}))["images"], json!([]));
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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});
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -171,10 +171,13 @@ mod tests {
|
||||
let expected: Vec<_> =
|
||||
["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect();
|
||||
assert_eq!(startup, expected);
|
||||
// Korean and Devanagari faces are fetched only on demand, never at startup or in the
|
||||
// background queue every session runs.
|
||||
// Korean, Devanagari and Gujarati faces are fetched only on demand, never at startup or in
|
||||
// the background queue every session runs.
|
||||
let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect();
|
||||
let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect();
|
||||
let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari", "Noto Sans Gujarati"]
|
||||
.into_iter()
|
||||
.filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n))
|
||||
.collect();
|
||||
assert_eq!(demand, expected);
|
||||
assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand)));
|
||||
}
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
# startup = fetched before the app starts (fallbacks the first frame needs)
|
||||
# background = fetched after the app starts (fonts users pick by name)
|
||||
# demand = fetched only when the interface language or the interface's own text needs one of
|
||||
# the face's scripts (Korean, Hindi)
|
||||
# the face's scripts (Korean, Hindi, Gujarati)
|
||||
# Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook).
|
||||
startup | Noto Sans Arabic | Regular
|
||||
startup | Noto Sans Thai | Regular
|
||||
startup | Noto Sans Georgian | Regular
|
||||
demand | NanumGothic | Regular
|
||||
demand | Noto Sans Devanagari | Regular
|
||||
demand | Noto Sans Gujarati | Regular
|
||||
|
||||
+56
-11
@@ -110,6 +110,8 @@ struct HandlePress {
|
||||
moved: bool,
|
||||
/// The picked handles when the press began.
|
||||
picked: PickedHandles,
|
||||
/// A mirroring Cmd/Ctrl press on one of several picked handles: they stay picked after its drag.
|
||||
keeps_picks: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -1046,6 +1048,33 @@ impl Tool for DirectSelectionTool {
|
||||
self.lent_cmd = value.as_bool().unwrap_or(false);
|
||||
}
|
||||
}
|
||||
/// A Cmd/Ctrl press without Alt on the end of a shown direction handle (a path's, type on a
|
||||
/// path's or a selected blend spine anchor's) stays with Direct Selection, so the drag mirrors
|
||||
/// the opposite handle ([`DirectSelectionTool::mirrors`]). A press on a handle of the bounding
|
||||
/// box the lent Selection tool shows still goes to that tool, and so does a press anywhere else,
|
||||
/// including one that a press of the tool gives to something it checks before the handles (a
|
||||
/// corner widget, a bracket of type on a path, a gradient mesh point).
|
||||
fn keeps_cmd_press(&self, cx: &ToolContext, p: Point, mods: Mods) -> bool {
|
||||
if self.group || mods.alt || crate::select::bbox_handle_at(cx, p) {
|
||||
return false;
|
||||
}
|
||||
let point = cx.point_tol();
|
||||
// The order of the checks is the order `pointer` tries them in on a press.
|
||||
let ev = PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods);
|
||||
if CornerDrag::hit(cx, &ev, true).is_some_and(|c| !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w)))) {
|
||||
return false;
|
||||
}
|
||||
if !over_path_type_anchor(cx, p) && BracketDrag::hit_any(cx, &ev).is_some() {
|
||||
return false;
|
||||
}
|
||||
if self.spine.filter(|(id, _)| cx.selection.contains(*id)).and_then(|sel| hit_spine_handle(cx, sel, p, point)).is_some() {
|
||||
return true;
|
||||
}
|
||||
if self.mesh.hit(cx, &cx.selection.objects, p).is_some() {
|
||||
return false;
|
||||
}
|
||||
hit_handle(cx, p, point).is_some()
|
||||
}
|
||||
/// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh
|
||||
/// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved
|
||||
/// goes back and the tool waits for the next press (#1743).
|
||||
@@ -1087,13 +1116,16 @@ impl Tool for DirectSelectionTool {
|
||||
self.mesh.cancel();
|
||||
// The frame anchors or handles a cancelled drag held stay selected.
|
||||
let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty();
|
||||
let handles = matches!(self.state, State::Handles { .. });
|
||||
let kept = self.handle_press.take().filter(|press| press.keeps_picks && matches!(self.state, State::Handle { .. }));
|
||||
let handles = matches!(self.state, State::Handles { .. }) || kept.is_some();
|
||||
if let Some(press) = kept {
|
||||
self.handles = press.picked;
|
||||
}
|
||||
self.state = State::Idle;
|
||||
self.guides.clear();
|
||||
(self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None);
|
||||
self.last_location = None;
|
||||
(self.click, self.click_segment, self.click_group, self.frame_click) = (None, None, None, None);
|
||||
self.handle_press = None;
|
||||
match (frame, handles) {
|
||||
(true, _) => vec![Action::Cancel, Action::Notify(FRAME_PICKED.into())],
|
||||
(_, true) => vec![Action::Cancel, Action::Notify(HANDLES_PICKED.into())],
|
||||
@@ -1896,9 +1928,11 @@ impl DirectSelectionTool {
|
||||
self.state = State::Handle { id, si, ai, out, drag: Some(drag) };
|
||||
vec![Action::Preview("path.setHandle".into(), params)]
|
||||
}
|
||||
/// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift on one of two or
|
||||
/// more picked handles (`picks`, as they were before the press), a drag moves them all; any
|
||||
/// other press drags that handle alone, as before handles could be picked.
|
||||
/// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift or a mirroring
|
||||
/// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were
|
||||
/// before the press), a drag moves them all; any other press drags that handle alone, as before
|
||||
/// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. The picked handles
|
||||
/// stay picked after such a Cmd/Ctrl or Cmd/Ctrl+Shift drag of one of them.
|
||||
fn press_handle(
|
||||
&mut self,
|
||||
cx: &ToolContext,
|
||||
@@ -1931,8 +1965,11 @@ impl DirectSelectionTool {
|
||||
};
|
||||
let handle = (id, (si, ai, out));
|
||||
let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1));
|
||||
let several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::<usize>() > 1;
|
||||
let begin = if several {
|
||||
let one_of_several = on && picks.values().map(BTreeSet::len).sum::<usize>() > 1;
|
||||
let among_several = one_of_several && !ev.mods.shift;
|
||||
// A mirroring drag keeps the picks with Shift held too.
|
||||
let keeps_picks = one_of_several && self.mirrors(ev);
|
||||
let begin = if among_several && !keeps_picks {
|
||||
let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect();
|
||||
self.state = State::Handles { handle, from, start: p, items, began: false };
|
||||
self.handles = picks.clone();
|
||||
@@ -1942,7 +1979,7 @@ impl DirectSelectionTool {
|
||||
self.state = State::Handle { id, si, ai, out, drag };
|
||||
vec![Action::Begin("Reshape".into())]
|
||||
};
|
||||
self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks });
|
||||
self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks, keeps_picks });
|
||||
begin
|
||||
}
|
||||
/// The release of a press on one of several picked handles: a drag commits, and the picked
|
||||
@@ -1957,10 +1994,18 @@ impl DirectSelectionTool {
|
||||
self.handles = BTreeMap::from([(handle.0, BTreeSet::from([handle.1]))]);
|
||||
vec![Action::Notify(HANDLES_PICKED.into())]
|
||||
}
|
||||
/// After the release of a press on a handle that did not drag: a click picks the handle alone,
|
||||
/// and a Shift-click adds it to the picked handles or takes it away.
|
||||
/// After the release of a press on a handle: a click picks the handle alone, and a Shift-click
|
||||
/// adds it to the picked handles or takes it away. A mirroring drag of one of several picked
|
||||
/// handles leaves them all picked.
|
||||
fn pick_clicked_handle(&mut self) -> Option<Action> {
|
||||
let press = self.handle_press.take().filter(|press| !press.moved)?;
|
||||
let press = self.handle_press.take()?;
|
||||
if press.moved {
|
||||
if !press.keeps_picks {
|
||||
return None;
|
||||
}
|
||||
self.handles = press.picked;
|
||||
return Some(Action::Notify(HANDLES_PICKED.into()));
|
||||
}
|
||||
let (id, h) = press.handle;
|
||||
let mut picked = if press.shift { press.picked } else { BTreeMap::new() };
|
||||
let set = picked.entry(id).or_default();
|
||||
|
||||
@@ -279,6 +279,12 @@ pub trait Tool: Send {
|
||||
fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option<NodeId> {
|
||||
None
|
||||
}
|
||||
/// Does a press at `p` with Cmd/Ctrl and `mods` held stay with the tool, instead of going to
|
||||
/// the selection tool the session lends for Cmd/Ctrl? Direct Selection keeps a press on a shown
|
||||
/// direction handle, where Cmd/Ctrl mirrors the opposite handle.
|
||||
fn keeps_cmd_press(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> bool {
|
||||
false
|
||||
}
|
||||
/// What the Info panel shows for the tool as it is now: the drag in progress (a move of the
|
||||
/// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear
|
||||
/// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show.
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use craft::ui::docking::IconGroupSeparator;
|
||||
use craft::ui::list::{CommandHighlight, ThumbRows};
|
||||
use craft::ui::menu::{MenuTitleLook, MenuTitlePad};
|
||||
use craft::ui::patterns::form_dialogs::PresetCardLook;
|
||||
use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey};
|
||||
use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env};
|
||||
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
use craft::ui::runtime::toast::{self, Toast};
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
@@ -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
|
||||
@@ -771,7 +799,7 @@ impl VectorcraftApp {
|
||||
let mut control_bar_place = chrome::control_bar_place(&self.ui);
|
||||
// PLAN: assumed `chrome::window_title(&VectorcraftApp) -> String` (shell-01 A1 names the call, no row gives its signature; shell-w9).
|
||||
let window_title = chrome::window_title(self);
|
||||
let shown = AppShell::new(WindowKey::main())
|
||||
let shell = AppShell::new(WindowKey::main())
|
||||
.title_bar_if(true, |_| None, chrome::app_bar)
|
||||
.options_bar(
|
||||
self.ui.control_bar,
|
||||
@@ -801,8 +829,11 @@ impl VectorcraftApp {
|
||||
.body(|ui, cx, app: &mut VectorcraftApp| {
|
||||
panel_docking::show(app, ui, cx.shell().is_some_and(|shell| shell.panels_hidden()));
|
||||
crate::place::window_files(app, ui);
|
||||
})
|
||||
.show(ui, self);
|
||||
});
|
||||
// The shell shows the window's dialogs under these words. Temporary: removed once the craft-libs pin includes
|
||||
// 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 {
|
||||
self.ui.follow_screen_mode(shown.screen_mode);
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use craft::behavior::{ColumnWidth, IconId};
|
||||
use craft::i18n::WordSet as _;
|
||||
use craft::ui::buttons::{Link, LinkLook};
|
||||
use craft::ui::contract::{Bind, Gap, Pad, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout::CellAlign;
|
||||
use craft::ui::layout_components::{Grid, Stack};
|
||||
use craft::ui::runtime::env::{Env, Overrides, with_env};
|
||||
use craft::ui::runtime::env::{Env, Overrides, WordRows, WordsOverride, with_env};
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::shell::{RecentFile, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template};
|
||||
use craft::ui::shell::{RecentFile, ShellWords, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template};
|
||||
use craft::ui::style::{SurfaceKind, TypeRole};
|
||||
|
||||
use super::{Ui, VectorcraftApp, json};
|
||||
@@ -45,9 +46,14 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
}
|
||||
let mut pressed = None;
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
// Production's community links read in the accent alone, with no underline.
|
||||
let plain_links = |overrides: &mut Overrides| {
|
||||
let words = recent_words(app.ui_language());
|
||||
// Production's community links read in the accent alone, with no underline, and the recent files are headed
|
||||
// "Recent Files".
|
||||
let set_env = |overrides: &mut Overrides| {
|
||||
overrides.values.set(LinkLook::Plain);
|
||||
if let Some(words) = words {
|
||||
overrides.words = Some(WordsOverride::Overlay(words));
|
||||
}
|
||||
};
|
||||
// Learn follows the presets, which stand right under New and Open as in production 0.24.1.
|
||||
let start = StartScreen::new(Bind::bound(&mut app.ui.home_view), Bind::bound(&mut app.ui.home_sort), &recent)
|
||||
@@ -62,7 +68,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
.links(&links)
|
||||
.links_title(tl!("Community"))
|
||||
.section(StartPlace::AfterSections, |ui, _| learn(ui, &mut pressed));
|
||||
let out = with_env(&mut child, plain_links, |ui| start.show(ui));
|
||||
let out = with_env(&mut child, set_env, |ui| start.show(ui));
|
||||
for action in out.actions {
|
||||
run_action(app, action);
|
||||
}
|
||||
@@ -73,6 +79,17 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
}
|
||||
}
|
||||
|
||||
/// VectorCraft's heading for the Home screen's recent files, "Recent Files", over the framework's "Recent". Outside
|
||||
/// English, a language whose catalog does not translate it keeps the framework's translation.
|
||||
// Workaround for craft-libs#4890: once the craft-libs pin includes it, the start screen's `recent_title` heads the
|
||||
// list, and this word row is removed.
|
||||
fn recent_words(lang: crate::i18n::Lang) -> Option<WordRows> {
|
||||
const ENGLISH: &str = "Recent Files";
|
||||
let shown = crate::i18n::tr(lang, ENGLISH);
|
||||
let word = ShellWords::word("startScreen.recent")?;
|
||||
(lang == crate::i18n::Lang::EN || shown != ENGLISH).then(|| WordRows::new().row(word, shown))
|
||||
}
|
||||
|
||||
/// What the start screen's user did. A command that fails says why in the status bar (#6160).
|
||||
fn run_action(app: &mut VectorcraftApp, action: StartAction) {
|
||||
fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) {
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
@@ -1238,6 +1263,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();
|
||||
@@ -1543,8 +1600,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");
|
||||
@@ -1560,6 +1616,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]
|
||||
@@ -1658,6 +1758,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]
|
||||
|
||||
@@ -33,7 +33,7 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKi
|
||||
use craft::ui::patterns::presets::{NamedPresetEvent, PresetError, PresetRow};
|
||||
use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook};
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::runtime::env::{LengthUnits, UnitKind};
|
||||
use craft::ui::runtime::env::{LengthUnits, UnitKind, WordRows};
|
||||
use craft::ui::shell::WindowDialogs;
|
||||
use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -518,6 +518,15 @@ pub(super) fn settings(fields: &DialogFields) -> Value {
|
||||
Value::Object(nested(p))
|
||||
}
|
||||
|
||||
/// The words that title File › Print "Print" while the Print dialog is open in Print mode, for the window's shell to
|
||||
/// show its dialogs under. The framework titles a dialog in sections "Print Settings". Temporary: this is removed, and
|
||||
/// the dialog is titled with `HostedPrint::title`, once the craft-libs pin includes storytold/craft-libs#4891.
|
||||
pub(crate) fn title_words(app: &VectorcraftApp) -> Option<WordRows> {
|
||||
app.print_dialog.open.as_ref().filter(|open| open.mode == PrintMode::Print)?;
|
||||
let title = craft::i18n::Word::keyed("printDialog.title", "Print Settings");
|
||||
Some(WordRows::new().row(title, tl!("Print")))
|
||||
}
|
||||
|
||||
/// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was
|
||||
/// dragged to, the presets and OK.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
|
||||
@@ -143,6 +143,42 @@ fn pages(pdf: &[u8]) -> usize {
|
||||
vectorcraft_pdf::info(pdf, None).unwrap().pages.len()
|
||||
}
|
||||
|
||||
/// The texts the whole window paints, with where each is drawn, once the open dialog has faded in (each frame is a
|
||||
/// quarter second on).
|
||||
fn window_texts(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> {
|
||||
let ctx = ctx(app);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0));
|
||||
let mut texts = vec![];
|
||||
for k in 0..4 {
|
||||
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
|
||||
let out = crate::testing::app_frame(app, &ctx, raw);
|
||||
texts = crate::tests_labels::text_shapes(&out)
|
||||
.into_iter()
|
||||
.map(|(t, transform)| (t.galley.text().to_string(), transform * t.galley.rect.translate(t.pos.to_vec2())))
|
||||
.collect();
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_print_dialog_is_titled_print_and_the_preset_editor_keeps_its_title() {
|
||||
let (mut printing, _) = app();
|
||||
printing.run("file.print", json!({})).unwrap();
|
||||
let texts = window_texts(&mut printing);
|
||||
let painted = |texts: &[(String, egui::Rect)], text: &str| texts.iter().filter(|(t, _)| t == text).map(|(_, r)| *r).collect::<Vec<_>>();
|
||||
assert!(painted(&texts, "Print Settings").is_empty(), "the Print dialog is not titled Print Settings: {texts:?}");
|
||||
let preset_row = painted(&texts, "Print Preset");
|
||||
let preset_row = preset_row.first().expect("the Print Preset row is shown");
|
||||
// The title sits above the dialog's first row; the Print button sits below it.
|
||||
assert!(painted(&texts, "Print").iter().any(|title| title.bottom() <= preset_row.top()), "the dialog is titled Print: {texts:?}");
|
||||
|
||||
// The preset editor keeps the framework's title.
|
||||
let (mut editing, _) = app();
|
||||
editing.run("ui.printPresetDialog", json!({"preset": vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET})).unwrap();
|
||||
let texts = window_texts(&mut editing);
|
||||
assert!(!painted(&texts, "Print Settings").is_empty(), "the preset editor is titled Print Settings: {texts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_sends_every_page_to_the_chosen_printer_and_keeps_the_settings() {
|
||||
let (mut app, jobs) = app();
|
||||
|
||||
@@ -74,17 +74,33 @@ static EMBEDDED: &Embedded = &[
|
||||
|
||||
/// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font
|
||||
/// fallback, so on the web a language whose text would be missing-glyph boxes (Gujarati without a
|
||||
/// bundled Gujarati face) is not offered, including when restoring a preference. Arabic is kept
|
||||
/// unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed.
|
||||
/// Gujarati face, see [`has_gujarati_face`]) is not offered, including when restoring a preference.
|
||||
/// Arabic is kept unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed.
|
||||
fn offered_codes(web: bool, gujarati_font: bool) -> Vec<&'static str> {
|
||||
EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect()
|
||||
}
|
||||
|
||||
/// Whether the interface has a Gujarati face: an embedded craft-fonts face, or on the web a face
|
||||
/// the interface font stack serves (`SERVED_FONTS`, the `startup` and `demand` lines of
|
||||
/// `crates/text/web-fonts.txt`) and fetches when Gujarati text needs it.
|
||||
fn has_gujarati_face() -> bool {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let served = vectorcraft_text::SERVED_FONTS.iter().map(|f| f.scripts);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let served = std::iter::empty();
|
||||
has_gujarati_face_in(vectorcraft_text::CRAFT_FONTS, served)
|
||||
}
|
||||
|
||||
/// [`has_gujarati_face`] for the given embedded faces and the scripts of each served face.
|
||||
fn has_gujarati_face_in<'a>(embedded: &[vectorcraft_text::EmbeddedFace], mut served: impl Iterator<Item = &'a [&'a str]>) -> bool {
|
||||
embedded.iter().any(|f| f.has_script("Gujr")) || served.any(|scripts| scripts.contains(&"Gujr"))
|
||||
}
|
||||
|
||||
/// The one catalog set of the process, built on first use.
|
||||
fn shared_cell() -> &'static Arc<I18n> {
|
||||
static SHARED: OnceLock<Arc<I18n>> = OnceLock::new();
|
||||
SHARED.get_or_init(|| {
|
||||
let offered = offered_codes(cfg!(target_arch = "wasm32"), vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr")));
|
||||
let offered = offered_codes(cfg!(target_arch = "wasm32"), has_gujarati_face());
|
||||
let (i18n, problems) = I18n::new(EMBEDDED, &offered);
|
||||
for problem in problems {
|
||||
log::warn!("vectorcraft: interface language catalog: {problem}");
|
||||
|
||||
@@ -159,6 +159,23 @@ fn gujarati_web_selection_requires_a_bundled_interface_font() {
|
||||
assert!(codes(true, false).contains(&"hi".to_string()));
|
||||
}
|
||||
|
||||
/// The web build embeds no Gujarati face, but serves Noto Sans Gujarati on demand: the web's
|
||||
/// served faces are the `startup` and `demand` lines of `crates/text/web-fonts.txt`, so the web
|
||||
/// offers Gujarati. Checked where the craft-fonts checkout has the face.
|
||||
#[test]
|
||||
fn web_offers_gujarati_with_the_served_gujarati_face() {
|
||||
if !vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr")) {
|
||||
eprintln!("skipped: built without craft-fonts, or one without a Gujarati face");
|
||||
return;
|
||||
}
|
||||
let served = || vectorcraft_text::WEB_FONTS.iter().filter(|w| w.startup || w.demand).map(|w| w.scripts);
|
||||
let web_embedded: Vec<_> = vectorcraft_text::CRAFT_FONTS.iter().filter(|f| !f.has_script("Gujr")).copied().collect();
|
||||
let font = has_gujarati_face_in(&web_embedded, served());
|
||||
assert!(font, "a served Gujarati face counts on the web");
|
||||
assert!(offered_codes(true, font).contains(&"gu"));
|
||||
assert!(!has_gujarati_face_in(&web_embedded, std::iter::empty()), "without it, nothing draws Gujarati on the web");
|
||||
}
|
||||
|
||||
/// A numbered built-in name shows its name before the number translated and the number as it
|
||||
/// is; a name with a row of its own uses that row, and any other name comes back unchanged.
|
||||
#[test]
|
||||
|
||||
@@ -30,6 +30,7 @@ pub const TOGGLES: &[&str] = &[
|
||||
"view.rulers",
|
||||
"view.boundingBox",
|
||||
"view.transparencyGrid",
|
||||
"view.showMissingLinks",
|
||||
"view.guides",
|
||||
"view.grid",
|
||||
"view.slices.hide",
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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(),
|
||||
]
|
||||
|
||||
@@ -7,15 +7,17 @@
|
||||
//! list stays after the selection changes, so choosing a font in it sets that font on the live text
|
||||
//! selected then, as the font menus do. The sample field sets the text the samples show, and the
|
||||
//! panel menu sets their size; Reset Retype Panel clears the list. `retype.find`, `retype.list`,
|
||||
//! `retype.preview` and `retype.reset` do the same.
|
||||
//! `retype.preview` and `retype.reset` do the same. A font's menu (a secondary click on its row, or
|
||||
//! Shift+F10 on the focused row) selects the row and holds Apply Font, which sets that font as a
|
||||
//! click does, then the panel menu's sample sizes and Reset Retype Panel.
|
||||
|
||||
use craft::behavior::{EditEvent, Mixed, keyed};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::{Button, Link};
|
||||
use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _};
|
||||
use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize};
|
||||
use craft::ui::menu::PanelRow;
|
||||
use craft::ui::menu::{Menu, MenuItem, PanelRow};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::commands::{CommandState, CommandStates};
|
||||
use craft::ui::style::Variant;
|
||||
@@ -50,7 +52,7 @@ const SIZES: [(Size, &str, ThumbSize); 3] =
|
||||
[(Size::Small, "small", ThumbSize::Small), (Size::Medium, "medium", ThumbSize::Medium), (Size::Large, "large", ThumbSize::Large)];
|
||||
|
||||
/// One font in the list.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Found {
|
||||
pub family: String,
|
||||
pub style: String,
|
||||
@@ -114,21 +116,47 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let on_white = app.session.prefs.font_samples_on_white;
|
||||
let indexed: Vec<(usize, &Found)> = view.fonts.iter().enumerate().collect();
|
||||
let source = keyed(&indexed, |(at, _)| *at);
|
||||
// A click activates a row, so the same row chosen again sets its font again.
|
||||
let list = List::<usize>::new(tl!("Matching fonts")).select(SelectMode::Single).activate(ActivateOn::Click).show_items(
|
||||
ui,
|
||||
&source,
|
||||
&mut |key, _| {
|
||||
// The rows are keyed by place, so a list with other fonts, or another document, is another
|
||||
// list: a row's menu closes rather than act on the font that took its place.
|
||||
let document = app.session.active().map(|st| st.uid);
|
||||
// A click activates a row, so the same row chosen again sets its font again. A secondary
|
||||
// click selects its row and asks for the row's menu; it does not activate the row.
|
||||
let list = List::<usize>::new(tl!("Matching fonts"))
|
||||
.id(ui.scope_id().with(("matching-fonts", document, &view.fonts)))
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
.row_menu()
|
||||
.show_items(ui, &source, &mut |key, _| {
|
||||
let (family, style) = indexed.get(*key).map_or(("", ""), |(_, f)| (f.family.as_str(), f.style.as_str()));
|
||||
ListRow::new(format!("{family} {style}")).thumb_aspect(size, ThumbAspect::new(8, 1), move |cx: &ContentPainterCx, rect: Rect| {
|
||||
crate::font_menu::paint_family_sample(cx, rect, family, style, sample, on_white);
|
||||
})
|
||||
},
|
||||
);
|
||||
let chosen = list.events.iter().find_map(|e| match e {
|
||||
});
|
||||
let mut chosen = list.events.iter().find_map(|e| match e {
|
||||
CollectionEvent::Activate(at) => view.fonts.get(*at),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(request) = list.menu
|
||||
&& let Some(f) = view.fonts.get(request.key)
|
||||
{
|
||||
// Apply Font is off while choosing the font would set it on nothing.
|
||||
let live = live_text_selected(app);
|
||||
Menu::context(format!("{} {}", f.family, f.style), &list.response).show(ui, |ui, _| {
|
||||
if MenuItem::new(tl!("Apply Font")).enabled(live).show(ui).ran {
|
||||
chosen = Some(f);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
for (size, name, _) in SIZES {
|
||||
if MenuItem::new(size_label(size)).check(view.size == size).show(ui).ran {
|
||||
run = Some(("retype.preview", json!({ "size": name })));
|
||||
}
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
if MenuItem::new(tl!("Reset Retype Panel")).show(ui).ran {
|
||||
run = Some(("retype.reset", json!({})));
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(f) = chosen
|
||||
&& live_text_selected(app)
|
||||
{
|
||||
|
||||
@@ -232,3 +232,125 @@ fn choosing_a_listed_font_sets_it_on_the_selected_live_text() {
|
||||
click(&mut app, &ctx, "Source Serif 4 Regular");
|
||||
assert!(app.session.active().unwrap().doc == before);
|
||||
}
|
||||
|
||||
/// Live text in Source Sans 3, selected, and a list of two fonts → the app and the text's id.
|
||||
fn listed_with_live_text() -> (VectorcraftApp, u64) {
|
||||
let mut app = app();
|
||||
let font = |family: &str, style: &str| super::Found { family: family.into(), style: style.into(), matched: 1 };
|
||||
app.ui.retype.searched = true;
|
||||
app.ui.retype.fonts = vec![font("Source Sans 3", "Bold"), font("Source Serif 4", "Regular")];
|
||||
let t = app.session.execute("text.create", &json!({"x": 10, "y": 300, "text": "live", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
|
||||
select(&mut app, &[t]);
|
||||
(app, t)
|
||||
}
|
||||
|
||||
fn family_of(app: &VectorcraftApp, id: u64) -> String {
|
||||
let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
text.first_style().font_family.clone()
|
||||
}
|
||||
|
||||
fn undo_len(app: &VectorcraftApp) -> usize {
|
||||
app.session.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
const SERIF: &str = "Source Serif 4 Regular";
|
||||
const SANS: &str = "Source Sans 3 Bold";
|
||||
|
||||
#[test]
|
||||
fn a_fonts_menu_selects_its_row_without_setting_the_font() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, t) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let undo = undo_len(&panel.app());
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(panel.menu_item_enabled("Apply Font"), "live text is selected");
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "the secondary click sets no font");
|
||||
assert_eq!(undo_len(&panel.app()), undo);
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
assert!(panel.selected(SERIF), "the row the menu opened on is selected");
|
||||
assert!(!panel.selected(SANS));
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_font_sets_the_rows_font_on_the_live_text_in_one_undo_step() {
|
||||
let (app, t) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let undo = undo_len(&panel.app());
|
||||
// A menu opened on another row first, then closed: the menu acts on the row it opened on last.
|
||||
panel.secondary_click(SANS);
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
panel.secondary_click(SERIF);
|
||||
panel.click_menu_item("Apply Font");
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Serif 4", "the font of the row the menu opened on");
|
||||
assert_eq!(undo_len(&panel.app()), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_font_is_off_without_live_text() {
|
||||
let (mut app, t) = listed_with_live_text();
|
||||
select(&mut app, &[]);
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(!panel.menu_item_enabled("Apply Font"));
|
||||
assert!(panel.menu_item_enabled("Reset Retype Panel"), "the panel's own items stay on");
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "text that is not selected keeps its font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fonts_menu_sets_the_sample_size_and_resets_the_panel() {
|
||||
use craft::behavior::Mixed;
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, _) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let before = panel.app().ui.retype.size;
|
||||
let (other, label) = if before == Size::Large { (Size::Small, "Small") } else { (Size::Large, "Large") };
|
||||
panel.secondary_click(SERIF);
|
||||
panel.click_role(label, Role::MENU_ITEM_CHECK_BOX);
|
||||
assert_eq!(panel.app().ui.retype.size, other, "the size changed to the one chosen");
|
||||
panel.secondary_click(SERIF);
|
||||
assert_eq!(panel.toggled(label), Some(Mixed::Same(true)), "the size chosen is checked");
|
||||
panel.click_menu_item("Reset Retype Panel");
|
||||
assert!(!panel.app().ui.retype.searched, "the list is cleared");
|
||||
assert_eq!(panel.app().ui.retype.size, other, "the size stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_opens_the_fonts_menu_and_escape_returns_focus() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, t) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.focus(SERIF);
|
||||
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
|
||||
panel.frame();
|
||||
assert!(panel.menu_item_enabled("Apply Font"));
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
assert!(panel.focused(SERIF));
|
||||
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "opening and closing the menu sets no font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fonts_menu_closes_when_the_list_or_the_document_changes() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let (app, _) = listed_with_live_text();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
// Another search puts another font in the row's place.
|
||||
panel.app().ui.retype.fonts.reverse();
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
panel.secondary_click(SERIF);
|
||||
assert!(panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
panel.frame();
|
||||
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -164,6 +164,27 @@ fn home_lists_recent_files_and_a_click_opens_one() {
|
||||
assert!(!app.ui.status.is_empty(), "a file that can't be opened says so");
|
||||
}
|
||||
|
||||
/// The Home screen heads its recent files "Recent Files", in the interface language where the catalog translates it.
|
||||
#[test]
|
||||
fn home_heads_the_recent_files_recent_files() {
|
||||
use crate::i18n::LangExt as _;
|
||||
let shown = |lang: &str| {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
app.session.prefs.interface_language = lang.into();
|
||||
app.ui.recent_files = vec![std::env::temp_dir().join("vectorcraft-home-heading").join("Drawing.svg").to_string_lossy().into_owned()];
|
||||
home_screen(app)
|
||||
};
|
||||
let home = shown("en");
|
||||
assert!(home.shows("Recent Files"), "the recent files are headed Recent Files");
|
||||
assert!(!home.shows("Recent"), "not Recent alone");
|
||||
let home = shown("de");
|
||||
let de = crate::i18n::Lang::from_code("de").expect("German is registered");
|
||||
let german = crate::i18n::tr(de, "Recent Files");
|
||||
// Without a German row for Recent Files, the framework's heading stays.
|
||||
let heading = if german == "Recent Files" { crate::i18n::tr_id(de, "startScreen.recent", "Recent") } else { german };
|
||||
assert!(home.shows(heading), "German shows {heading}");
|
||||
}
|
||||
|
||||
/// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A
|
||||
/// tutorial shows the Learn panel at its steps and no document is opened; the Quick skill guide
|
||||
/// shows its list of skills.
|
||||
|
||||
@@ -510,6 +510,11 @@ impl Panel {
|
||||
self.fixture.tree().focused_key() == self.look(name).node
|
||||
}
|
||||
|
||||
/// Whether the row or item named `name` reports itself selected.
|
||||
pub(crate) fn selected(&self, name: &str) -> bool {
|
||||
self.fixture.tree().selected_of(self.look(name).node).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the zero-based control of `role` has focus, including rows with identical names.
|
||||
pub(crate) fn focused_nth(&self, role: craft::ui::contract::Role, index: usize) -> bool {
|
||||
self.fixture.tree().focused_key() == self.look_nth(role, index).node
|
||||
|
||||
@@ -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};
|
||||
@@ -44,6 +89,28 @@ mod tests {
|
||||
assert_covers(&ui_fonts().stack(), [Sample::new("hi", "hindi", HINDI)]);
|
||||
}
|
||||
|
||||
/// The face the web serves for Gujarati (a `demand` line of `crates/text/web-fonts.txt`) draws
|
||||
/// every Gujarati character of the Gujarati catalog on its own, as on the web, which has no
|
||||
/// other Gujarati face.
|
||||
#[test]
|
||||
fn web_gujarati_face_covers_the_gujarati_catalog() {
|
||||
if !embeds("Gujr") {
|
||||
eprintln!("skipped: built without craft-fonts, or one without a Gujarati face");
|
||||
return;
|
||||
}
|
||||
let served: Vec<_> = vectorcraft_text::CRAFT_FONTS
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
vectorcraft_text::WEB_FONTS.iter().any(|w| w.demand && w.scripts.contains(&"Gujr") && w.family == f.family && w.style == f.style)
|
||||
})
|
||||
.copied()
|
||||
.collect();
|
||||
assert!(!served.is_empty(), "the web serves a Gujarati face (a `demand` line of web-fonts.txt)");
|
||||
let gujarati: String = include_str!("i18n/gu.tsv").chars().filter(|c| ('\u{0A80}'..='\u{0AFF}').contains(c)).collect();
|
||||
assert!(!gujarati.is_empty());
|
||||
assert_covers(&UiFonts::new(&I18nScripts).craft_faces(&served).stack(), [Sample::new("gu", "gu.tsv", &gujarati)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn japanese_renders_with_the_craft_fonts_without_installed_fonts() {
|
||||
if !embeds("Jpan") {
|
||||
@@ -53,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();
|
||||
|
||||
@@ -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`.
|
||||
|
||||
+9
-3
File diff suppressed because one or more lines are too long
@@ -24,7 +24,7 @@ English) in-app help, and the docs are English.
|
||||
(`bflatastic`), with community contributors adding or correcting (German by `dwetscher`, Japanese and Traditional
|
||||
Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded as reviewed by native speakers; the contributor approved all 387 later Gujarati additions on 2026-11-14.
|
||||
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, but the web startup list contains no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged.
|
||||
|
||||
## The thirteen key languages
|
||||
|
||||
@@ -34,7 +34,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a
|
||||
| Simplified Chinese (Mandarin) | `zh-hans` | 9,625 rows, 3,735 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`) | all (the untranslated report lists 237 messages without a row for it) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) |
|
||||
| Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) |
|
||||
| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout |
|
||||
| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); not in the web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font |
|
||||
| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); the web fetches Noto Sans Gujarati when the interface needs it | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages |
|
||||
| Arabic | `ar` | preparatory registration (native name العربية) and 6-form CLDR plural probe only; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) and not yet consumed | none (UI not exposed pending shared catalog) | document text: existing bidirectional layout and paragraph direction; interface UI: not exposed pending shared catalog, with full shell mirroring pending STD-I18N-001 | — (preparatory) | preparatory (not exposed) | 15–20 |
|
||||
| French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) |
|
||||
| Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) |
|
||||
@@ -101,6 +101,7 @@ font for the web build.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. |
|
||||
| 2026-11-25 | patch | Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; kept unavailable to users pending upstream `storytold/craft-i18n` catalog |
|
||||
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
|
||||
| 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) |
|
||||
|
||||
+96
-33
@@ -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:
|
||||
|
||||
@@ -3247,7 +3292,8 @@ through `$`:
|
||||
and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document.
|
||||
`removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`,
|
||||
`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
|
||||
@@ -3685,7 +3731,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 `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item
|
||||
members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`,
|
||||
@@ -9181,6 +9231,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
|
||||
@@ -10268,7 +10329,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
|
||||
@@ -10862,7 +10925,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
|
||||
|
||||
+6
-4
File diff suppressed because one or more lines are too long
@@ -37,7 +37,7 @@ Native saves on Unix flush the destination directory after writing or replacing
|
||||
|
||||
> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged.
|
||||
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged.
|
||||
|
||||
## Feature submission evidence
|
||||
|
||||
@@ -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).
|
||||
@@ -1119,7 +1121,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- 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`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes 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`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes 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`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Loading the built-in preset the tracing already has, by its name with or without brackets (`[Default]`), with unchanged options does not trace again. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.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; compound paths expose `PathItems` objects and reject unsupported path creation. 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; compound paths expose `PathItems` objects and reject unsupported path creation; `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`).
|
||||
@@ -1277,7 +1279,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Swedish messages (2026-11-13): the Swedish (`sv`) catalog has an `@msg` row for 464 of the 628 status and error messages the untranslated report listed for it; 162 messages that no complete-message catalog translates, 36 composite font errors among them, are not translated yet, and two unknown-parameter errors that start with the `{within}` placeholder stay in English, as does `{name} must be {lo}–{hi}{unit} (got {v})`, whose existing row can't match because two of its placeholders sit side by side; the rows keep their placeholders, backticked names, quoted values and command ids; native review remains; scores and estimates unchanged.
|
||||
- Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and workspaces keep the setting. A floating Tools panel dropped on the canvas's left edge, right of panels docked on the left, docks there and turns the setting on, and one dropped on the window's left edge docks there and turns it off; with no panels docked on the left, a drop leaves the setting as it is (#7837). Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows`, `tools_dropped_where_the_left_edges_overlap_keep_the_setting`, `tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on`).
|
||||
- Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md).
|
||||
- Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged.
|
||||
- Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so Gujarati can be selected on the web. Current-head validation is recorded in the PR; scores and estimates unchanged.
|
||||
- Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged.
|
||||
- Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged.
|
||||
- Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged.
|
||||
@@ -3442,6 +3444,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. |
|
||||
| 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours 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-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. |
|
||||
|
||||
+8
-5
File diff suppressed because one or more lines are too long
@@ -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"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user