diff --git a/Cargo.lock b/Cargo.lock index be4b734a08..74aba289b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/ROADMAP.md b/ROADMAP.md index 8b29a40471..f81353a895 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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). | diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 25cffe599e..9c87a0045e 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -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", diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 51d2aec7b6..b049ac18ca 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.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) -> 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 = None; let mut headless = false; + let mut when_closed: Option = None; let mut allow_grants = false; let (mut read_roots, mut write_roots): (Vec, Vec) = (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 `".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())), } }; diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 0b1c560901..dc96dd69b8 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -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}"); +} diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 64a596e5ba..519056ba0c 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option 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::(&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, ""); + } +} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 4b1c77e0f1..7ffdb4b291 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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, launched: Option<&Listening>) -> Option { + 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, 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); diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 24228604a6..e7f50fa8ee 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -277,6 +277,57 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, 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>, + anchors: &BTreeSet, + edit: impl FnOnce(&mut PathData, &BTreeSet), +) -> 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 = 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::*; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8fe1cef218..059a3d4bdc 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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, diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 9a5be1fc4f..3a3c981229 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -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); diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index b9f304ddf4..bff15c6540 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -10,9 +10,12 @@ //! custom character sets: //! . +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 { ] } +/// 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> { + 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, + pub(super) combined: Vec, +} + +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, cmd: &str) -> Result { + 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, source_families: BTreeSet, target: &Document, cmd: &str) -> Result { + 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 diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 5d849cfed2..60a7aaba29 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -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 { "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 { 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>> { + 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::>()?; + 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::>>()?; + 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 { const C: &str = "effect.move"; @@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { 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 = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect(); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index a5e00eab67..62a84418b0 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -40,6 +40,12 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_do pub fn specs() -> Vec { 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 (Status, Option) { + #[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) { (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>, 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 { } 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