mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
Merge main into feat/scripts-api-d11-perspective-presets
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
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"`
|
||||
//! the objects inside them (see `appearance`).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -115,7 +116,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Move Effect",
|
||||
[],
|
||||
None,
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
has_doc,
|
||||
move_effect
|
||||
),
|
||||
@@ -678,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Can the Appearance panel reorder shared effects on the exact subjects it displays?
|
||||
/// A generated graph design or a selection normalized to different objects has no matching row.
|
||||
pub fn can_reorder_selected_effects(&self) -> bool {
|
||||
let Ok(st) = self.doc() else { return false };
|
||||
let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false };
|
||||
let selected: HashSet<_> = st.selection.subjects().iter().copied().collect();
|
||||
roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the
|
||||
/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing.
|
||||
fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option<Vec<Option<usize>>> {
|
||||
let mut seen = HashSet::with_capacity(ids.len());
|
||||
let mut appearances: Vec<&vectorcraft_doc::Appearance> =
|
||||
ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::<Option<_>>()?;
|
||||
let first = *appearances.get(anchor)?;
|
||||
if source == ItemTarget::Top {
|
||||
return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]);
|
||||
}
|
||||
let item = source.effects_item(first, "effect.move").ok()??;
|
||||
appearances.swap(0, anchor);
|
||||
let shared = SharedStack::of(&appearances);
|
||||
let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::<Option<Vec<_>>>()?;
|
||||
slots.swap(0, anchor);
|
||||
Some(slots)
|
||||
}
|
||||
|
||||
/// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s.
|
||||
fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.move";
|
||||
@@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
let roots = edit_targets(s, p, C)?;
|
||||
// Where an aligned effect would go in each of several different stacks isn't one place.
|
||||
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) {
|
||||
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
|
||||
}
|
||||
let reference = design_reference(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) {
|
||||
// An omitted item and a numbered item can use different anchors and still name the same row.
|
||||
let shared = (!copy && reference.is_none())
|
||||
.then(|| {
|
||||
shared_reorder_slots(d, &roots, src, src.anchor(s, &roots))
|
||||
.filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source))
|
||||
})
|
||||
.flatten();
|
||||
Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Where the effect landed in each object it moved in, in the order of `ids`.
|
||||
let mut landed = vec![];
|
||||
let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| {
|
||||
let mut done = vec![];
|
||||
for id in &roots {
|
||||
for (k, id) in roots.iter().enumerate() {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?);
|
||||
let (si, di) = match &slots {
|
||||
Some(slots) => (slots[k], slots[k]),
|
||||
None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?),
|
||||
};
|
||||
let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue };
|
||||
// Taken out from the top down, so the lower positions stay valid; put back in order.
|
||||
let mut taken: Vec<Effect> = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect();
|
||||
|
||||
@@ -40,6 +40,12 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_do
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "view.showMissingLinks", "Show Missing Links", ["View"], None,
|
||||
"{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}",
|
||||
has_doc, show_missing_links),
|
||||
cmd!(query "links.marked", "Marked Missing Links", [], None,
|
||||
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
|
||||
has_doc, marked),
|
||||
cmd!(
|
||||
query "links.check",
|
||||
"Check Links",
|
||||
@@ -518,6 +524,8 @@ fn refused(link: &LinkInfo, doc_path: Option<&str>) -> Option<craft_docpath::Ref
|
||||
/// the content shown. Its bytes are read only when its size or modification time changed. An image
|
||||
/// placed from a DCS file is modified when one of its plate files of their own changed.
|
||||
fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) {
|
||||
#[cfg(test)]
|
||||
probe_gate::hold(&g.link.path);
|
||||
let Some(mut f) = locate(&g.link, base) else { return (Status::Missing, None) };
|
||||
let l = &g.link;
|
||||
if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) {
|
||||
@@ -536,6 +544,24 @@ fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) {
|
||||
(if same { Status::Ok } else { Status::Modified }, Some(f))
|
||||
}
|
||||
|
||||
/// Whether [`probe`] would find group `g`'s file missing, without reading or hashing its content.
|
||||
/// A changed file is opened to check it can be read, and nothing more: the canvas markers ask only
|
||||
/// this, and with Update Links set to Manually a changed file keeps differing from its stored link,
|
||||
/// so a full probe would read the whole file again on every look while the markers are on.
|
||||
fn missing(g: &Group, base: LinkBase) -> bool {
|
||||
#[cfg(test)]
|
||||
probe_gate::hold(&g.link.path);
|
||||
let Some(f) = locate(&g.link, base) else { return true };
|
||||
let l = &g.link;
|
||||
if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) {
|
||||
return false;
|
||||
}
|
||||
if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified {
|
||||
return false;
|
||||
}
|
||||
fileio::read_file_head(&f.path, 0).is_err()
|
||||
}
|
||||
|
||||
/// Is image `key` of `d` showing its preview (its file not read)?
|
||||
fn previewing(d: &Document, key: &str) -> bool {
|
||||
d.images.get(key).is_none_or(ImageBlob::is_proxy)
|
||||
@@ -2159,6 +2185,7 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))
|
||||
})?;
|
||||
}
|
||||
clear_markers(s, &updated)?;
|
||||
let mut out = json!({ "updated": updated, "missing": missing });
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
@@ -2451,6 +2478,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
not_found.sort();
|
||||
not_found.dedup();
|
||||
clear_markers(s, &relinked)?;
|
||||
let mut out = json!({ "relinked": relinked, "notFound": not_found });
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
@@ -2630,6 +2658,56 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option
|
||||
out
|
||||
}
|
||||
|
||||
/// Missing placed objects, using the same file resolution as the Links panel. Hidden ones are
|
||||
/// included: [`crate::DocState::marked_missing_links`] leaves out what is hidden when it is drawn, so
|
||||
/// artwork shown later is marked without another scan. Also used on the link watch worker, away
|
||||
/// from the UI thread.
|
||||
pub(crate) fn missing_markers(doc: &Document, base: LinkBase) -> Vec<NodeId> {
|
||||
groups(doc, None).iter().filter(|g| !g.ids.is_empty() && missing(g, base)).flat_map(|g| g.ids.iter().copied()).collect()
|
||||
}
|
||||
|
||||
fn show_missing_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
let on = super::switch_or(p, "on", !st.show_missing_links, "view.showMissingLinks")?;
|
||||
// Never probes files here: a changed linked file is read in full to tell whether it still
|
||||
// matches, which would hold up the caller (the desktop UI thread) on a large or slow file.
|
||||
// Turning the overlay on leaves its markers unscanned; the link watch worker scans them
|
||||
// at once ([`Session::missing_link_scan_due`]) and the canvas repaints from its result.
|
||||
// `links.marked` stays the explicit, synchronous inspection. The web build has no worker
|
||||
// and no files to read: its app marks them in place ([`Session::mark_missing_links_in_place`]).
|
||||
if !on || !st.show_missing_links {
|
||||
st.missing_link_markers = None;
|
||||
}
|
||||
st.show_missing_links = on;
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
|
||||
fn marked(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
let ids = if st.show_missing_links { missing_markers(&st.doc, LinkBase::of(st)) } else { vec![] };
|
||||
let images: Vec<Value> = ids
|
||||
.iter()
|
||||
.filter(|id| st.doc.is_visible(**id))
|
||||
.filter_map(|id| {
|
||||
let b = st.doc.node(*id)?.geometric_bounds()?;
|
||||
Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
|
||||
})
|
||||
.collect();
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
Ok(json!({"on": st.show_missing_links, "images": images}))
|
||||
}
|
||||
|
||||
/// Successful repair clears its decoration even when the file's metadata is unchanged.
|
||||
fn clear_markers(s: &mut Session, repaired: &[u64]) -> Result<()> {
|
||||
if !repaired.is_empty()
|
||||
&& let Some((_, ids)) = &mut s.doc_mut()?.missing_link_markers
|
||||
{
|
||||
let repaired: std::collections::HashSet<_> = repaired.iter().copied().collect();
|
||||
ids.retain(|id| !repaired.contains(&id.0));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The format of the file image `im` of `d` shows: its link's extension, else its pixels' type.
|
||||
fn format_label(d: &Document, im: &ImageObject) -> &'static str {
|
||||
if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_separated) {
|
||||
@@ -3319,6 +3397,64 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(shown) }))
|
||||
}
|
||||
|
||||
/// Test seam: hold the probe of one linked path until the test releases it, so a test can
|
||||
/// tell whether a command returned before the probe finished, and on which thread it ran.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod probe_gate {
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A gated path: (open, entered on thread named, finished), and the condition signalling
|
||||
/// each change.
|
||||
#[derive(Default)]
|
||||
pub struct Gate {
|
||||
state: Mutex<(bool, Option<String>, bool)>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
static GATES: Mutex<Vec<(String, Arc<Gate>)>> = Mutex::new(Vec::new());
|
||||
|
||||
impl Gate {
|
||||
/// Gate probes of the link stored as `path` until [`Gate::open`].
|
||||
pub fn close(path: &str) -> Arc<Gate> {
|
||||
let g = Arc::new(Gate::default());
|
||||
GATES.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), g.clone()));
|
||||
g
|
||||
}
|
||||
pub fn open(&self) {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).0 = true;
|
||||
self.changed.notify_all();
|
||||
}
|
||||
/// The name of the thread that entered the probe, waiting up to `limit` for one.
|
||||
pub fn entered(&self, limit: Duration) -> Option<String> {
|
||||
let s = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let (s, _) = self.changed.wait_timeout_while(s, limit, |s| s.1.is_none()).unwrap_or_else(PoisonError::into_inner);
|
||||
s.1.clone()
|
||||
}
|
||||
pub fn finished(&self) -> bool {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).2
|
||||
}
|
||||
}
|
||||
|
||||
/// Called at the start of every probe: blocks while `path` is gated and closed (at most
|
||||
/// ten seconds, so a regression fails the test instead of hanging it).
|
||||
pub(super) fn hold(path: &str) {
|
||||
let gate = GATES.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, g)| g.clone());
|
||||
let Some(g) = gate else { return };
|
||||
let mut s = g.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
s.1 = Some(std::thread::current().name().unwrap_or("").to_string());
|
||||
g.changed.notify_all();
|
||||
let (mut s, _) = g.changed.wait_timeout_while(s, Duration::from_secs(10), |s| !s.0).unwrap_or_else(PoisonError::into_inner);
|
||||
s.2 = true;
|
||||
g.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Stop gating `path`.
|
||||
pub fn remove(path: &str) {
|
||||
GATES.lock().unwrap_or_else(PoisonError::into_inner).retain(|(p, _)| p != path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() {
|
||||
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() {
|
||||
let mut s = session();
|
||||
let (a, b) = reversed_pair(&mut s);
|
||||
for (id, item) in [(a, 1), (b, 2)] {
|
||||
for effect in ["distort.twist", "distort.roughen"] {
|
||||
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect}));
|
||||
}
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [b.0, a.0]}));
|
||||
let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone());
|
||||
let before = appearances(&s);
|
||||
for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] {
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
|
||||
let moved = run(&mut s, "effect.move", params);
|
||||
assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor");
|
||||
assert_eq!(moved["index"], json!(0));
|
||||
for (appearance, item) in appearances(&s).iter().zip([1, 2]) {
|
||||
let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(ids, ["distort.roughen", "distort.twist"]);
|
||||
assert!(appearance.effects_at(Some(0)).unwrap().is_empty());
|
||||
}
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(appearances(&s), before);
|
||||
}
|
||||
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
|
||||
for destination in [0, 2] {
|
||||
assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err());
|
||||
assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list");
|
||||
}
|
||||
|
||||
run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"}));
|
||||
let before = appearances(&s);
|
||||
assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err());
|
||||
assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row");
|
||||
}
|
||||
|
||||
/// `effect.move`'s reply names where the effect landed in the object whose row the active item is
|
||||
/// (the first selected object), also when that object paints above the others.
|
||||
#[test]
|
||||
|
||||
@@ -152,7 +152,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
// The worker takes its turn after the slot is read and before the flag is, if the slot is free.
|
||||
let ended = link_watch::ended_without_stamps(&scan, |flag| {
|
||||
if let Ok(mut slot) = scan.0.try_lock() {
|
||||
*slot = Some((uid, stamps.clone()));
|
||||
*slot = Some(link_watch::LinkScanResult::stamps(uid, stamps.clone()));
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
}
|
||||
flag.load(Ordering::SeqCst)
|
||||
@@ -163,7 +163,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
let scan = scan.clone();
|
||||
move || {
|
||||
let _ended = link_watch::Ended(scan.clone());
|
||||
*scan.0.lock().unwrap() = Some((uid, stamps));
|
||||
*scan.0.lock().unwrap() = Some(link_watch::LinkScanResult::stamps(uid, stamps));
|
||||
}
|
||||
});
|
||||
worker.join().unwrap();
|
||||
|
||||
@@ -1241,3 +1241,258 @@ fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transf
|
||||
let asked = double_click(&mut s, "directSelection");
|
||||
assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}");
|
||||
}
|
||||
|
||||
/// Live radii of every corner of path `id`, or `None` when it has no Live Corners left.
|
||||
fn live_radii(s: &Session, id: NodeId) -> Option<Vec<f64>> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n)?;
|
||||
let all = lc.all();
|
||||
Some(all.iter().map(|k| lc.drawn_radius(*k)).collect())
|
||||
}
|
||||
|
||||
/// #10545: moving an anchor of a rounded rectangle moves its corner and keeps every corner live
|
||||
/// at its radius, in one undo step.
|
||||
#[test]
|
||||
fn moving_an_anchor_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 0, "y": 25})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert_eq!(n.path_data().unwrap().anchor_count(), 8);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(corners(&s, id), ([10.0; 4], [CornerKind::Round; 4], 8));
|
||||
}
|
||||
|
||||
/// #10545: dragging direct-selected anchors of a rounded rectangle keeps its corners live, and
|
||||
/// the corner they belong to moves by the drag.
|
||||
#[test]
|
||||
fn dragging_selected_anchors_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let before = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
// The two ends of the top-left corner's arc.
|
||||
let arc: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(arc.len(), 2);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": arc, "mode": "set"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": -20, "dy": 0})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
let after = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
assert!(after.x0 < before.x0 - 10.0 && (after.x1 - before.x1).abs() < 1e-6, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path() {
|
||||
for xf in [Affine::scale_non_uniform(2.0, 1.0), Affine::new([1.0, 0.0, 0.5, 1.0, 10.0, 10.0])] {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
let live = LiveShape::Rectangle { w: 50.0, h: 60.0, radii: [10.0; 4], kinds: Default::default(), radii_relative: false, xf };
|
||||
let mut expected = live.to_path();
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let NodeKind::Path { path, live: slot, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not a path") };
|
||||
*path = expected.clone();
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
let delta = vectorcraft_geom::Vec2::new(-20.0, 5.0);
|
||||
let a = expected.anchor_mut(0, 0).unwrap();
|
||||
*a = a.transform(Affine::translate(delta));
|
||||
let target = a.p;
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 0, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": delta.x, "dy": delta.y, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(n.live_shape().is_none(), "{command}: {xf:?}");
|
||||
assert_eq!(n.path_data().unwrap(), &expected, "{command}: {xf:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_remaps_the_whole_anchor_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected: BTreeSet<_> = [0, 2].into_iter().map(|k| *lc.anchors_of(&BTreeSet::from([k])).first().unwrap()).collect();
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([0])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(50.0, 30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected);
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 0)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": 50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
assert_eq!(selected_anchors(&s, id), Some(lc.anchors_of(&BTreeSet::from([0, 2]))), "{command}");
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id), "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected = lc.anchors_of(&BTreeSet::from([1]));
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([2])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, -30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected.clone());
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": moved.1, "x": target.x, "y": target.y})).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources);
|
||||
assert_eq!(lc.anchors_of(&BTreeSet::from([1])), selected);
|
||||
assert_eq!(selected_anchors(&s, id), Some(selected));
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_corner_layout_keeps_the_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, anchors(&[0, 1, 2]));
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let sources = LiveCorners::of(n).unwrap().sources().to_vec();
|
||||
let target = n.path_data().unwrap().subpaths[0].anchors[4].p + vectorcraft_geom::Vec2::new(-20.0, 0.0);
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 4, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -20, "dy": 0, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().sources(), sources);
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_keeps_the_key_anchor_on_its_corner() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, key, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
// The top right corner moves to the middle of the rectangle.
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([1])).first().unwrap();
|
||||
let key = *lc.anchors_of(&BTreeSet::from([3])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, 30.0);
|
||||
(BTreeSet::from([moved, key]), moved, key, target, lc.sources().to_vec())
|
||||
};
|
||||
let sel = &mut s.doc_mut().unwrap().selection;
|
||||
sel.anchors.insert(id, selected);
|
||||
sel.key_anchor = Some((id, key));
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
let now = s.doc().unwrap().selection.key_anchor;
|
||||
assert_eq!(now, lc.anchors_of(&BTreeSet::from([3])).first().map(|r| (id, *r)), "{command}");
|
||||
assert_ne!(now, Some((id, key)), "{command}: the key anchor's index changed with the recut");
|
||||
}
|
||||
}
|
||||
|
||||
/// A nudge of a pixel-aligned rounded rectangle's edge that the pixel-grid snap takes back
|
||||
/// changes nothing and records no undo step.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_records_no_undo_step() {
|
||||
let (mut s, id) = session();
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(left.len(), 4);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
// A first move by a whole point makes the rectangle a live path; the snap keeps that move.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// The same nudge on a rounded rectangle that no anchor edit has touched yet records no undo
|
||||
/// step and leaves it a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_keeps_a_live_rectangle() {
|
||||
for x in [10, 50, 137] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "x = {x}");
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })), "x = {x}");
|
||||
assert_eq!(s.doc().unwrap().doc, doc, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same nudge with a second pixel-aligned rectangle selected whole, which the snap also takes
|
||||
/// back, records no undo step and leaves the rounded rectangle a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_with_an_object_selected_whole_records_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let whole = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [whole.0]})).unwrap();
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [whole.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.whole(), vec![whole]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })));
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Canvas marker state and command API, independent of artwork and link update preferences.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::tests_links::{Folder, RED, place, png, session, write};
|
||||
use crate::*;
|
||||
|
||||
fn marked(s: &mut Session) -> Vec<u64> {
|
||||
s.execute("links.marked", &json!({})).unwrap()["images"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_toggle_is_transient_per_document_and_validated() {
|
||||
let mut s = session();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
for p in [json!({"on": "false"}), json!({"on": 1}), json!({"on": []})] {
|
||||
assert!(s.execute("view.showMissingLinks", &p).is_err());
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().show_missing_links);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({})).unwrap(), json!({"on": false}));
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_follow_files_relink_update_and_embed() {
|
||||
let dir = Folder::new("marker-lifecycle");
|
||||
let path = dir.file("art.png");
|
||||
let replacement = dir.file("replacement.png");
|
||||
let bytes = png(40, 40, RED);
|
||||
write(&path, &bytes);
|
||||
write(&replacement, &bytes);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let saved = vectorcraft_format::save_file(&doc);
|
||||
let pixels = vectorcraft_render::Renderer::new().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels;
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection, selection);
|
||||
assert_eq!(st.history.undo.len(), undo);
|
||||
assert_eq!(vectorcraft_format::save_file(&st.doc), saved);
|
||||
assert_eq!(
|
||||
vectorcraft_render::Renderer::new().render_region(&st.doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels,
|
||||
pixels
|
||||
);
|
||||
s.execute("links.relink", &json!({"ids": [id.0], "path": replacement})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
write(&replacement, &bytes);
|
||||
s.execute("links.update", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() {
|
||||
for mode in ["automatically", "askWhenModified", "manually"] {
|
||||
let dir = Folder::new(&format!("marker-watch-{mode}"));
|
||||
let path = dir.file("art.png");
|
||||
let bytes = png(20, 20, RED);
|
||||
write(&path, &bytes);
|
||||
let mut s = session();
|
||||
s.prefs.update_links = mode.into();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert_eq!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1, vec![id]);
|
||||
write(&path, &bytes);
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
let seen = s.doc().unwrap().missing_link_markers.as_ref().unwrap().0.clone();
|
||||
s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 3, "height": 4})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&seen, &s.doc().unwrap().missing_link_markers.as_ref().unwrap().0));
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
// Switching the toggle off while a look is pending must not resurrect its markers.
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_missing_links_on_returns_before_the_file_probe_and_scans_on_the_link_watcher() {
|
||||
use crate::cmd::links::probe_gate::{self, Gate};
|
||||
use std::time::Duration;
|
||||
let dir = Folder::new("marker-toggle-nonblocking");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let stored = crate::tests_links::image(&s, id).link.unwrap().path;
|
||||
let gate = Gate::close(&stored);
|
||||
// The toggle returns while the probe of the (slow) linked file is held closed.
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
assert!(!gate.finished(), "the toggle waited for the file probe");
|
||||
assert_eq!(gate.entered(Duration::ZERO), None, "the toggle probed the file on the calling thread");
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
// The desktop app starts the watcher's look at once, and the probe runs there.
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
assert_eq!(gate.entered(Duration::from_secs(10)).as_deref(), Some("link-watch"));
|
||||
assert!(s.poll_link_scan().is_none(), "the look ended before its probe was released");
|
||||
gate.open();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
probe_gate::remove(&stored);
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.missing_link_scan_due());
|
||||
// Turning it on again while on keeps the markers; off clears them.
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_scan_for_a_document_without_links_ends_without_a_worker() {
|
||||
let mut s = session();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(s.link_scan.is_none());
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_hidden_when_the_overlay_turns_on_is_marked_once_shown() {
|
||||
let dir = Folder::new("marker-hidden-then-shown");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
// Found by the desktop's link watch worker, and in place as the web app does.
|
||||
for in_place in [false, true] {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let mark = |s: &mut Session| {
|
||||
if in_place {
|
||||
s.mark_missing_links_in_place();
|
||||
} else {
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
}
|
||||
};
|
||||
mark(&mut s);
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty(), "hidden art is not marked");
|
||||
s.execute("object.showAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id], "shown art is marked without another scan");
|
||||
if in_place {
|
||||
// Artwork restored while the overlay is on is marked again.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.mark_missing_links_in_place());
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.mark_missing_links_in_place(), "unchanged art is not looked at again");
|
||||
}
|
||||
write(&path, &png(20, 20, RED));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_include_placed_documents_and_exclude_hidden_art() {
|
||||
let dir = Folder::new("marker-placed");
|
||||
let path = dir.file("placed.vectorcraft");
|
||||
write(&path, &vectorcraft_format::save_file(&vectorcraft_doc::Document::new(40.0, 20.0)));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::PlacedDocument(_)));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
s.execute("object.move", &json!({"ids": [id.0], "dx": 15, "dy": 10})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
@@ -2722,6 +2722,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)
|
||||
}
|
||||
|
||||
+89
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape};
|
||||
use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape};
|
||||
|
||||
use crate::path::{FillRule, PathData};
|
||||
|
||||
@@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> {
|
||||
|
||||
/// Distance from `p` to the nearest point on the path outline.
|
||||
pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 {
|
||||
path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt()
|
||||
path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt()
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of the path's stroke of width `width`?
|
||||
pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool {
|
||||
let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol);
|
||||
quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol
|
||||
let radius = width / 2.0 + tol;
|
||||
if !path.bounding_box().inflate(radius, radius).contains(p) {
|
||||
return false;
|
||||
}
|
||||
if !radius.is_finite() {
|
||||
return distance_to_outline(path, p) <= radius;
|
||||
}
|
||||
|
||||
// Keep candidates whose squared distance could underflow near a zero radius.
|
||||
let search_radius = radius.max(f64::MIN_POSITIVE.sqrt());
|
||||
path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius)
|
||||
}
|
||||
|
||||
// A Bézier stays inside the bounds of its control points. A line projection is
|
||||
// already cheap, so only check the bounds before running a curve solver.
|
||||
fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool {
|
||||
let bounds = match segment {
|
||||
PathSeg::Line(_) => return false,
|
||||
PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2),
|
||||
PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3),
|
||||
};
|
||||
outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1)
|
||||
}
|
||||
|
||||
fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool {
|
||||
// Leave room for rounding in the curve evaluation and the distance comparison.
|
||||
let scale = p.abs().max(low.abs()).max(high.abs()).max(radius);
|
||||
let padded = radius + 8.0 * f64::EPSILON * scale;
|
||||
p < low - padded || p > high + padded
|
||||
}
|
||||
|
||||
fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 {
|
||||
#[cfg(test)]
|
||||
OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1));
|
||||
segment.nearest(p, 1e-9).distance_sq
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static OUTLINE_NEAREST_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for
|
||||
@@ -185,6 +223,53 @@ mod tests {
|
||||
assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_hit_skips_distant_curves_without_changing_results() {
|
||||
let mut path = BezPath::new();
|
||||
for i in 0..96 {
|
||||
let x = f64::from(i) * 16.0;
|
||||
path.move_to((x, 0.0));
|
||||
path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0));
|
||||
}
|
||||
path.move_to((512.0, 0.0));
|
||||
path.quad_to((513.0, 4.0), (514.0, 0.0));
|
||||
|
||||
for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] {
|
||||
assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit);
|
||||
assert!(path.bounding_box().contains(point));
|
||||
OUTLINE_NEAREST_CALLS.with(|count| count.set(0));
|
||||
assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit);
|
||||
assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls);
|
||||
}
|
||||
|
||||
assert_stroke_hits_at_cutoff();
|
||||
}
|
||||
|
||||
fn assert_stroke_hits_at_cutoff() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.line_to((0.0, 0.0));
|
||||
path.quad_to((4.0, 8.0), (8.0, 0.0));
|
||||
path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0));
|
||||
path.close_path();
|
||||
path.move_to((2.0, -3.0));
|
||||
path.line_to((2.0, -3.0));
|
||||
|
||||
for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] {
|
||||
let transformed = transform * path.clone();
|
||||
for x in -2..23 {
|
||||
for y in -5..9 {
|
||||
let point = transform * Point::new(f64::from(x), f64::from(y));
|
||||
let distance = distance_to_outline(&transformed, point);
|
||||
for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] {
|
||||
let inside = transformed.bounding_box().inflate(radius, radius).contains(point);
|
||||
assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evenodd_hole() {
|
||||
let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf};
|
||||
use super::{
|
||||
Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind,
|
||||
@@ -19,6 +21,37 @@ fn brushed(b: Option<Rect>, reach: f64) -> Option<Rect> {
|
||||
if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b }
|
||||
}
|
||||
|
||||
/// Can the patch shade its own outline without folding across it? The differences of adjacent
|
||||
/// tensor control points bound each directional derivative in a convex cone. If every pair of
|
||||
/// derivatives has the same strict orientation, averaging them along any segment keeps them
|
||||
/// independent, so distinct parameter points cannot map to the same point.
|
||||
fn unfolded_patch(points: [(f32, f32); 12]) -> bool {
|
||||
let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y)));
|
||||
let top = [p[0], p[11], p[10], p[9]];
|
||||
let bottom = [p[3], p[4], p[5], p[6]];
|
||||
let left = [p[0], p[1], p[2], p[3]];
|
||||
let right = [p[9], p[8], p[7], p[6]];
|
||||
// Raise the linear blending terms of the Coons surface to cubic degree in each direction.
|
||||
let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| {
|
||||
let v = row as f64 / 3.0;
|
||||
std::array::from_fn(|col| {
|
||||
let u = col as f64 / 3.0;
|
||||
let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v;
|
||||
top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear
|
||||
})
|
||||
});
|
||||
let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col]));
|
||||
let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col]));
|
||||
let orientation = du[0][0].cross(dv[0][0]).signum();
|
||||
du.into_iter().flatten().all(|u| {
|
||||
dv.iter().flatten().all(|v| {
|
||||
let cross = u.cross(*v) * orientation;
|
||||
// Keep near-parallel directions on the existing clipped path through PDF quantization.
|
||||
cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// The objects this thread has measured for the walk and for the links (tests).
|
||||
@@ -542,7 +575,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1,
|
||||
/// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1,
|
||||
/// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and
|
||||
/// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads
|
||||
/// instead banded, left seams between them, and made files with many meshes very large.
|
||||
@@ -560,7 +593,6 @@ impl Exporter<'_> {
|
||||
if !writable(s, Affine::IDENTITY, bounds) {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false };
|
||||
let page: Vec<vectorcraft_color::Color> = m.points.iter().map(|p| self.page_color(&p.color)).collect();
|
||||
let mixed = page.windows(2).any(|w| w[0].model() != w[1].model());
|
||||
let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. }));
|
||||
@@ -584,6 +616,14 @@ impl Exporter<'_> {
|
||||
patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] });
|
||||
}
|
||||
}
|
||||
// An unfolded single patch shades its own outline. Filling that exact outline makes some
|
||||
// readers antialias it twice and leave seams where patches touch. Keep the outline for
|
||||
// folded geometry and for meshes with more than one patch, which can overlap themselves.
|
||||
let bounds_path = match patches.as_slice() {
|
||||
[patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false };
|
||||
let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false };
|
||||
s.set_stroke(None);
|
||||
s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero }));
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
//! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small
|
||||
//! flat-coloured paths that band, show seams and make the file large.
|
||||
|
||||
use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction};
|
||||
use craft::pdf::syntax::object::{Name, Object};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, MeshAppearance};
|
||||
use vectorcraft_doc::{ColorMode, Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
|
||||
use vectorcraft_testkit::raster::{assert_similar, render_artboard};
|
||||
|
||||
use super::import_fidelity::stream;
|
||||
use crate::*;
|
||||
|
||||
/// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured
|
||||
@@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) {
|
||||
(meshes, paths)
|
||||
}
|
||||
|
||||
fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document {
|
||||
use std::fmt::Write as _;
|
||||
let mut data = String::new();
|
||||
for boundary in boundaries {
|
||||
data.push_str("00"); // Every patch supplies all its vertices.
|
||||
for (x, y) in boundary {
|
||||
write!(data, "{x:02X}{y:02X}").unwrap();
|
||||
}
|
||||
data.push_str(&"28465A".repeat(4));
|
||||
}
|
||||
data.push('>');
|
||||
let shading = stream(
|
||||
"/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \
|
||||
/Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode",
|
||||
&data,
|
||||
);
|
||||
let page = PdfPage {
|
||||
resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)),
|
||||
..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q")
|
||||
};
|
||||
let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap();
|
||||
assert_eq!(kinds(&imported).0, boundaries.len());
|
||||
imported
|
||||
}
|
||||
|
||||
fn has_curved_outline(bytes: &[u8]) -> bool {
|
||||
let output = crate::pages::open(bytes, None).unwrap();
|
||||
let pages = output.pages();
|
||||
let has_curve = |content: &[u8]| {
|
||||
let mut ops = TypedIter::new(content);
|
||||
while let Some(op) = ops.next() {
|
||||
if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
};
|
||||
if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) {
|
||||
return true;
|
||||
}
|
||||
output.objects().into_iter().any(|object| match object {
|
||||
Object::Stream(form) if form.dict().get::<Name<'_>>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => {
|
||||
has_curve(&form.decoded().unwrap())
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() {
|
||||
// The same cubic, in opposite directions, is the two patches' inner edge.
|
||||
let imported = import_patches(&[
|
||||
[(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)],
|
||||
[(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)],
|
||||
]);
|
||||
let bytes = export(&imported, &PdfOptions::default()).unwrap();
|
||||
assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself");
|
||||
let reimported = import(&bytes).unwrap();
|
||||
assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings");
|
||||
assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folded_pdf_mesh_still_uses_its_outline() {
|
||||
let imported =
|
||||
import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]);
|
||||
let bytes = export(&imported, &PdfOptions::default()).unwrap();
|
||||
assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() {
|
||||
let d = doc(rgb, 1.0);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let pass = pass.into_inner();
|
||||
if let Some(list) = shown.inner {
|
||||
let opener = list.response.clone();
|
||||
apply_list(app, node.as_deref(), &order, selection, list);
|
||||
apply_list(app, node.as_deref(), &order, mix, selection, list);
|
||||
if let (Some(key), Some(n)) = (app.ui.appearance_panel.menu, node.as_deref()) {
|
||||
row_menu(app, ui, &opener, n, key);
|
||||
}
|
||||
@@ -530,8 +530,7 @@ fn object_row_label(app: &VectorcraftApp, summary: Option<&Summary>, mixed: bool
|
||||
}
|
||||
}
|
||||
|
||||
/// The list over `rows` (`order` their keys), bound to `selection`. A mixed selection's rows don't
|
||||
/// drag: where one would go in each of the different stacks isn't one place.
|
||||
/// The list over `rows` (`order` their keys), bound to `selection`.
|
||||
fn show_list(
|
||||
ui: &mut Ui,
|
||||
cx: &RowCx<'_>,
|
||||
@@ -555,10 +554,11 @@ fn show_list(
|
||||
.deletable(true)
|
||||
.selection(Bind::bound(selection))
|
||||
.can_drag(|key: &RowKey| key.drags());
|
||||
if let Some(n) = cx.node.filter(|_| cx.mix.is_none()) {
|
||||
if let Some(n) = cx.node {
|
||||
let mix = cx.mix;
|
||||
list = list
|
||||
.reorder(ReorderRule::new().copy_with(CopyKeys::Alt).into_groups())
|
||||
.accepts(move |drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize| accepts(n, order, drag, over, insert, copy));
|
||||
.accepts(move |drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize| accepts(n, order, mix, drag, over, insert, copy));
|
||||
}
|
||||
list.show_items(ui, rows, &mut |key, item| build_row(cx, *key, item))
|
||||
}
|
||||
@@ -569,6 +569,7 @@ fn apply_list(
|
||||
app: &mut VectorcraftApp,
|
||||
node: Option<&Node>,
|
||||
order: &[RowKey],
|
||||
mix: Option<&Mixed>,
|
||||
selection: Selection<RowKey>,
|
||||
list: CollectionResponse<RowKey, RowEvent>,
|
||||
) {
|
||||
@@ -610,7 +611,7 @@ fn apply_list(
|
||||
delete_selected(app, node, sel).ok();
|
||||
}
|
||||
if let Some(mv) = moved {
|
||||
reorder(app, n, order, &mv);
|
||||
reorder(app, n, order, mix, &mv);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1192,7 +1193,14 @@ fn mixed(app: &VectorcraftApp) -> Option<Mixed> {
|
||||
}
|
||||
let aps: Vec<&vectorcraft_doc::Appearance> = nodes.iter().map(|n| &*n.appearance).collect();
|
||||
let fills_differ = rest.iter().any(|n| n.appearance.fill_paint() != first.appearance.fill_paint());
|
||||
Some(Mixed { shared: vectorcraft_doc::appearance::SharedStack::of(&aps), transparency, fills_differ })
|
||||
let object_effects_match = rest.iter().all(|n| n.appearance.effects == first.appearance.effects);
|
||||
Some(Mixed {
|
||||
shared: vectorcraft_doc::appearance::SharedStack::of(&aps),
|
||||
transparency,
|
||||
fills_differ,
|
||||
object_effects_match,
|
||||
effect_targets_match: app.session.can_reorder_selected_effects(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A mixed selection as the panel lists it ([`mixed`]).
|
||||
@@ -1203,6 +1211,10 @@ struct Mixed {
|
||||
transparency: bool,
|
||||
/// Their topmost fills differ: the object row shows no fill chip.
|
||||
fills_differ: bool,
|
||||
/// All objects have the same complete, ordered object effect list.
|
||||
object_effects_match: bool,
|
||||
/// The command edits the same subjects whose rows the panel shows.
|
||||
effect_targets_match: bool,
|
||||
}
|
||||
|
||||
/// The selection's [`object_label`] and [`mixed`] summary for the active document as of one
|
||||
@@ -1673,17 +1685,40 @@ fn delete_selected(app: &mut VectorcraftApp, node: Option<&Node>, sel: Sel) -> R
|
||||
/// Whether the rows of `drag` may land before position `insert` of `order` (`over`: the row under
|
||||
/// the pointer, which takes them when it holds rows): a drop that moves or copies them
|
||||
/// ([`reorder_command`]).
|
||||
fn accepts(n: &Node, order: &[RowKey], drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize, copy: bool) -> bool {
|
||||
fn accepts(n: &Node, order: &[RowKey], mix: Option<&Mixed>, drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize, copy: bool) -> bool {
|
||||
let before = order.get(..insert).map_or(0, |rows| rows.iter().filter(|key| drag.keys.contains(key)).count());
|
||||
let mv = ReorderMove::new(drag.grabbed, drag.keys.clone(), insert.saturating_sub(before), copy);
|
||||
let into = over.copied().filter(|key| key.has_children()).map(|key| mv.clone().in_group(Some(key)));
|
||||
reorder_command(n, order, &mv).is_some() || into.is_some_and(|mv| reorder_command(n, order, &mv).is_some())
|
||||
reorder_for_selection(n, order, mix, &mv).is_some() || into.is_some_and(|mv| reorder_for_selection(n, order, mix, &mv).is_some())
|
||||
}
|
||||
|
||||
/// A mixed selection has an unambiguous destination only within a list that all its objects share.
|
||||
fn reorder_for_selection(n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove<RowKey>) -> Option<(&'static str, Value)> {
|
||||
let (cmd, params) = reorder_command(n, order, mv)?;
|
||||
let Some(mix) = mix else { return Some((cmd, params)) };
|
||||
let (item, _) = mv.key.effect()?;
|
||||
let shared = item.map_or(mix.object_effects_match, |i| mix.shared.has_item(i));
|
||||
(cmd == "effect.move" && !mv.copy && mix.effect_targets_match && shared && params["fromItem"] == params["toItem"]).then_some((cmd, params))
|
||||
}
|
||||
|
||||
/// Runs the reorder `mv` of the rows `order` of `n` and picks the moved rows (the copies), the
|
||||
/// grabbed one the lead; a moved Contents row keeps its selection.
|
||||
fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mv: &ReorderMove<RowKey>) {
|
||||
let Some((cmd, params)) = reorder_command(n, order, mv) else { return };
|
||||
fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove<RowKey>) {
|
||||
let Some((cmd, mut params)) = reorder_for_selection(n, order, mix, mv) else { return };
|
||||
if mix.is_some() {
|
||||
if let Some((Some(item), _)) = mv.key.effect() {
|
||||
// The panel shows the first selected object's rows. The engine's implicit active
|
||||
// item uses that same anchor, even when another target paints first.
|
||||
if app.session.appearance_item() != Some(item) && app.run("appearance.setActiveItem", json!({"index": item})).is_err() {
|
||||
return;
|
||||
}
|
||||
if let Some(fields) = params.as_object_mut() {
|
||||
fields.remove("fromItem");
|
||||
fields.remove("toItem");
|
||||
}
|
||||
}
|
||||
params = aligned(app, params);
|
||||
}
|
||||
let Ok(result) = app.run(cmd, params.clone()) else { return };
|
||||
let Some((kind, grabbed)) = mv.key.sel().rows() else { return };
|
||||
let mut set: Vec<usize> = mv.keys.iter().filter_map(|key| key.sel().rows().map(|(_, k)| k)).collect();
|
||||
@@ -1808,6 +1843,20 @@ fn items_move(
|
||||
Some(("appearance.moveItem", params))
|
||||
}
|
||||
|
||||
/// An edge between rows in an expanded fill or stroke can report that item as its parent.
|
||||
/// A drop immediately after the item header still means append to its effects.
|
||||
fn item_effect_gap(remaining: &[RowKey], gap: usize, item: usize) -> Option<usize> {
|
||||
let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied();
|
||||
if above == Some(RowKey::Item(item)) {
|
||||
return None;
|
||||
}
|
||||
let index = |key: Option<RowKey>| match key {
|
||||
Some(RowKey::ItemEffect(row, index)) if row == item => Some(index),
|
||||
_ => None,
|
||||
};
|
||||
index(remaining.get(gap).copied()).or_else(|| index(above).map(|at| at + 1))
|
||||
}
|
||||
|
||||
/// The effects `set` (ascending) of list `from_item` moved or copied to `gap` of `remaining`.
|
||||
fn effects_move(
|
||||
n: &Node,
|
||||
@@ -1818,7 +1867,11 @@ fn effects_move(
|
||||
mv: &ReorderMove<RowKey>,
|
||||
) -> Option<(&'static str, Value)> {
|
||||
let (item, pos) = match mv.parent {
|
||||
Some(RowKey::Item(i)) => (Some(i), n.appearance.effects_at(Some(i))?.len()),
|
||||
Some(RowKey::Item(i)) => {
|
||||
let end = n.appearance.effects_at(Some(i))?.len();
|
||||
let pos = if from_item == Some(i) && !mv.copy { item_effect_gap(remaining, gap, i).unwrap_or(end) } else { end };
|
||||
(Some(i), pos)
|
||||
}
|
||||
Some(key) => key.effect()?,
|
||||
None => {
|
||||
let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied();
|
||||
|
||||
@@ -353,6 +353,8 @@ fn drops_pick_the_command() {
|
||||
(mv(&[item(1)], 3, false, None), None),
|
||||
(mv(&[item(1)], 3, false, Some(ItemEffect(1, 0))), None),
|
||||
(mv(&[ItemEffect(1, 0)], 5, false, None), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))),
|
||||
(mv(&[ItemEffect(1, 1)], 4, false, Some(item(1))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 1, "copy": false}))),
|
||||
(mv(&[ItemEffect(1, 0)], 3, false, Some(item(1))), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))),
|
||||
(mv(&[ItemEffect(1, 0)], 4, false, None), None),
|
||||
(mv(&[ItemEffect(1, 1)], 5, true, Some(item(0))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 0, "copy": true}))),
|
||||
(mv(&[ItemEffect(1, 1)], 7, false, None), effects(json!({"from": 1, "fromItem": 1, "to": 1, "toItem": null, "copy": false}))),
|
||||
@@ -362,8 +364,8 @@ fn drops_pick_the_command() {
|
||||
assert_eq!(reorder_command(&path, &order, &moved), want, "{moved:?}");
|
||||
}
|
||||
let drag = |keys: &[RowKey]| ListDrag::new(egui::Id::NULL, keys.to_vec(), keys[0]);
|
||||
assert!(accepts(&path, &order, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row");
|
||||
assert!(!accepts(&path, &order, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is");
|
||||
assert!(accepts(&path, &order, None, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row");
|
||||
assert!(!accepts(&path, &order, None, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is");
|
||||
|
||||
// A group listed top-down S3, FA*, Contents, S1*, F0 (paint order F0 S1 FA S3, Contents above
|
||||
// two), FA and S1 dragged together.
|
||||
@@ -419,7 +421,7 @@ fn drops_pick_the_command() {
|
||||
] {
|
||||
assert_eq!(reorder_command(&group, &order, &moved), want, "{moved:?}");
|
||||
}
|
||||
assert!(!accepts(&group, &order, &drag(&[Contents]), Some(&Contents), 3, false), "where it is");
|
||||
assert!(!accepts(&group, &order, None, &drag(&[Contents]), Some(&Contents), 3, false), "where it is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -604,6 +606,74 @@ fn a_mixed_selection_lists_what_its_objects_share() {
|
||||
assert!(panel.shows("Mixed Objects"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mixed_selection_reorders_its_identical_object_effect_lists() {
|
||||
let mut app = app_with_a_selected_rectangle();
|
||||
let a = node(&app).id;
|
||||
let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [b], "color": "#ff0000"})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a.0, b]})).unwrap();
|
||||
for effect in ["distort.twist", "distort.roughen"] {
|
||||
app.run("effect.apply", json!({"effect": effect, "item": null})).unwrap();
|
||||
}
|
||||
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
|
||||
let order = |app: &VectorcraftApp| {
|
||||
[a, NodeId(b)]
|
||||
.map(|id| app.session.active().unwrap().doc.node(id).unwrap().appearance.effects.iter().map(|e| e.id.clone()).collect::<Vec<_>>())
|
||||
};
|
||||
let before = order(&app);
|
||||
let undo = steps(&app);
|
||||
let mut panel = Panel::new(app, show);
|
||||
assert!(panel.shows("Mixed Appearances"));
|
||||
let drag = |panel: &mut Panel| {
|
||||
let from = crate::panels::tests_appearance::row_spot(panel, &effect_row_label("distort.roughen"));
|
||||
let above = panel.rect(&effect_row_label("distort.twist"));
|
||||
panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE);
|
||||
};
|
||||
drag(&mut panel);
|
||||
{
|
||||
let mut app = panel.app();
|
||||
assert_eq!(order(&app), [vec!["distort.roughen", "distort.twist"], vec!["distort.roughen", "distort.twist"]]);
|
||||
assert_eq!(steps(&app), undo + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(order(&app), before);
|
||||
app.run("effect.apply", json!({"ids": [b], "effect": "stylize.feather", "item": null})).unwrap();
|
||||
}
|
||||
let before = order(&panel.app());
|
||||
drag(&mut panel);
|
||||
assert_eq!(order(&panel.app()), before, "a common prefix does not make both lists reorderable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mixed_selection_reorders_shared_stroke_effects_at_different_item_indices() {
|
||||
let mut app = app_with_a_selected_rectangle();
|
||||
let a = node(&app).id;
|
||||
let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [b]})).unwrap();
|
||||
app.run("appearance.addFill", json!({})).unwrap();
|
||||
app.run("appearance.moveItem", json!({"from": 2, "to": 0})).unwrap();
|
||||
app.run("appearance.setItem", json!({"index": 0, "color": "#ff0000"})).unwrap();
|
||||
for (id, item) in [(a.0, 1), (b, 2)] {
|
||||
for effect in ["distort.twist", "distort.roughen"] {
|
||||
app.run("effect.apply", json!({"ids": [id], "item": item, "effect": effect})).unwrap();
|
||||
}
|
||||
}
|
||||
app.run("select.set", json!({"ids": [b, a.0]})).unwrap();
|
||||
app.ui.appearance_panel.open.insert(RowKey::Item(2));
|
||||
|
||||
let mut panel = Panel::new(app, show);
|
||||
let from = crate::panels::tests_appearance::row_spot(&mut panel, &effect_row_label("distort.roughen"));
|
||||
let above = panel.rect(&effect_row_label("distort.twist"));
|
||||
panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE);
|
||||
let app = panel.app();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
for (id, item) in [(a, 1), (NodeId(b), 2)] {
|
||||
let effects = doc.node(id).unwrap().appearance.effects_at(Some(item)).unwrap();
|
||||
assert_eq!(effects.iter().map(|effect| effect.id.as_str()).collect::<Vec<_>>(), ["distort.roughen", "distort.twist"]);
|
||||
}
|
||||
assert_eq!(app.ui.appearance_panel.selection.lead, Some(RowKey::ItemEffect(2, 0)));
|
||||
}
|
||||
|
||||
/// The [`summary`] the canvas cache holds for the active document, checked field by field against
|
||||
/// what [`object_label`] and [`mixed`] work out from scratch.
|
||||
fn fresh_summary(app: &mut VectorcraftApp) -> Arc<Summary> {
|
||||
|
||||
@@ -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`.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user