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