diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/Cargo.lock b/Cargo.lock index 75c87011b4..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" @@ -2900,6 +2926,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -8637,6 +8664,7 @@ dependencies = [ name = "vectorcraft-cli" version = "0.25.1" dependencies = [ + "craft", "log", "objc2-core-foundation", "objc2-core-text", @@ -9642,6 +9670,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b31216ad837f3f4062538be333d8431d37c11832ef86924a3d0ad50defdc2f" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + [[package]] name = "webpki-root-certs" version = "1.0.11" diff --git a/ROADMAP.md b/ROADMAP.md index f74399f93a..f81353a895 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. + - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. - 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. @@ -269,6 +271,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. | | 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. | | 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. | | 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | 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/assets/cursors/cursor-pen-convert.svg b/assets/cursors/cursor-pen-convert.svg index fa78f562ef..79e29af75d 100644 --- a/assets/cursors/cursor-pen-convert.svg +++ b/assets/cursors/cursor-pen-convert.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-curvature.svg b/assets/cursors/cursor-pen-curvature.svg index 94ba1708b5..b8d4bd3650 100644 --- a/assets/cursors/cursor-pen-curvature.svg +++ b/assets/cursors/cursor-pen-curvature.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-join.svg b/assets/cursors/cursor-pen-join.svg index 3dd7ce7f6e..05a020bb12 100644 --- a/assets/cursors/cursor-pen-join.svg +++ b/assets/cursors/cursor-pen-join.svg @@ -1 +1,6 @@ - + + + + + + diff --git a/assets/cursors/cursor-pen-new.svg b/assets/cursors/cursor-pen-new.svg index 6690b1ffd6..a27dc0ddae 100644 --- a/assets/cursors/cursor-pen-new.svg +++ b/assets/cursors/cursor-pen-new.svg @@ -1 +1,8 @@ - + + + + + + + + diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..5f2d41d538 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -21,6 +21,7 @@ //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; #[cfg(test)] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 7c40d9d133..fe7ef7a6be 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -21,11 +21,12 @@ use std::sync::Arc; use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv}; +use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; -use crate::node::{Node, NodeId, NodeKind}; +use crate::node::{LiveShape, Node, NodeId, NodeKind}; use crate::text::TextObject; // ===================================================================================== @@ -1032,6 +1033,9 @@ enum Shape { /// Paths and compound paths; `members`: the subpath count of each member when both keys are /// compound paths. Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec, Vec)> }, + /// Two live rectangles: each step is a live rectangle whose size, transform and corner radii + /// lie between the keys', so their rounded corners stay circular arcs. + LiveRect(Box<(LiveRectParts, LiveRectParts)>), /// Text, symbols and images: their transforms interpolate. Placed, /// Anything else: a copy of the nearer key moved and scaled into the interpolated box. @@ -1046,6 +1050,43 @@ pub struct Lerp { shape: Shape, } +/// A live rectangle's size, transform, corner kinds and corner radii in document units. +#[derive(Clone, Debug)] +struct LiveRectParts { + w: f64, + h: f64, + radii: [f64; 4], + kinds: [CornerKind; 4], + xf: Affine, +} + +/// The parts of `s` when it is a live rectangle, with its radii as the lengths it draws. +fn live_rect(s: &LiveShape) -> Option { + let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = s else { return None }; + let base = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative); + let corners = vectorcraft_geom::corners::path_corners(&base); + let mut drawn = [0.0; 4]; + for (c, r) in corners.iter().zip(vectorcraft_geom::corners::fitted_radii(&corners, &resolved)) { + if let Some(d) = drawn.get_mut(c.index) { + *d = r; + } + } + Some(LiveRectParts { w: *w, h: *h, radii: drawn, kinds: *kinds, xf: *xf }) +} + +/// The parts of `a` and `b` when steps between them can be live rectangles: both are live +/// rectangles with the same corner kinds, turned and reflected alike, and with no scale or shear +/// left in their transforms, so each step only moves and resizes and its corners stay circular. +fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> { + let (x, y) = (live_rect(a)?, live_rect(b)?); + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + // A rotation or a reflection: unit columns at right angles. + let rigid = + |c: [f64; 6]| (c[0].hypot(c[1]) - 1.0).abs() < 1e-9 && (c[2].hypot(c[3]) - 1.0).abs() < 1e-9 && (c[0] * c[2] + c[1] * c[3]).abs() < 1e-9; + (x.kinds == y.kinds && rigid(p) && rigid(q) && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() < 1e-9)).then_some((x, y)) +} + /// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has. fn collapsed(n: &Node, c: Point) -> Node { let mut x = n.clone(); @@ -1083,6 +1124,12 @@ impl Lerp { | (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. }) | (NodeKind::Image(_), NodeKind::Image(_)) | (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed, + // A clicked start point asks for anchors to be paired; the path route does that. + (NodeKind::Path { live: Some(la), .. }, NodeKind::Path { live: Some(lb), .. }) + if let Some(parts) = live_rect_pair(la, lb).filter(|_| starts == (None, None)) => + { + Shape::LiveRect(Box::new(parts)) + } _ => match (node_path(a), node_path(b)) { (Some((pa, ra, ma)), Some((pb, rb, mb))) => { Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) } @@ -1145,6 +1192,28 @@ impl Lerp { } } } + Shape::LiveRect(parts) => { + let (x, y) = &**parts; + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + let live = LiveShape::Rectangle { + w: lerp_f64(x.w, y.w, t), + h: lerp_f64(x.h, y.h, t), + radii: std::array::from_fn(|i| lerp_f64(x.radii[i], y.radii[i], t)), + kinds: x.kinds, + radii_relative: false, + xf: Affine::new([p[0], p[1], p[2], p[3], lerp_f64(p[4], q[4], t), lerp_f64(p[5], q[5], t)]), + }; + let rule = match &base.kind { + NodeKind::Path { rule, .. } => *rule, + _ => FillRule::default(), + }; + let mut n = Node::path(NodeId(0), live.to_path(), Appearance::default()); + if let NodeKind::Path { rule: r, live: l, .. } = &mut n.kind { + *r = rule; + *l = Some(Box::new(live)); + } + n + } Shape::Placed => { let mut n = base.clone(); match (&mut n.kind, &a.kind, &b.kind) { @@ -2321,6 +2390,110 @@ mod tests { assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0)); } + /// A live rectangle `w` by `h` at `(x, 0)` with every corner radius `r`. + fn rounded(x: f64, w: f64, h: f64, r: f64) -> Node { + let live = + LiveShape::Rectangle { w, h, radii: [r; 4], kinds: [CornerKind::Round; 4], radii_relative: false, xf: Affine::translate((x, 0.0)) }; + let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut n.kind { + *l = Some(Box::new(live)); + } + n + } + + /// The step's live radii, after checking that every curve of its outline is a circular arc of + /// that radius about the matching corner center. + fn round_step_radii(step: &Node) -> [f64; 4] { + let Some(LiveShape::Rectangle { radii, .. }) = step.live_shape() else { panic!("a live rectangle step: {step:?}") }; + let r = radii[0]; + let b = step.path_data().and_then(|p| p.bounds()).unwrap_or_default(); + let centers = [(b.x0 + r, b.y0 + r), (b.x1 - r, b.y0 + r), (b.x1 - r, b.y1 - r), (b.x0 + r, b.y1 - r)].map(|(x, y)| Point::new(x, y)); + let path = step.path_data().map(|p| p.to_bezpath()).unwrap_or_default(); + let curves = path.segments().filter(|s| matches!(s, vectorcraft_geom::kurbo::PathSeg::Cubic(_))).count(); + assert_eq!(curves, if r > 1e-9 { 4 } else { 0 }, "one arc per corner: {path:?}"); + for seg in path.segments() { + if let vectorcraft_geom::kurbo::PathSeg::Cubic(c) = seg { + for u in [0.0, 0.25, 0.5, 0.75, 1.0] { + let p = c.eval(u); + let d = centers.iter().map(|q| (p - *q).hypot()).fold(f64::INFINITY, f64::min); + assert!((d - r).abs() < 0.01 * r.max(1.0), "{p:?} is {d} from its corner center, not {r}"); + } + } + } + *radii + } + + /// Steps between live rectangles are live rectangles whose corner radii lie between the keys'. + #[test] + fn steps_between_rounded_rectangles_keep_round_corners() { + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 20.0).abs() < 1e-9, "{r}"); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 0.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for t in [0.25, 0.5, 0.75] { + for r in round_step_radii(&blend.at(t)) { + assert!((r - 30.0 * t).abs() < 1e-9, "{t}: {r}"); + } + } + // A radius too large for its rectangle counts as the radius it draws. + let blend = Lerp::new(&rounded(0.0, 20.0, 20.0, 100.0), &rounded(300.0, 200.0, 200.0, 10.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 10.0).abs() < 1e-9, "{r}"); + } + // Keys turned differently keep the anchor-by-anchor route. + let mut turned = rounded(300.0, 200.0, 60.0, 30.0); + turned.transform(Affine::rotate(0.5), false); + assert!(matches!(Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &turned, (None, None)).shape, Shape::Path { .. })); + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::rotate(30.0_f64.to_radians()), false); + b.transform(Affine::rotate(390.0_f64.to_radians()), false); + let blend = Lerp::new(&a, &b, (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let step = blend.at(0.5); + let Some(LiveShape::Rectangle { xf, .. }) = step.live_shape() else { panic!("a live rectangle step") }; + let Some(LiveShape::Rectangle { xf: first, .. }) = a.live_shape() else { panic!("a live rectangle key") }; + assert_eq!(xf.as_coeffs()[..4], first.as_coeffs()[..4]); + for starts in [(Some(0), None), (None, Some(0))] { + assert!(matches!(Lerp::new(&a, &b, starts).shape, Shape::Path { .. })); + } + b.transform(Affine::scale_non_uniform(-1.0, 1.0), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + for scale in [1.0, 1e-200] { + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::scale_non_uniform(scale, scale * 1e-12), false); + b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + } + // Keys whose corner kinds differ keep the anchor-by-anchor route. + let mut kinds = [CornerKind::Round; 4]; + kinds[2] = CornerKind::InvertedRound; + let live = LiveShape::Rectangle { w: 200.0, h: 60.0, radii: [30.0; 4], kinds, radii_relative: false, xf: Affine::translate((300.0, 0.0)) }; + let mut inverted = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut inverted.kind { + *l = Some(Box::new(live)); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &inverted, (None, None)); + assert!(matches!(blend.shape, Shape::Path { .. })); + // The last step is the inverted key's outline. + assert_eq!(blend.at(1.0).path_data().and_then(|p| p.bounds()), inverted.path_data().and_then(|p| p.bounds())); + // Each step keeps the fill rule of the key it is nearer. + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + if let NodeKind::Path { rule, .. } = &mut a.kind { + *rule = FillRule::EvenOdd; + } + let blend = Lerp::new(&a, &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let rule = |n: &Node| match &n.kind { + NodeKind::Path { rule, .. } => *rule, + _ => panic!("a path step: {n:?}"), + }; + assert_eq!(rule(&blend.at(0.25)), FillRule::EvenOdd); + assert_eq!(rule(&blend.at(0.75)), FillRule::NonZero); + } + /// A step between two distorted images has its corners between the keys' corners. #[test] fn steps_between_distorted_images_have_corners_between_theirs() { 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 cb8f077dae..059a3d4bdc 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; @@ -102,7 +103,7 @@ pub use appearance::{ }; pub use assets::ExportAsset; pub use compound_shape::ShapeMode; -pub use corners::LiveCorners; +pub use corners::{LiveCorners, edit_corner_anchors}; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..c2be1804db 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; 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