From 44afcbfb2aca52f692103c82d7a9dfa2676c16c3 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 21:19:24 +0530 Subject: [PATCH 1/7] Spell-check other languages from the Craft apps' Language packs Part of #4936. Spelling and hyphenation now read the Language packs installed in the font store the Craft apps share, and proof.packs, proof.installPack and proof.removePack list, install and remove them. Installs need downloading on, which only the person turns on; in the desktop app they run in the background and the documents are laid out again when one ends. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + Cargo.toml | 3 + apps/vectorcraft-cli/src/main.rs | 3 + apps/vectorcraft/src/main.rs | 4 + apps/vectorcraft/src/prefs_dir.rs | 8 + crates/engine/Cargo.toml | 4 + crates/engine/src/cmd.rs | 5 + crates/engine/src/cmd/packs.rs | 101 +++++++ crates/engine/src/cmd/spelling.rs | 7 +- crates/engine/src/lib.rs | 5 + crates/engine/src/packs.rs | 370 +++++++++++++++++++++++++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/store.rs | 24 ++ crates/engine/src/tests.rs | 2 + crates/engine/src/tests/packs.rs | 219 +++++++++++++++ crates/ui-egui/src/app.rs | 5 + docs/gaps.md | 3 +- docs/mcp.md | 33 ++- 18 files changed, 794 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/packs.rs create mode 100644 crates/engine/src/packs.rs create mode 100644 crates/engine/src/tests/packs.rs diff --git a/Cargo.lock b/Cargo.lock index 28a8205997..3c9e8caff6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8536,6 +8536,8 @@ dependencies = [ "craft-cdr", "craft-codepage", "craft-docpath", + "craft-font-catalog", + "craft-font-store", "craft-image-codecs", "craft-jxl", "craft-proof", diff --git a/Cargo.toml b/Cargo.toml index 51693818bb..4699191ed0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,9 @@ craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["interpret", "write"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +# Language packs: the Craft apps' shared font store installs them (#4936). +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" } diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 2416b17b89..3064392942 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -201,6 +201,9 @@ fn main() -> ExitCode { #[cfg(target_os = "macos")] mac_fonts::install(); prefs_dir::install_fonts(); + // The Language packs installed in the shared font store; `proof.installPack` returns once + // installed. + prefs_dir::use_language_packs(); let mut args: Vec = std::env::args().skip(1).collect(); // Before any subcommand attaches the plug-in folder. let safe_mode = args.first().is_some_and(|a| a == "--safe-mode"); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 8907fe4bd1..92178a9f4a 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -571,6 +571,10 @@ fn main() -> std::process::ExitCode { mac_fonts::install(); // VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into. prefs_dir::install_fonts(); + // Language packs: installs and index fetches run on their own threads, so the window keeps + // working while a pack downloads. + prefs_dir::use_language_packs(); + vectorcraft_engine::packs::run_in_background(true); // The log file lives in the settings directory, next to the preferences; opened after the // arguments, so `--version` leaves no file behind. Records logged until now are written to it // first. Runs without preferences (agents' test runs) log to standard error only, so they diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 8f1b50dd58..4a14bf6f79 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -24,6 +24,14 @@ pub fn install_fonts() { } } +/// Have spelling and hyphenation read the Language packs installed in the Craft apps' shared font +/// store (`proof.installPack`, or another Craft app), and install new ones there (#4936). Like the +/// Fonts folder, whether or not `VECTORCRAFT_NO_PREFS` is set: the packs are the store's, not +/// VectorCraft's preferences. +pub fn use_language_packs() { + vectorcraft_engine::packs::use_font_store(); +} + /// The folder `name` next to the settings, for what the user keeps: none in a run without /// preferences (`VECTORCRAFT_NO_PREFS`), which keeps nothing. fn store_dir(name: &str) -> Option { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6732c973f4..bc74ee5503 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -87,6 +87,10 @@ windows-native-keyring-store = "1.1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true } rayon = { version = "1.12", optional = true } +# Language packs (packs.rs): the shared font store installs them and finds its folder. Already in +# Cargo.lock (craft-font-manager), so this adds no new crate. +craft-font-store = { workspace = true } +craft-font-catalog = { workspace = true } # The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the # user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on # Linux. All MIT OR Apache-2.0. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index fbe46f41c8..76c9914a26 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -92,6 +92,8 @@ pub(crate) mod shaper; pub mod shortcutset; pub(crate) mod slices; pub mod spelling; +#[cfg(not(target_arch = "wasm32"))] +pub mod packs; mod stroke; mod style; pub use style::styled_node; @@ -381,6 +383,9 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(tags::specs()); v.extend(interactivity::specs()); v.extend(spelling::specs()); + // Language packs need a font store, which the web build has none of. + #[cfg(not(target_arch = "wasm32"))] + v.extend(packs::specs()); v.extend(svgfilter::specs()); v.extend(newart::specs()); v.extend(colortheme::specs()); diff --git a/crates/engine/src/cmd/packs.rs b/crates/engine/src/cmd/packs.rs new file mode 100644 index 0000000000..9941596f59 --- /dev/null +++ b/crates/engine/src/cmd/packs.rs @@ -0,0 +1,101 @@ +//! Language packs as commands (#4936): list, install and remove the packs that spell-check and +//! hyphenate languages other than English ([`crate::packs`]). They open nothing and never turn +//! downloading on: an install needs the Craft apps' shared download setting, which only the person +//! using an app turns on. + +use serde_json::{Value, json}; + +use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param}; +use crate::packs::{self, Outcome}; + +/// The Language pack commands. +pub fn specs() -> Vec { + vec![ + cmd!( + query "proof.packs", + "Language Packs", + [], + None, + "{refresh?: bool (fetch the pinned pack index again; needs downloading on; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}", + always, + list + ), + cmd!( + query "proof.installPack", + "Install Language Pack", + [], + None, + "{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}", + always, + install + ), + cmd!( + query "proof.removePack", + "Remove Language Pack", + [], + None, + "{locale} removes the installed pack (not while it installs); that language is no longer checked with it → {locale, installed: false}", + always, + remove + ), + ] +} + +fn locale_param(p: &Value, command: &str) -> Result { + let raw = text_param(p, "locale", command)?.ok_or_else(|| bad(command, "`locale` (a language tag like nl) is required"))?; + packs::parse_locale(raw).map_err(|e| bad(command, e)) +} + +fn list(s: &mut Session, p: &Value) -> Result { + const C: &str = "proof.packs"; + match p.get("refresh") { + None | Some(Value::Null) | Some(Value::Bool(false)) => {} + Some(Value::Bool(true)) => { + packs::refresh().map_err(EngineError::Other)?; + } + Some(_) => return Err(bad(C, "`refresh` must be true or false")), + } + let installed = craft_proof::packs::installed(); + let backend = packs::backend(); + let rows: Vec = packs::available() + .iter() + .map(|p| { + json!({ + "locale": p.locale, "name": p.name, "size": p.size, "licence": p.licence, "class": p.class, + "spelling": p.spelling, "hyphenation": p.hyphenation, + "installed": installed.iter().any(|i| i.locale == p.locale), + }) + }) + .collect(); + let (installing, refreshing, errors) = packs::status(); + // An install that ended since the last frame shows in every document's layout. + s.poll_language_packs(); + Ok(json!({ + "packs": rows, + "installed": installed.iter().map(|i| json!({"locale": i.locale, "name": i.name, "licence": i.licence})).collect::>(), + "installing": installing.iter().map(|(l, done, total)| json!({"locale": l, "done": done, "total": total})).collect::>(), + "refreshing": refreshing, + "errors": errors, + "downloads": backend.as_ref().is_some_and(|b| b.downloads_on()), + "indexOverride": backend.as_ref().and_then(|b| b.index_override()), + "available": backend.is_some(), + })) +} + +fn install(s: &mut Session, p: &Value) -> Result { + let locale = locale_param(p, "proof.installPack")?; + match packs::install(&locale).map_err(EngineError::Other)? { + Outcome::Started => Ok(json!({"locale": locale, "started": true})), + Outcome::Done => { + s.poll_language_packs(); + Ok(json!({"locale": locale, "installed": true})) + } + } +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let locale = locale_param(p, "proof.removePack")?; + packs::remove(&locale).map_err(EngineError::Other)?; + s.poll_language_packs(); + Ok(json!({"locale": locale, "installed": false})) +} diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index cd8b4890f2..ef238e7b91 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -325,10 +325,11 @@ pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet, from: usize /// not, since a save takes in the words another window saved), and a dictionary file attached. static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0); -/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be -/// out of date (Auto Spell Check checks the type again). +/// The dictionaries' generation: what [`misspellings`] found before it last changed may be out of +/// date (Auto Spell Check checks the type again). It moves on with the custom dictionary and with +/// craft-proof's own dictionaries, which change when a Language pack is installed or removed. pub fn dictionary_generation() -> u64 { - DICTIONARY_GENERATION.load(Ordering::Relaxed) + DICTIONARY_GENERATION.load(Ordering::Relaxed).wrapping_add(craft_proof::dictionary_generation()) } fn dictionary_changed() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 722192a185..6694d6953f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,8 @@ pub mod guard; pub mod inspect; pub mod journal; pub mod link_watch; +#[cfg(not(target_arch = "wasm32"))] +pub mod packs; pub mod schemas; pub mod steps; pub mod store; @@ -216,6 +218,9 @@ pub struct Session { /// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call /// that starts them ([`Session::load_plugins_in_background`]). plugin_loads_in_background: bool, + /// The Language packs' generation the documents were last laid out for + /// ([`Session::poll_language_packs`]). + packs_seen: u64, /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, diff --git a/crates/engine/src/packs.rs b/crates/engine/src/packs.rs new file mode 100644 index 0000000000..ba1e85c3d0 --- /dev/null +++ b/crates/engine/src/packs.rs @@ -0,0 +1,370 @@ +//! Language packs (#4936, RFC-0011): the spelling dictionary, hyphenation patterns and licence +//! texts of a language other than English, published by storytold/craft-i18n and installed into the +//! Craft apps' shared font store (craft-libs `craft-font-store`, item kind `language-pack`), where +//! craft-proof reads them (`craft_proof::packs`). A pack installed by another Craft app is used +//! here too, since the apps share the store. +//! +//! The store downloads only while its download setting is on, which only the person using an app +//! turns on, with their own click. Nothing here turns it on: [`use_font_store`] opens the store as +//! an agent's, so `proof.installPack` from the CLI, MCP or a script installs only after the person +//! allowed downloads. +//! +//! The packs state is the process's, like craft-proof's: one backend ([`set_backend`]), one list of +//! installs running and one error per locale. In the desktop app installs run on a thread of their +//! own ([`run_in_background`]) and [`crate::Session::poll_language_packs`] lays out the documents +//! again when one ends; elsewhere they return once installed. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock}; + +pub use craft_font_store::Cancel; + +/// One pack the pack index lists. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Pack { + /// Lowercase BCP 47 tag (`nl`, `pt-br`), also the installed pack's folder name. + pub locale: String, + /// The language's own name (`Nederlands`). + pub name: String, + /// The download's size in bytes. + pub size: u64, + /// SPDX licence expression of the pack's data. + pub licence: String, + /// The licence class: `Embeddable` or `Download-only`. + pub class: String, + /// Whether it has a spelling dictionary. + pub spelling: bool, + /// Whether it has hyphenation patterns. + pub hyphenation: bool, +} + +/// Where packs come from and go to: the font store ([`use_font_store`]), or a stand-in in tests. +pub trait Backend: Send + Sync { + /// The installed-packs folder craft-proof reads. + fn packs_dir(&self) -> PathBuf; + /// Whether the person allowed downloads. + fn downloads_on(&self) -> bool; + /// The packs of the index fetched last, with no request; empty before the first fetch. + fn cached_index(&self) -> Vec; + /// Fetches the pinned pack index (needs downloads on). + fn fetch_index(&self, cancel: &Cancel) -> Result, String>; + /// Downloads, checks and installs the pack for `locale`, which the index lists (needs downloads + /// on), calling `progress(done, total)` in bytes. + fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String>; + /// Removes the installed pack for `locale`. + fn remove(&self, locale: &str) -> Result<(), String>; + /// The test index used instead of the pinned one (`CRAFT_LANGUAGE_PACK_INDEX`), if any. + fn index_override(&self) -> Option { + None + } +} + +/// An install running. +struct Job { + done: u64, + total: u64, + cancel: Cancel, +} + +#[derive(Default)] +struct Jobs { + installing: BTreeMap, + /// A fetch of the index running. + refreshing: Option, + /// The last failure of each locale's install or removal, and of the index fetch (key `""`). + errors: BTreeMap, +} + +static BACKEND: RwLock>> = RwLock::new(None); +static JOBS: Mutex = Mutex::new(Jobs { installing: BTreeMap::new(), refreshing: None, errors: BTreeMap::new() }); +static BACKGROUND: AtomicBool = AtomicBool::new(false); +/// Goes up each time the installed packs change. +static GENERATION: AtomicU64 = AtomicU64::new(0); + +fn jobs() -> MutexGuard<'static, Jobs> { + JOBS.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Use `backend` for packs (`None`: none), and have craft-proof read its installed packs. +pub fn set_backend(backend: Option>) { + let dir = backend.as_ref().map(|b| b.packs_dir()); + *BACKEND.write().unwrap_or_else(PoisonError::into_inner) = backend; + craft_proof::packs::set_packs_dir(dir); + changed(); +} + +/// The backend [`set_backend`] set. +pub fn backend() -> Option> { + BACKEND.read().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Use the Craft apps' shared font store for packs, as an agent's store (it can't turn downloads +/// on): the desktop app and `vectorcraft-cli` call it at startup. Without a per-user folder there +/// are no packs. +pub fn use_font_store() { + let env = craft_font_catalog::FontEnv::from_process(); + set_backend(craft_font_store::FontStore::for_agent(&env).map(|store| Arc::new(FontStoreBackend::new(store)) as Arc)); +} + +/// Run installs and index fetches on a thread of their own (the desktop app, so its window keeps +/// working) instead of returning once they are done. +pub fn run_in_background(on: bool) { + BACKGROUND.store(on, Ordering::Relaxed); +} + +/// Goes up each time the installed packs change ([`crate::Session::poll_language_packs`]). +pub fn generation() -> u64 { + GENERATION.load(Ordering::Relaxed) +} + +/// Read the packs folder again: spelling and hyphenation in its languages change. +fn changed() { + craft_proof::packs::reload(); + GENERATION.fetch_add(1, Ordering::Relaxed); +} + +/// Whether an install or an index fetch is running. +pub fn busy() -> bool { + let j = jobs(); + !j.installing.is_empty() || j.refreshing.is_some() +} + +/// `raw` as a pack locale: trimmed, lower case, `_` read as `-` (`pt_BR` is `pt-br`); a language +/// tag of letters and digits, at most 35 bytes, in parts of at most 8. +pub fn parse_locale(raw: &str) -> Result { + let l = raw.trim().to_ascii_lowercase().replace('_', "-"); + let ok = !l.is_empty() + && l.len() <= 35 + && l.split('-').all(|p| !p.is_empty() && p.len() <= 8 && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())); + if ok { Ok(l) } else { Err(format!("{:?} is not a language tag like nl or pt-br", raw.chars().take(40).collect::())) } +} + +fn no_backend() -> String { + "Language packs aren't available: there is no font store folder for this user".into() +} + +fn downloads_off() -> String { + "downloading is turned off; only the person using a Craft app can turn it on, by installing a Language pack there".into() +} + +/// The packs the index fetched last lists. +pub fn available() -> Vec { + backend().map(|b| b.cached_index()).unwrap_or_default() +} + +/// What `proof.packs` reports about the jobs: the installs running as (locale, done, total), whether +/// the index is being fetched, and the last error of each locale (`""`: the index). +pub fn status() -> (Vec<(String, u64, u64)>, bool, BTreeMap) { + let j = jobs(); + (j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(), j.refreshing.is_some(), j.errors.clone()) +} + +/// What an install or a fetch did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + /// Done. + Done, + /// Running in the background ([`run_in_background`]). + Started, +} + +/// Runs `f` on a thread of its own in the background, else here. +fn run(f: impl FnOnce() + Send + 'static) -> Result { + if !BACKGROUND.load(Ordering::Relaxed) { + f(); + return Ok(Outcome::Done); + } + std::thread::Builder::new().name("language-pack".into()).spawn(f).map(|_| Outcome::Started).map_err(|e| format!("couldn't start the download: {e}")) +} + +/// Fetches the pinned pack index again. Needs downloads on. +pub fn refresh() -> Result { + let b = backend().ok_or_else(no_backend)?; + if !b.downloads_on() { + return Err(downloads_off()); + } + let cancel = { + let mut j = jobs(); + if j.refreshing.is_some() { + return Ok(Outcome::Started); + } + let cancel = Cancel::new(); + j.refreshing = Some(cancel.clone()); + j.errors.remove(""); + cancel + }; + let outcome = run(move || { + let r = b.fetch_index(&cancel); + let mut j = jobs(); + j.refreshing = None; + if let Err(e) = r { + j.errors.insert(String::new(), e); + } + }); + if outcome.is_err() { + jobs().refreshing = None; + } + let outcome = outcome?; + match jobs().errors.get("") { + Some(e) if outcome == Outcome::Done => Err(e.clone()), + _ => Ok(outcome), + } +} + +/// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs +/// downloads on. Spelling and hyphenation in that language use it once it is installed. +pub fn install(locale: &str) -> Result { + let b = backend().ok_or_else(no_backend)?; + if !b.downloads_on() { + return Err(downloads_off()); + } + let locale = locale.to_string(); + let cancel = { + let mut j = jobs(); + if j.installing.contains_key(&locale) { + return Ok(Outcome::Started); + } + let cancel = Cancel::new(); + j.installing.insert(locale.clone(), Job { done: 0, total: 0, cancel: cancel.clone() }); + j.errors.remove(&locale); + cancel + }; + let l = locale.clone(); + let outcome = run(move || { + let r = install_now(&*b, &l, &cancel); + if r.is_ok() { + changed(); + } + let mut j = jobs(); + j.installing.remove(&l); + if let Err(e) = r { + j.errors.insert(l, e); + } + }); + if outcome.is_err() { + jobs().installing.remove(&locale); + } + let outcome = outcome?; + match jobs().errors.get(&locale) { + Some(e) if outcome == Outcome::Done => Err(e.clone()), + _ => Ok(outcome), + } +} + +fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> { + let listed = |packs: &[Pack]| packs.iter().any(|p| p.locale == locale); + if !listed(&b.cached_index()) && !listed(&b.fetch_index(cancel)?) { + return Err(format!("there is no Language pack for {locale}")); + } + b.install(locale, cancel, &mut |done, total| { + if let Some(job) = jobs().installing.get_mut(locale) { + (job.done, job.total) = (done, total); + } + }) +} + +/// Stops the install of `locale` (or the index fetch, for `""`) if one is running. +pub fn cancel(locale: &str) { + let j = jobs(); + let c = if locale.is_empty() { j.refreshing.as_ref() } else { j.installing.get(locale).map(|job| &job.cancel) }; + if let Some(c) = c { + c.cancel(); + } +} + +/// Removes the installed pack for `locale`; not while it is installing. +pub fn remove(locale: &str) -> Result<(), String> { + let b = backend().ok_or_else(no_backend)?; + if jobs().installing.contains_key(locale) { + return Err(format!("the {locale} pack is still installing")); + } + let r = b.remove(locale); + changed(); + let mut j = jobs(); + match &r { + Ok(()) => j.errors.remove(locale), + Err(e) => j.errors.insert(locale.to_string(), e.clone()), + }; + r +} + +/// The pack index this build trusts: craft-i18n's Language pack release `language-packs-2` (75 +/// packs), pinned by the sha256 of its `index.json`. The font store reads +/// `CRAFT_LANGUAGE_PACK_INDEX` itself, to try packs from a test index (testing only). +pub const PACK_INDEX: craft_font_store::PackIndexPin = craft_font_store::PackIndexPin { + url: "https://github.com/storytold/craft-i18n/releases/download/language-packs-2/index.json", + sha256: "b35c7aef0591177f18233b551da16035dcd615549ff874e169ffd19f16fea74b", +}; + +/// The font store as the packs [`Backend`]. +struct FontStoreBackend { + store: craft_font_store::FontStore, + /// The index read or fetched last: an install takes its entry (URL, size, sha256) from it. + index: Mutex>, +} + +impl FontStoreBackend { + fn new(store: craft_font_store::FontStore) -> Self { + Self { store, index: Mutex::new(None) } + } + + fn keep(&self, index: craft_font_store::PackIndex) -> Vec { + let packs = index + .packs + .iter() + .map(|e| Pack { + locale: e.locale.clone(), + name: e.name.clone(), + size: e.size, + licence: e.licence.clone(), + class: e.class.clone(), + spelling: e.spelling, + hyphenation: e.hyphenation, + }) + .collect(); + *self.index.lock().unwrap_or_else(PoisonError::into_inner) = Some(index); + packs + } +} + +impl Backend for FontStoreBackend { + fn packs_dir(&self) -> PathBuf { + self.store.language_packs_dir() + } + + fn downloads_on(&self) -> bool { + self.store.network() == craft_font_store::Network::On + } + + fn cached_index(&self) -> Vec { + self.store.cached_language_pack_index(&PACK_INDEX).map(|i| self.keep(i)).unwrap_or_default() + } + + fn fetch_index(&self, cancel: &Cancel) -> Result, String> { + let index = self.store.fetch_language_pack_index(&PACK_INDEX, cancel).map_err(|e| e.to_string())?; + Ok(self.keep(index)) + } + + fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> { + let held = self.index.lock().unwrap_or_else(PoisonError::into_inner).clone(); + let index = held.or_else(|| self.store.cached_language_pack_index(&PACK_INDEX)).ok_or("the list of Language packs hasn't been fetched")?; + let entry = index.pack(locale).ok_or_else(|| format!("there is no Language pack for {locale}"))?.clone(); + self.store.install_language_pack(&index, &entry, cancel, &mut |p| progress(p.done, p.total)).map(|_| ()).map_err(|e| e.to_string()) + } + + fn remove(&self, locale: &str) -> Result<(), String> { + self.store.remove_language_pack(locale).map_err(|e| e.to_string()) + } + + fn index_override(&self) -> Option { + craft_font_store::language_pack_index_overridden() + } +} + +/// The font store backend in `dir`, for tests that need the real store without a request. +#[cfg(test)] +pub(crate) fn font_store_in(dir: PathBuf) -> Arc { + Arc::new(FontStoreBackend::new(craft_font_store::FontStore::new(dir, craft_font_store::Caller::Agent))) +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2890618dd8..2d249a7091 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -110,6 +110,7 @@ impl Session { plugin_dir: None, plugin_loads: Default::default(), plugin_loads_in_background: false, + packs_seen: 0, scripts_dir: None, startup_scripts_dir: None, metadata_templates_dir: None, diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 29cd6f1bea..eeb730b0ac 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -974,6 +974,30 @@ impl Session { self.plugin_loads_in_background = on; } + /// Lays every document out again when the installed Language packs changed since the last + /// call (an install in the background ended, or a pack was removed), since spelling and + /// hyphenation in their languages change → whether an install or index fetch is still running, + /// so the app looks again. The app calls it as its frames go by. + pub fn poll_language_packs(&mut self) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + let now = crate::packs::generation(); + if now != self.packs_seen { + self.packs_seen = now; + for st in &mut self.docs { + st.revision += 1; + } + } + crate::packs::busy() + } + // The web build has no packs. + #[cfg(target_arch = "wasm32")] + { + let _ = self.packs_seen; + false + } + } + /// Installs what the plug-in loads have loaded so far, in the order the loads started and each /// load's file-name order, up to the first module still loading, without waiting → whether /// some are still loading. A load starts once the loads before it are done. When another diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f0c8393339..c4fbc09a3b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -127,6 +127,8 @@ mod outlineobject; pub(super) mod outlinestroke; mod overprint; mod package; +#[cfg(not(target_arch = "wasm32"))] +mod packs; mod paintopacity; mod paintproxy; mod panelcmds; diff --git a/crates/engine/src/tests/packs.rs b/crates/engine/src/tests/packs.rs new file mode 100644 index 0000000000..473640f263 --- /dev/null +++ b/crates/engine/src/tests/packs.rs @@ -0,0 +1,219 @@ +//! Language packs (`proof.packs`, `proof.installPack`, `proof.removePack`, #4936): an installed pack +//! spell-checks its language in the documents, an install needs downloads on, and a pack installed +//! in the background reaches the documents once it ends. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +use serde_json::{Value, json}; + +use crate::packs::{self, Backend, Cancel, Pack}; +use crate::*; + +/// Tests that set the process-wide packs backend take turns. +fn packs_lock() -> MutexGuard<'static, ()> { + static LOCK: Mutex<()> = Mutex::new(()); + LOCK.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Puts the process back to no packs and no background installs when dropped, also when the test +/// panicked, and deletes the test's folder. +struct Reset(PathBuf); + +impl Drop for Reset { + fn drop(&mut self) { + packs::run_in_background(false); + packs::set_backend(None); + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A new folder for one test. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-packs-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +/// Writes a small Dutch pack into `packs/nl`, laid out as the font store unpacks one. +fn write_dutch_pack(packs: &Path) { + let dir = packs.join("nl"); + std::fs::create_dir_all(dir.join("LICENCES")).unwrap(); + std::fs::write(dir.join("pack.toml"), "locale = \"nl\"\nname = \"Nederlands (test)\"\nlicence = \"MIT\"\n").unwrap(); + std::fs::write(dir.join("LICENCES").join("COPYING"), "Test licence text.").unwrap(); + std::fs::write(dir.join("spelling.aff"), "SET UTF-8\nTRY esianrtolducgmphbykfvwjzxq\n").unwrap(); + std::fs::write(dir.join("spelling.dic"), "5\nhet\nhuis\nen\nde\nfiets\n").unwrap(); +} + +/// A session with a new document holding Dutch point type with one misspelt word, `fietz`. +fn dutch_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Het huis en de fietz"})).unwrap()["id"].clone(); + s.execute("text.setFormat", &json!({"ids": [id], "language": "Dutch"})).unwrap(); + s +} + +/// The unknown words a check lists, as (word, lang). +fn unknown(s: &mut Session) -> Vec<(String, String)> { + let r = s.execute("text.spelling.check", &json!({})).unwrap(); + r["words"].as_array().unwrap().iter().map(|w| (w["word"].as_str().unwrap().into(), w["lang"].as_str().unwrap().into())).collect() +} + +fn installed_locales(s: &mut Session) -> Vec { + let r = s.execute("proof.packs", &json!({})).unwrap(); + r["installed"].as_array().unwrap().iter().map(|p| p["locale"].as_str().unwrap().to_string()).collect() +} + +#[test] +fn a_pack_in_the_font_store_checks_its_language_until_it_is_removed() { + let _turn = packs_lock(); + let root = folder("store"); + let _reset = Reset(root.clone()); + let mut s = dutch_session(); + let without = unknown(&mut s); + // A pack another Craft app installed into the shared store. + let store = packs::font_store_in(root.clone()); + write_dutch_pack(&store.packs_dir()); + packs::set_backend(Some(store)); + assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())], "checked in Dutch by the pack"); + assert_eq!(installed_locales(&mut s), ["nl"]); + let listed = s.execute("proof.packs", &json!({})).unwrap(); + assert_eq!((listed["available"].clone(), listed["downloads"].clone()), (json!(true), json!(false)), "downloads stay off"); + let before = s.doc().unwrap().revision; + assert_eq!(s.execute("proof.removePack", &json!({"locale": "NL"})).unwrap()["installed"], false); + assert!(s.doc().unwrap().revision > before, "the document is laid out again"); + assert_eq!(unknown(&mut s), without, "checked as before the pack"); + assert!(installed_locales(&mut s).is_empty()); + assert!(s.execute("proof.removePack", &json!({"locale": "nl"})).is_err(), "no longer installed"); +} + +/// A stand-in for the font store: it lists a Dutch pack and installs it by writing its files. +struct Fake { + dir: PathBuf, + downloads: bool, + /// While set, an install waits until it is cleared. + hold: AtomicBool, +} + +impl Backend for Fake { + fn packs_dir(&self) -> PathBuf { + self.dir.clone() + } + + fn downloads_on(&self) -> bool { + self.downloads + } + + fn cached_index(&self) -> Vec { + let nl = Pack { + locale: "nl".into(), + name: "Nederlands".into(), + size: 2, + licence: "MIT".into(), + class: "Embeddable".into(), + spelling: true, + hyphenation: false, + }; + vec![nl] + } + + fn fetch_index(&self, _: &Cancel) -> Result, String> { + Ok(self.cached_index()) + } + + fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> { + progress(1, 2); + while self.hold.load(Ordering::Relaxed) { + if cancel.is_cancelled() { + return Err("cancelled".into()); + } + std::thread::yield_now(); + } + // The index lists only Dutch, which `packs::install` checks first. + if locale != "nl" { + return Err(format!("asked to install {locale}")); + } + write_dutch_pack(&self.dir); + Ok(()) + } + + fn remove(&self, locale: &str) -> Result<(), String> { + std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string()) + } +} + +fn error(s: &mut Session, id: &str, p: Value) -> String { + s.execute(id, &p).unwrap_err().to_string() +} + +#[test] +fn an_install_needs_downloads_on_and_a_pack_the_index_lists() { + let _turn = packs_lock(); + let root = folder("fake"); + let _reset = Reset(root.clone()); + let mut s = dutch_session(); + assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("aren't available"), "no store, no packs"); + packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: false, hold: AtomicBool::new(false) }))); + assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("downloading is turned off")); + assert!(error(&mut s, "proof.packs", json!({"refresh": true})).contains("downloading is turned off")); + assert!(installed_locales(&mut s).is_empty(), "nothing installed"); + packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) }))); + for bad in [json!({}), json!({"locale": ""}), json!({"locale": "../nl"}), json!({"locale": 5})] { + assert!(s.execute("proof.installPack", &bad).is_err(), "{bad} is refused"); + } + assert!(!root.exists(), "a refused locale writes nothing"); + assert!(error(&mut s, "proof.installPack", json!({"locale": "fy"})).contains("no Language pack for fy")); + assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["fy"].is_string(), "the failure is reported"); + let before = s.doc().unwrap().revision; + assert!(error(&mut s, "proof.installPack", json!({"locale": "nl_NL"})).contains("no Language pack for nl-nl"), "nl_NL reads as nl-nl"); + assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true); + assert!(s.doc().unwrap().revision > before, "the document is laid out again"); + assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]); + let listed = s.execute("proof.packs", &json!({})).unwrap(); + assert_eq!(listed["packs"][0]["installed"], true); +} + +#[test] +fn an_install_in_the_background_reaches_the_documents_when_it_ends() { + let _turn = packs_lock(); + let root = folder("background"); + let _reset = Reset(root.clone()); + let mut s = dutch_session(); + let without = unknown(&mut s); + let fake = Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) }); + packs::set_backend(Some(fake.clone())); + packs::run_in_background(true); + assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true); + assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true, "asked again, it is the same install"); + let listed = s.execute("proof.packs", &json!({})).unwrap(); + assert_eq!(listed["installing"][0]["locale"], "nl"); + assert!(error(&mut s, "proof.removePack", json!({"locale": "nl"})).contains("still installing")); + assert_eq!(unknown(&mut s), without, "not used before it is installed"); + let before = s.doc().unwrap().revision; + fake.hold.store(false, Ordering::Relaxed); + while s.poll_language_packs() { + std::thread::yield_now(); + } + s.poll_language_packs(); + assert!(s.doc().unwrap().revision > before, "the document is laid out again"); + assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]); +} + +#[test] +fn a_cancelled_background_install_installs_nothing() { + let _turn = packs_lock(); + let root = folder("cancel"); + let _reset = Reset(root.clone()); + let mut s = dutch_session(); + packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) }))); + packs::run_in_background(true); + assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true); + packs::cancel("nl"); + while packs::busy() { + std::thread::yield_now(); + } + assert!(installed_locales(&mut s).is_empty()); + assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["nl"].as_str().unwrap_or_default().contains("cancelled")); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index c5a97a940a..447199bb6f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -535,6 +535,11 @@ impl VectorcraftApp { // what waits for them. They install after the control requests are drained, so the frame // after the last one opens the files held for them (the desktop app does that before this // pass) before a control request waiting for them runs. + // A Language pack installed or removed lays the documents out again; while one downloads + // the host keeps coming back to look. + if self.session.poll_language_packs() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } if self.session.plugins_loading() { if self.session.poll_plugin_loads() { ctx.request_repaint_after(std::time::Duration::from_millis(50)); diff --git a/docs/gaps.md b/docs/gaps.md index e1f45bff43..766c215388 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -531,7 +531,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** COLR and SVG glyphs go with type that geometry effects reshape, into Expand Appearance and EMF/WMF export, where the type's outlines used to leave them out; bitmap glyphs (emoji) too, as images that hold their own pixels until a document takes them in; estimate unchanged. -- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation. Estimate unchanged. +- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation; Language packs for languages other than English, read from the Craft apps' shared font store, with `proof.packs`, `proof.installPack` and `proof.removePack` (a Preferences page to install them and the missing-pack bar remain). Estimate unchanged. - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), @@ -1021,6 +1021,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-27 | minor | G4 type: Language packs (#4936): spelling and hyphenation read the packs installed in the Craft apps' shared font store, and `proof.packs`, `proof.installPack` and `proof.removePack` list, install and remove them (installs need downloading on, which only the person turns on); a Preferences page to install them and the missing-pack bar remain; scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | | 2026-11-21 | minor | G13: View › Snapping groups five existing toggles and Pixel Snapping Options…; top-level commands and shortcuts remain; headless click/checkmark coverage added; scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 808f600e69..e26c2a193c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12612,7 +12612,7 @@ returns the new value. `text.spelling.check {ids?}` lists the words of the document's type that its dictionaries don't know: every visible, unlocked type object in paint order, or those in `ids` (and in the groups `ids` names). Each run is checked in its Character panel Language (English when it has none) by craft-proof, one paragraph at a time; a language without -a spelling dictionary marks nothing. English words come from the first dictionary craft-proof finds: a Hunspell +a spelling dictionary marks nothing (see [Language packs](#language-packs)). English words come from the first dictionary craft-proof finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof. Words in capitals, words with digits and web addresses are taken as correct. The result is `{words: [{id, start, end, word, lang}], more}`: `start` and `end` are byte offsets in the type object's text, the @@ -12663,6 +12663,37 @@ for it (each a `text.editRange {id, start, end, insert}` item labelled with its All (`text.spelling.ignoreAll {word}`) and Add to Dictionary (`text.spelling.addWord {word}`); the context menu's entries list them with their params. A right-click on type also has Spelling › Auto Spell Check (`edit.autoSpellCheck`). +### Language packs + +Languages other than English are spell-checked, and hyphenated, from **Language packs**: one per language, with its +Hunspell dictionary, hyphenation patterns and licence texts, published by storytold/craft-i18n (release +`language-packs-2`, whose `index.json` VectorCraft pins by its sha256). They are installed into the font store folder +the Craft apps share, so a pack installed in another Craft app is used here too. A language's dictionary is looked up +in an installed pack, then in the system's Hunspell dictionaries. The desktop app and `vectorcraft-cli` read the +installed packs; the web app has none, and no `proof.*` commands. + +- `proof.packs {refresh?}` lists the packs of the index fetched last (`packs`, each with `locale`, `name`, `size` in + bytes, `licence`, `class`, `spelling`, `hyphenation` and `installed`), the packs in use (`installed`), the installs + running (`installing`, with bytes `done` of `total`), whether the index is being fetched (`refreshing`), the last + failure of each locale (`errors`; `""` is the index fetch), whether downloading is on (`downloads`), a test index + used instead of the pinned one (`indexOverride`, from `CRAFT_LANGUAGE_PACK_INDEX`) and whether there is a store to + install into (`available`). `refresh: true` fetches the index again. +- `proof.installPack {locale}` downloads a pack, checks its sha256 and installs it (fetching the index first when it + doesn't list the locale). Every open document is laid out and checked again with it. `locale` is the pack's tag, + like `nl` or `pt-br` (`pt_BR` reads as `pt-br`). +- `proof.removePack {locale}` removes an installed pack, not while it installs. + +Installs and index fetches need downloading on. Only the person using a Craft app turns it on, with their own click +(the setting is the font store's, shared by the apps): no command turns it on, and until then an install is an error +that says so. In the desktop app installs and fetches run in the background: `proof.installPack` returns +`{locale, started: true}` and `proof.packs` shows the install in `installing`, then in `installed` or `errors`. In +`vectorcraft-cli` they return once done. + +```json +{"name":"run_command","arguments":{"command":"proof.packs","params":{"refresh":true}}} +{"name":"run_command","arguments":{"command":"proof.installPack","params":{"locale":"nl"}}} +``` + ## Find and Replace `edit.findNext {find, matchCase?, wholeWord?, backwards?, hiddenLayers?, lockedLayers?, from?}` finds the next match From fef393ddc06f4eadaeb916963bc84eed5ce11071 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 21:56:59 +0530 Subject: [PATCH 2/7] Language packs: fmt, a Status struct for clippy, std Result in the tests Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd.rs | 4 ++-- crates/engine/src/cmd/packs.rs | 2 +- crates/engine/src/packs.rs | 27 ++++++++++++++++++++++----- crates/engine/src/tests/packs.rs | 6 +++--- 4 files changed, 28 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 76c9914a26..c8fb66f630 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -65,6 +65,8 @@ pub(crate) mod objects_on_path; mod opacitymask; mod overprint; pub mod package; +#[cfg(not(target_arch = "wasm32"))] +pub mod packs; mod paint; mod panelcmds; pub mod params; @@ -92,8 +94,6 @@ pub(crate) mod shaper; pub mod shortcutset; pub(crate) mod slices; pub mod spelling; -#[cfg(not(target_arch = "wasm32"))] -pub mod packs; mod stroke; mod style; pub use style::styled_node; diff --git a/crates/engine/src/cmd/packs.rs b/crates/engine/src/cmd/packs.rs index 9941596f59..b90cec9c3d 100644 --- a/crates/engine/src/cmd/packs.rs +++ b/crates/engine/src/cmd/packs.rs @@ -67,7 +67,7 @@ fn list(s: &mut Session, p: &Value) -> Result { }) }) .collect(); - let (installing, refreshing, errors) = packs::status(); + let packs::Status { installing, refreshing, errors } = packs::status(); // An install that ended since the last frame shows in every document's layout. s.poll_language_packs(); Ok(json!({ diff --git a/crates/engine/src/packs.rs b/crates/engine/src/packs.rs index ba1e85c3d0..8ab8f2be17 100644 --- a/crates/engine/src/packs.rs +++ b/crates/engine/src/packs.rs @@ -154,11 +154,24 @@ pub fn available() -> Vec { backend().map(|b| b.cached_index()).unwrap_or_default() } -/// What `proof.packs` reports about the jobs: the installs running as (locale, done, total), whether -/// the index is being fetched, and the last error of each locale (`""`: the index). -pub fn status() -> (Vec<(String, u64, u64)>, bool, BTreeMap) { +/// What `proof.packs` reports about the jobs. +pub struct Status { + /// The installs running, as (locale, bytes done, bytes in all). + pub installing: Vec<(String, u64, u64)>, + /// Whether the index is being fetched. + pub refreshing: bool, + /// The last error of each locale (`""`: the index fetch). + pub errors: BTreeMap, +} + +/// The jobs running and the last errors. +pub fn status() -> Status { let j = jobs(); - (j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(), j.refreshing.is_some(), j.errors.clone()) + Status { + installing: j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(), + refreshing: j.refreshing.is_some(), + errors: j.errors.clone(), + } } /// What an install or a fetch did. @@ -176,7 +189,11 @@ fn run(f: impl FnOnce() + Send + 'static) -> Result { f(); return Ok(Outcome::Done); } - std::thread::Builder::new().name("language-pack".into()).spawn(f).map(|_| Outcome::Started).map_err(|e| format!("couldn't start the download: {e}")) + std::thread::Builder::new() + .name("language-pack".into()) + .spawn(f) + .map(|_| Outcome::Started) + .map_err(|e| format!("couldn't start the download: {e}")) } /// Fetches the pinned pack index again. Needs downloads on. diff --git a/crates/engine/src/tests/packs.rs b/crates/engine/src/tests/packs.rs index 473640f263..37825e8cd2 100644 --- a/crates/engine/src/tests/packs.rs +++ b/crates/engine/src/tests/packs.rs @@ -119,11 +119,11 @@ impl Backend for Fake { vec![nl] } - fn fetch_index(&self, _: &Cancel) -> Result, String> { + fn fetch_index(&self, _: &Cancel) -> std::result::Result, String> { Ok(self.cached_index()) } - fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> { + fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> std::result::Result<(), String> { progress(1, 2); while self.hold.load(Ordering::Relaxed) { if cancel.is_cancelled() { @@ -139,7 +139,7 @@ impl Backend for Fake { Ok(()) } - fn remove(&self, locale: &str) -> Result<(), String> { + fn remove(&self, locale: &str) -> std::result::Result<(), String> { std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string()) } } From 22f5ca3cbf45b925fabdaf12f486f6cd0661e4cd Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 23:55:40 +0530 Subject: [PATCH 3/7] Language packs: review fixes, and plug-ins can't call proof commands - proof.installPack, proof.removePack and proof.packs {refresh} are refused under automation roots: the shared font store is outside them. - Plug-ins may not call proof.* (DENIED_PREFIXES), which plugin_call's every_command_is_reviewed requires of new commands. - A synchronous install or refresh returns its own result, not one read back from the shared errors. - proof.packs reads the jobs before the installed packs, and poll_language_packs reads busy() before the generation, so an install that ends between the reads is never missed. - A pack change measures type with a language of its own again (refresh_document_text_bounds), so selection boxes and hits follow. - The tests' Reset cancels and waits for background jobs. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/packs.rs | 24 +++++-- crates/engine/src/cmd/plugin_call.rs | 2 + crates/engine/src/packs.rs | 90 +++++++++++++------------- crates/engine/src/session/documents.rs | 2 +- crates/engine/src/store.rs | 14 +++- crates/engine/src/tests/packs.rs | 35 +++++++++- docs/mcp.md | 4 +- 7 files changed, 117 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/cmd/packs.rs b/crates/engine/src/cmd/packs.rs index b90cec9c3d..9dd85a79f9 100644 --- a/crates/engine/src/cmd/packs.rs +++ b/crates/engine/src/cmd/packs.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Language Packs", [], None, - "{refresh?: bool (fetch the pinned pack index again; needs downloading on; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}", + "{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}", always, list ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Install Language Pack", [], None, - "{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}", + "{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Refused under automation roots (the store is outside them). Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}", always, install ), @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Remove Language Pack", [], None, - "{locale} removes the installed pack (not while it installs); that language is no longer checked with it → {locale, installed: false}", + "{locale} removes the installed pack (not while it installs; refused under automation roots); that language is no longer checked with it → {locale, installed: false}", always, remove ), @@ -51,10 +51,14 @@ fn list(s: &mut Session, p: &Value) -> Result { match p.get("refresh") { None | Some(Value::Null) | Some(Value::Bool(false)) => {} Some(Value::Bool(true)) => { + not_confined(C)?; packs::refresh().map_err(EngineError::Other)?; } Some(_) => return Err(bad(C, "`refresh` must be true or false")), } + // The jobs before the installed packs: an install makes craft-proof read its pack before it + // leaves the jobs, so one that ends between the two reads is in one list or the other. + let packs::Status { installing, refreshing, errors } = packs::status(); let installed = craft_proof::packs::installed(); let backend = packs::backend(); let rows: Vec = packs::available() @@ -67,7 +71,6 @@ fn list(s: &mut Session, p: &Value) -> Result { }) }) .collect(); - let packs::Status { installing, refreshing, errors } = packs::status(); // An install that ended since the last frame shows in every document's layout. s.poll_language_packs(); Ok(json!({ @@ -82,8 +85,20 @@ fn list(s: &mut Session, p: &Value) -> Result { })) } +/// Refuses `command` for a caller confined to automation roots: the packs are written into the font +/// store the Craft apps share, which is outside them. +fn not_confined(command: &str) -> Result<()> { + if crate::file_access::current().is_some() { + return Err(EngineError::Other(format!( + "automation path rejected: {command} writes the Language packs into the font store the Craft apps share, outside the automation roots" + ))); + } + Ok(()) +} + fn install(s: &mut Session, p: &Value) -> Result { let locale = locale_param(p, "proof.installPack")?; + not_confined("proof.installPack")?; match packs::install(&locale).map_err(EngineError::Other)? { Outcome::Started => Ok(json!({"locale": locale, "started": true})), Outcome::Done => { @@ -95,6 +110,7 @@ fn install(s: &mut Session, p: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { let locale = locale_param(p, "proof.removePack")?; + not_confined("proof.removePack")?; packs::remove(&locale).map_err(EngineError::Other)?; s.poll_language_packs(); Ok(json!({"locale": locale, "installed": false})) diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 867c1f2ff0..fc69773561 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -70,6 +70,8 @@ const DENIED_PREFIXES: &[&str] = &[ "text.rescanFonts", "text.fontList", "text.spelling.", + // Language packs: downloads into, and removals from, the font store the Craft apps share. + "proof.", "colorTheme.", "magicWand.", "eyedropper.", diff --git a/crates/engine/src/packs.rs b/crates/engine/src/packs.rs index 8ab8f2be17..fec380c1c2 100644 --- a/crates/engine/src/packs.rs +++ b/crates/engine/src/packs.rs @@ -183,17 +183,23 @@ pub enum Outcome { Started, } -/// Runs `f` on a thread of its own in the background, else here. -fn run(f: impl FnOnce() + Send + 'static) -> Result { +/// Runs `job` on a thread of its own in the background, else here and gives its own result (never +/// another call's, which the shared errors also hold). `undo` takes the job's entry back when its +/// thread can't start. +fn run(job: impl FnOnce() -> Result<(), String> + Send + 'static, undo: impl FnOnce()) -> Result { if !BACKGROUND.load(Ordering::Relaxed) { - f(); - return Ok(Outcome::Done); + return job().map(|()| Outcome::Done); + } + match std::thread::Builder::new().name("language-pack".into()).spawn(move || { + // The result is kept in the shared errors for `proof.packs`. + let _ = job(); + }) { + Ok(_) => Ok(Outcome::Started), + Err(e) => { + undo(); + Err(format!("couldn't start the download: {e}")) + } } - std::thread::Builder::new() - .name("language-pack".into()) - .spawn(f) - .map(|_| Outcome::Started) - .map_err(|e| format!("couldn't start the download: {e}")) } /// Fetches the pinned pack index again. Needs downloads on. @@ -212,22 +218,18 @@ pub fn refresh() -> Result { j.errors.remove(""); cancel }; - let outcome = run(move || { - let r = b.fetch_index(&cancel); - let mut j = jobs(); - j.refreshing = None; - if let Err(e) = r { - j.errors.insert(String::new(), e); - } - }); - if outcome.is_err() { - jobs().refreshing = None; - } - let outcome = outcome?; - match jobs().errors.get("") { - Some(e) if outcome == Outcome::Done => Err(e.clone()), - _ => Ok(outcome), - } + run( + move || { + let r = b.fetch_index(&cancel).map(|_| ()); + let mut j = jobs(); + j.refreshing = None; + if let Err(e) = &r { + j.errors.insert(String::new(), e.clone()); + } + r + }, + || jobs().refreshing = None, + ) } /// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs @@ -249,25 +251,25 @@ pub fn install(locale: &str) -> Result { cancel }; let l = locale.clone(); - let outcome = run(move || { - let r = install_now(&*b, &l, &cancel); - if r.is_ok() { - changed(); - } - let mut j = jobs(); - j.installing.remove(&l); - if let Err(e) = r { - j.errors.insert(l, e); - } - }); - if outcome.is_err() { - jobs().installing.remove(&locale); - } - let outcome = outcome?; - match jobs().errors.get(&locale) { - Some(e) if outcome == Outcome::Done => Err(e.clone()), - _ => Ok(outcome), - } + run( + move || { + let r = install_now(&*b, &l, &cancel); + // craft-proof reads the new pack before the job ends, so a caller that sees no + // install running sees the pack installed (`proof.packs`, `busy`). + if r.is_ok() { + changed(); + } + let mut j = jobs(); + j.installing.remove(&l); + if let Err(e) = &r { + j.errors.insert(l, e.clone()); + } + r + }, + || { + jobs().installing.remove(&locale); + }, + ) } fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2d249a7091..2ed3cd6a34 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -335,7 +335,7 @@ impl Session { /// [`Session::refresh_text_bounds`] walks them), as a change that is not an edit: a saved /// document stays saved, and its undo history keeps its documents as they are. The document is /// left as it is when `stale` picks nothing. - fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) { + pub(crate) fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) { let Some(st) = self.docs.get_mut(index) else { return }; if !text_trees(&st.doc).any(|n| has_text_where(n, &mut stale)) { return; diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index eeb730b0ac..428b88d51c 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -981,14 +981,22 @@ impl Session { pub fn poll_language_packs(&mut self) -> bool { #[cfg(not(target_arch = "wasm32"))] { + // Busy first: an install moves the generation on before it ends, so when none is + // running any more its change is read below. + let busy = crate::packs::busy(); let now = crate::packs::generation(); if now != self.packs_seen { self.packs_seen = now; - for st in &mut self.docs { - st.revision += 1; + for index in 0..self.docs.len() { + // Type in a language of its own may break its lines elsewhere now: it is + // measured again (not an edit), so its selection box and hits follow. + self.refresh_document_text_bounds(index, |t| t.runs.iter().any(|r| r.style.language.is_some())); + if let Some(st) = self.docs.get_mut(index) { + st.revision += 1; + } } } - crate::packs::busy() + busy } // The web build has no packs. #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/tests/packs.rs b/crates/engine/src/tests/packs.rs index 37825e8cd2..0218a9d39d 100644 --- a/crates/engine/src/tests/packs.rs +++ b/crates/engine/src/tests/packs.rs @@ -18,11 +18,19 @@ fn packs_lock() -> MutexGuard<'static, ()> { } /// Puts the process back to no packs and no background installs when dropped, also when the test -/// panicked, and deletes the test's folder. +/// panicked: the jobs still running are cancelled and waited for, so none outlives its test. Then +/// it deletes the test's folder. struct Reset(PathBuf); impl Drop for Reset { fn drop(&mut self) { + while packs::busy() { + for (locale, _, _) in packs::status().installing { + packs::cancel(&locale); + } + packs::cancel(""); + std::thread::yield_now(); + } packs::run_in_background(false); packs::set_backend(None); let _ = std::fs::remove_dir_all(&self.0); @@ -217,3 +225,28 @@ fn a_cancelled_background_install_installs_nothing() { assert!(installed_locales(&mut s).is_empty()); assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["nl"].as_str().unwrap_or_default().contains("cancelled")); } + +/// A caller confined to automation roots lists the packs but can't fetch, install or remove them: +/// the store they are written into is outside its roots. +#[test] +fn a_confined_caller_lists_packs_but_cannot_change_them() { + let _turn = packs_lock(); + let root = folder("confined"); + let _reset = Reset(root.clone()); + let roots_dir = folder("confined-roots"); + std::fs::create_dir_all(&roots_dir).unwrap(); + let mut s = dutch_session(); + write_dutch_pack(&root); + packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) }))); + let roots = crate::file_access::AutomationRoots::new(&[roots_dir.as_path()], &[roots_dir.as_path()]).unwrap(); + let mut confined = |cmd: &str, p: Value| crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string()); + for (cmd, p) in + [("proof.installPack", json!({"locale": "nl"})), ("proof.removePack", json!({"locale": "nl"})), ("proof.packs", json!({"refresh": true}))] + { + let e = confined(cmd, p).unwrap_err(); + assert!(e.contains("automation path rejected"), "{cmd}: {e}"); + } + assert_eq!(confined("proof.packs", json!({})).unwrap()["installed"][0]["locale"], "nl", "listing is allowed"); + assert!(root.join("nl").join("pack.toml").exists(), "the pack is still there"); + let _ = std::fs::remove_dir_all(&roots_dir); +} diff --git a/docs/mcp.md b/docs/mcp.md index e26c2a193c..5b083aa51e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12685,7 +12685,9 @@ installed packs; the web app has none, and no `proof.*` commands. Installs and index fetches need downloading on. Only the person using a Craft app turns it on, with their own click (the setting is the font store's, shared by the apps): no command turns it on, and until then an install is an error -that says so. In the desktop app installs and fetches run in the background: `proof.installPack` returns +that says so. A caller with automation roots (`--automation-read-root`, `--automation-write-root`) can list packs +but not fetch, install or remove them, since the store is outside its roots. In the desktop app installs and fetches +run in the background: `proof.installPack` returns `{locale, started: true}` and `proof.packs` shows the install in `installing`, then in `installed` or `errors`. In `vectorcraft-cli` they return once done. From 979ae2dc1bd848dbfe63e84228ca75f0eb5a0ae2 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Sat, 28 Nov 2026 00:19:55 +0530 Subject: [PATCH 4/7] Language packs: measure back documents in their own composite fonts When the packs change, poll_language_packs measures the type of every open document again. A document in the back now has its own composite fonts lent while it is measured, as measure_back_document does, so type set in a composite font of the same name as one of the front document's is not measured in the front document's definition. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/store.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 428b88d51c..4a547d6513 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -988,9 +988,15 @@ impl Session { if now != self.packs_seen { self.packs_seen = now; for index in 0..self.docs.len() { + // A document in the back is measured in its own composite fonts, lent for the + // measuring, as `measure_back_document` does: the front document's are the + // ones registered, and one of the same name may differ. + let back_fonts = (self.active != Some(index)).then(|| self.docs.get(index).map(|st| st.doc.composite_fonts.clone())).flatten(); + let lent = back_fonts.as_ref().map(|fonts| vectorcraft_text::FontDb::global().lend_document_composite_fonts(fonts)); // Type in a language of its own may break its lines elsewhere now: it is // measured again (not an edit), so its selection box and hits follow. self.refresh_document_text_bounds(index, |t| t.runs.iter().any(|r| r.style.language.is_some())); + drop(lent); if let Some(st) = self.docs.get_mut(index) { st.revision += 1; } From 1b18ab3a3763215bff9ab116de2763167d4b0c23 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Sat, 28 Nov 2026 11:06:36 +0530 Subject: [PATCH 5/7] Language packs: a script cannot run the proof commands A script's rollback cannot put back what proof.installPack, proof.removePack and proof.packs {refresh: true} write to or delete from the font store the Craft apps share, and in the desktop app an install keeps running after the run ends. refused_to_scripts now refuses the proof. prefix, as plugin_call does. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/script/mod.rs | 1 + crates/engine/src/tests/packs.rs | 15 +++++++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index c5fffb6574..49853c8609 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -159,6 +159,7 @@ pub fn refused_to_scripts(id: &str) -> bool { "edit.undoGroup.", "file.recovery.", "stroke.widthProfile.", + "proof.", ]; const IDS: &[&str] = &[ "text.addFontFiles", diff --git a/crates/engine/src/tests/packs.rs b/crates/engine/src/tests/packs.rs index 0218a9d39d..0c09a5e259 100644 --- a/crates/engine/src/tests/packs.rs +++ b/crates/engine/src/tests/packs.rs @@ -250,3 +250,18 @@ fn a_confined_caller_lists_packs_but_cannot_change_them() { assert!(root.join("nl").join("pack.toml").exists(), "the pack is still there"); let _ = std::fs::remove_dir_all(&roots_dir); } + +/// A script's rollback cannot put back what an install writes into the shared font store, so a +/// script cannot run the pack commands. +#[test] +fn a_script_cannot_install_a_pack() { + let _turn = packs_lock(); + let root = folder("script"); + let _reset = Reset(root.clone()); + let mut s = dutch_session(); + packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) }))); + let e = error(&mut s, "script.run", json!({"source": "vc.run('proof.installPack', {locale: 'nl'});", "name": "t.js"})); + assert!(e.contains("a script cannot run `proof.installPack`"), "{e}"); + assert!(installed_locales(&mut s).is_empty(), "nothing installed"); + assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true, "outside a script it installs"); +} diff --git a/docs/mcp.md b/docs/mcp.md index 5b083aa51e..a7bf2d3168 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3080,7 +3080,7 @@ returns `{stopped}`. `notifications/cancelled` stops a run only while the `tools for it, as in a headless server; use `script.stop` for a run the app started. A script cannot run commands that change anything outside the documents: `script.*` except `script.check`, `plugin.*`, `prefs.*`, `actionSet.*`, `shortcutSet.*`, `help.*`, `print.*`, `library.*`, `importMatches.*`, `edit.undoGroup.*`, `file.recovery.*`, -`stroke.widthProfile.*`, saving, importing or deleting a preset, `text.addFontFiles`, `text.findFontFiles`, +`stroke.widthProfile.*`, `proof.*` (Language packs), saving, importing or deleting a preset, `text.addFontFiles`, `text.findFontFiles`, `text.rescanFonts`, `links.findFiles`, `file.place.queue`, `color.loadProfile`, `color.removeProfile`, `file.print`, `view.proofSetup`, `view.proofSetup.save`, `view.proofSetup.load`, `view.proofColors`, `view.overprintPreview` and `view.separationsPreview`. It also cannot run @@ -12686,7 +12686,8 @@ installed packs; the web app has none, and no `proof.*` commands. Installs and index fetches need downloading on. Only the person using a Craft app turns it on, with their own click (the setting is the font store's, shared by the apps): no command turns it on, and until then an install is an error that says so. A caller with automation roots (`--automation-read-root`, `--automation-write-root`) can list packs -but not fetch, install or remove them, since the store is outside its roots. In the desktop app installs and fetches +but not fetch, install or remove them, since the store is outside its roots. A script cannot run the `proof.*` +commands at all, since a run's rollback cannot put the store back. In the desktop app installs and fetches run in the background: `proof.installPack` returns `{locale, started: true}` and `proof.packs` shows the install in `installing`, then in `installed` or `errors`. In `vectorcraft-cli` they return once done. From 2b61bdc7520f75987de5b6a025598b5f21ead919 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 03:38:29 -0800 Subject: [PATCH 6/7] Arrange Tools: Offset Objects chains the selection in a row or a column with a set gap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Arrange Tools › Offset Objects… (addon.arrange.offset) puts the selected objects one after another in a row (left to right) or a column (top to bottom), each a gap past the one before it; a negative gap overlaps them. The order is the stacking order from the back or the position (left or top edges), and Reverse Order runs it the other way. The first object stays where it is, and the others move only along the row or column, keeping their place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step, none when nothing moves; bad params are refused. The dialog has Direction, Gap, Order and Reverse Order with Preview. Docs: docs/mcp.md, docs/ui-parity.md, docs/target-app-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/arrange.rs | 50 ++++++- crates/engine/src/cmd/addons/arrange/tests.rs | 128 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 2 + crates/ui-egui/src/addons/arrange.rs | 27 +++- crates/ui-egui/src/addons/arrange/tests.rs | 54 ++++++++ docs/mcp.md | 6 +- docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 10 files changed, 268 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index d40c33e9e1..c743448b07 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index f81d7a599a..a25f341d1c 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -1,5 +1,6 @@ //! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects -//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two; +//! out in rows and columns, a row or a column; Offset Objects chains them one after another in a +//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two; //! Replace with Top Object puts a copy of the topmost selected object in place of each of the //! others; and Set Size of Each gives every selected object an exact width and height. Places and //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the @@ -17,7 +18,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; use vectorcraft_doc::{Node, NodeId, OrientedBox}; -use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use vectorcraft_render::effects; use super::super::appearance::series_children_in_paint_order; @@ -52,6 +53,15 @@ pub fn specs() -> Vec { has_selection, grid ), + cmd!( + "addon.arrange.offset", + "Offset Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}", + has_multi, + offset + ), cmd!( "addon.arrange.swap", "Swap Objects", @@ -228,6 +238,42 @@ fn grid(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": n })) } +fn offset(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.offset"; + let row = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row"; + let gap = number_in(p, "gap", 10.0, (-LIMIT, LIMIT), C)?; + let by_position = choice(p, C, "order", &["stacking", "position"])?.unwrap_or("stacking") == "position"; + let reverse = switch_or(p, "reverse", false, C)?; + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + // The objects in stacking order from the back, each with its leading and trailing edge along the direction. + let mut items: Vec<(NodeId, f64, f64)> = roots + .iter() + .filter_map(|id| { + let b = effects::preview::bounds_of(d, &[*id], true)?; + Some(if row { (*id, b.x0, b.x1) } else { (*id, b.y0, b.y1) }) + }) + .collect(); + if by_position { + items.sort_by(|a, b| a.1.total_cmp(&b.1)); + } + if reverse { + items.reverse(); + } + // The first stays; each later one starts `gap` past where the one before it now ends. + let mut end: Option = None; + let xfs: Vec<(NodeId, Affine)> = items + .iter() + .map(|&(id, start, finish)| { + let shift = end.map_or(0.0, |e| e + gap - start); + end = Some(finish + shift); + (id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) })) + }) + .collect(); + transform_each(s, "Offset Objects", false, &xfs)?; + Ok(json!({ "count": items.len() })) +} + fn swap(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.swap"; let size = switch_or(p, "size", false, C)?; diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 759f6f321e..498a927898 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -106,6 +106,134 @@ fn grid_measures_visual_bounds() { assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); } +#[test] +fn offset_chains_a_row_in_stacking_order_from_the_first_in_place() { + let mut s = session(); + let a = rect(&mut s, 100.0, 50.0, 20.0, 10.0); + let b = rect(&mut s, 0.0, 200.0, 40.0, 30.0); + let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0); + select(&mut s, &[c, a, b]); + let n = steps(&s); + let r = s.execute("addon.arrange.offset", &json!({"gap": 5})).unwrap(); + assert_eq!(r["count"], json!(3)); + assert_eq!(steps(&s), n + 1, "one undo step"); + // From the back: a stays, b starts 5 past a's right edge, c 5 past b's; each keeps its y. + assert!(near(bounds(&s, a), (100.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (125.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (170.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(bounds(&s, b), (0.0, 200.0, 40.0, 30.0))); + assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0))); + // Reversed: c stays, then b, then a. The gap defaults to 10. + s.execute("addon.arrange.offset", &json!({"reverse": true})).unwrap(); + assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, b), (320.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, a), (370.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); +} + +#[test] +fn offset_chains_a_column_by_position_either_way_and_overlaps_with_a_negative_gap() { + let mut s = session(); + let a = rect(&mut s, 0.0, 100.0, 10.0, 20.0); + let b = rect(&mut s, 50.0, 0.0, 10.0, 10.0); + let c = rect(&mut s, 100.0, 40.0, 10.0, 30.0); + select(&mut s, &[a, b, c]); + // Top to bottom: b, c, a; each 5 into the one before it, keeping its x. + s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "gap": -5})).unwrap(); + assert!(near(bounds(&s, b), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (100.0, 5.0, 10.0, 30.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, a), (0.0, 30.0, 10.0, 20.0)), "{:?}", bounds(&s, a)); + s.execute("edit.undo", &json!({})).unwrap(); + // Bottom to top: a stays, then c, then b. + s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "reverse": true, "gap": 0})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, c), (100.0, 120.0, 10.0, 30.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, b), (50.0, 150.0, 10.0, 10.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + // Left to right in a row: a, b, c. + s.execute("addon.arrange.offset", &json!({"order": "position", "gap": 1})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (11.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (22.0, 40.0, 10.0, 30.0)), "{:?}", bounds(&s, c)); +} + +#[test] +fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap(); + // Visual boxes 24 wide, touching. + assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + // A 200 wide object clipped to a 30 wide mask at x 100. + let clipped = rect(&mut s, 50.0, 50.0, 200.0, 10.0); + let mask = rect(&mut s, 100.0, 40.0, 30.0, 30.0); + select(&mut s, &[clipped, mask]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0]; + let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, group, c]); + s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap(); + // The mask starts at a's right edge, and c at the mask's. + assert!(near(bounds(&s, mask), (20.0, 40.0, 30.0, 30.0)), "{:?}", bounds(&s, mask)); + assert!(near(bounds(&s, clipped), (-30.0, 50.0, 200.0, 10.0)), "{:?}", bounds(&s, clipped)); + assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); +} + +#[test] +fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 50.0, 20.0, 20.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.offset"), "off with one object"); + select(&mut s, &[a, b]); + assert!(enabled(&s, "addon.arrange.offset")); + // Already 10 apart in a row. + let n = steps(&s); + s.execute("addon.arrange.offset", &json!({})).unwrap(); + assert_eq!(steps(&s), n, "no step when nothing moves"); + // Two objects in one group are one object: nothing to chain. + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + assert!(!enabled(&s, "addon.arrange.offset"), "off with one group"); + refuses(&mut s, "addon.arrange.offset", &[json!({"gap": 50})]); + s.execute("edit.undo", &json!({})).unwrap(); + let c = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap(); + assert!(near(bounds(&s, b), (30.0, 50.0, 20.0, 20.0)), "the locked object stays, {:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (20.0, 200.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); +} + +#[test] +fn offset_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + select(&mut s, &[a, b]); + refuses( + &mut s, + "addon.arrange.offset", + &[ + json!({"direction": "diagonal"}), + json!({"direction": 1}), + json!({"gap": 1e7}), + json!({"gap": -1e7}), + json!({"gap": "10"}), + json!({"order": "size"}), + json!({"reverse": "yes"}), + ], + ); +} + #[test] fn swap_trades_places_and_optionally_sizes() { let mut s = session(); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..9849a22077 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -6,6 +6,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.arrange.grid", "addon.arrange.groupOverlapping", + "addon.arrange.offset", "addon.arrange.randomizeOpacity", "addon.arrange.replace", "addon.arrange.size", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..c98cd9278e 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -995,6 +995,8 @@ fn structured_junk() { ("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})), ("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})), ("addon.arrange.grid", json!({"layout": "column", "gapX": -1e6})), + ("addon.arrange.offset", json!({"direction": "column", "gap": -1e6, "order": "position", "reverse": true})), + ("addon.arrange.offset", json!({"direction": "diagonal", "gap": f64::MAX, "order": 3, "reverse": "x"})), ("addon.arrange.swap", json!({"size": true, "scaleStrokes": true})), ("addon.arrange.replace", json!({"fit": "proportional", "keep": true})), ("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a26f5f7a28..ccd32bd7aa 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,5 +1,5 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, +//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, //! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping //! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. @@ -22,19 +22,21 @@ use crate::menus::{Sep, c, cp}; /// Zoom to Selection: a view command, since the view is the interface's. pub const ZOOM: &str = "addon.arrange.zoomSelection"; const GRID: &str = "addon.arrange.grid"; +const OFFSET: &str = "addon.arrange.offset"; const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 5] = [ +const DIALOGS: [(&str, &str); 6] = [ (GRID, "Arrange in Grid"), + (OFFSET, "Offset Objects"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), ]; -/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. +/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid and Offset Objects take. const SIZES: std::ops::RangeInclusive = 0.001..=1e6; const GAPS: std::ops::RangeInclusive = -1e6..=1e6; /// The seeds the Randomize Opacity dialog offers. @@ -56,6 +58,7 @@ const ATTRIBUTES: [(&str, &str); 7] = [ pub fn menu() -> Vec { vec![ c("Arrange in Grid…", GRID), + c("Offset Objects…", OFFSET), cp("Swap Objects", "addon.arrange.swap", json!({})), cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })), c("Replace with Top Object…", REPLACE), @@ -69,6 +72,7 @@ pub fn menu() -> Vec { } static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None }; +static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None }; static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None }; static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; @@ -116,6 +120,17 @@ fn grid_rows(lengths: LengthUnits) -> Vec { ] } +fn offset_rows(lengths: LengthUnits) -> Vec { + let directions = [("row", "Row (Left to Right)"), ("column", "Column (Top to Bottom)")]; + let orders = [("stacking", "Stacking Order"), ("position", "Position")]; + vec![ + choice("direction", "Direction:", &directions, "row"), + length("gap", "Gap:", 10.0, GAPS, lengths), + choice("order", "Order:", &orders, "stacking"), + check("reverse", "Reverse Order", false), + ] +} + fn replace_rows() -> Vec { let fits = [("keep", "Actual Size"), ("bounds", "Bounds"), ("proportional", "Bounds (Fit Proportionally)")]; vec![choice("fit", "Size:", &fits, "keep"), check("keep", "Keep Original", false), scale_strokes()] @@ -156,6 +171,10 @@ fn grid_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&grid_rows(POINTS), fields)) } +fn offset_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&offset_rows(POINTS), fields)) +} + fn replace_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&replace_rows(), fields)) } @@ -196,6 +215,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })), REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })), // A new seed each time the document has changed, so running it again varies the result. OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })), @@ -223,6 +243,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), + OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))), REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 420bfdb01d..e0c0e693d3 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -61,6 +61,60 @@ fn real_grid_edits_reach_the_preview_and_confirmed_geometry() { assert!(!app.any_dialog_open()); } +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn real_offset_edits_reach_the_preview_and_ok_applies_them_as_one_step() { + let (app, a, b) = app(); + let n = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Offset Objects…"); + type_number(&mut panel, "Gap", "3"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.number("gap")), Some(3.0)); + { + // From the back: a stays and b starts 3 past its right edge, keeping its y. + let app = panel.app(); + assert_eq!((bounds(&app, a).x0, bounds(&app, a).y0), (0.0, 0.0)); + assert_eq!((bounds(&app, b).x0, bounds(&app, b).y0), (23.0, 100.0)); + } + panel.focus("Reverse Order"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + panel.frame(); + let preview = { + // Reversed: b stays and a starts 3 past b's right edge, keeping its y. + let app = panel.app(); + assert_eq!((bounds(&app, b).x0, bounds(&app, b).y0), (100.0, 100.0)); + assert_eq!((bounds(&app, a).x0, bounds(&app, a).y0), (143.0, 0.0)); + (bounds(&app, a), bounds(&app, b)) + }; + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert_eq!((bounds(&app, a), bounds(&app, b)), preview); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert!(!app.any_dialog_open()); +} + +#[test] +fn real_offset_cancel_puts_the_objects_back() { + let (app, a, b) = app(); + let n = steps(&app); + let before = (bounds(&app, a), bounds(&app, b)); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Offset Objects…"); + type_number(&mut panel, "Gap", "50"); + assert_eq!(bounds(&panel.app(), b).x0, 70.0, "the preview moves b"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert_eq!((bounds(&app, a), bounds(&app, b)), before); + assert_eq!(steps(&app), n); + assert!(!app.any_dialog_open()); +} + #[test] fn real_size_keyboard_edits_keep_unticked_sides_unchanged() { let (app, a, b) = app(); diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..fbd68a9bca 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17430,11 +17430,12 @@ images and patterns keep their colours. → `{changed, swatches: [the document s Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are `addon.arrange.*`, and in the desktop app it lives in Object › Plug-ins › Arrange Tools. Each command acts on the top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured -as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid, which uses visual bounds. +as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds. | Command | Parameters (default) | Does | |---|---|---| | `addon.arrange.grid` | `layout`: `grid`, `row`, `column` (`grid`); `columns`: 1…10000 (⌈√count⌉, never more than the count); `gapX` pt (10), `gapY` pt (`gapX`), each −1000000…1000000; `centerOnArtboard` (false) | Lays the objects out in their stacking order from the back, left to right and top to bottom. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, and each object is centred in its cell. The grid starts at the selection's top-left, or is centred on the artboard under the selection's centre (the first artboard when none is there). → `{count}` | +| `addon.arrange.offset` | `direction`: `row` (left to right), `column` (top to bottom) (`row`); `gap` pt, −1000000…1000000 (10; negative overlaps the objects); `order`: `stacking` (stacking order from the back), `position` (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (`stacking`); `reverse` (false) | Chains the objects one after another in that order: the first stays where it is, and each later one moves only along the direction so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Measured by visual bounds, a clipping group by its mask. Needs two objects or more. → `{count}` | | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | @@ -17447,9 +17448,12 @@ active view so the selection's visual bounds fill the window with a margin, as ` and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. +Offset Objects… opens one the same way (`ui.menuDialog {command: "addon.arrange.offset"}`), with Direction, Gap, Order +and Reverse Order. ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} +{"name":"run_command","arguments":{"command":"addon.arrange.offset","params":{"direction":"column","gap":6,"order":"position"}}} {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..001f3a2ecb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3156,6 +3156,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Sort Objects… sorts the top-level selected objects (or `ids`, at most 20000) by one attribute (width, height, area, x or y position, opacity or stacking order; small to large, large to small, or a random order from a seed) and gives them another in that order, the first the smallest value: the objects trade the values they have, or with Distribute Evenly the values step evenly from the smallest to the largest. Lining objects up left to right by size, restacking them so the largest is at the back, or giving them heights that step with their x position are each one run. Sizes and places are measured and set as `object.setBounds` measures them (Use Preview Bounds); a width, height or area changes about each object's centre (an area in proportion), and stacking order trades places only among objects of the same layer or group. One undo step; no step when nothing changes. Tests: `sort_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each attribute sorted by and applied, both directions, distribute, layers kept apart, the seeded random order, `ids`, no step when in order, bad params), `sort_objects_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Offset Objects (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 453bda832d..ac20453f86 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -567,6 +567,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | From 92a2056a8bcf7b86bc38ab5bac935e3262843e08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:26:04 -0800 Subject: [PATCH 7/7] Scripts: page-item setters report a stale item before a bad value The name, note, hidden, locked, opacity, blendingMode, position, left, top, width and height setters checked the assigned value before the item, so a bad value on a removed item reported the value error instead of "Stale page item". Each setter now looks up its item first. --- crates/engine/src/script/dom.rs | 18 ++++++++++++------ crates/engine/src/tests/script_dom.rs | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index facf010415..25269a62e5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2140,6 +2140,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result { /// `name = value`: a number or a Boolean becomes the text `String(value)` gives. fn item_set_name(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let name = &text_arg(arg(a, 1), "name")?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); @@ -2158,11 +2159,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer { /// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number /// or a Boolean becomes the text `String(value)` gives. fn item_set_note(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let note = &text_arg(arg(a, 1), "note")?; if note.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the note is too long".into())); } - let item = this_item(h, a)?; let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim())); if !same { edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?; @@ -2196,8 +2197,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer { } fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let hidden = boolean(arg(a, 1), "hidden")?; - refuse_protected_edit(h, this_item(h, a)?)?; + refuse_protected_edit(h, item)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -2206,8 +2208,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { } fn item_set_locked(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let locked = boolean(arg(a, 1), "locked")?; - refuse_protected_edit(h, this_item(h, a)?)?; + refuse_protected_edit(h, item)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -2216,6 +2219,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer { } fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let v = number(arg(a, 1), "opacity")?; if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); @@ -2225,7 +2229,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // replaces the one the graph keeps for its series or kind. // The opacity the item already has may be assigned while its layer is hidden or locked, unless // it would still replace the opacity a graph keeps for the item's series or kind. - let item = this_item(h, a)?; let (now, keeps_other) = with_doc(h, item.doc, |_, st| { let d = &st.doc; // Only the exact number the getter reports counts as the same opacity. @@ -2271,12 +2274,12 @@ fn item_blending_mode(h: &Host, a: &[Data]) -> Answer { /// The mode the object already has may be assigned while its layer is hidden or locked, unless it /// would still replace the blend mode a graph keeps for the item's series or kind. fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let mode = match arg(a, 1) { Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode), _ => None, }; let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?; - let item = this_item(h, a)?; let (same, keeps_other) = with_doc(h, item.doc, |_, st| { let d = &st.doc; let same = d.node(item.id).is_some_and(|n| n.blend == mode); @@ -2403,16 +2406,19 @@ fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { } fn item_set_position(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let p = point(arg(a, 1), "position")?; move_to(h, a, Some(p[0]), Some(p[1])) } fn item_set_left(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let x = coordinate(arg(a, 1), "left")?; move_to(h, a, Some(x), None) } fn item_set_top(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let y = coordinate(arg(a, 1), "top")?; move_to(h, a, None, Some(y)) } @@ -2421,12 +2427,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer { /// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated /// objects included. fn resize(h: &Host, a: &[Data], width: bool) -> Answer { + let item = this_item(h, a)?; let what = if width { "width" } else { "height" }; let size = number(arg(a, 1), what)?; if size <= 0.0 || size > MAX_SIZE { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } - let item = this_item(h, a)?; refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 03cab27e93..bb333e91d8 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1702,6 +1702,29 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +/// A setter on a removed item reports the stale item before it checks the value it was given. +#[test] +fn setters_on_a_stale_item_report_it_before_a_bad_value() { + let (mut s, _, _) = doc(); + for set in [ + "name = {}", + "note = {}", + "hidden = 'x'", + "locked = 'x'", + "opacity = 500", + "blendingMode = 'x'", + "selected = 'x'", + "position = 'x'", + "left = 'x'", + "top = 'x'", + "width = -1", + "height = -1", + ] { + let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0].duplicate(); i.remove(); i.{set};")); + assert!(e.contains("Stale page item"), "{set}: {e}"); + } +} + /// File › Revert loads objects with the ids they were saved with: an object or a layer read before /// the revert does not name the loaded one. #[test]