From 23be2d879fd7689e0877c190a0846c2e64e6dd97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:09:24 -0800 Subject: [PATCH 1/4] View: Proof Setup saves and loads a custom proof setup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Proof Setup dialog gets Save… and Load… buttons. Save… writes the dialog's settings to a proof setup file, and Load… reads one back into the dialog. View › Proof Setup lists the setups in the Proof Setups folder next to the preferences below Customize…, and choosing one makes it the proof setup with Proof Colors on. view.proofSetup.save, view.proofSetup.load, view.proofSetup.read and view.proofSetup.list do the same from scripts and control clients. The file is VectorCraft's own JSON format (.vcproof, at most 64 KiB). --- apps/vectorcraft-cli/src/main.rs | 1 + apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/prefs_dir.rs | 8 + crates/engine/src/cmd/colormgmt.rs | 86 +++- crates/engine/src/cmd/colormgmt/proof_file.rs | 255 +++++++++++ crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/command_sets.rs | 1 + crates/engine/src/lib.rs | 5 + crates/engine/src/script/mod.rs | 2 + crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests/colormgmt.rs | 152 +++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/app.rs | 1 + .../src/dialogs/action_insert_menu_item.rs | 43 +- crates/ui-egui/src/dialogs/proof_setup.rs | 396 +++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 2 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/menus/entries.rs | 3 +- crates/ui-egui/src/menus/invoke.rs | 14 +- crates/ui-egui/src/menus/labels.rs | 15 +- crates/ui-egui/src/menus/tree.rs | 16 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/native_menu.rs | 3 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 1 + 52 files changed, 1015 insertions(+), 46 deletions(-) create mode 100644 crates/engine/src/cmd/colormgmt/proof_file.rs diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b66c15070f..2fb30d50f4 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -243,6 +243,7 @@ fn main() -> ExitCode { fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); + prefs_dir::attach_proof_setups(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c55785cfdf..4e6b6a4d32 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -499,6 +499,7 @@ fn main() -> std::process::ExitCode { // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_proof_setups(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..92f05322bd 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -73,6 +73,14 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Have View › Proof Setup list the proof setups saved in the `Proof Setups` folder, which +/// `view.proofSetup.save` makes when it saves a setup by name. +pub fn attach_proof_setups(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Proof Setups") { + session.attach_proof_setups(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 7fb1fae68b..7b782b5e66 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -26,6 +26,8 @@ use vectorcraft_render::proof; use super::EngineError; use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param}; +pub mod proof_file; + /// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated /// to `Document::color_profiles` on load). pub const PROFILES_KEY: &str = vectorcraft_doc::profiles::LEGACY_PROFILES_KEY; @@ -104,6 +106,42 @@ pub fn specs() -> Vec { always, proof_setup ), + cmd!( + query "view.proofSetup.save", + "Save Proof Setup…", + [], + None, + "{path?: file | name?: a setup in the Proof Setups folder next to the preferences (at most 100 characters and no path characters; exactly one of the two), target?, intent?, simulatePaper?, preserveNumbers?, simulateBlack? (as view.proofSetup; default: the current proof setup's)} write a custom proof setup to a VectorCraft proof setup file (.vcproof, JSON) without changing the proof view. The target must be a device: workingCmyk, cmyk: or rgb: → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}", + always, + proof_file::save + ), + cmd!( + query "view.proofSetup.load", + "Load Proof Setup…", + [], + None, + "{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} read a proof setup file of at most 64 KiB that view.proofSetup.save wrote, make it the proof setup and turn Proof Colors on → {path} and the proof state. A file whose device names a profile that is not loaded is refused and nothing changes", + always, + proof_file::load + ), + cmd!( + query "view.proofSetup.read", + "Read Proof Setup", + [], + None, + "{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} the settings of a proof setup file, read as view.proofSetup.load reads it, without changing the proof view → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}", + always, + proof_file::read + ), + cmd!( + query "view.proofSetup.list", + "Saved Proof Setups", + [], + None, + "{} the proof setup files in the Proof Setups folder next to the preferences, by name, at most 100 → {folder (null without the folder), setups: [{name, path}], truncated}", + always, + proof_file::list + ), cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| { toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors)) }), @@ -817,26 +855,7 @@ fn view_json(v: &proof::ProofView) -> Value { fn proof_setup(s: &mut Session, p: &Value) -> Result { const C: &str = "view.proofSetup"; let mut v = proof::view(); - if let Some(t) = text_param(p, "target", C)? { - let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?; - if let ProofTarget::Cmyk(name) = &t - && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk) - { - return Err(bad(C, format!("unknown CMYK profile `{name}`"))); - } - if let ProofTarget::Rgb(name) = &t - && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Rgb) - { - return Err(bad(C, format!("unknown RGB profile `{name}`"))); - } - v.setup.target = t; - } - if let Some(i) = intent_param(p, C)? { - v.setup.intent = i; - } - v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?; - v.setup.preserve_numbers = switch_or(p, "preserveNumbers", v.setup.preserve_numbers, C)?; - v.setup.simulate_black = switch_or(p, "simulateBlack", v.setup.simulate_black, C)?; + setup_params(p, &mut v.setup, C)?; if let Some(on) = on_param(p, "proof", C)? { v.proof_colors = on; } @@ -844,6 +863,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result { Ok(view_json(&v)) } +/// Take the proof setup settings `p` gives (`target`, `intent`, `simulatePaper`, `preserveNumbers` +/// and `simulateBlack`, as `view.proofSetup` reads them) into `setup`. A `cmyk:` or `rgb:` target +/// must name a CMYK or RGB profile that is loaded. +fn setup_params(p: &Value, setup: &mut cms::ProofSetup, cmd: &str) -> Result<()> { + if let Some(t) = text_param(p, "target", cmd)? { + let t = ProofTarget::parse(t).ok_or_else(|| bad(cmd, format!("unknown proof target `{t}`")))?; + if let ProofTarget::Cmyk(name) = &t + && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk) + { + return Err(bad(cmd, format!("unknown CMYK profile `{name}`"))); + } + if let ProofTarget::Rgb(name) = &t + && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Rgb) + { + return Err(bad(cmd, format!("unknown RGB profile `{name}`"))); + } + setup.target = t; + } + if let Some(i) = intent_param(p, cmd)? { + setup.intent = i; + } + setup.simulate_paper = switch_or(p, "simulatePaper", setup.simulate_paper, cmd)?; + setup.preserve_numbers = switch_or(p, "preserveNumbers", setup.preserve_numbers, cmd)?; + setup.simulate_black = switch_or(p, "simulateBlack", setup.simulate_black, cmd)?; + Ok(()) +} + /// Make `v` the proof view and redraw every document. When `v` equals the current view, the view /// and the revisions stay as they are; Separations Preview's visible plates are compared as a set. fn store_view(s: &mut Session, v: proof::ProofView) { diff --git a/crates/engine/src/cmd/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs new file mode 100644 index 0000000000..16d0b29f5d --- /dev/null +++ b/crates/engine/src/cmd/colormgmt/proof_file.rs @@ -0,0 +1,255 @@ +//! View → Proof Setup → Customize…'s Save… and Load…: a custom proof setup (the device to simulate, +//! Preserve Numbers, the rendering intent, Simulate Paper Color and Simulate Black Ink) in a file, +//! and the setups saved in the `Proof Setups` folder next to the preferences, which View → Proof +//! Setup lists ([`Session::attach_proof_setups`]). `view.proofSetup.read` reads a file without +//! applying it, which is how Load… fills the dialog. +//! +//! The file format is VectorCraft's own: JSON with `format` [`FORMAT`], `version` 1, `target`, +//! `intent`, `simulatePaper`, `preserveNumbers` and `simulateBlack`, as `view.proofSetup` names +//! them, at most [`MAX_FILE`] bytes. + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{self, Intent, ProofSetup, ProofTarget}; +use vectorcraft_render::proof; + +use super::super::{EngineError, fileio}; +use super::{Result, Session, bad, setup_params, store_view, text_param, view_json}; + +/// The extension of a proof setup file. +pub const EXT: &str = "vcproof"; +/// The `format` a proof setup file names. +pub const FORMAT: &str = "vectorcraft-proof-setup"; +/// The format version this build writes and reads. +const VERSION: u64 = 1; +/// The largest proof setup file `view.proofSetup.load` reads, bytes (VectorCraft's own limit). +pub const MAX_FILE: usize = 64 << 10; +/// The most setups `view.proofSetup.list` lists. +pub const MAX_LISTED: usize = 100; +/// The most folder entries `view.proofSetup.list` looks at, setup files or not. +const MAX_SCANNED: usize = 100_000; +/// The longest `name`, in characters. +const MAX_NAME: usize = 100; + +impl Session { + /// Keep the proof setups that `view.proofSetup.save` saves by name in the folder `dir` (`Proof + /// Setups` next to the preferences), which `view.proofSetup.list` lists. The folder is made + /// when a setup is first saved there. + pub fn attach_proof_setups(&mut self, dir: std::path::PathBuf) { + self.proof_setup_dir = Some(dir); + } + + /// The saved proof setups' folder ([`Session::attach_proof_setups`]); none on the web. + pub fn proof_setup_dir(&self) -> Option<&std::path::Path> { + self.proof_setup_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// How many proof setup files `view.proofSetup.save` wrote in this session; the menus list the + /// Proof Setups folder again when it changes. + pub fn proof_setup_saves(&self) -> u64 { + self.proof_setup_saves + } +} + +/// The file `p` names for `cmd`: its `path`, or the setup `name` in the Proof Setups folder. +fn file_path(s: &Session, p: &Value, cmd: &str) -> Result<(String, bool)> { + match (text_param(p, "path", cmd)?, text_param(p, "name", cmd)?) { + (Some(path), None) if path.trim().is_empty() => Err(bad(cmd, "`path` is empty")), + (Some(path), None) => Ok((path.to_string(), false)), + (None, Some(name)) => { + let name = setup_name(name, cmd)?; + let dir = s.proof_setup_dir().ok_or_else(|| bad(cmd, "saved proof setups need the preferences folder, which this run doesn't have"))?; + Ok((dir.join(format!("{name}.{EXT}")).to_string_lossy().into_owned(), true)) + } + (Some(_), Some(_)) => Err(bad(cmd, "give `path` or `name`, not both")), + (None, None) => Err(bad(cmd, "missing `path` or `name`")), + } +} + +/// `name` trimmed, when it can name a file in the Proof Setups folder: not empty, at most +/// [`MAX_NAME`] characters, no path or control characters, and not starting with a dot. +fn setup_name<'a>(name: &'a str, cmd: &str) -> Result<&'a str> { + let name = name.trim(); + if name.is_empty() { + return Err(bad(cmd, "`name` is empty")); + } + if name.chars().count() > MAX_NAME { + return Err(bad(cmd, format!("`name` is longer than {MAX_NAME} characters"))); + } + if name.starts_with('.') || name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) { + return Err(bad(cmd, format!("`name` can't hold path characters: `{name}`"))); + } + Ok(name) +} + +/// `Ok` when `t` is a device a custom proof setup can simulate and its profile is loaded. +fn check_device(t: &ProofTarget) -> std::result::Result<(), String> { + let loaded = |name: &str, kind| cms::profile(name).is_some_and(|k| k.kind == kind); + match t { + ProofTarget::WorkingCmyk => Ok(()), + ProofTarget::Cmyk(name) if loaded(name, cms::ProfileKind::Cmyk) => Ok(()), + ProofTarget::Rgb(name) if loaded(name, cms::ProfileKind::Rgb) => Ok(()), + ProofTarget::Cmyk(name) => Err(format!("the device to simulate is the CMYK profile `{name}`, which is not loaded")), + ProofTarget::Rgb(name) => Err(format!("the device to simulate is the RGB profile `{name}`, which is not loaded")), + t => Err(format!("`{}` is not a device to simulate: a custom proof setup simulates workingCmyk, cmyk: or rgb:", t.id())), + } +} + +/// The settings of `setup`, as `view.proofSetup` names them. +fn setup_json(setup: &ProofSetup) -> serde_json::Map { + let v = json!({ + "target": setup.target.id(), + "intent": setup.intent.id(), + "simulatePaper": setup.simulate_paper, + "preserveNumbers": setup.preserve_numbers, + "simulateBlack": setup.simulate_black, + }); + match v { + Value::Object(m) => m, + _ => serde_json::Map::new(), + } +} + +/// The proof setup in a file's `bytes`, or why it can't be read. +pub fn parse(bytes: &[u8]) -> std::result::Result { + let v: Value = serde_json::from_slice(bytes).map_err(|e| format!("not a proof setup file: {e}"))?; + if v.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err("not a VectorCraft proof setup file".into()); + } + match v.get("version").and_then(Value::as_u64) { + Some(VERSION) => {} + Some(n) if n > VERSION => return Err(format!("the file is version {n}, made by a newer VectorCraft")), + _ => return Err("the file has no version VectorCraft reads".into()), + } + let text = |key: &str| v.get(key).and_then(Value::as_str); + let target = text("target").ok_or("the file names no device to simulate")?; + let target = ProofTarget::parse(target).ok_or_else(|| format!("unknown proof target `{target}`"))?; + let intent = text("intent").ok_or("the file names no rendering intent")?; + let intent = Intent::parse(intent).ok_or_else(|| format!("unknown intent `{intent}`"))?; + let on = |key: &str| match v.get(key) { + None | Some(Value::Null) => Ok(false), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(format!("`{key}` must be true or false")), + }; + Ok(ProofSetup { + target, + intent, + simulate_paper: on("simulatePaper")?, + preserve_numbers: on("preserveNumbers")?, + simulate_black: on("simulateBlack")?, + separations: None, + }) +} + +/// A proof setup file holding `setup`. +pub fn encode(setup: &ProofSetup) -> Vec { + let mut m = serde_json::Map::new(); + m.insert("format".into(), json!(FORMAT)); + m.insert("version".into(), json!(VERSION)); + m.extend(setup_json(setup)); + let mut bytes = serde_json::to_vec_pretty(&Value::Object(m)).unwrap_or_default(); + bytes.push(b'\n'); + bytes +} + +pub(super) fn save(s: &mut Session, p: &Value) -> Result { + const C: &str = "view.proofSetup.save"; + let (path, named) = file_path(s, p, C)?; + let mut setup = proof::view().setup; + setup_params(p, &mut setup, C)?; + check_device(&setup.target).map_err(|e| bad(C, e))?; + if named + && let Some(dir) = std::path::Path::new(&path).parent() + && !dir.is_dir() + { + crate::file_access::check_write(&path).map_err(EngineError::Other)?; + std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?; + } + fileio::write_file(&path, &encode(&setup))?; + s.proof_setup_saves += 1; + let mut r = setup_json(&setup); + r.insert("path".into(), json!(path)); + Ok(Value::Object(r)) +} + +/// The file `p` names for `cmd` and the usable proof setup in it. +fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> { + let (path, _) = file_path(s, p, cmd)?; + // One byte past the limit shows a file over it, which is not read further. + let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?; + if bytes.len() > MAX_FILE { + return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes"))); + } + let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + Ok((path, setup)) +} + +pub(super) fn read(s: &mut Session, p: &Value) -> Result { + let (path, setup) = read_setup(s, p, "view.proofSetup.read")?; + let mut r = setup_json(&setup); + r.insert("path".into(), json!(path)); + Ok(Value::Object(r)) +} + +pub(super) fn load(s: &mut Session, p: &Value) -> Result { + let (path, setup) = read_setup(s, p, "view.proofSetup.load")?; + let mut v = proof::view(); + // Separations Preview's plates are not part of a proof setup file. + v.setup = ProofSetup { separations: v.setup.separations.take(), ..setup }; + v.proof_colors = true; + store_view(s, v.clone()); + let mut r = view_json(&v); + r["path"] = json!(path); + Ok(r) +} + +pub(super) fn list(s: &mut Session, _: &Value) -> Result { + let none = json!({"folder": null, "setups": [], "truncated": false}); + let Some(dir) = s.proof_setup_dir() else { return Ok(none) }; + listed(dir).map(|l| l.unwrap_or(none)) +} + +/// The web keeps no saved setups ([`Session::proof_setup_dir`]). +#[cfg(target_arch = "wasm32")] +pub fn listed(_: &std::path::Path) -> Result> { + Ok(None) +} + +/// The listing of the Proof Setups folder `dir`, as `view.proofSetup.list` gives it; `None` for a +/// request that may not read it. The app calls it on another thread, without a session. +#[cfg(not(target_arch = "wasm32"))] +pub fn listed(dir: &std::path::Path) -> Result> { + let folder = dir.to_string_lossy().into_owned(); + // A request that may not read the folder learns nothing of it, nor where it is. + if crate::file_access::check_read(&folder).is_err() { + return Ok(None); + } + // No folder yet: nothing has been saved. + let Ok(entries) = std::fs::read_dir(dir) else { return Ok(Some(json!({"folder": folder, "setups": [], "truncated": false}))) }; + // The setup files' names, the first MAX_LISTED by name; other entries are passed over before + // the limit applies. A link is not followed. + let (mut names, mut truncated) = (Vec::::new(), false); + for (i, e) in entries.flatten().enumerate() { + if i == MAX_SCANNED { + truncated = true; + break; + } + let name = e.file_name().to_string_lossy().into_owned(); + let setup = name.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(EXT) && !stem.trim().is_empty()); + if !setup || !e.file_type().is_ok_and(|t| t.is_file()) { + continue; + } + names.push(name); + if names.len() > 2 * MAX_LISTED { + names.sort(); + names.truncate(MAX_LISTED); + truncated = true; + } + } + names.sort(); + truncated |= names.len() > MAX_LISTED; + names.truncate(MAX_LISTED); + let setups: Vec = + names.iter().filter_map(|name| Some(json!({"name": name.rsplit_once('.')?.0, "path": dir.join(name).to_string_lossy()}))).collect(); + Ok(Some(json!({"folder": folder, "setups": setups, "truncated": truncated}))) +} diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 5b9e911b0a..d338b27c1e 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. 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, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. 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, 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, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index ee594bae25..e16e09f67b 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -100,6 +100,7 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[ "symbol.selectInstances", "view.guides.lock", "view.proofSetup", + "view.proofSetup.load", "view.proofColors", "view.overprintPreview", "view.separationsPreview", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4b47966463..00bafcc748 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -181,6 +181,11 @@ pub struct Session { /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option, + /// The folder of the proof setups `view.proofSetup.save` saves by name and View → Proof Setup + /// lists; `None`: no folder ([`Session::attach_proof_setups`]). + proof_setup_dir: Option, + /// How many proof setup files `view.proofSetup.save` wrote ([`Session::proof_setup_saves`]). + proof_setup_saves: u64, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index b52fa6e66a..04a8d21f14 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -142,6 +142,8 @@ pub fn refused_to_scripts(id: &str) -> bool { "color.removeProfile", "file.print", "view.proofSetup", + "view.proofSetup.save", + "view.proofSetup.load", "view.proofColors", "view.overprintPreview", "view.separationsPreview", diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1244b77432..aada066351 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -94,6 +94,8 @@ impl Session { plugin_dir: None, scripts_dir: None, new_doc_profile_dir: None, + proof_setup_dir: None, + proof_setup_saves: 0, plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 6bbe174e93..2ef1f1a12f 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -648,6 +648,158 @@ fn proof_setup_takes_the_custom_proof_settings() { assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws"); } +/// A custom proof setup saved to a file loads back as the same setup with Proof Colors on; saving +/// leaves the proof view as it is, and `view.proofSetup.read` only reads the file. +#[test] +fn a_saved_proof_setup_loads_back() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-file"); + let path = dir.join("press.vcproof").to_string_lossy().to_string(); + let mut s = session(); + let device = format!("cmyk:{}", cms::GENERIC_CMYK); + let r = s + .execute( + "view.proofSetup.save", + &json!({"path": path, "target": device, "intent": "perceptual", "preserveNumbers": true, "simulateBlack": true}), + ) + .unwrap(); + assert_eq!((r["path"].as_str(), r["target"].as_str(), r["intent"].as_str()), (Some(path.as_str()), Some(device.as_str()), Some("perceptual"))); + assert_eq!(vectorcraft_render::proof::view(), Default::default(), "saving leaves the proof view alone"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("\"format\": \"vectorcraft-proof-setup\"") && text.contains("\"version\": 1"), "{text}"); + let r = s.execute("view.proofSetup.read", &json!({"path": path})).unwrap(); + assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(device.as_str()), Some(true), Some(true))); + assert_eq!(vectorcraft_render::proof::view(), Default::default(), "reading changes nothing"); + assert!(!crate::waits_for_tool_edit("view.proofSetup.read"), "reading does not finish a tool's edit"); + let rev = s.doc().unwrap().revision; + let r = s.execute("view.proofSetup.load", &json!({"path": path})).unwrap(); + assert_eq!((r["proofColors"].as_bool(), r["path"].as_str()), (Some(true), Some(path.as_str()))); + let v = vectorcraft_render::proof::view(); + assert!(v.proof_colors); + let want = ProofSetup { + target: ProofTarget::Cmyk(cms::GENERIC_CMYK.into()), + intent: Intent::Perceptual, + simulate_paper: false, + preserve_numbers: true, + simulate_black: true, + ..Default::default() + }; + assert_eq!(v.setup, want); + assert!(s.doc().unwrap().revision > rev, "the canvas redraws"); + // Saved from the current setup, the file holds that setup: the round trip keeps every field. + let again = dir.join("again.vcproof").to_string_lossy().to_string(); + s.execute("view.proofSetup.save", &json!({"path": again, "simulatePaper": true})).unwrap(); + s.execute("view.proofSetup", &json!({"target": "workingCmyk"})).unwrap(); + s.execute("view.proofSetup.load", &json!({"path": again})).unwrap(); + assert_eq!(vectorcraft_render::proof::view().setup, ProofSetup { simulate_paper: true, ..want }); +} + +/// Saving refuses a target that is not a device, bad params and a bad name; loading refuses a file +/// that is too large, not a proof setup, newer, or whose device is a profile that is not loaded, +/// and the proof view stays as it was. +#[test] +fn proof_setup_files_refuse_what_they_cannot_use() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-refused"); + let file = |n: &str| dir.join(n).to_string_lossy().to_string(); + let mut s = session(); + let path = file("a.vcproof"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "protanopia"}), "`protanopia` is not a device to simulate"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "rgb:Nope"}), "unknown RGB profile `Nope`"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "simulateBlack": "yes"}), "`simulateBlack` must be true or false"); + refused(&mut s, "view.proofSetup.save", json!({}), "missing `path` or `name`"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "name": "x"}), "not both"); + refused(&mut s, "view.proofSetup.save", json!({"path": " "}), "`path` is empty"); + refused(&mut s, "view.proofSetup.save", json!({"name": "x"}), "need the preferences folder"); + assert!(!std::path::Path::new(&path).exists(), "nothing is written"); + s.attach_proof_setups(dir.join("Proof Setups")); + for bad_name in ["", " ", "../up", "a/b", "a\\b", ".hidden", "c:d"] { + refused(&mut s, "view.proofSetup.save", json!({"name": bad_name}), "`name`"); + } + refused(&mut s, "view.proofSetup.save", json!({"name": "x".repeat(101)}), "longer than 100 characters"); + let before = vectorcraft_render::proof::view(); + let write = |n: &str, text: &str| { + let p = file(n); + std::fs::write(&p, text).unwrap(); + p + }; + let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#; + let cases = [ + (write("big.vcproof", &format!("{ok}{}", " ".repeat(64 << 10))), "larger than 65536 bytes"), + (write("junk.vcproof", "not json"), "not a proof setup file"), + (write("other.vcproof", r#"{"format": "other", "version": 1}"#), "not a VectorCraft proof setup file"), + (write("newer.vcproof", &ok.replace("\"version\": 1", "\"version\": 2")), "made by a newer VectorCraft"), + (write("missing.vcproof", &ok.replace("workingCmyk", "cmyk:Not Loaded")), "the CMYK profile `Not Loaded`, which is not loaded"), + (write("blind.vcproof", &ok.replace("workingCmyk", "deuteranopia")), "not a device to simulate"), + (write("intent.vcproof", &ok.replace("relative", "vivid")), "unknown intent `vivid`"), + (write("flag.vcproof", &ok.replace("}", r#", "simulatePaper": 1}"#)), "`simulatePaper` must be true or false"), + ]; + for (p, msg) in cases { + for cmd in ["view.proofSetup.load", "view.proofSetup.read"] { + refused(&mut s, cmd, json!({"path": p}), msg); + } + } + refused(&mut s, "view.proofSetup.load", json!({"path": file("gone.vcproof")}), "gone.vcproof"); + assert_eq!(vectorcraft_render::proof::view(), before, "the proof view is unchanged"); + // A file of the limit's size is read. + let padded = format!("{ok}{}", " ".repeat((64 << 10) - ok.len())); + s.execute("view.proofSetup.load", &json!({"path": write("limit.vcproof", &padded)})).unwrap(); +} + +/// Setups saved by name go in the Proof Setups folder, made on the first save, and are listed by +/// name; other files there are left out, and a run without the folder lists none. +#[test] +fn proof_setups_saved_by_name_are_listed() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + assert_eq!(s.execute("view.proofSetup.list", &json!({})).unwrap(), json!({"folder": null, "setups": [], "truncated": false})); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list"); + let folder = dir.join("Proof Setups"); + s.attach_proof_setups(folder.clone()); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!(r["setups"], json!([]), "no folder yet: none saved"); + let r = s.execute("view.proofSetup.save", &json!({"name": " Coated Press ", "target": format!("rgb:{}", cms::DISPLAY_P3)})).unwrap(); + let saved = folder.join("Coated Press.vcproof"); + assert_eq!(r["path"].as_str(), Some(saved.to_string_lossy().as_ref())); + s.execute("view.proofSetup.save", &json!({"name": "Bright"})).unwrap(); + std::fs::write(folder.join("notes.txt"), "x").unwrap(); + std::fs::create_dir(folder.join("Sub.vcproof")).unwrap(); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + let names: Vec<&str> = r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str()).collect(); + assert_eq!(names, ["Bright", "Coated Press"]); + assert_eq!(r["truncated"], false); + s.execute("view.proofSetup.load", &json!({"name": "Coated Press"})).unwrap(); + assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into())); + for i in 0..101 { + std::fs::write(folder.join(format!("z{i:03}.vcproof")), "x").unwrap(); + } + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (100, Some(true))); + assert_eq!((r["setups"][0]["name"].as_str(), r["setups"][99]["name"].as_str()), (Some("Bright"), Some("z097")), "the first 100 by name"); +} + +/// Other files in the Proof Setups folder, however many, do not keep its setups from the listing. +#[test] +fn proof_setups_are_listed_among_many_other_files() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-crowded"); + let folder = dir.join("Proof Setups"); + std::fs::create_dir_all(&folder).unwrap(); + for i in 0..5000 { + std::fs::write(folder.join(format!("a{i:04}.txt")), "").unwrap(); + } + s.attach_proof_setups(folder.clone()); + s.execute("view.proofSetup.save", &json!({"name": "Press"})).unwrap(); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (1, Some(false))); + assert_eq!(r["setups"][0]["name"], "Press"); +} + /// Whether the content has a DeviceCMYK fill/stroke operator (`c m y k k` / `K`). fn has_cmyk_op(pdf: &str) -> bool { let toks: Vec<&str> = pdf.split_ascii_whitespace().collect(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index d4f06bd2a0..710788fe37 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -979,7 +979,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.proofSetupDialog", "Customize…", "", - "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back)", + "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder, whose setups View › Proof Setup lists below Customize…)", ), ( "ui.indexedColorDialog", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index f708d0f454..e872bbd6c3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -353,6 +353,7 @@ impl VectorcraftApp { // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); + crate::dialogs::proof_setup::poll(self, ctx); if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { // A script in `$.sleep` goes on when its time is up; until then the app can idle. match self.session.script_sleep_left() { diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index 0b4bd8dc7d..2423999694 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -66,23 +66,27 @@ fn build(lang: crate::i18n::Lang, english_names: bool) -> Vec { .map(|item| { let parts = || item.path.iter().chain(std::iter::once(&item.label)).copied(); let english = parts().collect::>().join(" › "); - let shown = parts().map(|s| crate::i18n::tr(lang, s)).collect::>().join(" › "); + // A saved proof setup keeps its file's name. + let own_name = item.command == crate::dialogs::proof_setup::LOAD; + let path = item.path.iter().map(|s| crate::i18n::tr(lang, s)); + let label = if own_name { item.label } else { crate::i18n::tr(lang, item.label) }; + let shown = path.chain(std::iter::once(label)).collect::>().join(" › "); let haystack = format!("{}\n{}\n{}", english.to_lowercase(), shown.to_lowercase(), item.command.to_lowercase()); Row { command: item.command, params: item.params, shown, haystack } }) .collect() } -/// The rows, built again only when the language, the installed plug-ins, the font name setting or -/// the loaded fonts change, not on every frame. +/// The rows, built again only when the language, the installed plug-ins, the font name setting, +/// the loaded fonts or the saved proof setups change, not on every frame. fn rows(app: &VectorcraftApp, ctx: &egui::Context) -> Arc> { - type Key = (&'static str, u64, bool, u64, bool); + type Key = (&'static str, u64, bool, u64, bool, u64); let lang = crate::i18n::current(); let english_names = app.session.prefs.font_names_in_english; let db = vectorcraft_text::FontDb::global(); // Read before building, as the Font menu does: fonts that load meanwhile build the rows again. let (cataloged, generation) = (db.installed_fonts_ready(), db.generation()); - let key: Key = (lang.code(), menus::plugin_revision(), english_names, generation, cataloged); + let key: Key = (lang.code(), menus::plugin_revision(), english_names, generation, cataloged, crate::dialogs::proof_setup::saved_revision()); let id = egui::Id::unique("action-insert-menu-item-rows"); if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, Arc>)>(id)) && k == key @@ -301,4 +305,33 @@ mod tests { let shared = rows.iter().any(|r| rows.iter().any(|o| o.command == r.command && o.params != r.params)); assert!(shared, "items that share a command are listed apart, by their params"); } + + /// A proof setup saved while the dialog is open is listed at once, by its file's name in every + /// UI language. + #[test] + fn a_proof_setup_saved_meanwhile_is_listed_by_its_name() { + use crate::dialogs::proof_setup; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let dir = vectorcraft_testkit::TempDir::new("insert-menu-item-proof-setups"); + app.session.attach_proof_setups(dir.join("Proof Setups")); + proof_setup::refresh_saved(&app, None); + proof_setup::wait(); + let de = Lang::from_code("de").unwrap(); + crate::i18n::set_current(de); + let listed = + |app: &VectorcraftApp| rows(app, &ctx).iter().filter(|r| r.command == proof_setup::LOAD).map(|r| r.shown.clone()).collect::>(); + // The installed fonts' scan, which builds the rows again when it ends, is over first. + vectorcraft_text::FontDb::global().menu_family_list(); + let before = listed(&app); + app.run("view.proofSetup.save", json!({"name": "Group", "target": "workingCmyk"})).unwrap(); + proof_setup::refresh_saved(&app, None); + proof_setup::wait(); + let after = listed(&app); + crate::i18n::set_current(Lang::EN); + assert!(before.is_empty(), "{before:?}"); + let view = crate::i18n::tr(de, "View"); + let menu = crate::i18n::tr(de, "Proof Setup"); + assert_eq!(after, [format!("{view} › {menu} › Group")]); + } } diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index 7e534de2f4..ca47722db3 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -2,19 +2,28 @@ //! RGB profile), Preserve CMYK Numbers or Preserve RGB Numbers, the rendering intent (used while //! the numbers are not preserved), Simulate Paper Color and Simulate Black Ink (CMYK devices only). //! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and -//! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. +//! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save… +//! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one +//! into the dialog (`view.proofSetup.read`); both pickers start in the Proof Setups +//! folder next to the preferences, whose setups View → Proof Setup lists below Customize… +//! ([`saved_items`]). //! //! Fields: `device` (`workingCmyk`, `cmyk:` or `rgb:`), `preserveNumbers`, //! `intent`, `simulatePaper`, `simulateBlack` and `preview`. +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::sync::{Mutex, MutexGuard}; + use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Intent, ProfileKind, ProofTarget}; +use vectorcraft_engine::cmd::colormgmt::proof_file::{self, EXT}; use vectorcraft_render::proof; use super::{DialogSpec, form}; -use crate::VectorcraftApp; +use crate::menus::Item; use crate::state::Dialog; use crate::widgets; +use crate::{FilePick, VectorcraftApp}; /// The dialog kind of Proof Setup › Customize. pub const KIND: &str = "proofSetup"; @@ -123,6 +132,27 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if widgets::check(ui, tl!("Simulate Black Ink"), (black || paper) && !rgb, !rgb && !paper) { d.fields.insert("simulateBlack".into(), json!(!black)); } + // The web has no folder to keep setups in. + if !cfg!(target_arch = "wasm32") { + ui.add_space(6.0); + let (mut save_clicked, mut load_clicked) = (false, false); + ui.horizontal(|ui| { + save_clicked = widgets::flat_button(ui, tl!("Save…"), 64.0).clicked(); + load_clicked = widgets::flat_button(ui, tl!("Load…"), 64.0).clicked(); + }); + // Their file dialogs, shown off the UI thread, save from or load into the dialog as it is + // then. + let r = if save_clicked { + crate::picks::in_app_dialog(app, d, save) + } else if load_clicked { + crate::picks::in_app_dialog(app, d, load) + } else { + Ok(()) + }; + if let Err(e) = r { + app.status(e); + } + } ui.add_space(8.0); form::preview_check(ui, d); preview(app, d); @@ -169,6 +199,220 @@ pub(super) fn cancel(app: &mut VectorcraftApp, d: &Dialog) { } } +/// A file dialog for proof setup files, starting in the Proof Setups folder. +fn pick(app: &VectorcraftApp, name: String) -> FilePick { + let folder = app.session.proof_setup_dir().map(|f| f.to_string_lossy().into_owned()); + FilePick { name, folder, filters: vec![FilePick::filter("Proof setups", &[EXT])] } +} + +/// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again. +fn save(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + // The picker opens in the folder, made for it when it may be written. When the picker is + // canceled, the folder it made is removed again while it is still empty: here for a picker + // shown in line, and by [`poll`] once a picker shown off the UI thread has closed. + let made = app + .session + .proof_setup_dir() + .filter(|dir| !dir.is_dir() && vectorcraft_engine::file_access::check_write(&dir.to_string_lossy()).is_ok()) + .map(std::path::Path::to_path_buf) + .filter(|dir| std::fs::create_dir_all(dir).is_ok()); + let pick = pick(app, format!("{}.{EXT}", tl!("Proof Setup"))); + let Some((picked, file_type)) = crate::picks::save_with_type(app, &pick) else { + if let Some(dir) = made { + if app.picks.is_waiting() { + saved().made = Some(dir); + } else { + let _ = std::fs::remove_dir(dir); + } + } + return Ok(()); + }; + let path = if std::path::Path::new(&picked).extension().is_none() { format!("{picked}.{EXT}") } else { picked.clone() }; + // The picker asked only about the name as typed: a file at the name with the extension added + // is replaced after a question, whose OK runs Save… again. + if path != picked && crate::picks::ask_to_replace(app, crate::picks::PickRequest::Save(pick.clone()), &picked, file_type.as_deref(), &path) { + return Ok(()); + } + let mut p = params(d); + if let Some(o) = p.as_object_mut() { + o.remove("proof"); + o.insert("path".into(), json!(path)); + } + app.run("view.proofSetup.save", p)?; + refresh_saved(app, None); + app.status(format!("Saved {path}")); + Ok(()) +} + +/// Load…: the picked file's settings fill the dialog (Preview then shows them). +fn load(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let pick = pick(app, String::new()); + // A canceled picker leaves the dialog as it is. + let Some(path) = crate::picks::open(app, &pick) else { return Ok(()) }; + let r = app.run("view.proofSetup.read", json!({ "path": path }))?; + let fields = [ + ("device", "target"), + ("intent", "intent"), + ("preserveNumbers", "preserveNumbers"), + ("simulatePaper", "simulatePaper"), + ("simulateBlack", "simulateBlack"), + ]; + for (field, key) in fields { + d.fields.insert(field.into(), r[key].clone()); + } + Ok(()) +} + +// ---------- the saved setups in View › Proof Setup ---------- + +/// The command a saved setup's menu item runs. +pub const LOAD: &str = "view.proofSetup.load"; + +#[derive(Default)] +struct Saved { + /// (name, path) of each setup, as `view.proofSetup.list` last gave them. + setups: Vec<(&'static str, String)>, + /// How many listings differed from the one before (the macOS menu bar follows it). + revision: u64, + /// A first listing was read. + started: bool, + /// The window was the active one at the last [`poll`]. + focused: bool, + /// The session's count of saved setups at the last [`poll`] (`Session::proof_setup_saves`). + saves: u64, + /// The Proof Setups folder that Save… made for a picker shown off the UI thread, removed by + /// [`poll`] once the picker has closed if it is still empty. + made: Option, + /// The listing being read on another thread, as (name, path) of each setup. + reading: Option>>, + /// Another read was asked for while one was under way; [`poll`] starts it when that one ends. + pending: bool, +} + +/// The listing the menus show. One per process in the app; one per thread in unit tests, which run +/// in parallel threads, each with its own folder. +fn saved() -> MutexGuard<'static, Saved> { + #[cfg(not(test))] + let saved: &'static Mutex = { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + S.get_or_init(Default::default) + }; + #[cfg(test)] + let saved: &'static Mutex = { + thread_local!(static S: &'static Mutex = Box::leak(Box::default())); + S.with(|s| *s) + }; + saved.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Read the Proof Setups folder's listing again on another thread (`view.proofSetup.list`'s +/// listing: file names only, at most 100), unless the session has no folder. While a read is under +/// way, another read starts when it ends ([`poll`]). `ctx` is asked to draw when the read ends. +pub fn refresh_saved(app: &VectorcraftApp, ctx: Option<&egui::Context>) { + let Some(dir) = app.session.proof_setup_dir().map(std::path::Path::to_path_buf) else { return }; + let mut saved = saved(); + if saved.reading.is_some() { + saved.pending = true; + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.cloned(); + let spawned = std::thread::Builder::new().name("vectorcraft-proof-setups".into()).spawn(move || { + // The app's own folder, read for the person at the keyboard. + let listed = vectorcraft_engine::file_access::unconfined(|| proof_file::listed(&dir)); + let setups = listed + .ok() + .flatten() + .and_then(|r| r["setups"].as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|e| Some((e["name"].as_str()?.to_string(), e["path"].as_str()?.to_string()))) + .collect(); + if tx.send(setups).is_ok() + && let Some(ctx) = ctx + { + ctx.request_repaint(); + } + }); + if spawned.is_ok() { + saved.reading = Some(rx); + } +} + +/// Take in the read under way: when it has ended, or with `wait` once it ends. A name past the +/// menu's name limit is left out. +fn take(wait: bool) { + let mut saved = saved(); + let Some(reading) = &saved.reading else { return }; + let listed = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; + match listed { + Ok(listed) => { + let setups: Vec<(&'static str, String)> = + listed.into_iter().filter_map(|(name, path)| Some((crate::scripts_menu::intern(&name)?, path))).collect(); + if saved.setups != setups { + saved.setups = setups; + saved.revision += 1; + } + saved.reading = None; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => saved.reading = None, + } +} + +/// Wait for the read under way and take it in. +#[cfg(test)] +pub(crate) fn wait() { + take(true); +} + +/// Once per iteration: list the folder on the first one, after `view.proofSetup.save` wrote a +/// setup (from the dialog, a control client or the command palette), and when the window becomes +/// the active one, so a setup copied into the folder is listed without a restart; take in a read +/// that ended, and then start a read asked for while it was under way. Once Save…'s picker shown +/// off the UI thread has closed, the folder it made is removed if it is still empty. +pub fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) { + let focused = ctx.input(|i| i.focused); + let saves = app.session.proof_setup_saves(); + let start = { + let mut saved = saved(); + if !app.picks.is_waiting() + && let Some(dir) = saved.made.take() + { + // A folder that a setup was saved in is not empty, and stays. + let _ = std::fs::remove_dir(dir); + } + let start = !saved.started || (focused && !saved.focused) || saves != saved.saves; + (saved.started, saved.focused, saved.saves) = (true, focused, saves); + start + }; + if start { + refresh_saved(app, Some(ctx)); + } + take(false); + let again = { + let mut saved = saved(); + let again = saved.pending && saved.reading.is_none(); + if again { + saved.pending = false; + } + again + }; + if again { + refresh_saved(app, Some(ctx)); + } +} + +/// Changes whenever the menus' listing changes. +pub fn saved_revision() -> u64 { + saved().revision +} + +/// View › Proof Setup's saved setups, each by its file's name, loading it with Proof Colors on. +pub fn saved_items() -> Vec { + saved().setups.iter().map(|&(name, ref path)| Item::Cmd(name, LOAD, json!({ "path": path }))).collect() +} + #[cfg(test)] mod tests { use super::*; @@ -283,6 +527,154 @@ mod tests { assert_eq!(proof::view(), Default::default()); } + /// Save… writes the dialog's settings to the picked file in the Proof Setups folder, which View › + /// Proof Setup then lists; Load… puts a file's settings back in the dialog, and the menu item + /// applies the setup with Proof Colors on. + #[test] + fn save_and_load_keep_a_custom_proof_setup() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + refresh_saved(&app, None); + wait(); + assert!(saved_items().is_empty()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + let d = app.ui.dialog.as_mut().unwrap(); + for (k, v) in [("device", json!(rgb)), ("intent", json!("saturation")), ("preserveNumbers", json!(true)), ("preview", json!(false))] { + d.fields.insert(k.into(), v); + } + let picked = std::rc::Rc::new(std::cell::RefCell::new(None::)); + let seen = picked.clone(); + let path = folder.join("Screen").to_string_lossy().to_string(); + let answer = path.clone(); + app.services.pick_save = Some(Box::new(move |p: &FilePick| { + *seen.borrow_mut() = Some(p.clone()); + Some(answer.clone()) + })); + let mut d = app.ui.dialog.take().unwrap(); + save(&mut app, &mut d).unwrap(); + let pick = picked.borrow().clone().unwrap(); + assert_eq!(pick.folder.as_deref(), Some(folder.to_string_lossy().as_ref()), "the picker starts in the Proof Setups folder"); + let file = format!("{path}.{EXT}"); + assert!(std::path::Path::new(&file).is_file(), "the extension is added"); + assert_eq!(proof::view(), Default::default(), "saving leaves the proof view alone"); + wait(); + let items = crate::menus::menu_entries(&app).into_iter().filter(|e| e.path == ["View", "Proof Setup"] && e.command.as_deref() == Some(LOAD)); + let items: Vec<_> = items.map(|e| (e.label.to_string(), e.params.clone())).collect(); + assert_eq!(items, [("Screen".to_string(), json!({ "path": file }))]); + // A control client that may not read the folder is not shown the saved setup. + std::fs::create_dir_all(dir.join("out")).unwrap(); + let write_only = vectorcraft_engine::file_access::AutomationRoots::new(&[], &[&dir.join("out")]).unwrap(); + let listed = vectorcraft_engine::file_access::confine(write_only.as_ref(), || crate::menus::menu_entries(&app)); + assert!(!listed.iter().any(|e| e.command.as_deref() == Some(LOAD)), "a setup outside the read roots is left out"); + // A setup the command saves, outside the dialog, is listed at the next iteration. + poll(&mut app, &ctx); + wait(); + app.run("view.proofSetup.save", json!({ "name": "Direct" })).unwrap(); + poll(&mut app, &ctx); + wait(); + assert_eq!(saved_items().len(), 2, "the menu lists the new setup"); + std::fs::remove_file(folder.join(format!("Direct.{EXT}"))).unwrap(); + refresh_saved(&app, None); + wait(); + // Load… puts the file's settings back in the dialog. + for (k, v) in [("device", json!(WORKING)), ("intent", json!("perceptual")), ("preserveNumbers", json!(false))] { + d.fields.insert(k.into(), v); + } + let answer = file.clone(); + app.services.pick_open = Some(Box::new(move |_: &FilePick| Some(answer.clone()))); + load(&mut app, &mut d).unwrap(); + assert_eq!((d.str("device"), d.str("intent"), d.bool("preserveNumbers")), (rgb.clone(), "saturation".to_string(), true)); + assert_eq!(proof::view(), Default::default(), "loading into the dialog leaves the proof view alone"); + app.ui.dialog = Some(d); + frame(&mut app, &ctx); + super::super::cancel(&mut app); + // The menu item applies the saved setup and turns Proof Colors on. + app.run(LOAD, json!({ "path": file })).unwrap(); + let v = proof::view(); + assert!(v.proof_colors && v.setup.preserve_numbers); + assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); + } + + /// Save… whose picker is canceled saves nothing and leaves no Proof Setups folder behind. + #[test] + fn a_canceled_save_leaves_no_folder() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-cancel"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let opened = std::rc::Rc::new(std::cell::Cell::new(false)); + let seen = opened.clone(); + let f = folder.clone(); + app.services.pick_save = Some(Box::new(move |_: &FilePick| { + seen.set(f.is_dir()); + None + })); + save(&mut app, &mut d).unwrap(); + assert!(opened.get(), "the picker opens in the folder"); + assert!(!folder.exists(), "the canceled save removes the folder it made"); + // A picker shown off the UI thread is still open when Save… returns: its folder stays. + let (shown, _) = crate::tests::picks::off_the_ui_thread(&mut app.services); + app.ui.dialog = Some(d.clone()); + crate::picks::in_app_dialog(&mut app, &mut d, save).unwrap(); + assert_eq!(shown.requests().len(), 1, "the picker is shown off the UI thread"); + poll(&mut app, &ctx); + assert!(folder.is_dir(), "the open picker's folder stays"); + // Canceled, the picker leaves no folder once the next iteration runs. + shown.answer(&[]); + crate::picks::poll(&mut app, &ctx); + poll(&mut app, &ctx); + assert!(!folder.exists(), "the canceled picker's folder is removed"); + // A picker that answers a file there saves it, and the folder stays. + crate::picks::in_app_dialog(&mut app, &mut d, save).unwrap(); + let file = folder.join(format!("Kept.{EXT}")); + shown.answer(&[&file.to_string_lossy()]); + crate::picks::poll(&mut app, &ctx); + poll(&mut app, &ctx); + assert!(file.is_file(), "the picked file is saved"); + } + + /// A saved setup whose name ends in an ellipsis still loads when its menu item is chosen. + #[test] + fn a_saved_setup_named_with_an_ellipsis_loads() { + let p = json!({ "path": "Press….vcproof" }); + assert_eq!(crate::menus::click_target("Press…", LOAD, &p), (LOAD.to_string(), p.clone())); + } + + /// A saved setup keeps its file's name in every UI language, also a name the catalogs translate. + #[test] + fn a_saved_setup_keeps_its_name_in_other_languages() { + let (app, _) = app(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let shown = crate::menus::display_label(&app, LOAD, "Save…"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(shown, "Save…"); + } + + /// Load… of a file whose device is not loaded leaves the dialog's settings as they were. + #[test] + fn load_of_an_unusable_file_keeps_the_dialog() { + let _v = DefaultView::new(); + let (mut app, _) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-bad"); + let file = dir.join("gone.vcproof").to_string_lossy().to_string(); + let text = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "cmyk:Not Loaded", "intent": "relative"}"#; + std::fs::write(&file, text).unwrap(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let before = d.fields.clone(); + app.services.pick_open = Some(Box::new(move |_: &FilePick| Some(file.clone()))); + let e = load(&mut app, &mut d).unwrap_err(); + assert!(e.contains("`Not Loaded`, which is not loaded"), "{e}"); + assert_eq!(d.fields, before); + } + /// The device list holds the working CMYK space and every CMYK and RGB profile, each a target /// `view.proofSetup` accepts. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5e50088157..25f2881d5b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2536,6 +2536,7 @@ font-technology Variable Променливи Device to Simulate: Устройство за симулиране: Simulate Paper Color Симулиране на цвета на хартията Simulate Black Ink Симулиране на черното мастило + Load… Зареди… Preserve Editing Capabilities Запазване на възможностите за редактиране Preserve editing capabilities Запазване на възможностите за редактиране Preserve Lightness Запазване на светлината diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6250cb8317..a77c86d99e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2823,6 +2823,7 @@ digits Malayalam Malajalam Device to Simulate: Uređaj za simulaciju: Simulate Paper Color Simuliraj boju papira Simulate Black Ink Simuliraj crnu tintu + Load… Učitaj… Previous page Prethodna stranica Print Layers: Štampaj slojeve: Print Preset: Predložak štampanja: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index eb007f8561..f84843acc7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3293,6 +3293,7 @@ digits Malayalam Malaiàlam Device to Simulate: Dispositiu que se simula: Simulate Paper Color Simula el color del paper Simulate Black Ink Simula la tinta negra + Load… Carrega… Preserve Editing Capabilities Conserva les capacitats d’edició Preserve editing capabilities Conserva les capacitats d’edició Preserve Lightness Conserva la lluminositat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f04fb06bf9..ed3e75809a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2858,6 +2858,7 @@ digits Malayalam Malajálamské Device to Simulate: Simulované zařízení: Simulate Paper Color Simulovat barvu papíru Simulate Black Ink Simulovat černou barvu + Load… Načíst… Previous page Předchozí stránka Print Layers: Tisknout vrstvy: Print Preset: Přednastavení tisku: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 61c79e04fe..de41046275 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3249,6 +3249,7 @@ digits Malayalam Malayalam Device to Simulate: Enhed, der simuleres: Simulate Paper Color Simulér papirfarve Simulate Black Ink Simulér sort blæk + Load… Indlæs… Previous page Forrige side Print Layers: Udskriv lag: Print Preset: Udskriftsforudindstilling: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2c8ffd5ca8..d371f15b79 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2578,6 +2578,7 @@ diagnostics ui Oberfläche Device to Simulate: Zu simulierendes Gerät: Simulate Paper Color Papierfarbe simulieren Simulate Black Ink Schwarze Druckfarbe simulieren + Load… Laden… Preserve Editing Capabilities Bearbeitungsfunktionen beibehalten Preserve editing capabilities Bearbeitungsfunktionen beibehalten Preserve Lightness Helligkeit beibehalten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c656395311..2c3cf7a602 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3396,6 +3396,7 @@ theme Appearance Εμφάνιση Device to Simulate: Συσκευή προς προσομοίωση: Simulate Paper Color Προσομοίωση χρώματος χαρτιού Simulate Black Ink Προσομοίωση μαύρης μελάνης + Load… Φόρτωση… Preserve Editing Capabilities Διατήρηση δυνατοτήτων επεξεργασίας Preserve editing capabilities Διατήρηση δυνατοτήτων επεξεργασίας Preserve Lightness Διατήρηση φωτεινότητας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 0b64216297..cd7a0eed2d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2614,6 +2614,7 @@ font-technology Variable Variables Device to Simulate: Dispositivo que simular: Simulate Paper Color Simular color del papel Simulate Black Ink Simular tinta negra + Load… Cargar… Preserve Editing Capabilities Conservar capacidades de edición Preserve editing capabilities Conservar capacidades de edición Preserve Lightness Conservar luminosidad diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b333b52aff..acb6f6d95c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2802,6 +2802,7 @@ digits Malayalam Malajalam Device to Simulate: Simuloitava laite: Simulate Paper Color Simuloi paperin väriä Simulate Black Ink Simuloi mustaa mustetta + Load… Lataa… Previous page Edellinen sivu Print Layers: Tulosta tasot: Print Preset: Tulostuksen esiasetus: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 582e497cea..dedd058f3e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2606,6 +2606,7 @@ font-technology Variable Variables Device to Simulate: Périphérique à simuler : Simulate Paper Color Simuler la couleur du papier Simulate Black Ink Simuler l’encre noire + Load… Charger… Preserve Editing Capabilities Conserver les fonctions d’édition Preserve editing capabilities Conserver les fonctions d’édition Preserve Lightness Conserver la luminosité diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index a3d13450df..3605866d93 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2686,6 +2686,7 @@ Device to Simulate: અનુકરણ કરવાનું ઉપકરણ: Simulate Paper Color કાગળના રંગનું અનુકરણ કરો Simulate Black Ink કાળી શાહીનું અનુકરણ કરો + Load… લોડ કરો… Preserve Editing Capabilities સંપાદન ક્ષમતાઓ જાળવો Preserve Lightness તેજ જાળવો Preserve Overprints and Spot Colors ઓવરપ્રિન્ટ અને સ્પોટ રંગ જાળવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b3e2b58449..ea41797443 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3636,6 +3636,7 @@ antiAlias Sharp शार्प Device to Simulate: सिम्युलेट करने के लिए डिवाइस: Simulate Paper Color पेपर का रंग सिम्युलेट करें Simulate Black Ink काली स्याही सिम्युलेट करें + Load… लोड करें… Preserve editing capabilities संपादन क्षमताओं को संरक्षित करना Preserve Editing Capabilities संपादन क्षमताओं को संरक्षित करना Preserve Lightness प्रकाश संरक्षण diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 96c94f5d1a..bc9e3a23d5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3163,6 +3163,7 @@ diagnostics ui felület Device to Simulate: Szimulálandó eszköz: Simulate Paper Color Papírszín szimulálása Simulate Black Ink Fekete festék szimulálása + Load… Betöltés… Preserve editing capabilities Szerkeszthetőség megtartása Preserve Editing Capabilities Szerkeszthetőség megtartása Preserve Lightness Világosság megtartása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f949134efb..b9999e2b7c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2640,6 +2640,7 @@ digits Malayalam Malayalam Device to Simulate: Perangkat yang disimulasikan: Simulate Paper Color Simulasikan warna kertas Simulate Black Ink Simulasikan tinta hitam + Load… Muat… Previous page Halaman sebelumnya Print Layers: Lapisan cetak: Print Preset: Preset cetak: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 4cfcadc283..5fc7487209 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2654,6 +2654,7 @@ diagnostics ui interfaccia Device to Simulate: Dispositivo da simulare: Simulate Paper Color Simula colore carta Simulate Black Ink Simula inchiostro nero + Load… Carica… Preserve Editing Capabilities Mantieni possibilità di modifica Preserve editing capabilities Mantieni possibilità di modifica Preserve Lightness Mantieni luminosità diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8cc0af36c2..d821a1aacf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2763,6 +2763,7 @@ diagnostics ui UI Device to Simulate: シミュレートするデバイス: Simulate Paper Color 用紙の色をシミュレート Simulate Black Ink インキの黒をシミュレート + Load… 読み込み… Preserve Editing Capabilities 編集機能を保持 Preserve Lightness 明度を保持 Preserve Overprints and Spot Colors オーバープリントと特色を保持 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8d8aecc8c1..5ca174df46 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2562,6 +2562,7 @@ digits Malayalam მალაიალამური Device to Simulate: სიმულირებადი მოწყობილობა: Simulate Paper Color ქაღალდის ფერის იმიტაცია Simulate Black Ink შავი მელნის იმიტაცია + Load… ჩატვირთვა… Previous page წინა გვერდი Print Layers: შრეების ბეჭდვა: Print Preset: ბეჭდვის პრესეტი: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 104fe2c161..7648417c9c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2753,6 +2753,7 @@ diagnostics ui UI Device to Simulate: 시뮬레이션할 장치: Simulate Paper Color 용지 색상 시뮬레이션 Simulate Black Ink 검정 잉크 시뮬레이션 + Load… 불러오기… Preserve Editing Capabilities 편집 기능 보존 Preserve Lightness 명도 보존 Preserve Overprints and Spot Colors 오버프린트 및 별색 보존 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 8f408a72e5..d8a4f48663 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3158,6 +3158,7 @@ digits Malayalam Malayalam Device to Simulate: Te simuleren apparaat: Simulate Paper Color Papierkleur simuleren Simulate Black Ink Zwarte inkt simuleren + Load… Laden… Previous page Vorige pagina Print Layers: Lagen afdrukken: Print Preset: Afdrukvoorinstelling: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index bb9d20ac5b..d928566a03 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2771,6 +2771,7 @@ digits Malayalam Malajalam Device to Simulate: Symulowane urządzenie: Simulate Paper Color Symuluj kolor papieru Simulate Black Ink Symuluj czarną farbę + Load… Wczytaj… Previous page Poprzednia strona Print Layers: Drukuj warstwy: Print Preset: Ustawienie drukowania: diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 1d2e8acfa4..a6a4319f52 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2183,6 +2183,7 @@ antiAlias Sharp Nítido Device to Simulate: Dispositivo a Simular: Simulate Paper Color Simular Cor do Papel Simulate Black Ink Simular Tinta Preta + Load… Carregar… Preserve Editing Capabilities Preservar Capacidades de Edição Preserve Lightness Preservar Luminosidade Preserve Overprints and Spot Colors Preservar Sobreimpressões e Cores Spot diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a7b502bc82..f34b93877e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2641,6 +2641,7 @@ diagnostics ui интерфейс Device to Simulate: Имитируемое устройство: Simulate Paper Color Имитировать цвет бумаги Simulate Black Ink Имитировать чёрную краску + Load… Загрузить… Preserve Editing Capabilities Сохранять возможности редактирования Preserve editing capabilities Сохранять возможности редактирования Preserve Lightness Сохранять светлоту diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index eea00904bf..6252530fc2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2551,6 +2551,7 @@ font-technology Variable Variabla Device to Simulate: Enhet att simulera: Simulate Paper Color Simulera pappersfärg Simulate Black Ink Simulera svart bläck + Load… Läs in… Preserve Editing Capabilities Bevara redigeringsmöjligheter Preserve editing capabilities Bevara redigeringsmöjligheter Preserve Lightness Bevara ljushet diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7042a5044c..03393bf3a5 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -421,6 +421,8 @@ fn proof_setup_dialog_labels_are_in_complete_catalogs() { "Rendering intent:", "Simulate Paper Color", "Simulate Black Ink", + "Save…", + "Load…", ]; for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { for label in labels { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6dd5c08a70..21abc40cf1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2398,6 +2398,7 @@ shape Open Açık Device to Simulate: Simüle Edilecek Aygıt: Simulate Paper Color Kağıt Rengini Simüle Et Simulate Black Ink Siyah Mürekkebi Simüle Et + Load… Yükle… Preserve Editing Capabilities Düzenleme Yeteneklerini Koruyun Preserve editing capabilities Düzenleme yeteneklerini koruyun Preserve Lightness Hafifliği Koruyun diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1ae336fd89..f08cbcf27b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2646,6 +2646,7 @@ diagnostics ui інтерфейс Device to Simulate: Імітований пристрій: Simulate Paper Color Імітувати колір паперу Simulate Black Ink Імітувати чорну фарбу + Load… Завантажити… Preserve Editing Capabilities Зберігати можливості редагування Preserve editing capabilities Зберігати можливості редагування Preserve Lightness Зберігати світлоту diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e6f33ee246..417672435a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2955,6 +2955,7 @@ diagnostics ui giao diện Device to Simulate: Thiết bị cần giả lập: Simulate Paper Color Giả lập màu giấy Simulate Black Ink Giả lập mực đen + Load… Tải… Preserve Editing Capabilities Bảo lưu khả năng chỉnh sửa Preserve editing capabilities Bảo lưu khả năng chỉnh sửa Preserve Lightness Bảo lưu độ sáng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0783f58758..99e8cbd167 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2507,6 +2507,7 @@ diagnostics ui 界面 Device to Simulate: 要模拟的设备: Simulate Paper Color 模拟纸张颜色 Simulate Black Ink 模拟黑色油墨 + Load… 载入… Preserve Editing Capabilities 保留编辑功能 Preserve editing capabilities 保留编辑能力 Preserve Lightness 保留亮度 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7f90c08327..13fc721c05 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3728,6 +3728,7 @@ diagnostics ui 介面 Device to Simulate: 要模擬的裝置: Simulate Paper Color 模擬紙張顏色 Simulate Black Ink 模擬黑色油墨 + Load… 載入… Preserve Editing Capabilities 保留編輯功能 Preserve editing capabilities 保留編輯功能 Preserve Lightness 保留亮度 diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 953b5b58f4..65945b2f2f 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -249,7 +249,8 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve for it in items { match it { Item::Cmd(l, id, p) => { - if *id == crate::scripts_menu::COMMAND && !crate::scripts_menu::readable(p) { + // A listed script or saved proof setup outside an automation read root is left out. + if matches!(*id, crate::scripts_menu::COMMAND | crate::dialogs::proof_setup::LOAD) && !crate::scripts_menu::readable(p) { continue; } // The other rows keep their ids: `file.openRecent3` still opens the third file. diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 752d42b9ae..4ec0172ade 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -3,11 +3,21 @@ use super::{Value, VectorcraftApp, json}; /// What a menu click runs: items whose label ends with "…" and that carry default params open a /// generic parameter dialog (fields = the defaults) instead of running immediately. A script of the -/// Scripts folder runs, whatever its name ends with. +/// Scripts folder runs, whatever its name ends with, and so does a proof setup saved in the Proof +/// Setups folder. pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { let dialog = label.ends_with('…') && p.as_object().is_some_and(|o| !o.is_empty()) - && !matches!(id, "effect.dialog" | "window.panel" | "window.brightness" | "view.screenMode" | "plugin.dialog" | crate::scripts_menu::COMMAND); + && !matches!( + id, + "effect.dialog" + | "window.panel" + | "window.brightness" + | "view.screenMode" + | "plugin.dialog" + | crate::scripts_menu::COMMAND + | crate::dialogs::proof_setup::LOAD + ); if dialog { return ("ui.paramDialog".into(), json!({"command": id, "label": label.trim_end_matches('…'), "params": p})); } diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index b8829ac0a2..2fc684f630 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -140,7 +140,13 @@ pub(crate) fn shows_a_name(id: &str, label: &str) -> bool { || saved_selection_slot(id).is_some() || matches!( id, - "text.setStyle" | "plugin.dialog" | "file.openWith" | "window.toolbar.custom" | "svgFilter.apply" | crate::scripts_menu::COMMAND + "text.setStyle" + | "plugin.dialog" + | "file.openWith" + | "window.toolbar.custom" + | "svgFilter.apply" + | crate::scripts_menu::COMMAND + | crate::dialogs::proof_setup::LOAD ) || vectorcraft_engine::cmd::plugin::is_command_id(id) || (id == "window.workspace" && !crate::workspaces::is_builtin(label)) @@ -332,11 +338,14 @@ pub(crate) fn holds_plugin_commands(children: &[Item]) -> bool { /// Every English string the menus, the command palette, the panel registry, the toolbar and the /// Preferences dialog can show: what a complete language catalog has to cover. Names that are user /// data (fonts, recent files, saved views, libraries, installed plug-ins, the scripts and subfolders -/// of the Scripts folder), the point sizes and the view angles are left out. +/// of the Scripts folder, saved proof setups), the point sizes and the view angles are left out. pub fn menu_strings() -> std::collections::BTreeSet { use std::collections::BTreeSet; fn user_data(id: &str, params: &Value) -> bool { - hidden_when_disabled(id) || id.starts_with("type.recentFont") || lists_plugin(id, params) || id == crate::scripts_menu::COMMAND + hidden_when_disabled(id) + || id.starts_with("type.recentFont") + || lists_plugin(id, params) + || matches!(id, crate::scripts_menu::COMMAND | crate::dialogs::proof_setup::LOAD) } fn walk(items: &[Item], under: &str, out: &mut BTreeSet) { for it in items { diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index dcc44c5130..237f7db7cb 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -557,9 +557,8 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ], ), Sep, - sub( - "Proof Setup", - vec![ + sub("Proof Setup", { + let mut v = vec![ cp("Working CMYK", "view.proofSetup", json!({"target": "workingCmyk", "proof": true})), cp("Legacy Macintosh RGB (Gamma 1.8)", "view.proofSetup", json!({"target": "legacyMacRgb", "proof": true})), cp("Internet Standard RGB (sRGB)", "view.proofSetup", json!({"target": "srgb", "proof": true})), @@ -568,8 +567,15 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { cp("Color blindness – Deuteranopia-type", "view.proofSetup", json!({"target": "deuteranopia", "proof": true})), cp("Color blindness – Tritanopia-type", "view.proofSetup", json!({"target": "tritanopia", "proof": true})), c("Customize…", "ui.proofSetupDialog"), - ], - ), + ]; + // The setups saved in the Proof Setups folder. + let saved = crate::dialogs::proof_setup::saved_items(); + if !saved.is_empty() { + v.push(Sep); + v.extend(saved); + } + v + }), c("Proof Colors", "view.proofColors"), Sep, c("Zoom In", "view.zoomIn"), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 2faded66f6..fa6c040e71 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -980,7 +980,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.proofSetupDialog", "Customize…", "", - "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back)", + "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder, whose setups View › Proof Setup lists below Customize…)", ), ( "ui.indexedColorDialog", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 510131be0e..d406f6c55a 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -622,7 +622,8 @@ fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { } (app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h); app.file_dialog_open().hash(&mut h); - (crate::i18n::current().code(), menus::plugin_revision(), crate::scripts_menu::revision()).hash(&mut h); + (crate::i18n::current().code(), menus::plugin_revision(), crate::scripts_menu::revision(), crate::dialogs::proof_setup::saved_revision()) + .hash(&mut h); crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed).hash(&mut h); let fonts = vectorcraft_text::FontDb::global(); (fonts.generation(), fonts.installed_fonts_ready()).hash(&mut h); diff --git a/docs/mcp.md b/docs/mcp.md index 25bb561b5f..8e2fdc6e0b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1057,9 +1057,9 @@ Convert to Grayscale before the switch would give); other colors convert as usua colors that changed in the art, symbols, graph designs and pattern tiles; it does not count the colors of graphic styles and brushes. `edit.colorSettings`, `file.documentColorMode`, `color.convert`, `color.gamutCheck`, `color.loadProfile`, -`color.removeProfile`, `view.proofSetup`, `view.proofColors`, `view.overprintPreview`, `view.separationsPreview` and -`swatch.setSpot` reject a param of the wrong type, such as `"bpc": "no"`, `"on": 1`, `"to": 5` or `"colors": "#fff"`, -and change nothing. Omitting a param or giving null keeps its default. +`color.removeProfile`, `view.proofSetup`, `view.proofSetup.save`, `view.proofColors`, `view.overprintPreview`, +`view.separationsPreview` and `swatch.setSpot` reject a param of the wrong type, such as `"bpc": "no"`, `"on": 1`, +`"to": 5` or `"colors": "#fff"`, and change nothing. Omitting a param or giving null keeps its default. View › Proof Setup › Customize… (`ui.proofSetupDialog`, dialog `proofSetup`) sets the custom proof through `view.proofSetup`: `target` `"cmyk:"` or `"rgb:"` names any CMYK or RGB profile as the device to simulate (a profile that is not loaded is an error), `preserveNumbers` sends the colors' numbers in the document's @@ -1069,6 +1069,17 @@ the proofed colors on the device's paper), and `simulateBlack` shows the device's black as the dark gray it prints (`simulatePaper` does so too, on the paper's color; both act on CMYK devices only). The reply carries `preserveNumbers` and `simulateBlack` with the other proof settings. +The dialog's Save… and Load… buttons save and load a custom proof setup +([Save or load a custom proof setup](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=148)). +`view.proofSetup.save {path}` writes the current proof setup, or the settings it is given as `view.proofSetup` takes +them, to a proof setup file without changing the proof view; the device must be `workingCmyk`, `cmyk:` or +`rgb:`. `view.proofSetup.load {path}` reads one back, makes it the proof setup and turns Proof Colors on; +`view.proofSetup.read {path}` only returns the file's settings, which is how Load… fills the dialog. All three take +`name` in place of `path` for a setup in the Proof Setups folder next to the preferences, and `view.proofSetup.list` lists the setups +there, at most 100, which View › Proof Setup shows below Customize…. A name is at most 100 characters without path +characters. These are VectorCraft's own choices: the file is VectorCraft's own JSON format (extension `.vcproof`) of +at most 64 KiB, checked by size before it is read; a file whose device is a profile that is not loaded is refused +with an error naming the profile, and nothing changes. The Separations panel's Assign rows (where Edit › Assign Profile… goes) act on the profile of the document's color mode: Don't Color Manage This Document runs `edit.assignProfile` with null for that model (no profile, so the colors show through the working space), Working RGB or Working CMYK with the working space's name (that profile stays @@ -2333,7 +2344,8 @@ change anything outside the documents: `script.*` except `script.check`, `plugin `shortcutSet.*`, `help.*`, `print.*`, `library.*`, `importMatches.*`, `edit.undoGroup.*`, `file.recovery.*`, `stroke.widthProfile.*`, 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.proofColors`, `view.overprintPreview` and `view.separationsPreview`. It also cannot run +`view.proofSetup`, `view.proofSetup.save`, `view.proofSetup.load`, `view.proofColors`, `view.overprintPreview` and +`view.separationsPreview`. It also cannot run `edit.clearHistory`: a run keeps each document's undo steps from before it and adds one. Calling one of these throws an error. With Data Recovery off for complex documents, a run in the web build does not start while a complex document has unsaved changes. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c4092fccf3..708bebffdd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1588,6 +1588,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click right of an RGB field switches the Color panel's R, G and B between percent and 0 to 255 ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Color panel). In VectorCraft the color does not change, Web Safe RGB and the hex field stay in 0 to 255, and the panel keeps the choice between sessions (`ui.colorPanel {rgbPercent}`); the color mixer of the Fill and Stroke chips and the gradient stop dialog follow the same setting. Toggle RGB Percent (`ui.colorRgbPercent`) in the command palette and Keyboard Shortcuts switches the units from the keyboard. Tests: `rgb_percent_switches_the_rgb_fields_between_percent_and_0_to_255`, `rgb_percent_does_not_switch_while_the_rows_are_disabled`, `rgb_percent_comes_back_after_a_restart` and `toggle_rgb_percent_switches_the_units_from_the_keyboard` in `crates/ui-egui/src/panels/color/tests.rs`. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. View › Proof Setup › Customize… opens a Proof Setup dialog with Device to Simulate (the working CMYK space or any CMYK or RGB profile), Preserve CMYK Numbers or Preserve RGB Numbers, Rendering Intent (used while the numbers are not preserved), Simulate Paper Color and Simulate Black Ink, and Preview; OK sets the proof and turns Proof Colors on ([Soft-proof colors](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=146), "Custom soft-proof options"). In VectorCraft, Simulate Paper Color also shows the black ink, the two simulations act on CMYK devices only, and Cancel puts the earlier proof back (`ui.proofSetupDialog`, `view.proofSetup {preserveNumbers, simulateBlack}`). Tests: `simulate_black_ink_shows_the_press_black_as_gray`, `preserve_cmyk_numbers_sends_the_numbers_unchanged` and `rgb_device_proofs_show_the_device_numbers` in `crates/color/src/cms/tests.rs`, `proof_setup_takes_the_custom_proof_settings` in `crates/engine/src/tests/colormgmt.rs`, `customize_sets_the_proof_setup_and_turns_proof_colors_on` and `preview_shows_the_settings_and_cancel_puts_the_view_back` in `crates/ui-egui/src/dialogs/proof_setup.rs`. + The Proof Setup dialog's Save… and Load… buttons save the custom proof setup to a file and read one back, and View › Proof Setup lists the setups saved in the Proof Setups folder next to the preferences; choosing one applies it with Proof Colors on ([Save or load a custom proof setup](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=148)). The file format (`.vcproof`, JSON, at most 64 KiB), the folder and the error for a device profile that is not loaded are VectorCraft's own (`view.proofSetup.save`, `view.proofSetup.load`, `view.proofSetup.read`, `view.proofSetup.list`). Tests: `a_saved_proof_setup_loads_back`, `proof_setup_files_refuse_what_they_cannot_use`, `proof_setups_saved_by_name_are_listed` and `proof_setups_are_listed_among_many_other_files` in `crates/engine/src/tests/colormgmt.rs`, `save_and_load_keep_a_custom_proof_setup`, `a_canceled_save_leaves_no_folder`, `a_saved_setup_named_with_an_ellipsis_loads` and `load_of_an_unusable_file_keeps_the_dialog` in `crates/ui-egui/src/dialogs/proof_setup.rs`. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Segments dragged onto the grid (#3835):** with View › Snap to Grid (or Snap to Pixel) on, a straight segment dragged with Direct Selection or Group Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis as a moved object's does (Shift keeps the move on its line), instead of the point it was pressed at landing on an intersection and leaving both anchors off the grid; a dragged anchor still lands on an intersection itself, and drawn points and resize handles already snapped (`direct::tests::a_dragged_segment_lands_its_anchors_on_the_grid`). From ad60b1e8c52b428129dc4299b7115de74858da0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:25:31 -0800 Subject: [PATCH 2/4] Proof Setup: saved setups are listed by names that load them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - view.proofSetup.list lists only files named .vcproof whose name `name` takes unchanged, sorted by that name before the 100 limit. An entry that can't be read or whose file name is not valid Unicode sets `truncated`, and a folder that can't be read is an error instead of an empty listing. - ui.inspect leaves out the path of a saved setup picked in an open Insert Menu Item dialog when it is outside the read root. - The listing Save… starts asks for a frame when it ends, so an idle window shows the new setup. - Load…'s picker starts in its own default folder until a save has made the Proof Setups folder. - The command help, docs/mcp.md and the progress line say the buttons and the saved setups are desktop only. --- crates/engine/src/cmd/colormgmt/proof_file.rs | 52 ++++++++++---- crates/engine/src/tests/colormgmt.rs | 69 +++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/control.rs | 16 ++++- crates/ui-egui/src/dialogs/proof_setup.rs | 68 ++++++++++++++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/tests/automation.rs | 24 +++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 9 files changed, 218 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs index 16d0b29f5d..2113cddbc2 100644 --- a/crates/engine/src/cmd/colormgmt/proof_file.rs +++ b/crates/engine/src/cmd/colormgmt/proof_file.rs @@ -58,7 +58,9 @@ fn file_path(s: &Session, p: &Value, cmd: &str) -> Result<(String, bool)> { (None, Some(name)) => { let name = setup_name(name, cmd)?; let dir = s.proof_setup_dir().ok_or_else(|| bad(cmd, "saved proof setups need the preferences folder, which this run doesn't have"))?; - Ok((dir.join(format!("{name}.{EXT}")).to_string_lossy().into_owned(), true)) + let path = dir.join(format!("{name}.{EXT}")); + let path = path.to_str().ok_or_else(|| bad(cmd, format!("{}: the folder's path is not valid Unicode", dir.display())))?; + Ok((path.to_string(), true)) } (Some(_), Some(_)) => Err(bad(cmd, "give `path` or `name`, not both")), (None, None) => Err(bad(cmd, "missing `path` or `name`")), @@ -219,27 +221,54 @@ pub fn listed(_: &std::path::Path) -> Result> { /// request that may not read it. The app calls it on another thread, without a session. #[cfg(not(target_arch = "wasm32"))] pub fn listed(dir: &std::path::Path) -> Result> { + const C: &str = "view.proofSetup.list"; let folder = dir.to_string_lossy().into_owned(); // A request that may not read the folder learns nothing of it, nor where it is. if crate::file_access::check_read(&folder).is_err() { return Ok(None); } - // No folder yet: nothing has been saved. - let Ok(entries) = std::fs::read_dir(dir) else { return Ok(Some(json!({"folder": folder, "setups": [], "truncated": false}))) }; - // The setup files' names, the first MAX_LISTED by name; other entries are passed over before - // the limit applies. A link is not followed. + // The listed paths are text: a folder whose path is not valid Unicode can't be named in them. + if dir.to_str().is_none() { + return Err(bad(C, format!("{folder}: the folder's path is not valid Unicode"))); + } + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + // No folder yet: nothing has been saved. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Some(json!({"folder": folder, "setups": [], "truncated": false}))), + Err(e) => return Err(bad(C, format!("{folder}: {e}"))), + }; + // The setups' names, the first MAX_LISTED by name; other entries are passed over before the + // limit applies. A link is not followed. A file is listed only when it is named + // `.vcproof` and `name` takes that name unchanged, so each listed name loads its own + // file. An entry that can't be read, or whose file name is not valid Unicode, leaves the + // listing incomplete. let (mut names, mut truncated) = (Vec::::new(), false); - for (i, e) in entries.flatten().enumerate() { + for (i, e) in entries.enumerate() { if i == MAX_SCANNED { truncated = true; break; } - let name = e.file_name().to_string_lossy().into_owned(); - let setup = name.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(EXT) && !stem.trim().is_empty()); - if !setup || !e.file_type().is_ok_and(|t| t.is_file()) { + let Ok(e) = e else { + truncated = true; + continue; + }; + let Ok(file) = e.file_name().into_string() else { + truncated = true; + continue; + }; + let Some(name) = file.strip_suffix(EXT).and_then(|s| s.strip_suffix('.')) else { continue }; + if setup_name(name, C).ok() != Some(name) { continue; } - names.push(name); + match e.file_type() { + Ok(t) if t.is_file() => {} + Ok(_) => continue, + Err(_) => { + truncated = true; + continue; + } + } + names.push(name.to_string()); if names.len() > 2 * MAX_LISTED { names.sort(); names.truncate(MAX_LISTED); @@ -249,7 +278,6 @@ pub fn listed(dir: &std::path::Path) -> Result> { names.sort(); truncated |= names.len() > MAX_LISTED; names.truncate(MAX_LISTED); - let setups: Vec = - names.iter().filter_map(|name| Some(json!({"name": name.rsplit_once('.')?.0, "path": dir.join(name).to_string_lossy()}))).collect(); + let setups: Vec = names.iter().map(|name| json!({"name": name, "path": dir.join(format!("{name}.{EXT}")).to_string_lossy()})).collect(); Ok(Some(json!({"folder": folder, "setups": setups, "truncated": truncated}))) } diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 91ee618897..29704fdb27 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -872,6 +872,75 @@ fn proof_setups_are_listed_among_many_other_files() { assert_eq!(r["setups"][0]["name"], "Press"); } +/// The listing names only files that `name` loads (`.vcproof`, a name `save` can give), in +/// the order of those names, and the limit keeps the first by name; a folder that can't be read is +/// an error, not an empty listing. +#[test] +fn proof_setups_are_listed_by_names_that_load_them() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-names"); + let folder = dir.join("Proof Setups"); + std::fs::create_dir_all(&folder).unwrap(); + s.attach_proof_setups(folder.clone()); + let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#; + for file in ["Press.vcproof", "Press Matte.vcproof", "Loud.VCPROOF", " Lead.vcproof"] { + std::fs::write(folder.join(file), ok).unwrap(); + } + let names = |r: &Value| r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str().map(str::to_string)).collect::>(); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!((names(&r), r["truncated"].as_bool()), (vec!["Press".to_string(), "Press Matte".to_string()], Some(false))); + for name in names(&r) { + s.execute("view.proofSetup.read", &json!({ "name": name })).unwrap(); + } + // `Press` and `Press Matte` compete for the last place: the first by name keeps it. + for i in 0..99 { + std::fs::write(folder.join(format!("A{i:02}.vcproof")), "x").unwrap(); + } + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + let listed = names(&r); + assert_eq!((listed.len(), listed.last().map(String::as_str), r["truncated"].as_bool()), (100, Some("Press"), Some(true))); + // A folder that is not one can't be listed. + let file = dir.join("not a folder"); + std::fs::write(&file, "x").unwrap(); + s.attach_proof_setups(file); + refused(&mut s, "view.proofSetup.list", json!({}), "not a folder"); +} + +/// A file name that is not valid Unicode is left out of the listing, which then says it is +/// incomplete: a path made from a lossy copy of the name would name another file. +#[test] +fn proof_setup_names_that_are_not_unicode_are_left_out() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-bytes"); + let folder = dir.join("Proof Setups"); + std::fs::create_dir_all(&folder).unwrap(); + #[cfg(unix)] + let odd = { + use std::os::unix::ffi::OsStringExt; + std::ffi::OsString::from_vec(b"Odd\xff.vcproof".to_vec()) + }; + #[cfg(windows)] + let odd = { + use std::os::windows::ffi::OsStringExt; + std::ffi::OsString::from_wide(&"Odd?.vcproof".encode_utf16().map(|u| if u == u16::from(b'?') { 0xD800 } else { u }).collect::>()) + }; + // A file system that refuses such a name has nothing to leave out. + if std::fs::write(folder.join(odd), "x").is_err() { + return; + } + std::fs::write(folder.join("Press.vcproof"), "x").unwrap(); + s.attach_proof_setups(folder); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!( + (r["setups"].as_array().map(Vec::len), r["setups"][0]["name"].as_str(), r["truncated"].as_bool()), + (Some(1), Some("Press"), Some(true)) + ); +} + /// Whether the content has a DeviceCMYK fill/stroke operator (`c m y k k` / `K`). fn has_cmyk_op(pdf: &str) -> bool { let toks: Vec<&str> = pdf.split_ascii_whitespace().collect(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c235dfaafa..771f9fee3e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1102,7 +1102,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.proofSetupDialog", "Customize…", "", - "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder, whose setups View › Proof Setup lists below Customize…)", + "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; on the desktop only, Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder (Load… once a save has made it), whose setups View › Proof Setup lists below Customize…)", ), ( "ui.indexedColorDialog", diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b5b829ebbf..6d2417a0fd 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1146,9 +1146,9 @@ fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) { /// Takes out of `ui.inspect`'s copy of the UI state the paths the request may not read: recent files, /// a library panel's file, folder preferences (saved, and in an open Preferences dialog) and the paths -/// in recorded actions' steps outside the read root. The file selected in an open JavaScript Files -/// dialog is named as `svgInteractivity.info` names the active document's linked files. The UI state -/// itself is not changed. +/// in recorded actions' steps and in the item an open Insert Menu Item dialog picked, outside the +/// read root. The file selected in an open JavaScript Files dialog is named as `svgInteractivity.info` +/// names the active document's linked files. The UI state itself is not changed. fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map) { if let Some(Value::Array(files)) = ui.get_mut("recent_files") { files.retain(|f| f.as_str().is_some_and(readable)); @@ -1172,6 +1172,16 @@ fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map` or `rgb:`), `preserveNumbers`, //! `intent`, `simulatePaper`, `simulateBlack` and `preview`. @@ -311,14 +312,19 @@ fn save(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { o.insert("path".into(), json!(path)); } app.run("view.proofSetup.save", p)?; - refresh_saved(app, None); + // The read asks for a frame when it ends, so an idle window lists the setup. + refresh_saved(app, app.ui_ctx.as_ref()); app.status(format!("Saved {path}")); Ok(()) } /// Load…: the picked file's settings fill the dialog (Preview then shows them). fn load(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { - let pick = pick(app, String::new()); + let mut pick = pick(app, String::new()); + // Before a setup is saved there is no folder, and the picker starts in its own default folder. + if pick.folder.as_deref().is_some_and(|f| !std::path::Path::new(f).is_dir()) { + pick.folder = None; + } // A canceled picker leaves the dialog as it is. let Some(path) = crate::picks::open(app, &pick) else { return Ok(()) }; let r = app.run("view.proofSetup.read", json!({ "path": path }))?; @@ -911,6 +917,34 @@ mod tests { assert!(file.is_file(), "the picked file is saved"); } + /// The listing Save… starts asks for a frame when it ends, so an idle window takes it in. + #[test] + fn the_listing_after_a_save_asks_for_a_frame() { + let _v = DefaultView::new(); + let (mut app, _) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-frame"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + d.fields.insert("preview".into(), json!(false)); + let path = folder.join("Screen").to_string_lossy().to_string(); + app.services.pick_save = Some(Box::new(move |_: &FilePick| Some(path.clone()))); + let ctx = egui::Context::default(); + let (tx, frames) = std::sync::mpsc::channel(); + ctx.set_request_repaint_callback(move |_| { + let _ = tx.send(()); + }); + app.ui_ctx = Some(ctx); + save(&mut app, &mut d).unwrap(); + // With the app's copy of the context dropped, only the listing's thread can still ask for + // a frame; the channel closes without one when that thread ends without asking. + app.ui_ctx = None; + assert_eq!(frames.recv(), Ok(()), "the finished listing asks for a frame"); + wait(); + assert_eq!(saved_items().len(), 1); + } + /// A saved setup whose name ends in an ellipsis still loads when its menu item is chosen. #[test] fn a_saved_setup_named_with_an_ellipsis_loads() { @@ -928,6 +962,30 @@ mod tests { assert_eq!(shown, "Save…"); } + /// Load…'s picker starts in the Proof Setups folder once it exists, and in its own default + /// folder before; Load… does not make the folder. + #[test] + fn load_starts_in_the_folder_once_it_exists() { + let _v = DefaultView::new(); + let (mut app, _) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-load-folder"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let picked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = picked.clone(); + app.services.pick_open = Some(Box::new(move |p: &FilePick| { + seen.borrow_mut().push(p.folder.clone()); + None + })); + load(&mut app, &mut d).unwrap(); + assert!(!folder.exists(), "Load… does not make the folder"); + std::fs::create_dir_all(&folder).unwrap(); + load(&mut app, &mut d).unwrap(); + assert_eq!(*picked.borrow(), [None, Some(folder.to_string_lossy().into_owned())]); + } + /// Load… of a file whose device is not loaded leaves the dialog's settings as they were. #[test] fn load_of_an_unusable_file_keeps_the_dialog() { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 96085eaa42..66e4e27a08 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1103,7 +1103,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.proofSetupDialog", "Customize…", "", - "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder, whose setups View › Proof Setup lists below Customize…)", + "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; on the desktop only, Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder (Load… once a save has made it), whose setups View › Proof Setup lists below Customize…)", ), ( "ui.indexedColorDialog", diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 7a904e4646..eadda2b164 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -672,6 +672,30 @@ fn ui_inspect_leaves_out_paths_outside_the_read_root() { let _ = std::fs::remove_dir_all(base); } +/// `ui.inspect` leaves out the file of a saved proof setup that an open Insert Menu Item dialog +/// picked when it is outside the read root, and shows one inside it. +#[test] +fn ui_inspect_leaves_out_an_insert_menu_item_path_outside_the_read_root() { + let (mut app, tx, base) = confined("inspect-insert-menu-item"); + let load = crate::dialogs::proof_setup::LOAD; + let (inside, outside) = (s(base.join("in/Press.vcproof")), s(base.join("outside/Press.vcproof"))); + let dialog = |path: &str| { + let fields = json!({"find": "", "command": load, "params": {"path": path}, "note": ""}); + Some(crate::state::Dialog::new(crate::dialogs::action_insert_menu_item::KIND, fields)) + }; + app.ui.dialog = dialog(&outside); + let ctx = egui::Context::default(); + assert_eq!(crate::control::inspect(&app, &ctx)["ui"]["dialog"]["fields"]["params"]["path"], outside, "the person sees it"); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + let fields = &r["result"]["ui"]["dialog"]["fields"]; + assert_eq!((fields["command"].as_str(), fields["params"].get("path")), (Some(load), None), "{r}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["params"]["path"].clone()), Some(json!(outside)), "the UI state is not changed"); + app.ui.dialog = dialog(&inside); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + assert_eq!(r["result"]["ui"]["dialog"]["fields"]["params"]["path"], inside, "{r}"); + let _ = std::fs::remove_dir_all(base); +} + /// `ui.inspect` checks a folder preference as it is written: the read root's path with a space before /// it is a relative path, outside the root, and is left out. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 208f9c6695..78ebe22fa9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1236,13 +1236,17 @@ as the dark gray it prints (`simulatePaper` does so too, on the paper's color; b reply carries `preserveNumbers` and `simulateBlack` with the other proof settings. The dialog's Save… and Load… buttons save and load a custom proof setup ([Save or load a custom proof setup](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=148)). +The buttons and the saved setups in View › Proof Setup are desktop only; the web build has neither. Load…'s picker +starts in the Proof Setups folder once a save has made it. `view.proofSetup.save {path}` writes the current proof setup, or the settings it is given as `view.proofSetup` takes them, to a proof setup file without changing the proof view; the device must be `workingCmyk`, `cmyk:` or `rgb:`. `view.proofSetup.load {path}` reads one back, makes it the proof setup and turns Proof Colors on; `view.proofSetup.read {path}` only returns the file's settings, which is how Load… fills the dialog. All three take `name` in place of `path` for a setup in the Proof Setups folder next to the preferences, and `view.proofSetup.list` lists the setups -there, at most 100, which View › Proof Setup shows below Customize…. A name is at most 100 characters without path -characters. These are VectorCraft's own choices: the file is VectorCraft's own JSON format (extension `.vcproof`) of +there, at most 100, which View › Proof Setup shows below Customize…. The listing holds the files named +`.vcproof` whose name `name` accepts, the first 100 by name; `truncated` is true when more are there or an entry +could not be read or has a file name that is not valid Unicode, and a folder that cannot be read is an error. A name is +at most 100 characters without path characters. These are VectorCraft's own choices: the file is VectorCraft's own JSON format (extension `.vcproof`) of at most 64 KiB, checked by size before it is read; a file whose device is a profile that is not loaded is refused with an error naming the profile, and nothing changes. `view.separationsPreview {soloToggle: plate}` is the Separations panel's Alt-click on a plate's eye: it shows that diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c72a53704e..e2a18106c9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1894,7 +1894,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. In VectorCraft the Color Wheel panel menu's Show Color Vision Preview (`ui.colorWheel {vision: true}`) adds a row of four chips under the wheel or the box: the current color through the protanopia, deuteranopia and tritanopia simulations that View › Proof Setup uses, and an achromatopsia chip, which is VectorCraft's own gray with the color's CIE L*. Each chip takes the keyboard focus and gives its name and hex value in its tooltip and to screen readers, and a click on one does not apply it. The setting is kept with the preferences. Tests: `crates/ui-egui/src/panels/tests_color_wheel_vision.rs`. View › Proof Setup › Customize… opens a Proof Setup dialog with Device to Simulate (the working CMYK space or any CMYK or RGB profile), Preserve CMYK Numbers or Preserve RGB Numbers, Rendering Intent (used while the numbers are not preserved), Simulate Paper Color and Simulate Black Ink, and Preview; OK sets the proof and turns Proof Colors on ([Soft-proof colors](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=146), "Custom soft-proof options"). In VectorCraft, Simulate Paper Color also shows the black ink, the two simulations act on CMYK devices only, and Cancel puts the earlier proof back (`ui.proofSetupDialog`, `view.proofSetup {preserveNumbers, simulateBlack}`). Tests: `simulate_black_ink_shows_the_press_black_as_gray`, `preserve_cmyk_numbers_sends_the_numbers_unchanged` and `rgb_device_proofs_show_the_device_numbers` in `crates/color/src/cms/tests.rs`, `proof_setup_takes_the_custom_proof_settings` in `crates/engine/src/tests/colormgmt.rs`, `customize_sets_the_proof_setup_and_turns_proof_colors_on` and `preview_shows_the_settings_and_cancel_puts_the_view_back` in `crates/ui-egui/src/dialogs/proof_setup.rs`. - The Proof Setup dialog's Save… and Load… buttons save the custom proof setup to a file and read one back, and View › Proof Setup lists the setups saved in the Proof Setups folder next to the preferences; choosing one applies it with Proof Colors on ([Save or load a custom proof setup](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=148)). The file format (`.vcproof`, JSON, at most 64 KiB), the folder and the error for a device profile that is not loaded are VectorCraft's own (`view.proofSetup.save`, `view.proofSetup.load`, `view.proofSetup.read`, `view.proofSetup.list`). Tests: `a_saved_proof_setup_loads_back`, `proof_setup_files_refuse_what_they_cannot_use`, `proof_setups_saved_by_name_are_listed` and `proof_setups_are_listed_among_many_other_files` in `crates/engine/src/tests/colormgmt.rs`, `save_and_load_keep_a_custom_proof_setup`, `a_canceled_save_leaves_no_folder`, `a_saved_setup_named_with_an_ellipsis_loads` and `load_of_an_unusable_file_keeps_the_dialog` in `crates/ui-egui/src/dialogs/proof_setup.rs`. + The Proof Setup dialog's Save… and Load… buttons save the custom proof setup to a file and read one back, and View › Proof Setup lists the setups saved in the Proof Setups folder next to the preferences; choosing one applies it with Proof Colors on ([Save or load a custom proof setup](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=148)). The buttons and the saved setups are desktop only; the web build has neither. The file format (`.vcproof`, JSON, at most 64 KiB), the folder and the error for a device profile that is not loaded are VectorCraft's own (`view.proofSetup.save`, `view.proofSetup.load`, `view.proofSetup.read`, `view.proofSetup.list`). Tests: `a_saved_proof_setup_loads_back`, `proof_setup_files_refuse_what_they_cannot_use`, `proof_setups_saved_by_name_are_listed`, `proof_setups_are_listed_among_many_other_files`, `proof_setups_are_listed_by_names_that_load_them` and `proof_setup_names_that_are_not_unicode_are_left_out` in `crates/engine/src/tests/colormgmt.rs`, `save_and_load_keep_a_custom_proof_setup`, `a_canceled_save_leaves_no_folder`, `the_listing_after_a_save_asks_for_a_frame`, `load_starts_in_the_folder_once_it_exists`, `a_saved_setup_named_with_an_ellipsis_loads` and `load_of_an_unusable_file_keeps_the_dialog` in `crates/ui-egui/src/dialogs/proof_setup.rs`. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). The "?" on the Fill and Stroke proxies finds a few selected objects along their cached places in the document instead of walking every object; a large selection takes one walk, as before. The proxies show the same paints and question marks as before, also for an id that a damaged file repeats. On a document of 50,000 rectangles in 500 groups on 5 layers with one object selected, the check takes under 5 µs of CPU time instead of a median of 995 µs in a release build on Linux, so the gain shows on large documents (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. From d3acfff6619639f09727571838491f2c720b8050 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:57:04 -0800 Subject: [PATCH 3/4] i18n: French "Device to Simulate:" takes a no-break space before the colon The French row had an ordinary space before ":", which french_catalog_uses_nonbreaking_prose_punctuation rejects on main. --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 212cbee4c6..26d4f9a454 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2781,7 +2781,7 @@ font-technology Variable Variables Preserve Appearance and Overprints Conserver l’aspect et les surimpressions Preserve CMYK Numbers Conserver les valeurs CMJN Preserve RGB Numbers Conserver les valeurs RVB - Device to Simulate: Périphérique à simuler : + Device to Simulate: Périphérique à simuler : Simulate Paper Color Simuler la couleur du papier Simulate Black Ink Simuler l’encre noire Load… Charger… From efe4c7e30fa38a6ec0055ae7bcf54b6649e5bf9d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:39:51 -0800 Subject: [PATCH 4/4] Proof Setup: a setup that would be too large to load is not saved view.proofSetup.save refuses a setup whose file would be larger than the 64 KiB view.proofSetup.load reads (a device profile with a very long name), and writes nothing. --- crates/engine/src/cmd/colormgmt/proof_file.rs | 7 ++++++- crates/engine/src/tests/colormgmt.rs | 10 +++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs index 2113cddbc2..7f92bed6b4 100644 --- a/crates/engine/src/cmd/colormgmt/proof_file.rs +++ b/crates/engine/src/cmd/colormgmt/proof_file.rs @@ -159,6 +159,11 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { let mut setup = proof::view().setup; setup_params(p, &mut setup, C)?; check_device(&setup.target).map_err(|e| bad(C, e))?; + // A file `view.proofSetup.load` would refuse is not written (a device with a very long name). + let bytes = encode(&setup); + if bytes.len() > MAX_FILE { + return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes"))); + } if named && let Some(dir) = std::path::Path::new(&path).parent() && !dir.is_dir() @@ -166,7 +171,7 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { crate::file_access::check_write(&path).map_err(EngineError::Other)?; std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?; } - fileio::write_file(&path, &encode(&setup))?; + fileio::write_file(&path, &bytes)?; s.proof_setup_saves += 1; let mut r = setup_json(&setup); r.insert("path".into(), json!(path)); diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 29704fdb27..de28e1d01e 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -767,7 +767,8 @@ fn a_saved_proof_setup_loads_back() { assert_eq!(vectorcraft_render::proof::view().setup, ProofSetup { simulate_paper: true, ..want }); } -/// Saving refuses a target that is not a device, bad params and a bad name; loading refuses a file +/// Saving refuses a target that is not a device, bad params, a bad name and a file larger than +/// loading reads; loading refuses a file /// that is too large, not a proof setup, newer, or whose device is a profile that is not loaded, /// and the proof view stays as it was. #[test] @@ -791,6 +792,13 @@ fn proof_setup_files_refuse_what_they_cannot_use() { refused(&mut s, "view.proofSetup.save", json!({"name": bad_name}), "`name`"); } refused(&mut s, "view.proofSetup.save", json!({"name": "x".repeat(101)}), "longer than 100 characters"); + // A device whose name makes the file larger than load reads is refused, and nothing is written. + let long = "Long Profile Name ".repeat(4000); + cms::register_icc(&cms::icc_bytes(cms::DISPLAY_P3).unwrap(), Some(long.clone())).unwrap(); + let refusal = s.execute("view.proofSetup.save", &json!({"path": path, "target": format!("rgb:{long}")})); + cms::unregister_icc(&long); + assert!(refusal.unwrap_err().to_string().contains("larger than 65536 bytes"), "a setup load can't read is refused"); + assert!(!std::path::Path::new(&path).exists(), "nothing is written"); let before = vectorcraft_render::proof::view(); let write = |n: &str, text: &str| { let p = file(n);