From f71437f2a18e07b00b20f94e30572414f2b96eed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:51:30 -0800 Subject: [PATCH 01/10] Color Settings: Ask When Opening and Ask When Pasting prompt about profile mismatches edit.colorSettings takes askMismatchOpen, askMismatchPaste and askMissingOpen (off by default), kept in Color Settings.json and shown in the Separations panel's Color Settings section. With a box on, File > Open asks before a document opens whose color mode's profile is not the working space (use the embedded profile, convert the colors, discard the profile) or that has none (leave it, assign the working space, assign a profile), and Paste asks whether colors copied from a document with another profile keep their numbers or convert. Each prompt starts on what the policy does; Cancel opens or pastes nothing. document.open takes the answer as profileChoice (with assignProfile) and never asks. The paste commands take profileMismatch, and without it follow the policy of each model, as a drag between documents does. clipboard.profileMismatch lists the models a paste would ask about. --- crates/color/src/cms.rs | 12 + crates/color/src/cms/tests.rs | 17 + crates/engine/src/cmd/clipboard.rs | 92 +++- crates/engine/src/cmd/colormgmt.rs | 441 ++++++++++++++++-- crates/engine/src/cmd/edit.rs | 33 +- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 151 ++++-- crates/engine/tests/color_settings.rs | 343 +++++++++++++- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/commands.rs | 4 + crates/ui-egui/src/dialogs.rs | 10 + crates/ui-egui/src/dialogs/import_pdf.rs | 6 +- .../ui-egui/src/dialogs/profile_mismatch.rs | 244 ++++++++++ .../src/dialogs/profile_mismatch/tests.rs | 134 ++++++ crates/ui-egui/src/dialogs/swatch_conflict.rs | 7 +- crates/ui-egui/src/i18n/bg.tsv | 18 + crates/ui-egui/src/i18n/bs.tsv | 18 + crates/ui-egui/src/i18n/ca.tsv | 18 + crates/ui-egui/src/i18n/cs.tsv | 18 + crates/ui-egui/src/i18n/da.tsv | 18 + crates/ui-egui/src/i18n/de.tsv | 18 + crates/ui-egui/src/i18n/el.tsv | 18 + crates/ui-egui/src/i18n/es.tsv | 18 + crates/ui-egui/src/i18n/fi.tsv | 18 + crates/ui-egui/src/i18n/fr.tsv | 18 + crates/ui-egui/src/i18n/gu.tsv | 18 + crates/ui-egui/src/i18n/hi.tsv | 18 + crates/ui-egui/src/i18n/hu.tsv | 18 + crates/ui-egui/src/i18n/id.tsv | 18 + crates/ui-egui/src/i18n/it.tsv | 18 + crates/ui-egui/src/i18n/ja.tsv | 18 + crates/ui-egui/src/i18n/ka.tsv | 18 + crates/ui-egui/src/i18n/ko.tsv | 18 + crates/ui-egui/src/i18n/nl.tsv | 18 + crates/ui-egui/src/i18n/pl.tsv | 18 + crates/ui-egui/src/i18n/pt-br.tsv | 18 + crates/ui-egui/src/i18n/ru.tsv | 18 + crates/ui-egui/src/i18n/sv.tsv | 18 + crates/ui-egui/src/i18n/tr.tsv | 18 + crates/ui-egui/src/i18n/uk.tsv | 18 + crates/ui-egui/src/i18n/vi.tsv | 18 + crates/ui-egui/src/i18n/zh-hans.tsv | 18 + crates/ui-egui/src/i18n/zh-hant.tsv | 18 + crates/ui-egui/src/io.rs | 1 + crates/ui-egui/src/io/open.rs | 26 +- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/opening.rs | 18 +- crates/ui-egui/src/panels/separations.rs | 20 +- crates/ui-egui/src/place.rs | 5 +- crates/ui-egui/src/placing.rs | 39 +- docs/mcp.md | 13 + docs/target-app-parity.md | 1 + 53 files changed, 2028 insertions(+), 101 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/profile_mismatch.rs create mode 100644 crates/ui-egui/src/dialogs/profile_mismatch/tests.rs diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index eb7ddf9b7c..069c27943b 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -185,6 +185,15 @@ pub struct ColorSettings { /// The color management policy for CMYK profiles. Settings saved without one take the default. #[serde(default)] pub cmyk_policy: Policy, + /// Profile Mismatches: Ask When Opening. Off by default, as in settings saved without it. + #[serde(default)] + pub ask_mismatch_open: bool, + /// Profile Mismatches: Ask When Pasting. + #[serde(default)] + pub ask_mismatch_paste: bool, + /// Missing Profiles: Ask When Opening. + #[serde(default)] + pub ask_missing_open: bool, } impl Default for ColorSettings { @@ -196,6 +205,9 @@ impl Default for ColorSettings { bpc: true, rgb_policy: Policy::default(), cmyk_policy: Policy::default(), + ask_mismatch_open: false, + ask_mismatch_paste: false, + ask_missing_open: false, } } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 95e465b623..5804bc6313 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -459,6 +459,23 @@ fn policies_parse_and_default_in_saved_settings() { assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers"))); } +/// The three Ask boxes are off by default and in settings saved before they existed, and save +/// under their own keys. +#[test] +fn ask_boxes_default_off_and_save() { + let old: ColorSettings = + serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap(); + assert!(!old.ask_mismatch_open && !old.ask_mismatch_paste && !old.ask_missing_open); + let st = ColorSettings::default(); + assert!(!st.ask_mismatch_open && !st.ask_mismatch_paste && !st.ask_missing_open); + let saved = serde_json::to_value(ColorSettings { ask_mismatch_paste: true, ..Default::default() }).unwrap(); + assert_eq!(saved["askMismatchOpen"], false); + assert_eq!(saved["askMismatchPaste"], true); + assert_eq!(saved["askMissingOpen"], false); + let back: ColorSettings = serde_json::from_value(saved).unwrap(); + assert!(back.ask_mismatch_paste); +} + /// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into /// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and /// Lab colors stay as they are. diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 446634d21c..df37df96da 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,10 +47,19 @@ pub fn specs() -> Vec { "Swatch Conflicts", [], None, - "{} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none", + "{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", has_doc, conflicts ), + cmd!( + query "clipboard.profileMismatch", + "Paste Profile Mismatch", + [], + None, + "{} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\"}]} the color models whose colors the copied objects use and whose profile in the document they were copied from (its assigned profile, else the working space then) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* {profileMismatch} says, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", + has_doc, + profile_mismatch + ), ]; v.extend(flavours::specs()); v @@ -100,6 +109,15 @@ pub struct Clipboard { /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. pub guides: Vec, + /// The RGB and CMYK profiles the objects' colors showed through in the document they were + /// copied from (its assigned profiles, else the working spaces then), by name; none for objects + /// from outside an open document. Paste compares them with the destination's + /// ([`super::colormgmt::paste_mismatches`]). + pub source_profiles: Option<[String; 2]>, + /// The colors were converted for this paste ([`super::colormgmt::paste_profiles`]): back in the + /// source document its resources of the same names are compared with them, as another + /// document's are, while its layers are still found by id. + pub colors_converted: bool, } /// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level @@ -264,6 +282,7 @@ impl Clipboard { pub fn from_node(st: &DocState, node: Node) -> Self { let mut clip = Self::gather(&st.doc, vec![node]); clip.source_doc = Some(st.uid); + clip.source_profiles = Some(super::colormgmt::effective_profiles(&st.doc)); clip } @@ -335,6 +354,7 @@ impl Clipboard { source_artboard: board.and_then(|i| d.artboards.get(i)).map(|a| a.rect), source_layers, source_doc: Some(st.uid), + source_profiles: Some(super::colormgmt::effective_profiles(d)), ..Self::gather(d, nodes) } } @@ -369,7 +389,7 @@ impl Clipboard { /// The swatch name conflicts pasting into `st` raises, as (pasted, document) swatches: none /// back in the document the objects came from. pub fn swatch_conflicts<'a>(&'a self, st: &'a DocState) -> Vec<(&'a Swatch, &'a Swatch)> { - if self.source_doc == Some(st.uid) { + if self.source_doc == Some(st.uid) && !self.colors_converted { return vec![]; } self.conflicts(&st.doc, &self.used()) @@ -419,6 +439,56 @@ impl Clipboard { d } + /// The clipboard with every color of its objects and of the resources it carries (swatches, + /// symbols, patterns, graphic styles, brushes, character and paragraph styles, the background + /// colors of copied artboards) mapped by `conv`, + /// as Document Color Mode maps a document's ([`super::colormgmt::convert_art_and_style_colors`]). + /// Images keep their pixels. + pub(crate) fn with_colors(&self, conv: &dyn Fn(&vectorcraft_color::Color) -> vectorcraft_color::Color) -> Self { + let mut d = self.to_document(); + // Only what the clipboard carries: not the swatches, graphic styles and brushes every new + // document starts with. + d.swatches = self.swatches.clone().into(); + d.swatch_groups = Default::default(); + d.graphic_styles = self.graphic_styles.clone().into(); + vectorcraft_brush::store(&mut d, &self.brushes); + // Not the stand-in document's own artboard and Document Setup colors: only what the + // clipboard carries is mapped. + super::colormgmt::convert_art_and_style_colors(&mut d, conv); + // `to_document` puts the objects in its one layer. + let nodes = d.layers.first().and_then(|l| l.children()).map(|ch| ch.iter().map(|n| (**n).clone()).collect()).unwrap_or_default(); + Self { + nodes, + symbols: d.symbols.clone(), + patterns: d.patterns.clone(), + swatches: d.swatches.to_vec(), + graphic_styles: d.graphic_styles.to_vec(), + char_styles: d.char_styles.to_vec(), + para_styles: d.para_styles.to_vec(), + brushes: vectorcraft_brush::library(&d), + images: self.images.clone(), + symbol_options: self.symbol_options.clone(), + source_artboard: self.source_artboard, + source_layers: self.source_layers.clone(), + source_doc: self.source_doc, + // The background colors of copied artboards map too. + artboards: self + .artboards + .iter() + .map(|a| { + let mut a = a.clone(); + if let Some(c) = a.color.as_mut() { + *c = conv(c); + } + a + }) + .collect(), + guides: self.guides.clone(), + source_profiles: self.source_profiles.clone(), + colors_converted: self.colors_converted, + } + } + /// The objects as standalone SVG (`None` when there are none). pub fn svg(&self) -> Option { if !self.has_art() { @@ -463,17 +533,27 @@ fn import_svg(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": s.load_clipboard(clip, p)? })) } -fn conflicts(s: &mut Session, _: &Value) -> Result { +fn conflicts(s: &mut Session, p: &Value) -> Result { let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex()); - let list: Vec = s - .clipboard - .swatch_conflicts(s.doc()?) + // The swatches as the paste brings them: converted from another profile when it converts. + let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; + let st = s.doc()?; + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile); + let list: Vec = converted + .as_ref() + .unwrap_or(&s.clipboard) + .swatch_conflicts(st) .into_iter() .map(|(c, t)| json!({"name": c.name, "document": hex(t), "clipboard": hex(c), "spot": c.spot})) .collect(); Ok(json!({ "swatches": list })) } +fn profile_mismatch(s: &mut Session, _: &Value) -> Result { + let list: Vec = super::colormgmt::paste_mismatches(&s.clipboard, &s.doc()?.doc).iter().map(|m| m.to_json()).collect(); + Ok(json!({ "mismatches": list })) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 38b5cffea0..107b2a5e16 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, File › Revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", + "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, File › Revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), @@ -183,6 +183,9 @@ fn settings_json(st: &ColorSettings) -> Value { "bpc": st.bpc, "rgbPolicy": st.rgb_policy.id(), "cmykPolicy": st.cmyk_policy.id(), + "askMismatchOpen": st.ask_mismatch_open, + "askMismatchPaste": st.ask_mismatch_paste, + "askMissingOpen": st.ask_missing_open, "profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::>(), }) } @@ -225,6 +228,9 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? { st.cmyk_policy = v; } + st.ask_mismatch_open = switch_or(p, "askMismatchOpen", st.ask_mismatch_open, C)?; + st.ask_mismatch_paste = switch_or(p, "askMismatchPaste", st.ask_mismatch_paste, C)?; + st.ask_missing_open = switch_or(p, "askMissingOpen", st.ask_missing_open, C)?; if st != before { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; // Saved for the next start when the app attached a settings file (#6335). @@ -659,39 +665,258 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co /// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert /// from. → a note for each profile, and whether `d` changed. pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec, bool) { + // Without a choice nothing can fail. + apply_open_policies_choosing(d, None).unwrap_or_default() +} + +/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening +/// boxes): the profile of its color mode differs from the working space, or it has none. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProfileIssue { + /// Profile Mismatches: tagged with a profile other than the working space. + Mismatch, + /// Missing Profiles: not tagged with a profile. + Missing, +} + +impl ProfileIssue { + pub fn id(self) -> &'static str { + match self { + ProfileIssue::Mismatch => "mismatch", + ProfileIssue::Missing => "missing", + } + } +} + +/// The answer to a [`ProfileQuestion`] (`document.open`'s `profileChoice`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProfileChoice { + /// Mismatch: keep the profile (as Preserve Embedded Profiles). + UseEmbedded, + /// Mismatch: convert the colors of that model into the working space and take the profile off + /// (as Convert to Working Space). + Convert, + /// Mismatch: take the profile off and keep the color numbers (as Off). + Discard, + /// Missing: leave the document untagged (it follows the working space). + Leave, + /// Missing: tag the document with the working space of its color mode. + AssignWorking, + /// Missing: tag the document with this profile. + Assign(String), +} + +impl ProfileChoice { + /// The ids `profileChoice` takes. + pub const IDS: [&'static str; 6] = ["useEmbedded", "convert", "discard", "leave", "assignWorking", "assign"]; + + pub fn id(&self) -> &'static str { + match self { + ProfileChoice::UseEmbedded => "useEmbedded", + ProfileChoice::Convert => "convert", + ProfileChoice::Discard => "discard", + ProfileChoice::Leave => "leave", + ProfileChoice::AssignWorking => "assignWorking", + ProfileChoice::Assign(_) => "assign", + } + } + + /// The question kind this choice answers. + pub fn issue(&self) -> ProfileIssue { + match self { + ProfileChoice::UseEmbedded | ProfileChoice::Convert | ProfileChoice::Discard => ProfileIssue::Mismatch, + _ => ProfileIssue::Missing, + } + } + + /// The choice `id` (`profile`, which only `assign` takes, for `assign`), or an error naming + /// `cmd`. + pub fn parse(id: &str, profile: Option<&str>, cmd: &str) -> Result { + let key = "profileChoice"; + let choice = match id { + "useEmbedded" => ProfileChoice::UseEmbedded, + "convert" => ProfileChoice::Convert, + "discard" => ProfileChoice::Discard, + "leave" => ProfileChoice::Leave, + "assignWorking" => ProfileChoice::AssignWorking, + "assign" => match profile.filter(|p| !p.is_empty()) { + Some(p) => ProfileChoice::Assign(cms::canonical_name(p).to_string()), + None => { + let path = "assignProfile"; + return Err(bad(cmd, format!("missing `{path}`"))); + } + }, + _ => return Err(bad(cmd, format!("`{key}` must be one of {}", Self::IDS.join(", ")))), + }; + // `assignProfile` goes with `assign` only. + if profile.is_some() && !matches!(choice, ProfileChoice::Assign(_)) { + return Err(bad(cmd, format!("`{key}` must be one of {}", "assign"))); + } + Ok(choice) + } + + /// `document.open`'s `profileChoice` and `assignProfile` in `p` (`None` when left out). + pub(crate) fn param(p: &Value, cmd: &str) -> Result> { + let profile = text_param(p, "assignProfile", cmd)?; + match text_param(p, "profileChoice", cmd)? { + Some(id) => Self::parse(id, profile, cmd).map(Some), + None if profile.is_some() => { + let path = "profileChoice"; + Err(bad(cmd, format!("missing `{path}`"))) + } + None => Ok(None), + } + } +} + +/// What opening document `d` could ask about the profile of its color mode, with the working +/// settings `st`: none when it is tagged with the working space. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProfileQuestion { + pub issue: ProfileIssue, + /// The model of the document's color mode. + pub model: ColorMode, + /// The profile the document is tagged with (none when it is missing). + pub profile: Option, + /// The working space of that model. + pub working: String, + /// What the policy of that model does, the choice the prompt starts on. + pub default: ProfileChoice, +} + +impl ProfileQuestion { + /// The question for document `d` under the working settings `st` (whether or not they ask it). + pub fn of(d: &vectorcraft_doc::Document, st: &ColorSettings) -> Option { + let (rgb, cmyk) = doc_profiles(d); + let (tag, working, policy) = match d.color_mode { + ColorMode::Rgb => (rgb, cms::canonical_name(&st.rgb).to_string(), st.rgb_policy), + ColorMode::Cmyk => (cmyk, cms::canonical_name(&st.cmyk).to_string(), st.cmyk_policy), + }; + let (issue, default) = match &tag { + Some(t) if *t == working => return None, + Some(_) => ( + ProfileIssue::Mismatch, + match policy { + Policy::PreserveEmbedded => ProfileChoice::UseEmbedded, + Policy::Convert => ProfileChoice::Convert, + Policy::Off | Policy::PreserveNumbers => ProfileChoice::Discard, + }, + ), + // VectorCraft's own rule: Convert to Working Space starts on assigning the working + // space, the other policies on leaving the document as it is. + None => (ProfileIssue::Missing, if policy == Policy::Convert { ProfileChoice::AssignWorking } else { ProfileChoice::Leave }), + }; + Some(Self { issue, model: d.color_mode, profile: tag, working, default }) + } + + /// Do the settings `st` ask it (the Ask When Opening box of its kind is on)? + pub fn asked(&self, st: &ColorSettings) -> bool { + match self.issue { + ProfileIssue::Mismatch => st.ask_mismatch_open, + ProfileIssue::Missing => st.ask_missing_open, + } + } + + /// The model's name as the UI shows it ("RGB", "CMYK"). + pub fn model_label(&self) -> &'static str { + match self.model { + ColorMode::Rgb => "RGB", + ColorMode::Cmyk => "CMYK", + } + } + + pub fn to_json(&self) -> Value { + json!({ + "issue": self.issue.id(), + "model": self.model_label().to_ascii_lowercase(), + "profile": self.profile, + "working": self.working, + "default": self.default.id(), + }) + } +} + +/// [`apply_open_policies`] with the answer `choice` to the document's [`ProfileQuestion`]: a +/// mismatch choice takes the place of the policy of the document's color mode, and a missing +/// choice tags the document after the policies ran. A choice for the other kind of question, or +/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile +/// to assign is not a profile of that model. +pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec, bool)> { let working = cms::working_settings(); + let question = ProfileQuestion::of(d, &working); + let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue())); + // A mismatch answer stands in for the policy of the document's color mode. + let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) { + match choice { + Some(c) if d.color_mode == model => match c { + ProfileChoice::UseEmbedded => (Policy::PreserveEmbedded, true), + ProfileChoice::Convert => (Policy::Convert, true), + ProfileChoice::Discard => (Policy::Off, true), + _ => (policy, false), + }, + _ => (policy, false), + } + }; + let (rgb_policy, rgb_chosen) = chosen(ColorMode::Rgb, working.rgb_policy); + let (cmyk_policy, cmyk_chosen) = chosen(ColorMode::Cmyk, working.cmyk_policy); + // The profile a missing answer assigns, checked before anything changes. + let assign = match (choice, &question) { + (Some(ProfileChoice::AssignWorking), Some(q)) => Some(q.working.clone()), + (Some(ProfileChoice::Assign(name)), Some(q)) => { + let kind = if q.model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + let (key, n) = (q.model_label().to_ascii_lowercase(), name); + let info = cms::profile(name).filter(|p| p.kind == kind).ok_or_else(|| bad("document.open", format!("unknown {key} profile `{n}`")))?; + Some(info.name) + } + _ => None, + }; let (rgb, cmyk) = doc_profiles(d); let mut notes = Vec::new(); // What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after - // converting the colors from the profile it holds. - let mut decide = |label: &str, tag: Option, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option> { - let tag = tag.filter(|t| t != working)?; - let available = cms::profile(&tag).is_some_and(|p| p.kind == kind); - match policy { - Policy::PreserveEmbedded => None, - Policy::Off | Policy::PreserveNumbers => { - notes.push(format!( - "the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}", - policy.label() - )); - Some(None) - } - Policy::Convert if available => { - notes.push(format!( - "the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”" - )); - Some(Some(tag)) - } - Policy::Convert => { - notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted")); - None + // converting the colors from the profile it holds. `by_choice`: the prompt's answer decided. + let mut decide = + |label: &str, tag: Option, working: &str, policy: Policy, by_choice: bool, kind: cms::ProfileKind| -> Option> { + let tag = tag.filter(|t| t != working)?; + let available = cms::profile(&tag).is_some_and(|p| p.kind == kind); + match policy { + Policy::PreserveEmbedded => None, + Policy::Off | Policy::PreserveNumbers if by_choice => { + notes.push(format!("the {label} profile “{tag}” the file is tagged with was discarded, as chosen when it was opened")); + Some(None) + } + Policy::Off | Policy::PreserveNumbers => { + notes.push(format!( + "the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}", + policy.label() + )); + Some(None) + } + Policy::Convert if available => { + notes.push(format!( + "the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”" + )); + Some(Some(tag)) + } + Policy::Convert => { + notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted")); + None + } } + }; + let rgb_do = decide("RGB", rgb, &working.rgb, rgb_policy, rgb_chosen, cms::ProfileKind::Rgb); + let cmyk_do = decide("CMYK", cmyk, &working.cmyk, cmyk_policy, cmyk_chosen, cms::ProfileKind::Cmyk); + let mut changed = false; + if let (Some(name), Some(q)) = (assign, &question) { + let label = q.model_label(); + notes.push(format!("the document was assigned the {label} profile “{name}”, as chosen when it was opened")); + match q.model { + ColorMode::Rgb => d.color_profiles.rgb = Some(name), + ColorMode::Cmyk => d.color_profiles.cmyk = Some(name), } - }; - let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb); - let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk); + changed = true; + } if rgb_do.is_none() && cmyk_do.is_none() { - return (notes, false); + return Ok((notes, changed)); } let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten()); if from_rgb.is_some() || from_cmyk.is_some() { @@ -713,7 +938,162 @@ pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec Color) { + convert_colors(d, conv); + convert_style_colors(d, conv); +} + +/// The RGB and CMYK profiles the colors of `d` show through, by name: those it is assigned, else +/// the working spaces. +pub(crate) fn effective_profiles(d: &vectorcraft_doc::Document) -> [String; 2] { + let working = cms::working_settings(); + let (rgb, cmyk) = doc_profiles(d); + [rgb.unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()), cmyk.unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string())] +} + +/// What Paste does with the colors of a model when the document they were copied from showed them +/// through another profile than the document they go into (`profileMismatch`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PasteProfile { + /// The colors keep their numbers. + PreserveNumbers, + /// The colors convert from the source profile into the destination's, which keeps their + /// appearance. + Convert, +} + +impl PasteProfile { + pub fn id(self) -> &'static str { + match self { + PasteProfile::PreserveNumbers => "preserveNumbers", + PasteProfile::Convert => "convert", + } + } + + /// What a model's policy does to pasted colors (VectorCraft's own mapping): Convert to Working + /// Space converts them, the other policies keep their numbers. + pub fn of(policy: Policy) -> Self { + if policy == Policy::Convert { PasteProfile::Convert } else { PasteProfile::PreserveNumbers } + } + + /// The `profileMismatch` param of paste command `cmd` (`None` when left out). + pub(crate) fn param(p: &Value, cmd: &str) -> Result> { + match text_param(p, "profileMismatch", cmd)? { + None => Ok(None), + Some("preserveNumbers") => Ok(Some(PasteProfile::PreserveNumbers)), + Some("convert") => Ok(Some(PasteProfile::Convert)), + Some(_) => { + let key = "profileMismatch"; + Err(bad(cmd, format!("`{key}` must be one of {}", "preserveNumbers, convert"))) + } + } + } +} + +/// A model whose colors a paste brings from another profile than the destination's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PasteMismatch { + pub model: ColorMode, + /// The profile the colors showed through where they were copied. + pub from: String, + /// The profile they show through in the document they go into. + pub to: String, + /// What the model's policy does with them. + pub default: PasteProfile, +} + +impl PasteMismatch { + pub fn to_json(&self) -> Value { + let model = if self.model == ColorMode::Rgb { "rgb" } else { "cmyk" }; + json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id() }) + } +} + +/// The models whose colors pasting `clip` into `d` brings from another profile: RGB, CMYK or both, +/// each only when the copied objects or the resources they carry hold a color of that model. +pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document) -> Vec { + let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return vec![] }; + let [to_rgb, to_cmyk] = effective_profiles(d); + let working = cms::working_settings(); + let mut out: Vec = + [(ColorMode::Rgb, from_rgb, to_rgb, working.rgb_policy), (ColorMode::Cmyk, from_cmyk, to_cmyk, working.cmyk_policy)] + .into_iter() + .filter(|(_, from, to, _)| cms::canonical_name(from) != cms::canonical_name(to)) + .map(|(model, from, to, policy)| PasteMismatch { model, from: from.clone(), to, default: PasteProfile::of(policy) }) + .collect(); + if out.is_empty() { + return out; + } + // Which models the pasted colors use. + let seen = std::cell::Cell::new((false, false)); + let _ = clip.with_colors(&|c: &Color| { + let (rgb, cmyk) = seen.get(); + seen.set((rgb || matches!(c, Color::Rgb { .. }), cmyk || matches!(c, Color::Cmyk { .. }))); + *c + }); + let (rgb, cmyk) = seen.get(); + out.retain(|m| if m.model == ColorMode::Rgb { rgb } else { cmyk }); + out +} + +/// The clipboard `clip` as pasting it into `d` brings it: for each mismatched model +/// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into +/// the destination's with the working intent, as `choice` says (default: each model's policy, +/// [`PasteProfile::of`]). A source or destination profile that is not available keeps the numbers. +/// → the +/// converted clipboard (`None` when nothing converts; its resources paste as another document's) +/// and a +/// line for each mismatched model +/// (`{model, clipboard, document, choice}`). +pub(crate) fn paste_profiles( + clip: &super::clipboard::Clipboard, + d: &vectorcraft_doc::Document, + choice: Option, +) -> (Option, Vec) { + let mismatches = paste_mismatches(clip, d); + let mut report = Vec::new(); + let (mut rgb_on, mut cmyk_on) = (false, false); + for m in &mismatches { + let kind = if m.model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + // Both profiles must be here to convert between them. + let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); + let available = here(&m.from) && here(&m.to); + let picked = if available { choice.unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; + if picked == PasteProfile::Convert { + match m.model { + ColorMode::Rgb => rgb_on = true, + ColorMode::Cmyk => cmyk_on = true, + } + } + let mut line = m.to_json(); + if let Some(o) = line.as_object_mut() { + o.remove("default"); + o.insert("choice".into(), json!(picked.id())); + } + report.push(line); + } + if !rgb_on && !cmyk_on { + return (None, report); + } + let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return (None, report) }; + let source = cms::for_document(Some(from_rgb), Some(from_cmyk)); + let dest = doc_cms(d); + let intent = cms::working_settings().intent; + let conv = |c: &Color| match c { + Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent), + Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent), + _ => *c, + }; + let mut converted = clip.with_colors(&conv); + // Converted colors are not the source document's own: its resources of the same names are + // compared with them, as another document's are. + converted.colors_converted = true; + (Some(converted), report) } /// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each @@ -726,6 +1106,11 @@ fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Colo for c in &mut d.setup.grid_colors { *c = conv(c); } + convert_style_colors(d, conv); +} + +/// The fill and stroke colors of `d`'s character and paragraph styles, converted with `conv`. +fn convert_style_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) { // A tint of a global swatch is the converted swatch's color at its tint, which // [`convert_colors`] already gave it. let bases = global_bases(d); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00b6a338f2..4bad97641b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -114,7 +114,7 @@ pub fn specs() -> Vec { "Drop Artwork", [], None, - "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step", + "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as edit.colorSettings' policy of their model says (as edit.paste without profileMismatch)", has_doc, drop_selection ), @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent (default: as the model's policy of edit.colorSettings says; every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -188,7 +188,7 @@ pub fn specs() -> Vec { "Paste in Front", ["Edit"], Some("Cmd+F"), - "{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch? (as edit.paste), artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Front) ), @@ -197,7 +197,7 @@ pub fn specs() -> Vec { "Paste in Back", ["Edit"], Some("Cmd+B"), - "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Back) ), @@ -206,7 +206,7 @@ pub fn specs() -> Vec { "Paste in Place", ["Edit"], Some("Cmd+Shift+V"), - "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::InPlace) ), @@ -215,7 +215,7 @@ pub fn specs() -> Vec { "Paste on All Artboards", ["Edit"], Some("Cmd+Alt+Shift+V"), - "{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch? (as edit.paste)} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::AllArtboards) ), @@ -1223,7 +1223,9 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { } // A drop preserves the source colours even when the flyer has same-named swatches. let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?; - paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, &clip, &choices) + // Colors from another profile keep their numbers or convert as the policies say. + let (converted, _) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, None); + paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices) } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1258,10 +1260,22 @@ fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result { if mode == PasteMode::Offset { check_numbers(p, &["dx", "dy"], "edit.paste")?; } + let profile = super::colormgmt::PasteProfile::param(p, mode.label())?; // Taken out of the session for the edit (and put back whatever happens). let clip = std::mem::take(&mut s.clipboard); - let r = paste_clip(s, p, mode, &clip, &choices); + // Colors copied from a document with other profiles keep their numbers or convert + // (Edit › Color Settings' policies, or `profileMismatch`). + let (converted, report) = match s.doc() { + Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile), + Err(_) => (None, vec![]), + }; + let mut r = paste_clip(s, p, mode, converted.as_ref().unwrap_or(&clip), &choices); s.clipboard = clip; + if let Ok(v) = &mut r + && !report.is_empty() + { + v["profileMismatch"] = json!(report); + } r } @@ -1438,7 +1452,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho vec![Affine::IDENTITY] }; let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { - let imported = clip.import_into(d, choices, same_doc)?; + // Converted colors are compared with the document's resources, as another document's are. + let imported = clip.import_into(d, choices, same_doc && !clip.colors_converted)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; let artboards: Vec = boards diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6995075d2f..c7dbc96685 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -82,7 +82,7 @@ pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ Loaded, RasterImage, ReadFile, detect, file_name, load, load_with, open_bytes, open_bytes_with, open_read, open_template, raster_image, - read_for_open, texture_image, + read_for_open, read_for_open_asking, texture_image, }; pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source}; pub use load::{losses_summary, overwrite_losses}; diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a46f46492a..638989a657 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds), in a row, and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds), in a row, and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was used; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index fefe1f4a97..7789020ad2 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -660,6 +660,23 @@ pub struct ReadFile { links: Resolved, /// Whether the color management policies changed the document ([`apply_policies`]). policy_changed: bool, + /// The answer to the document's profile question (`profileChoice`, or the app's prompt). + choice: Option, + /// What opening still has to do while the app asks about the profile ([`ReadFile::question`]): + /// the policies, the color mode, the linked files and the type are left for + /// [`ReadFile::answer`] or [`open_read`]. + rest: Option, + /// The answer that was used and the question it answered (`document.open`'s `profileChoice` + /// reply). + answered: Option, +} + +/// The part of [`read_for_open`] a file waiting for a profile answer has left to do. +struct Rest { + update_links: bool, + low_res_proxy_eps: bool, + /// The color mode `colorMode` asks for, converted after the policies. + color_mode: Option, } /// Edit › Color Settings: the color management policies keep, take off or convert from the @@ -688,36 +705,109 @@ impl ReadFile { /// reads (`importer` in `p`, or an extension only an importer lists) is read by it /// ([`super::importer`]). pub fn read_for_open(name: &str, bytes: &[u8], path: Option, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result { + read_for_open_asking(name, bytes, path, p, update_links, low_res_proxy_eps, false) +} + +/// [`read_for_open`]; with `ask` (the desktop app's File › Open), a document whose profile +/// question ([`ReadFile::question`]) Edit › Color Settings asks, and that `p` gives no +/// `profileChoice` for, stops after it is decoded: the app asks, and [`ReadFile::answer`] (or +/// [`open_read`], with the policy's choice) does the rest. +pub fn read_for_open_asking( + name: &str, + bytes: &[u8], + path: Option, + p: &Value, + update_links: bool, + low_res_proxy_eps: bool, + ask: bool, +) -> Result { let opts = LoadOptions::from_params("document.open", p)?; - let (mut loaded, policy_changed) = if opts.link_pages { - let mut loaded = linked_pages(name, bytes, path.as_deref(), &opts)?; - let changed = apply_policies(&mut loaded); - (loaded, changed) + let choice = crate::cmd::colormgmt::ProfileChoice::param(p, "document.open")?; + let (loaded, color_mode) = if opts.link_pages { + (linked_pages(name, bytes, path.as_deref(), &opts)?, None) } else { match super::importer::pick(name, bytes, p)? { - Some(plugin) => { - let mut loaded = super::importer::load(name, bytes, &plugin, p)?; - let changed = apply_policies(&mut loaded); - (loaded, changed) - } - None => { - // The color mode `p` asks for converts the colors after the policies did, through - // the profiles the document keeps. - let mut loaded = load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?; - let changed = apply_policies(&mut loaded); - if let Some(mode) = opts.color_mode.filter(|m| *m != loaded.doc.color_mode) { - let doc = &mut loaded.doc; - vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || { - super::super::colormgmt::set_color_mode(doc, mode, true, None, opts.grays); - }); - } - (loaded, changed) - } + Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None), + // The color mode `p` asks for converts the colors after the policies did, through the + // profiles the document keeps. + None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode), } }; - let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps); - Session::refresh_text_bounds(&mut loaded.doc); - Ok(ReadFile { loaded, opts, path, links, policy_changed }) + let mut file = ReadFile { + loaded, + opts, + path, + links: Resolved::default(), + policy_changed: false, + choice, + rest: Some(Rest { update_links, low_res_proxy_eps, color_mode }), + answered: None, + }; + if ask && file.choice.is_none() && file.question().is_some() { + return Ok(file); + } + file.finish_read()?; + Ok(file) +} + +impl ReadFile { + /// The file's name, for a prompt. + pub fn name(&self) -> String { + self.path.as_deref().map(file_name).unwrap_or_else(|| self.loaded.doc.title.clone()) + } + + /// The profile question Edit › Color Settings asks about this file before it opens (its Ask + /// When Opening box of that kind is on), while the file waits for the answer + /// ([`read_for_open_asking`]); none once it is answered or read through. + pub fn question(&self) -> Option { + self.rest.as_ref()?; + let st = vectorcraft_color::cms::working_settings(); + crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &st).filter(|q| q.asked(&st)) + } + + /// Answer the profile question with `choice` and do the rest of the read: the policies (the + /// answer in place of the one of the document's color mode), the color mode, the linked files + /// and the type. An error (a profile to assign that is not one of that model) leaves the file + /// waiting. + pub fn answer(&mut self, choice: crate::cmd::colormgmt::ProfileChoice) -> Result<()> { + let before = self.choice.replace(choice); + let r = self.finish_read(); + if r.is_err() { + self.choice = before; + } + r + } + + /// The rest of [`read_for_open_asking`], once: the color management policies with the profile + /// answer, the color mode `colorMode` asks for, the linked files and the type. + fn finish_read(&mut self) -> Result<()> { + if self.rest.is_none() { + return Ok(()); + } + // The question the answer was given to, for the reply's `profileChoice`. + let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let answered = match (&self.choice, &question) { + (Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })), + _ => None, + }; + // A failure leaves the file waiting, unchanged. + let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?; + let Some(rest) = self.rest.take() else { return Ok(()) }; + self.answered = answered; + self.loaded.warnings.extend(notes); + self.policy_changed = changed; + if let Some(mode) = rest.color_mode.filter(|m| *m != self.loaded.doc.color_mode) { + let doc = &mut self.loaded.doc; + let grays = self.opts.grays; + vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || { + super::super::colormgmt::set_color_mode(doc, mode, true, None, grays); + }); + } + let base = crate::cmd::links::LinkBase::file(self.path.as_deref()); + self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, rest.update_links, rest.low_res_proxy_eps); + Session::refresh_text_bounds(&mut self.loaded.doc); + Ok(()) + } } /// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents @@ -731,8 +821,15 @@ fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions /// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active /// document → `document.open`'s result. -pub fn open_read(s: &mut Session, file: ReadFile) -> Result { - open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed) +/// A file still waiting for its profile answer ([`ReadFile::question`]) opens as its policy says. +pub fn open_read(s: &mut Session, mut file: ReadFile) -> Result { + file.finish_read()?; + let answered = file.answered.take(); + let mut r = open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed)?; + if let Some(a) = answered { + r["profileChoice"] = a; + } + Ok(r) } /// File → New from Template: any readable file (at `path`, if it is one: its links are looked for diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 988278b211..71c1337524 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -8,7 +8,7 @@ use std::sync::{Mutex, MutexGuard}; use serde_json::json; use vectorcraft_color::cms; use vectorcraft_engine::Session; -use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, doc_profiles}; +use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, ProfileChoice, ProfileIssue, doc_profiles}; use vectorcraft_engine::store::MAX_PRESET_FILE; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Renderer}; @@ -1019,3 +1019,344 @@ fn color_management_policies_are_checked_and_kept() { next.attach_color_settings(file); assert_eq!(cms::active_settings(), cms::ColorSettings::default()); } + +/// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in +/// `Color Settings.json`. +#[test] +fn ask_boxes_are_checked_and_kept() { + let _g = settings(); + let dir = fresh_dir("ask-kept"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + let file = dir.join("Color Settings.json"); + let mut s = session(); + s.attach_color_settings(file.clone()); + let r = exec(&mut s, "edit.colorSettings", json!({})); + assert_eq!( + (r["askMismatchOpen"].as_bool(), r["askMismatchPaste"].as_bool(), r["askMissingOpen"].as_bool()), + (Some(false), Some(false), Some(false)) + ); + for bad in [json!({"askMismatchOpen": "yes"}), json!({"askMismatchPaste": 1}), json!({"askMissingOpen": []})] { + assert!(s.execute("edit.colorSettings", &bad).is_err(), "{bad}"); + } + assert!(!file.exists(), "a refused change keeps nothing"); + let r = exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true, "askMissingOpen": true})); + assert_eq!( + (r["askMismatchOpen"].as_bool(), r["askMismatchPaste"].as_bool(), r["askMissingOpen"].as_bool()), + (Some(true), Some(false), Some(true)) + ); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert!(saved.ask_mismatch_open && !saved.ask_mismatch_paste && saved.ask_missing_open); +} + +/// Two saved documents with a blue rectangle (`blue`, filled `blue0`): `tagged`, assigned Wide +/// Gamut RGB, and `plain`, untagged. The files go when it drops, and the Color Settings go back to +/// the defaults. +struct ProfileFiles { + _reset: ColorSettingsReset, + _dir: vectorcraft_testkit::TempDir, + tagged: std::path::PathBuf, + plain: std::path::PathBuf, + blue: vectorcraft_doc::NodeId, + blue0: vectorcraft_color::Color, +} + +#[allow(clippy::unwrap_used, reason = "a test helper: a file that can't be written fails the test")] +fn profile_files(tag: &str) -> ProfileFiles { + let dir = fresh_dir(tag); + let reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let (tagged, plain) = (dir.join("tagged.vectorcraft"), dir.join("plain.vectorcraft")); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "file.saveAs", json!({"path": plain.to_str().unwrap()})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()})); + let blue0 = fill_of(&s, blue); + ProfileFiles { _reset: reset, _dir: dir, tagged, plain, blue, blue0 } +} + +/// The fill color of object `id` in the active document. +#[allow(clippy::unwrap_used, reason = "a test helper: a missing object or fill fails the test")] +fn fill_of(s: &Session, id: vectorcraft_doc::NodeId) -> vectorcraft_color::Color { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap() +} + +/// `document.open` of `path` with the params `extra` in a new session → the reply, and the session. +#[allow(clippy::unwrap_used, reason = "a test helper: params that are not an object fail the test")] +fn open_with(path: &std::path::Path, extra: serde_json::Value) -> (Result, Session) { + let mut s = session(); + let mut p = json!({"path": path.to_str().unwrap()}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("document.open", &p).map_err(|e| e.to_string()); + (r, s) +} + +/// `document.open`'s `profileChoice` answers what Color Settings' Profile Mismatches box asks: for +/// a document tagged with another profile than the working space of its color mode it keeps the +/// profile, converts the colors or discards the profile in place of the policy. A missing choice +/// for it is not used. +#[test] +fn profile_choice_answers_a_mismatch() { + let _g = settings(); + let ProfileFiles { tagged, blue, blue0, .. } = &profile_files("profile-mismatch"); + let (tagged, blue, blue0) = (tagged.as_path(), *blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let open = open_with; + let mut s = session(); + + // Each choice in place of the policy (Preserve Embedded Profiles). + let (r, kept) = open(tagged, json!({"profileChoice": "useEmbedded"})); + let r = r.unwrap(); + assert_eq!(r["profileChoice"], json!({"issue": "mismatch", "model": "rgb", "choice": "useEmbedded"})); + assert_eq!((doc_profiles(&kept.doc().unwrap().doc).0, fill(&kept)), (Some(cms::WIDE_GAMUT_RGB.into()), blue0)); + let (r, discarded) = open(tagged, json!({"profileChoice": "discard"})); + let r = r.unwrap(); + assert_eq!((doc_profiles(&discarded.doc().unwrap().doc).0, fill(&discarded)), (None, blue0), "the numbers stay"); + assert!(discarded.doc().unwrap().is_dirty()); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("as chosen when it was opened")), "{r}"); + let (r, converted) = open(tagged, json!({"profileChoice": "convert"})); + assert_eq!(r.unwrap()["profileChoice"]["choice"], "convert"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + let blue1 = fill(&converted); + assert_eq!(doc_profiles(&converted.doc().unwrap().doc).0, None); + assert!(blue1 != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&blue1)) < 1.0, "{blue0:?} → {blue1:?}"); + // Under policy Off, Use Embedded keeps the profile. + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "off"})); + let (_, kept) = open(tagged, json!({"profileChoice": "useEmbedded"})); + assert_eq!(doc_profiles(&kept.doc().unwrap().doc).0, Some(cms::WIDE_GAMUT_RGB.into())); + // A missing choice for a mismatched document is not used: the policy applies. + let (r, off) = open(tagged, json!({"profileChoice": "leave"})); + assert!(r.unwrap().get("profileChoice").is_none()); + assert_eq!(doc_profiles(&off.doc().unwrap().doc).0, None); +} + +/// `document.open`'s `profileChoice` answers what the Missing Profiles box asks: an untagged +/// document is left, assigned the working space or assigned a profile, its numbers kept. A +/// mismatch choice for it is not used, and wrong choices are refused. +#[test] +fn profile_choice_answers_a_missing_profile() { + let _g = settings(); + let ProfileFiles { tagged, plain, blue, blue0, .. } = &profile_files("profile-missing"); + let (tagged, plain, blue, blue0) = (tagged.as_path(), plain.as_path(), *blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let open = open_with; + let (r, left) = open(plain, json!({"profileChoice": "leave"})); + assert_eq!(r.unwrap()["profileChoice"], json!({"issue": "missing", "model": "rgb", "choice": "leave"})); + assert_eq!(doc_profiles(&left.doc().unwrap().doc).0, None); + assert!(!left.doc().unwrap().is_dirty()); + let (_, working) = open(plain, json!({"profileChoice": "assignWorking"})); + assert_eq!(doc_profiles(&working.doc().unwrap().doc).0.as_deref(), Some(cms::canonical_name(cms::SRGB))); + assert!(working.doc().unwrap().is_dirty()); + let (_, p3) = open(plain, json!({"profileChoice": "assign", "assignProfile": cms::DISPLAY_P3})); + assert_eq!((doc_profiles(&p3.doc().unwrap().doc).0, fill(&p3)), (Some(cms::DISPLAY_P3.into()), blue0), "assigning keeps the numbers"); + // A mismatch choice for an untagged document is not used. + let (r, plain_kept) = open(plain, json!({"profileChoice": "convert"})); + assert!(r.unwrap().get("profileChoice").is_none()); + assert_eq!(doc_profiles(&plain_kept.doc().unwrap().doc).0, None); + + for bad in [ + json!({"profileChoice": "bogus"}), + json!({"profileChoice": "assign"}), + json!({"profileChoice": "discard", "assignProfile": cms::DISPLAY_P3}), + json!({"assignProfile": cms::DISPLAY_P3}), + json!({"profileChoice": 3}), + ] { + assert!(open(tagged, bad.clone()).0.is_err(), "{bad}"); + } + let (r, none) = open(plain, json!({"profileChoice": "assign", "assignProfile": cms::DEVICE_CMYK})); + assert!(r.unwrap_err().contains("unknown rgb profile"), "a CMYK profile can't tag an RGB document"); + assert_eq!(none.documents().len(), 1, "nothing opened"); +} + +/// The app's half of the open prompts: a file read with asking stops at the question when its box +/// is on (never without asking), and opens as answered, or as the policy says when it opens +/// unanswered. A refused answer leaves it waiting. +#[test] +fn a_read_waits_for_the_profile_answer() { + let _g = settings(); + let ProfileFiles { tagged, plain, blue, blue0, .. } = &profile_files("profile-wait"); + let (blue, blue0) = (*blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let mut s = session(); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + let blue1 = source.convert_into(&cms::working(), &blue0, cms::working().settings().intent); + let bytes = std::fs::read(tagged).unwrap(); + let name = tagged.to_str().unwrap(); + let read = + |ask: bool| vectorcraft_engine::cmd::fileio::read_for_open_asking(name, &bytes, Some(name.into()), &json!({}), false, false, ask).unwrap(); + assert!(read(true).question().is_none(), "the box is off"); + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true, "rgbPolicy": "convert"})); + assert!(read(false).question().is_none(), "document.open never asks"); + let mut waiting = read(true); + let q = waiting.question().unwrap(); + assert_eq!((q.issue, q.profile.as_deref(), q.default.id()), (ProfileIssue::Mismatch, Some(cms::WIDE_GAMUT_RGB), "convert")); + assert_eq!(waiting.name(), "tagged.vectorcraft"); + waiting.answer(ProfileChoice::Discard).unwrap(); + assert!(waiting.question().is_none(), "answered"); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(r["profileChoice"]["choice"], "discard"); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill(&opened)), (None, blue0)); + // Unanswered, it opens as the policy (Convert to Working Space) says. + let mut opened = session(); + vectorcraft_engine::cmd::fileio::open_read(&mut opened, read(true)).unwrap(); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill(&opened)), (None, blue1)); + // A missing answer to a mismatch is not used: the policy decides. + let mut waiting = read(true); + waiting.answer(ProfileChoice::Leave).unwrap(); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert!(r.get("profileChoice").is_none()); + assert_eq!(fill(&opened), blue1); + // Missing Profiles: Ask When Opening, starting on assigning the working space under Convert. + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true})); + assert!(read(true).question().is_none(), "the mismatch box is off now"); + let plain_bytes = std::fs::read(plain).unwrap(); + let mut waiting = + vectorcraft_engine::cmd::fileio::read_for_open_asking("plain.vectorcraft", &plain_bytes, None, &json!({}), false, false, true).unwrap(); + let q = waiting.question().unwrap(); + assert_eq!((q.issue, q.profile.as_deref(), q.default.id()), (ProfileIssue::Missing, None, "assignWorking")); + assert!(waiting.answer(ProfileChoice::Assign(cms::DEVICE_CMYK.into())).is_err(), "not an RGB profile"); + assert!(waiting.question().is_some(), "still waiting after a refused answer"); + waiting.answer(ProfileChoice::Assign(cms::DISPLAY_P3.into())).unwrap(); + let mut opened = session(); + vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(doc_profiles(&opened.doc().unwrap().doc).0, Some(cms::DISPLAY_P3.into())); +} + +/// Swatch conflicts are checked against the colors as the paste brings them: a global swatch whose +/// name and color match the destination's conflicts once the paste converts it, and pasting back +/// into its own document with conversion compares its swatches too. +#[test] +fn swatch_conflicts_follow_the_profile_conversion() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": "#3366cc", "global": true})); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [r.0], "swatch": "Brand"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + select(&mut s, &[r]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": "#3366cc", "global": true})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({})), 0, "the numbers are kept: the same color"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "converted, it differs"); + assert!(s.execute("clipboard.conflicts", &json!({"profileMismatch": "keep"})).is_err()); + // Back in the first document, under another working space, a converting paste compares too. + exec(&mut s, "document.activate", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + assert_eq!(conflicts(&mut s, json!({})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1); +} + +/// A paste is a mismatch only for the models the copied colors use: CMYK art from a document with +/// other RGB and CMYK profiles is a CMYK mismatch alone, and so is an artboard copied without art +/// whose background is CMYK. +#[test] +fn a_paste_mismatches_only_the_models_its_colors_use() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + select(&mut s, &[ink]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let models = |s: &mut Session| -> Vec { + let r = exec(s, "clipboard.profileMismatch", json!({})); + r["mismatches"].as_array().unwrap().iter().map(|m| m["model"].as_str().unwrap().to_string()).collect() + }; + assert_eq!(models(&mut s), ["cmyk"]); + exec(&mut s, "document.activate", json!({"index": 0})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": {"c": 0, "m": 100, "y": 0, "k": 0}})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "document.activate", json!({"index": 1})); + assert_eq!(models(&mut s), ["cmyk"]); +} + +/// An artboard copied without art from a document with another profile is a mismatch through its +/// background color, which converts with a paste that converts. +#[test] +fn a_pasted_artboard_background_converts() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0]["model"], "rgb"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + let i = r["artboards"][0].as_u64().unwrap() as usize; + let paper = s.doc().unwrap().doc.artboards[i].color.unwrap(); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(paper != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&paper)) < 1.0, "{blue0:?} → {paper:?}"); +} + +/// Paste compares the profiles the copied colors showed through with the destination's: a model +/// whose profile differs and whose colors the objects use is a mismatch (clipboard.profileMismatch). +/// Its colors keep their numbers or convert, as `profileMismatch` says, else as the policy says; +/// the reply lists what was done. +#[test] +fn paste_keeps_or_converts_colors_from_another_profile() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + // Back in the same document: nothing to compare. + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([])); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = exec(&mut s, "clipboard.profileMismatch", json!({})); + // Only RGB: the objects use no CMYK color. + assert_eq!( + r["mismatches"], + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": cms::canonical_name(cms::SRGB), "default": "preserveNumbers"}]) + ); + let pasted = |s: &mut Session, p: serde_json::Value| { + let r = exec(s, "edit.paste", p); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + (r, c) + }; + let (r, kept) = pasted(&mut s, json!({})); + assert_eq!(kept, blue0, "the policy (Preserve Embedded Profiles) keeps the numbers"); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + let (r, moved) = pasted(&mut s, json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(moved != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert"})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0]["default"], "convert"); + let (_, by_policy) = pasted(&mut s, json!({})); + assert_eq!(by_policy, moved, "Convert to Working Space converts"); + let (_, numbers) = pasted(&mut s, json!({"profileMismatch": "preserveNumbers"})); + assert_eq!(numbers, blue0); + for bad in [json!({"profileMismatch": "keep"}), json!({"profileMismatch": true})] { + assert!(s.execute("edit.paste", &bad).is_err(), "{bad}"); + } + // A drag from the first document follows the policy too. + let source = s.documents()[0].uid; + let r = exec(&mut s, "edit.dropSelection", json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50]})); + let dropped = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(dropped).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + assert_eq!(c, moved, "dropped colors convert under Convert to Working Space"); + // A destination assigned the source's profile has nothing to compare. + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([])); + let (r, same) = pasted(&mut s, json!({})); + assert!(r.get("profileMismatch").is_none()); + assert_eq!(same, blue0); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 412dbcb4ef..6c4f566552 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -180,6 +180,7 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + pending_profile_open: None, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 6d40499106..ee01cd5373 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -214,6 +214,10 @@ impl VectorcraftApp { Ok(Some(started)) => return Ok(started), Ok(None) => {} } + // Edit › Color Settings' Ask When Pasting, then any swatch conflict. + if let Some(r) = dialogs::profile_mismatch::ask_paste(self, id, ¶ms) { + return r; + } if let Some(r) = dialogs::swatch_conflict::ask(self, id, ¶ms) { return r; } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 04e58d452e..6189855b03 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -96,6 +96,7 @@ pub mod plugin; mod png_options; pub mod print; pub mod print_presets; +pub mod profile_mismatch; mod psd_options; pub mod raster_effects; pub mod rearrange_artboards; @@ -382,6 +383,8 @@ registry! { ExportAs: ["exportAs"] => export_as::SPEC, ImportPdf: [import_pdf::KIND] => import_pdf::SPEC, SwatchConflict: [swatch_conflict::KIND] => swatch_conflict::SPEC, + ProfileMismatchOpen: [profile_mismatch::OPEN_KIND] => profile_mismatch::OPEN_SPEC, + ProfileMismatchPaste: [profile_mismatch::PASTE_KIND] => profile_mismatch::PASTE_SPEC, FileInfo: [file_info::KIND] => file_info::SPEC, RasterEffectsSettings: [raster_effects::KIND] => raster_effects::SPEC, EffectGallery: [effect_gallery::KIND] => effect_gallery::SPEC, @@ -666,6 +669,12 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == swatch_conflict::KIND { crate::placing::cancel_swatch_paste(app); } + if d.kind == profile_mismatch::OPEN_KIND { + profile_mismatch::cancel_open(app); + } + if d.kind == profile_mismatch::PASTE_KIND { + crate::placing::cancel_swatch_paste(app); + } if d.kind == plugin::INSTALL_KIND { app.pending_plugin_install = None; } @@ -726,6 +735,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> DialogResult { /// time). pub(crate) fn settle(app: &mut VectorcraftApp) { crate::placing::settle_swatch_paste(app); + profile_mismatch::settle(app); missing_fonts::requeue_replaced(app); missing_fonts::stop_when_closed(app); find_links::stop_when_closed(app); diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 4820680a09..df37f807db 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -233,7 +233,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }; match r { Ok(()) => { - app.ui.dialog = None; + // Opening may have asked something else (the profile of the document); only this + // dialog closes. + if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { + app.ui.dialog = None; + } Ok(Value::Null) } Err(e) => { diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs new file mode 100644 index 0000000000..e4d36da5f1 --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -0,0 +1,244 @@ +//! The questions Edit › Color Settings' Ask boxes add (Profile Mismatches: Ask When Opening and +//! Ask When Pasting, Missing Profiles: Ask When Opening), one dialog kind each for opening and for +//! pasting. +//! +//! Opening ([`OPEN_KIND`]): a document whose color mode's profile is not the working space asks +//! whether to use that profile, convert the colors to the working space or discard the profile; one +//! with no profile asks whether to leave it, assign the working space or assign a profile. The +//! choice the policy makes is chosen first. OK opens the document as chosen; Cancel doesn't open +//! it. The file read waits in [`VectorcraftApp::pending_profile_open`]. Fields: `issue` (`mismatch` +//! | `missing`), `name` (the file's), `model` (`RGB` | `CMYK`), `profile` (the one it is tagged +//! with), `working`, `choice` (a `profileChoice` of `document.open`) and `assignProfile`. +//! +//! Pasting ([`PASTE_KIND`]): colors copied from a document whose profile is not this document's ask +//! whether to keep their numbers or convert them. OK runs the paste with `profileMismatch`; Cancel +//! pastes nothing. Fields: `mismatches` (as `clipboard.profileMismatch` lists them), `choice` +//! (`preserveNumbers` | `convert`), `__command` and `__params` (the paste to run). + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{self, ProfileKind}; +use vectorcraft_engine::cmd::colormgmt::ProfileChoice; +use vectorcraft_engine::cmd::fileio::{self, ReadFile}; + +use super::swatch_options::{grid, label}; +use super::{DialogResult, DialogSpec}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the question opening asks. +pub const OPEN_KIND: &str = "profileMismatchOpen"; +/// The dialog kind of the question pasting asks. +pub const PASTE_KIND: &str = "profileMismatchPaste"; + +pub(super) const OPEN_SPEC: DialogSpec = DialogSpec { + heading: |d| if d.str("issue") == "missing" { tl!("Missing Profile") } else { tl!("Embedded Profile Mismatch") }.into(), + body: open_body, + confirm: open_confirm, + min_width: 400.0, + max_width: Some(480.0), + ..DialogSpec::FORM +}; + +pub(super) const PASTE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Paste Profile Mismatch").into(), + body: paste_body, + confirm: paste_confirm, + min_width: 400.0, + max_width: Some(480.0), + ..DialogSpec::FORM +}; + +/// A file read for File › Open that waits for the answer to its profile question. +pub(crate) struct PendingOpen { + file: ReadFile, + /// Where it was read from: it goes on the recent files once it opens. + path: Option, +} + +/// The choices of a mismatch (`missing`: of a missing profile), as (`choice`, label). +fn open_choices(missing: bool) -> [(&'static str, &'static str); 3] { + if missing { + [("leave", tl!("Leave as is")), ("assignWorking", tl!("Assign the working space")), ("assign", tl!("Assign profile:"))] + } else { + [ + ("useEmbedded", tl!("Use the embedded profile")), + ("convert", tl!("Convert the colors to the working space")), + ("discard", tl!("Discard the embedded profile")), + ] + } +} + +/// The choices pasting offers, as (`choice`, label). +fn paste_choices() -> [(&'static str, &'static str); 2] { + [("preserveNumbers", tl!("Preserve the color numbers")), ("convert", tl!("Convert to keep the colors' appearance"))] +} + +/// Open `file`, read for File › Open from `path`, as `document.open` does, unless Edit › Color +/// Settings asks about its profile ([`ReadFile::question`]): then the dialog asks first, and the +/// result is `{dialog}`. Opened, the views follow and the file goes on the recent files +/// ([`crate::io::opened`]). +pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option) -> Result { + // One question at a time: a file read while another waits opens as its policy says. + if app.pending_profile_open.is_none() + && let Some(q) = file.question() + { + let fields = json!({ + "issue": q.issue.id(), + "name": file.name(), + "model": q.model_label(), + "profile": q.profile, + "working": q.working, + "choice": q.default.id(), + "assignProfile": q.working, + }); + app.pending_profile_open = Some(PendingOpen { file, path }); + app.ui.dialog = Some(Dialog::new(OPEN_KIND, fields)); + return Ok(json!({ "dialog": OPEN_KIND })); + } + let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) +} + +/// The `profileChoice` the open dialog's fields give. +fn open_choice(d: &Dialog) -> Result { + let choice = d.str("choice"); + let profile = d.str("assignProfile"); + let profile = (choice == "assign").then_some(profile.as_str()); + ProfileChoice::parse(&choice, profile, "ui.dialog.confirm").map_err(|e| e.to_string()) +} + +fn open_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let missing = d.str("issue") == "missing"; + let (name, model, profile, working) = (d.str("name"), d.str("model"), d.str("profile"), d.str("working")); + let vars = [("name", name.as_str()), ("model", model.as_str()), ("profile", profile.as_str()), ("working", working.as_str())]; + let text = if missing { + tl!("“{name}” is not tagged with a {model} profile.") + } else { + tl!("“{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”.") + }; + ui.label(crate::i18n::fmt(text, &vars)); + ui.add_space(10.0); + let choice = d.str("choice"); + for (value, text) in open_choices(missing) { + ui.horizontal(|ui| { + if widgets::radio(ui, text, choice == value, true) { + d.fields.insert("choice".into(), json!(value)); + } + if value == "assign" { + let kind = if model == "CMYK" { ProfileKind::Cmyk } else { ProfileKind::Rgb }; + let current = d.str("assignProfile"); + ui.add_enabled_ui(choice == "assign", |ui| { + if let Some(n) = crate::panels::separations::profile_dropdown(ui, "profile-mismatch-assign", ¤t, kind, None) { + d.fields.insert("assignProfile".into(), json!(n)); + } + }); + } + }); + } + false +} + +/// OK: open the waiting file as chosen. A choice the file refuses keeps the dialog open. +fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let choice = open_choice(d)?; + let Some(mut pending) = app.pending_profile_open.take() else { + app.ui.dialog = None; + return Ok(Value::Null); + }; + if let Err(e) = pending.file.answer(choice) { + app.pending_profile_open = Some(pending); + return Err(e.to_string()); + } + app.ui.dialog = None; + let PendingOpen { file, path } = pending; + let name = file.name(); + match fileio::open_read(&mut app.session, file) { + Ok(r) => { + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) + } + Err(e) => { + let e = e.to_string(); + crate::io::report_open_error(app, &name, &e); + Err(e) + } + } +} + +/// Cancel, or the dialog closed some other way: the waiting file doesn't open. +pub(crate) fn cancel_open(app: &mut VectorcraftApp) { + app.pending_profile_open = None; +} + +/// A file still waiting once its dialog is gone (another dialog took its place) doesn't open. +pub(crate) fn settle(app: &mut VectorcraftApp) { + if app.pending_profile_open.is_some() && !app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) { + cancel_open(app); + } +} + +/// Before running paste `command` with `params`: when Ask When Pasting is on, `params` don't say +/// what to do (`profileMismatch`) and the pasted colors come from another profile, open the dialog +/// instead and answer `{dialog}`. +pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option { + if params.get("profileMismatch").is_some() || !cms::working_settings().ask_mismatch_paste { + return None; + } + let found = app.session.execute("clipboard.profileMismatch", &json!({})).ok()?; + let mismatches = found["mismatches"].as_array().filter(|a| !a.is_empty())?.clone(); + // The policy of the first model starts chosen. + let choice = mismatches[0]["default"].as_str().unwrap_or("preserveNumbers").to_string(); + let fields = json!({ "mismatches": mismatches, "choice": choice, "__command": command, "__params": params }); + // A deferred paste this dialog asked about gives way to the new one. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == PASTE_KIND) { + crate::placing::cancel_swatch_paste(app); + } + app.ui.dialog = Some(Dialog::new(PASTE_KIND, fields)); + Some(Ok(json!({ "dialog": PASTE_KIND }))) +} + +fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let mismatches = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); + for m in &mismatches { + let model = m["model"].as_str().unwrap_or_default().to_ascii_uppercase(); + let (from, to) = (m["clipboard"].as_str().unwrap_or_default(), m["document"].as_str().unwrap_or_default()); + let text = tl!("The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”."); + ui.label(crate::i18n::fmt(text, &[("model", model.as_str()), ("from", from), ("to", to)])); + } + ui.add_space(10.0); + let choice = d.str("choice"); + grid(ui, |ui| { + for (value, text) in paste_choices() { + label(ui, ""); + if widgets::radio(ui, text, choice == value, true) { + d.fields.insert("choice".into(), json!(value)); + } + ui.end_row(); + } + }); + false +} + +/// OK: run the paste with the choice; any Swatch Conflict question comes next. +fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let choice = d.str("choice"); + if !paste_choices().iter().any(|(v, _)| *v == choice) { + let key = "choice"; + return Err(format!("`{key}` must be one of {}", "preserveNumbers, convert")); + } + let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + params["profileMismatch"] = json!(choice); + app.ui.dialog = None; + // A paste that waited for its clipboard runs in the context it was given in. + crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, d.fields.get("__deferredPaste").and_then(Value::as_u64)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs new file mode 100644 index 0000000000..baed4f62ae --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -0,0 +1,134 @@ +use vectorcraft_engine::Session; + +use super::*; + +fn frame(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); +} + +/// The native file of a document with a blue rectangle, assigned `rgb` (none: untagged). +fn file(rgb: Option<&str>) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap(); + if let Some(p) = rgb { + s.execute("edit.assignProfile", &json!({ "rgb": p })).unwrap(); + } + let r = s.execute("document.serialize", &json!({})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +fn rgb_profile(app: &VectorcraftApp) -> Option { + vectorcraft_engine::cmd::colormgmt::doc_profiles(&app.session.doc().unwrap().doc).0 +} + +/// With Color Settings' Ask boxes on, File › Open asks about a document whose profile is not the +/// working space, or that has none, and opens it as chosen; Cancel doesn't open it, and a refused +/// choice keeps the dialog. Paste asks about colors from another profile and pastes as chosen. With +/// the boxes off, nothing asks. +#[test] +fn opening_and_pasting_ask_about_profiles() { + const CHILD: &str = "VECTORCRAFT_TEST_PROFILE_PROMPTS"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "dialogs::profile_mismatch::tests::opening_and_pasting_ask_about_profiles", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated profile prompt test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (tagged, plain) = (file(Some(cms::WIDE_GAMUT_RGB)), file(None)); + // The boxes are off: the document opens as the policy says. + let r = crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + assert!(r.get("index").is_some() && app.ui.dialog.is_none()); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB)); + + // Profile Mismatches: Ask When Opening. + app.run("edit.colorSettings", json!({"askMismatchOpen": true, "rgbPolicy": "convert"})).unwrap(); + let docs = app.session.documents().len(); + let r = crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + assert_eq!(app.session.documents().len(), docs, "not open yet"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!( + (d.str("issue"), d.str("model"), d.str("profile"), d.str("choice")), + ("mismatch".into(), "RGB".into(), cms::WIDE_GAMUT_RGB.into(), "convert".into()) + ); + let text = frame(&mut app); + for label in [ + "Embedded Profile Mismatch", + "Use the embedded profile", + "Convert the colors to the working space", + "Discard the embedded profile", + cms::WIDE_GAMUT_RGB, + ] { + assert!(text.contains(label), "{label} in {text}"); + } + // Cancel: nothing opens. + super::super::cancel(&mut app); + assert!(app.pending_profile_open.is_none()); + assert_eq!(app.session.documents().len(), docs); + crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + set(&mut app, "choice", json!("useEmbedded")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); + assert_eq!(app.session.documents().len(), docs + 1); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB), "kept, though the policy converts"); + + // Missing Profiles: Ask When Opening, and a choice the file refuses. + app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); + crate::io::open_bytes(&mut app, "plain.vectorcraft", &plain, None).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("issue"), d.str("choice")), (OPEN_KIND, "missing".into(), "leave".into())); + let text = frame(&mut app); + for label in ["Missing Profile", "Leave as is", "Assign the working space", "Assign profile:"] { + assert!(text.contains(label), "{label} in {text}"); + } + set(&mut app, "choice", json!("assign")); + set(&mut app, "assignProfile", json!(cms::DEVICE_CMYK)); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "still asking"); + set(&mut app, "assignProfile", json!(cms::DISPLAY_P3)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::DISPLAY_P3)); + assert!(app.session.doc().unwrap().is_dirty(), "assigning changed the document"); + + // Profile Mismatches: Ask When Pasting. + app.run("edit.colorSettings", json!({"askMissingOpen": false, "askMismatchPaste": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let r = app.run("edit.paste", json!({})).unwrap(); + assert_eq!(r, json!({ "dialog": PASTE_KIND })); + let text = frame(&mut app); + for label in ["Paste Profile Mismatch", "Preserve the color numbers", "Convert to keep the colors' appearance", cms::DISPLAY_P3] { + assert!(text.contains(label), "{label} in {text}"); + } + set(&mut app, "choice", json!("convert")); + let r = super::super::confirm(&mut app).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + assert!(app.ui.dialog.is_none()); + // Cancel pastes nothing; with the box off nothing asks. + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = count(&app); + app.run("edit.paste", json!({})).unwrap(); + super::super::cancel(&mut app); + assert_eq!(count(&app), before); + app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); + let r = app.run("edit.paste", json!({})).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + assert_eq!(count(&app), before + 1); +} diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index 490646e852..794a44df85 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -35,7 +35,12 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option Option { } /// Open a document through the engine loader with the `document.open` options in `p` → -/// `document.open`'s result. +/// `document.open`'s result, or `{dialog}` when Edit › Color Settings asks about its profile first +/// ([`dialogs::profile_mismatch::open_or_ask`]): the document then opens, and goes on the recent +/// files, once the question is answered. pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { - let r = fileio::open_bytes_with(&mut app.session, name, bytes, path, p).map_err(|e| e.to_string())?; - opened(app, &r); - Ok(r) + let update_links = app.session.prefs.update_links == "automatically"; + let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; + let file = fileio::read_for_open_asking(name, bytes, path.clone(), p, update_links, low_res_proxy_eps, true).map_err(|e| e.to_string())?; + dialogs::profile_mismatch::open_or_ask(app, file, path) +} + +/// Did an open answer that it asks a question first (`{dialog}`), so the file isn't open yet? +pub(crate) fn asks_first(r: &Value) -> bool { + r.get("dialog").is_some() } /// A document just opened (`r`: `document.open`'s result): the views follow, the status bar says @@ -400,9 +408,8 @@ pub(crate) fn open_with_on(app: &mut VectorcraftApp, p: &Value, background: bool Err(back) => bytes = back, } } - let r = open_document(app, &path, &bytes, Some(path.clone()), &o)?; - note_recent(app, &path); - Ok(r) + // The open notes it on the recent files, after any question it asks first. + open_document(app, &path, &bytes, Some(path.clone()), &o) }); if let Err(e) = &opened { report_open_error(app, &fileio::file_name(&path), e); @@ -566,7 +573,10 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va } } let r = open_bytes_with(app, path, &bytes, Some(path.to_string()), p)?; - note_recent(app, path); + // A document that asks a question first goes on the recent files once it opens. + if !asks_first(&r) { + note_recent(app, path); + } Ok(r) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 50ed3d8ee5..b1469fd684 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -344,6 +344,9 @@ pub struct VectorcraftApp { /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, + /// The file File › Open read that waits for the answer to its profile question + /// ([`dialogs::profile_mismatch`]), kept out of the dialog's fields. + pub(crate) pending_profile_open: Option, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 99e0e9d6b6..06dd2b6a0a 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -89,7 +89,9 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec, params: .run(|| { vectorcraft_engine::guard::catch_panic(|| { cancel::scope(&raised, None, || { - fileio::read_for_open(&name, &file, Some(name.clone()), ¶ms, update_links, low_res_proxy_eps).map_err(|e| e.to_string()) + // A profile question Edit › Color Settings asks waits for the UI thread. + fileio::read_for_open_asking(&name, &file, Some(name.clone()), ¶ms, update_links, low_res_proxy_eps, true) + .map_err(|e| e.to_string()) }) }) }) @@ -234,15 +236,13 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } } -/// Open a file read off the UI thread, as [`crate::io::open_reporting`] opens one read at once. +/// Open a file read off the UI thread, as [`crate::io::open_reporting`] opens one read at once, +/// after the profile question Edit › Color Settings asks about it, if any +/// ([`crate::dialogs::profile_mismatch::open_or_ask`]). fn finish(app: &mut VectorcraftApp, path: &str, r: Result) { - let opened = r.and_then(|file| fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())); - match opened { - Ok(r) => { - crate::io::opened(app, &r); - crate::io::note_recent(app, path); - } - Err(e) => crate::io::report_open_error(app, &fileio::file_name(path), &e), + let opened = r.and_then(|file| crate::dialogs::profile_mismatch::open_or_ask(app, file, Some(path.to_string()))); + if let Err(e) = opened { + crate::io::report_open_error(app, &fileio::file_name(path), &e); } } diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 6b7ce6b0e0..076722557a 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -102,8 +102,8 @@ fn settings_section(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The section's rows: the RGB and CMYK working spaces, intent, black point compensation, the RGB -/// and CMYK color management policies, Load -/// Profile… and Gamut Check, and the profile the active document is assigned. +/// and CMYK color management policies, the Ask boxes of Profile Mismatches and Missing Profiles, +/// Load Profile… and Gamut Check, and the profile the active document is assigned. fn settings_rows(app: &mut VectorcraftApp, ui: &mut Ui) { let st = cms::working_settings(); widgets::section_header(ui, tl!("Color Settings")); @@ -144,6 +144,22 @@ fn settings_rows(app: &mut VectorcraftApp, ui: &mut Ui) { } }); } + // Profile Mismatches and Missing Profiles: what opening and pasting ask about. + let asks: [(&str, &str, &str, bool); 3] = [ + ("askMismatchOpen", tl!("Profile Mismatches:"), tl!("Ask When Opening"), st.ask_mismatch_open), + ("askMismatchPaste", "", tl!("Ask When Pasting"), st.ask_mismatch_paste), + ("askMissingOpen", tl!("Missing Profiles:"), tl!("Ask When Opening"), st.ask_missing_open), + ]; + for (key, heading, label, on) in asks { + if !heading.is_empty() { + ui.label(heading); + } + ui.push_id(key, |ui| { + if widgets::check(ui, label, on, true) { + run(app, "edit.colorSettings", json!({ key: !on })); + } + }); + } ui.horizontal(|ui| { if widgets::flat_button(ui, tl!("Load Profile…"), 110.0).clicked() { // Its file dialog, shown off the UI thread, loads the profile when it answers. diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index fff3587182..1456acc149 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -503,8 +503,9 @@ pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile } DropTarget::Open => match path.as_deref() { Some(path) if app.services.read.is_some() => io::open_path(app, path).map(|_| ()), - _ => io::open_bytes(app, &name, &bytes, path.clone()).map(|_| { - if let Some(path) = &path { + _ => io::open_bytes(app, &name, &bytes, path.clone()).map(|r| { + // A document that asks a question first goes on the recent files once it opens. + if let Some(path) = path.as_ref().filter(|_| !io::asks_first(&r)) { io::note_recent(app, path); } }), diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index a627321d76..1549449cf6 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -543,7 +543,7 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { let _ = app.run(&paste.id, paste.params); // Also when the paste did not reach the clipboard (the Type tool took it). app.placing.adopted = false; - if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == crate::dialogs::swatch_conflict::KIND) { + if let Some(d) = app.ui.dialog.as_mut().filter(|d| asks_before_paste(&d.kind)) { d.fields.insert("__deferredPaste".into(), json!(chain)); if let Ok(st) = app.session.doc() { app.placing.swatch_paste = Some(PendingSwatch { @@ -597,19 +597,27 @@ pub(crate) fn cancel_swatch_paste(app: &mut VectorcraftApp) { } } +/// Is `kind` a dialog a paste asks before it runs (Paste Profile Mismatch, Swatch Conflict), whose +/// OK runs a deferred paste in the context it was given in? +fn asks_before_paste(kind: &str) -> bool { + kind == crate::dialogs::swatch_conflict::KIND || kind == crate::dialogs::profile_mismatch::PASTE_KIND +} + /// Release a deferred paste once its dialog is no longer the active dialog. pub(crate) fn settle_swatch_paste(app: &mut VectorcraftApp) { let active = app.placing.swatch_paste.as_ref().is_some_and(|waiting| { - app.ui.dialog.as_ref().is_some_and(|d| { - d.kind == crate::dialogs::swatch_conflict::KIND && d.fields.get("__deferredPaste").and_then(Value::as_u64) == Some(waiting.chain) - }) + app.ui + .dialog + .as_ref() + .is_some_and(|d| asks_before_paste(&d.kind) && d.fields.get("__deferredPaste").and_then(Value::as_u64) == Some(waiting.chain)) }); if app.placing.swatch_paste.is_some() && !active { cancel_swatch_paste(app); } } -/// Run the command confirmed by the deferred paste's Swatch Conflict dialog. +/// Run the command confirmed by the deferred paste's Swatch Conflict or Paste Profile Mismatch +/// dialog. pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: Value, token: Option) -> Result { if !app.placing.swatch_paste.as_ref().is_some_and(|waiting| Some(waiting.chain) == token) { if token.is_some() || app.placing.swatch_paste.is_some() { @@ -644,6 +652,27 @@ pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: V app.placing.adopted = true; let result = app.run(id, params); app.placing.adopted = false; + // The paste asked again (Swatch Conflict after Paste Profile Mismatch): it stays deferred, in + // the context it was given in. + let asked_again = app.ui.dialog.as_mut().filter(|d| asks_before_paste(&d.kind) && !d.fields.contains_key("__deferredPaste")); + if let Some(d) = asked_again + && let Ok(st) = app.session.doc() + { + d.fields.insert("__deferredPaste".into(), json!(waiting.chain)); + app.placing.swatch_paste = Some(PendingSwatch { + clipboard: app.session.clipboard.clone(), + insertion: insertion.clone(), + selection: waiting.selection, + doc: st.uid, + reverts: st.reverts, + chain: waiting.chain, + }); + if let Some(changed) = changed { + changed.restore_changed(&insertion, app); + } + app.session.clipboard = current; + return result; + } if let Some(changed) = changed { changed.restore_changed(&insertion, app); } diff --git a/docs/mcp.md b/docs/mcp.md index 5d545ef823..3bccdde628 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1634,6 +1634,19 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR target of `view.proofSetup` simulates the working CMYK space in such a document too. `color.convert`'s `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel and Color Picker check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. +- **Profile Mismatches and Missing Profiles** (`edit.colorSettings {askMismatchOpen, askMismatchPaste, + askMissingOpen}`, all off by default and kept in `Color Settings.json`): with `askMismatchOpen` or + `askMissingOpen` on, the desktop app's File › Open asks before a document opens when the profile of its color mode + is not the working space (use the embedded profile, convert the colors to the working space, or discard the + profile) or when it has none (leave it, assign the working space, or assign a profile), starting on what the + model's policy does; Cancel leaves the file closed. `document.open` never asks: `profileChoice` (`useEmbedded`, + `convert`, `discard`; `leave`, `assignWorking`, `assign` with `assignProfile`) states the answer, else the policy + applies, and the reply's `profileChoice` names the answer used. Copy remembers the profiles the colors showed + through; pasting them into a document with another RGB or CMYK profile keeps their numbers or converts them, as + `profileMismatch` on the paste commands says, else as the model's policy does (`convert` converts, the others keep + the numbers; a profile that is not available keeps them). `clipboard.profileMismatch` lists the models that differ, only those whose colors the copied objects + use, and with `askMismatchPaste` on the desktop app's Paste asks first. New from Template, File › Revert and a drag + between documents follow the policies without asking. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0dee2a464f..e3f3f7fad8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -746,6 +746,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. Opening or reverting a document tagged with a profile other than the working space keeps it, takes it off with the color numbers kept, or converts that model's colors into the working space and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf). Tests in `engine/tests/color_settings.rs` and `color/src/cms/tests.rs`. +- **Profile Mismatches and Missing Profiles:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has Profile Mismatches: Ask When Opening and Ask When Pasting, and Missing Profiles: Ask When Opening, off by default and kept in `Color Settings.json`. With a box on, File › Open asks before a document opens whose color mode's profile is not the working space (use the embedded profile, convert the colors to the working space, or discard the profile) or that has none (leave it, assign the working space, or assign a profile), and Paste asks whether colors copied from a document with another profile keep their numbers or convert; each starts on what the policy does. `document.open {profileChoice}` and the paste commands' `profileMismatch` give the answer without a prompt, and `clipboard.profileMismatch` lists what a paste would ask about. Asking about the profile of the document's color mode only, the choice a missing profile starts on under Convert to Working Space, and pastes and drags following the policies when nothing asks are VectorCraft's own rules. Public reference: [About missing and mismatched color profiles and Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `dialogs/profile_mismatch/tests.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From 2ab15e8acf18dfe7db8d54fe6c4839f6e237ea6d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:32:28 -0800 Subject: [PATCH 02/10] Color Settings: profile prompts finish where they were asked; CMYK falls back through its displayed Lab - Convert to Working Space between CMYK spaces with no direct transform goes through the Lab the source displays (black-point compensated), so dark inks keep their appearance instead of being compensated twice. - An open that waits on the Profile Mismatch dialog keeps the automation roots it was asked under: OK reads linked files and installs the document under them. - A paste that runs at once remembers the document it was asked in. When another document is active by the time OK is pressed, it pastes nothing. --- crates/color/src/cms.rs | 7 ++-- crates/color/src/cms/tests.rs | 22 +++++++++++ .../ui-egui/src/dialogs/profile_mismatch.rs | 37 ++++++++++++++----- .../src/dialogs/profile_mismatch/tests.rs | 35 +++++++++++++++++- 4 files changed, 87 insertions(+), 14 deletions(-) diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 069c27943b..8acf0b5e38 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -592,8 +592,9 @@ impl Cms { /// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to /// Working Space). RGB converts directly from profile to profile, with this context's /// black-point compensation. CMYK converts between two loaded profiles through ProPhoto RGB - /// ([`IccProfile::to_same_model_of`]), and through Lab when either space is built in. Grey and - /// Lab colours stay as they are. + /// ([`IccProfile::to_same_model_of`]), and through the Lab it displays as + /// ([`Self::cmyk_display_lab`]) when either space is built in. Grey and Lab colours stay as they + /// are. pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color { match *c { Color::Rgb { r, g, b } => { @@ -615,7 +616,7 @@ impl Cms { }; let [c, m, y, k] = match direct.as_deref() { Some(&[c, m, y, k]) => [c, m, y, k], - _ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent), + _ => dest.lab_to_cmyk(self.cmyk_display_lab(inks), intent), }; Color::Cmyk { c, m, y, k } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 5804bc6313..f3cdfefd33 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -495,3 +495,25 @@ fn convert_into_keeps_the_appearance() { assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c); } } + +/// With black-point compensation on, Generic CMYK displays its press black as black, so dark inks +/// converted out of it keep that appearance: into Device CMYK, and into another document whose +/// CMYK space is also Generic CMYK. +#[test] +fn convert_into_keeps_compensated_dark_inks() { + let generic = cms(); + let device = Cms::new(&ColorSettings { cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap(); + let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + for ink in [ + Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 }, + Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 1.0 }, + Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 }, + ] { + for dest in [&device, &other_generic] { + let moved = generic.convert_into(dest, &ink, Intent::RelativeColorimetric); + assert!(matches!(moved, Color::Cmyk { .. }), "{ink:?} → {moved:?}"); + let d = delta_e2000(generic.lab(&ink), dest.lab(&moved)); + assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index e4d36da5f1..83b8bdb030 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -13,12 +13,14 @@ //! Pasting ([`PASTE_KIND`]): colors copied from a document whose profile is not this document's ask //! whether to keep their numbers or convert them. OK runs the paste with `profileMismatch`; Cancel //! pastes nothing. Fields: `mismatches` (as `clipboard.profileMismatch` lists them), `choice` -//! (`preserveNumbers` | `convert`), `__command` and `__params` (the paste to run). +//! (`preserveNumbers` | `convert`), `__command` and `__params` (the paste to run), and `__doc` (the +//! uid of the document it was asked in). use serde_json::{Value, json}; use vectorcraft_color::cms::{self, ProfileKind}; use vectorcraft_engine::cmd::colormgmt::ProfileChoice; use vectorcraft_engine::cmd::fileio::{self, ReadFile}; +use vectorcraft_engine::file_access::ScopeHandle; use super::swatch_options::{grid, label}; use super::{DialogResult, DialogSpec}; @@ -53,6 +55,9 @@ pub(crate) struct PendingOpen { file: ReadFile, /// Where it was read from: it goes on the recent files once it opens. path: Option, + /// The automation roots in force where the open was asked for: its linked files are read, and + /// the document is installed, under them. + scope: ScopeHandle, } /// The choices of a mismatch (`missing`: of a missing profile), as (`choice`, label). @@ -91,7 +96,7 @@ pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option bool false } -/// OK: open the waiting file as chosen. A choice the file refuses keeps the dialog open. +/// OK: open the waiting file as chosen, under the automation roots of the open. A choice the file +/// refuses keeps the dialog open. fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = open_choice(d)?; let Some(mut pending) = app.pending_profile_open.take() else { app.ui.dialog = None; return Ok(Value::Null); }; - if let Err(e) = pending.file.answer(choice) { + if let Err(e) = pending.scope.clone().run(|| pending.file.answer(choice)) { app.pending_profile_open = Some(pending); return Err(e.to_string()); } app.ui.dialog = None; - let PendingOpen { file, path } = pending; + let PendingOpen { file, path, scope } = pending; let name = file.name(); - match fileio::open_read(&mut app.session, file) { + scope.run(|| match fileio::open_read(&mut app.session, file) { Ok(r) => { crate::io::opened(app, &r); if let Some(p) = &path { @@ -169,7 +175,7 @@ fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { crate::io::report_open_error(app, &name, &e); Err(e) } - } + }) } /// Cancel, or the dialog closed some other way: the waiting file doesn't open. @@ -195,7 +201,8 @@ pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Opt let mismatches = found["mismatches"].as_array().filter(|a| !a.is_empty())?.clone(); // The policy of the first model starts chosen. let choice = mismatches[0]["default"].as_str().unwrap_or("preserveNumbers").to_string(); - let fields = json!({ "mismatches": mismatches, "choice": choice, "__command": command, "__params": params }); + let doc = app.session.active().map(|st| st.uid); + let fields = json!({ "mismatches": mismatches, "choice": choice, "__command": command, "__params": params, DOC: doc }); // A deferred paste this dialog asked about gives way to the new one. if app.ui.dialog.as_ref().is_some_and(|d| d.kind == PASTE_KIND) { crate::placing::cancel_swatch_paste(app); @@ -226,18 +233,28 @@ fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool false } -/// OK: run the paste with the choice; any Swatch Conflict question comes next. +/// The field that holds the uid of the document the paste question is about. +const DOC: &str = "__doc"; + +/// OK: run the paste with the choice; any Swatch Conflict question comes next. When another +/// document has become the active one since a paste that runs at once asked, it closes as Cancel +/// does and pastes nothing. fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = d.str("choice"); if !paste_choices().iter().any(|(v, _)| *v == choice) { let key = "choice"; return Err(format!("`{key}` must be one of {}", "preserveNumbers, convert")); } + let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); + if deferred.is_none() && d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); params["profileMismatch"] = json!(choice); app.ui.dialog = None; // A paste that waited for its clipboard runs in the context it was given in. - crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, d.fields.get("__deferredPaste").and_then(Value::as_u64)) + crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, deferred) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index baed4f62ae..cd69293d22 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -27,10 +27,40 @@ fn rgb_profile(app: &VectorcraftApp) -> Option { vectorcraft_engine::cmd::colormgmt::doc_profiles(&app.session.doc().unwrap().doc).0 } +/// An open asked under automation roots finishes under them, though OK is pressed outside them: its +/// linked files are read, and the document is installed, with the roots of the open. `tagged` asks +/// with the settings in force. +fn open_asked_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-scope"); + let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); + let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None)).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + assert!(file_access::current().is_none(), "OK is pressed outside the roots"); + super::super::confirm(app).unwrap(); + assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the open"); +} + +/// Another document becomes the active one while the paste question is open: OK pastes nothing, into +/// neither document, and the document the paste was asked in is active again afterward. `count` +/// counts the active document's objects. +fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { + let (asked_in, before) = (app.session.active_index().unwrap(), count(app)); + assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND })); + app.run("document.activate", json!({"index": 0})).unwrap(); + let other = count(app); + super::super::confirm(app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(count(app), other, "nothing pasted into the document now active"); + app.run("document.activate", json!({ "index": asked_in })).unwrap(); + assert_eq!(count(app), before, "nor into the one it was asked in"); +} + /// With Color Settings' Ask boxes on, File › Open asks about a document whose profile is not the /// working space, or that has none, and opens it as chosen; Cancel doesn't open it, and a refused /// choice keeps the dialog. Paste asks about colors from another profile and pastes as chosen. With -/// the boxes off, nothing asks. +/// the boxes off, nothing asks. An open asked under automation roots finishes under them, and a +/// paste asked in one document pastes nothing once another is active. #[test] fn opening_and_pasting_ask_about_profiles() { const CHILD: &str = "VECTORCRAFT_TEST_PROFILE_PROMPTS"; @@ -88,6 +118,8 @@ fn opening_and_pasting_ask_about_profiles() { assert_eq!(app.session.documents().len(), docs + 1); assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB), "kept, though the policy converts"); + open_asked_under_roots(&mut app, &tagged); + // Missing Profiles: Ask When Opening, and a choice the file refuses. app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); crate::io::open_bytes(&mut app, "plain.vectorcraft", &plain, None).unwrap(); @@ -127,6 +159,7 @@ fn opening_and_pasting_ask_about_profiles() { app.run("edit.paste", json!({})).unwrap(); super::super::cancel(&mut app); assert_eq!(count(&app), before); + paste_asked_before_another_document_is_active(&mut app, count); app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); let r = app.run("edit.paste", json!({})).unwrap(); assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); From 5d75eb447549560dc299db1f9814227b78323322 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:50:32 -0800 Subject: [PATCH 03/10] Color Settings: a drag between documents asks about profile mismatches as Paste does - edit.dropSelection takes profileMismatch and reports what it did, and clipboard.profileMismatch {sourceDocument, ids} lists what a drop brings, so with Ask When Pasting on the desktop app asks before a drag from a document with another profile. - OK on the paste question asks again when the profiles the paste or drop brings have changed since it asked. - A profile question for an open runs under the automation roots in force where it was asked and those of the caller that confirms it. - An assignProfile beside another choice than assign is refused with a message that says it goes with assign only, with catalog rows. - edit.pasteWithoutFormatting's params text names profileMismatch, and two doc comments and a docs/mcp.md paragraph are rewrapped. --- crates/engine/src/cmd/clipboard.rs | 14 ++-- crates/engine/src/cmd/colormgmt.rs | 10 ++- crates/engine/src/cmd/edit.rs | 57 ++++++++++------ crates/engine/src/cmd/typemenu.rs | 2 +- crates/engine/src/file_access.rs | 65 ++++++++++++++++++- crates/engine/tests/color_settings.rs | 55 ++++++++++++++++ crates/ui-egui/src/app/commands.rs | 6 ++ .../ui-egui/src/dialogs/profile_mismatch.rs | 56 +++++++++++----- .../src/dialogs/profile_mismatch/tests.rs | 56 +++++++++++++++- 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/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 + docs/mcp.md | 9 +-- docs/target-app-parity.md | 2 +- 39 files changed, 301 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 16e1ba7e05..4da417940d 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Paste Profile Mismatch", [], None, - "{} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\"}]} the color models whose colors the copied objects use and whose profile in the document they were copied from (its assigned profile, else the working space then) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* {profileMismatch} says, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", + "{sourceDocument?, ids?: as edit.dropSelection} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\"}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", has_doc, profile_mismatch ), @@ -441,8 +441,8 @@ impl Clipboard { /// The clipboard with every color of its objects and of the resources it carries (swatches, /// symbols, patterns, graphic styles, brushes, character and paragraph styles, the background - /// colors of copied artboards) mapped by `conv`, - /// as Document Color Mode maps a document's ([`super::colormgmt::convert_art_and_style_colors`]). + /// colors of copied artboards) mapped by `conv`, as Document Color Mode maps a document's + /// ([`super::colormgmt::convert_art_and_style_colors`]). /// Images keep their pixels. pub(crate) fn with_colors(&self, conv: &dyn Fn(&vectorcraft_color::Color) -> vectorcraft_color::Color) -> Self { let mut d = self.to_document(); @@ -572,8 +572,12 @@ fn conflicts(s: &mut Session, p: &Value) -> Result { Ok(json!({ "swatches": list })) } -fn profile_mismatch(s: &mut Session, _: &Value) -> Result { - let list: Vec = super::colormgmt::paste_mismatches(&s.clipboard, &s.doc()?.doc).iter().map(|m| m.to_json()).collect(); +fn profile_mismatch(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "clipboard.profileMismatch"; + // With `sourceDocument` and `ids`, the objects a drop brings, else the clipboard's. + let dropped = if p.get("sourceDocument").is_some() || p.get("ids").is_some() { Some(super::edit::drop_clip(s, p, CMD)?) } else { None }; + let clip = dropped.as_ref().unwrap_or(&s.clipboard); + let list: Vec = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc).iter().map(|m| m.to_json()).collect(); Ok(json!({ "mismatches": list })) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 64ada14948..6afb68ef45 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -750,7 +750,8 @@ impl ProfileChoice { }; // `assignProfile` goes with `assign` only. if profile.is_some() && !matches!(choice, ProfileChoice::Assign(_)) { - return Err(bad(cmd, format!("`{key}` must be one of {}", "assign"))); + let path = "assignProfile"; + return Err(bad(cmd, format!("`{path}` goes with `{key}`: \"assign\" only"))); } Ok(choice) } @@ -1045,11 +1046,8 @@ pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcra /// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into /// the destination's with the working intent, as `choice` says (default: each model's policy, /// [`PasteProfile::of`]). A source or destination profile that is not available keeps the numbers. -/// → the -/// converted clipboard (`None` when nothing converts; its resources paste as another document's) -/// and a -/// line for each mismatched model -/// (`{model, clipboard, document, choice}`). +/// → the converted clipboard (`None` when nothing converts; its resources paste as another +/// document's) and a line for each mismatched model (`{model, clipboard, document, choice}`). pub(crate) fn paste_profiles( clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 4bad97641b..abf8dd7e4e 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -114,7 +114,7 @@ pub fn specs() -> Vec { "Drop Artwork", [], None, - "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as edit.colorSettings' policy of their model says (as edit.paste without profileMismatch)", + "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y], profileMismatch?: \"preserveNumbers\"|\"convert\"} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as profileMismatch says, else as edit.colorSettings' policy of their model says (as edit.paste; clipboard.profileMismatch {sourceDocument, ids} lists them, and with askMismatchPaste on the desktop app asks first) → {ids, added, merged, renamed, profileMismatch?}", has_doc, drop_selection ), @@ -1196,26 +1196,12 @@ fn clear(s: &mut Session, p: &Value) -> Result { /// Document ids scope node ids: two tabs may contain objects with the same node id. fn drop_selection(s: &mut Session, p: &Value) -> Result { const CMD: &str = "edit.dropSelection"; - let uid = u64_req(p, "sourceDocument", CMD)?; + u64_req(p, "sourceDocument", CMD)?; let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates"))); let grab = point("grab")?; let at = point("at")?; - let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(CMD, "that document is no longer open"))?; - let key = "ids"; - let values = p[key].as_array().ok_or_else(|| bad(CMD, format!("{key} must be an array of non-negative integer object ids")))?; - if values.is_empty() || values.len() > 10000 { - return Err(bad(CMD, "ids must contain 1–10000 object ids")); - } - let ids = values - .iter() - .map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(CMD, format!("invalid object id {value}: expected a non-negative integer")))) - .collect::>>()?; - // Validate the entire batch in one walk; node ids are local to the source document. - let paths = source.doc.index_paths(ids.iter().copied()); - if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { - return Err(EngineError::NoNode(*id)); - } - let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false); + let profile = super::colormgmt::PasteProfile::param(p, CMD)?; + let clip = drop_clip(s, p, CMD)?; let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?; let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]); if !center.x.is_finite() || !center.y.is_finite() { @@ -1223,9 +1209,38 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { } // A drop preserves the source colours even when the flyer has same-named swatches. let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?; - // Colors from another profile keep their numbers or convert as the policies say. - let (converted, _) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, None); - paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices) + // Colors from another profile keep their numbers or convert, as `profileMismatch` says, else as + // the policies say. + let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile); + let mut r = paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices); + if let Ok(v) = &mut r + && !report.is_empty() + { + v["profileMismatch"] = json!(report); + } + r +} + +/// The objects `ids` of the open document `sourceDocument` that `edit.dropSelection` drops, copied +/// as a clipboard is (errors name command `cmd`). +pub(crate) fn drop_clip(s: &Session, p: &Value, cmd: &str) -> Result { + let uid = u64_req(p, "sourceDocument", cmd)?; + let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(cmd, "that document is no longer open"))?; + let key = "ids"; + let values = p[key].as_array().ok_or_else(|| bad(cmd, format!("{key} must be an array of non-negative integer object ids")))?; + if values.is_empty() || values.len() > 10000 { + return Err(bad(cmd, "ids must contain 1–10000 object ids")); + } + let ids = values + .iter() + .map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(cmd, format!("invalid object id {value}: expected a non-negative integer")))) + .collect::>>()?; + // Validate the entire batch in one walk; node ids are local to the source document. + let paths = source.doc.index_paths(ids.iter().copied()); + if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { + return Err(EngineError::NoNode(*id)); + } + Ok(Clipboard::copy(source, &roots_of(&source.doc, ids), false)) } #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 0701f6eeca..0e65299b5f 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -138,7 +138,7 @@ pub fn specs() -> Vec { "Paste without Formatting", ["Edit"], Some("Cmd+Alt+V"), - "{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}", + "{center?, dx?, dy?, swatchConflict?, profileMismatch?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}", has_clipboard, paste_plain ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 3c203b64ee..78e53742fd 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -46,7 +46,7 @@ pub struct AutomationRoots { write: Vec, } -#[derive(Debug)] +#[derive(Clone, Debug)] struct Root { /// The folder made absolute, links followed: what paths are compared with. resolved: PathBuf, @@ -126,6 +126,25 @@ impl AutomationRoots { } } + /// The roots that grant only what both `self` and `other` grant: for each kind, every root of + /// one that lies inside a root of the other. A kind left with none grants no access of its kind. + pub fn intersect(&self, other: &Self) -> Arc { + let both = |a: &[Root], b: &[Root]| { + let mut out: Vec = Vec::new(); + for r in a + .iter() + .filter(|r| b.iter().any(|o| inside(&r.resolved, &o.resolved))) + .chain(b.iter().filter(|o| a.iter().any(|r| inside(&o.resolved, &r.resolved)))) + { + if !out.iter().any(|o| o.resolved == r.resolved) { + out.push(r.clone()); + } + } + out + }; + Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) }) + } + /// The roots for people: `read A, B; write C` (`none` for a kind without any). pub fn describe(&self) -> String { let list = |roots: &[Root]| { @@ -199,6 +218,27 @@ impl ScopeHandle { pub fn run(self, f: impl FnOnce() -> T) -> T { with_scope(self.0, f) } + + /// The roots in force in this scope, if any (as [`current`] gives them on its thread). + fn roots(&self) -> Option> { + match &self.0 { + Some(Scope::Confined(r)) => Some(r.clone()), + Some(Scope::Unconfined) => None, + None => PROCESS.get().cloned(), + } + } + + /// The captured scope narrowed to what the calling thread may reach as well: the roots of both + /// are in force ([`AutomationRoots::intersect`]), and without roots in either, none are. + pub fn within_current(self) -> Self { + let here = Self::capture(); + match (self.roots(), here.roots()) { + (None, None) => self, + (Some(r), None) | (None, Some(r)) => Self(Some(Scope::Confined(r))), + (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Self(Some(Scope::Confined(a))), + (Some(a), Some(b)) => Self(Some(Scope::Confined(a.intersect(&b)))), + } + } } /// The roots in force on this thread, if any. @@ -615,6 +655,29 @@ mod tests { p.to_string_lossy().into_owned() } + /// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind + /// only one grants is not granted. + #[test] + fn intersected_roots_grant_what_both_grant() { + let (base, roots) = folders("intersect"); + let narrow = AutomationRoots::new(&[&base.join("in/sub"), &base.join("in2")], &[]).unwrap().unwrap(); + let both = roots.intersect(&narrow); + assert_eq!(both.check(&s(base.join("in/sub/x.svg")), Access::Read), Ok(())); + assert!(both.check(&s(base.join("in/a.svg")), Access::Read).is_err(), "only the narrow root grants it"); + assert!(both.check(&s(base.join("in2")), Access::Read).is_err(), "only the narrow roots grant it"); + assert!(both.check(&s(base.join("out/x.svg")), Access::Write).is_err(), "only the first grants writes"); + assert_eq!(both.describe(), narrow.intersect(&roots).describe(), "either order"); + let unconfined = ScopeHandle(Some(Scope::Unconfined)); + let within = |saved: ScopeHandle, here: Option<&Arc>| { + confine(here, || saved.within_current()).run(|| current().map(|r| r.describe())) + }; + assert_eq!(within(unconfined.clone(), Some(&narrow)), Some(narrow.describe()), "a confined caller keeps its roots"); + assert_eq!(within(ScopeHandle(Some(Scope::Confined(roots.clone()))), None), Some(roots.describe()), "the saved roots stay"); + assert_eq!(within(ScopeHandle(Some(Scope::Confined(roots.clone()))), Some(&narrow)), Some(both.describe())); + assert!(unconfined.run(|| current().is_none())); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 58f7076b05..6188001b06 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1372,3 +1372,58 @@ fn paste_keeps_or_converts_colors_from_another_profile() { assert!(r.get("profileMismatch").is_none()); assert_eq!(same, blue0); } + +/// A drag between documents is a paste for Profile Mismatches: clipboard.profileMismatch with +/// `sourceDocument` and `ids` lists what the drop brings, edit.dropSelection takes `profileMismatch` +/// and reports what it did, and a wrong choice drops nothing. +#[test] +fn a_drop_takes_the_profile_mismatch_choice() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let source = s.documents()[0].uid; + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([]), "the clipboard is empty"); + let dragged = json!({"sourceDocument": source, "ids": [blue.0]}); + assert_eq!( + exec(&mut s, "clipboard.profileMismatch", dragged.clone())["mismatches"], + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": cms::canonical_name(cms::SRGB), "default": "preserveNumbers"}]) + ); + for bad in [json!({"sourceDocument": source}), json!({"ids": [blue.0]}), json!({"sourceDocument": 999_999, "ids": [blue.0]})] { + assert!(s.execute("clipboard.profileMismatch", &bad).is_err(), "{bad}"); + } + let dropped = |s: &mut Session, choice: Option<&str>| { + let mut p = json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50]}); + if let Some(c) = choice { + p["profileMismatch"] = json!(c); + } + let r = exec(s, "edit.dropSelection", p); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + (r, s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap()) + }; + let (r, kept) = dropped(&mut s, None); + assert_eq!((kept, &r["profileMismatch"][0]["choice"]), (blue0, &json!("preserveNumbers")), "the policy keeps the numbers"); + let (r, moved) = dropped(&mut s, Some("convert")); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let from = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(moved != blue0 && cms::delta_e2000(from.lab(&blue0), cms::working().lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = objects(&s); + let bad = json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50], "profileMismatch": "keep"}); + assert!(s.execute("edit.dropSelection", &bad).is_err()); + assert_eq!(objects(&s), before, "a refused choice drops nothing"); +} + +/// `assignProfile` beside another choice than `assign` is refused with a message that says it goes +/// with `assign` only. +#[test] +fn assign_profile_goes_with_assign_only() { + let _g = settings(); + let ProfileFiles { tagged, .. } = &profile_files("profile-assign-only"); + let err = open_with(tagged, json!({"profileChoice": "discard", "assignProfile": cms::DISPLAY_P3})).0.unwrap_err(); + assert!(err.contains("`assignProfile` goes with `profileChoice`: \"assign\" only"), "{err}"); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 5024e2c26e..085797f184 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -222,6 +222,12 @@ impl VectorcraftApp { return r; } } + // A drag from another document asks as Paste does (its swatches are always added). + if id == dialogs::profile_mismatch::DROP + && let Some(r) = dialogs::profile_mismatch::ask_paste(self, id, ¶ms) + { + return r; + } // Native files carry the view they reopen at. if fileio::SaveMode::of(id).is_some() { io::remember_view(self); diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index 83b8bdb030..10a1425a9e 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -10,11 +10,11 @@ //! | `missing`), `name` (the file's), `model` (`RGB` | `CMYK`), `profile` (the one it is tagged //! with), `working`, `choice` (a `profileChoice` of `document.open`) and `assignProfile`. //! -//! Pasting ([`PASTE_KIND`]): colors copied from a document whose profile is not this document's ask -//! whether to keep their numbers or convert them. OK runs the paste with `profileMismatch`; Cancel -//! pastes nothing. Fields: `mismatches` (as `clipboard.profileMismatch` lists them), `choice` -//! (`preserveNumbers` | `convert`), `__command` and `__params` (the paste to run), and `__doc` (the -//! uid of the document it was asked in). +//! Pasting ([`PASTE_KIND`]): colors copied, or dragged ([`DROP`]), from a document whose profile is +//! not this document's ask whether to keep their numbers or convert them. OK runs the paste or the +//! drop with `profileMismatch`; Cancel pastes or drops nothing. Fields: `mismatches` (as +//! `clipboard.profileMismatch` lists them), `choice` (`preserveNumbers` | `convert`), `__command` +//! and `__params` (the paste or drop to run), and `__doc` (the uid of the document it was asked in). use serde_json::{Value, json}; use vectorcraft_color::cms::{self, ProfileKind}; @@ -31,6 +31,8 @@ use crate::{VectorcraftApp, widgets}; pub const OPEN_KIND: &str = "profileMismatchOpen"; /// The dialog kind of the question pasting asks. pub const PASTE_KIND: &str = "profileMismatchPaste"; +/// The command a drag of artwork from another document runs, which asks as a paste does. +pub const DROP: &str = "edit.dropSelection"; pub(super) const OPEN_SPEC: DialogSpec = DialogSpec { heading: |d| if d.str("issue") == "missing" { tl!("Missing Profile") } else { tl!("Embedded Profile Mismatch") }.into(), @@ -56,7 +58,7 @@ pub(crate) struct PendingOpen { /// Where it was read from: it goes on the recent files once it opens. path: Option, /// The automation roots in force where the open was asked for: its linked files are read, and - /// the document is installed, under them. + /// the document is installed, under them and those of the caller that confirms. scope: ScopeHandle, } @@ -147,20 +149,21 @@ fn open_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool false } -/// OK: open the waiting file as chosen, under the automation roots of the open. A choice the file -/// refuses keeps the dialog open. +/// OK: open the waiting file as chosen, under the automation roots of the open and those of the +/// caller that confirms both. A choice the file refuses keeps the dialog open. fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = open_choice(d)?; let Some(mut pending) = app.pending_profile_open.take() else { app.ui.dialog = None; return Ok(Value::Null); }; - if let Err(e) = pending.scope.clone().run(|| pending.file.answer(choice)) { + let scope = pending.scope.clone().within_current(); + if let Err(e) = scope.clone().run(|| pending.file.answer(choice)) { app.pending_profile_open = Some(pending); return Err(e.to_string()); } app.ui.dialog = None; - let PendingOpen { file, path, scope } = pending; + let PendingOpen { file, path, .. } = pending; let name = file.name(); scope.run(|| match fileio::open_read(&mut app.session, file) { Ok(r) => { @@ -190,15 +193,15 @@ pub(crate) fn settle(app: &mut VectorcraftApp) { } } -/// Before running paste `command` with `params`: when Ask When Pasting is on, `params` don't say -/// what to do (`profileMismatch`) and the pasted colors come from another profile, open the dialog -/// instead and answer `{dialog}`. +/// Before running paste `command` (or `edit.dropSelection`, a drag from another document) with +/// `params`: when Ask When Pasting is on, `params` don't say what to do (`profileMismatch`) and the +/// pasted or dropped colors come from another profile, open the dialog instead and answer +/// `{dialog}`. pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option { if params.get("profileMismatch").is_some() || !cms::working_settings().ask_mismatch_paste { return None; } - let found = app.session.execute("clipboard.profileMismatch", &json!({})).ok()?; - let mismatches = found["mismatches"].as_array().filter(|a| !a.is_empty())?.clone(); + let mismatches = paste_mismatches(app, command, params).filter(|a| !a.is_empty())?; // The policy of the first model starts chosen. let choice = mismatches[0]["default"].as_str().unwrap_or("preserveNumbers").to_string(); let doc = app.session.active().map(|st| st.uid); @@ -211,6 +214,14 @@ pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Opt Some(Ok(json!({ "dialog": PASTE_KIND }))) } +/// The models whose profiles differ for paste `command` with `params` (`clipboard.profileMismatch`): +/// a drop brings the objects it names, a paste the clipboard's. `None` when they can't be listed. +fn paste_mismatches(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { + let query = if command == DROP { json!({ "sourceDocument": params.get("sourceDocument"), "ids": params.get("ids") }) } else { json!({}) }; + let found = app.session.execute("clipboard.profileMismatch", &query).ok()?; + found["mismatches"].as_array().cloned() +} + fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let mismatches = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); for m in &mismatches { @@ -238,7 +249,8 @@ const DOC: &str = "__doc"; /// OK: run the paste with the choice; any Swatch Conflict question comes next. When another /// document has become the active one since a paste that runs at once asked, it closes as Cancel -/// does and pastes nothing. +/// does and pastes nothing. When the profiles that paste or drop would bring have changed since it +/// asked (the clipboard or the dragged objects' document changed), it asks again about the new ones. fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = d.str("choice"); if !paste_choices().iter().any(|(v, _)| *v == choice) { @@ -250,11 +262,21 @@ fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { app.ui.dialog = None; return Ok(json!({})); } + let command = d.str("__command"); let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + if deferred.is_none() + && let Some(now) = paste_mismatches(app, &command, ¶ms).filter(|a| !a.is_empty()) + && d.fields.get("mismatches").and_then(Value::as_array) != Some(&now) + { + app.ui.dialog = None; + if let Some(r) = ask_paste(app, &command, ¶ms) { + return r; + } + } params["profileMismatch"] = json!(choice); app.ui.dialog = None; // A paste that waited for its clipboard runs in the context it was given in. - crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, deferred) + crate::placing::confirm_swatch_paste(app, &command, params, deferred) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index cd69293d22..e23f1a6f06 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -41,6 +41,18 @@ fn open_asked_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the open"); } +/// An open asked outside automation roots and confirmed by a caller under them finishes under that +/// caller's roots: the document is installed with them. `tagged` asks with the settings in force. +fn open_confirmed_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-confirm-scope"); + let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); + let r = crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + file_access::confine(roots.as_ref(), || super::super::confirm(app)).unwrap(); + assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the caller that confirmed"); +} + /// Another document becomes the active one while the paste question is open: OK pastes nothing, into /// neither document, and the document the paste was asked in is active again afterward. `count` /// counts the active document's objects. @@ -56,11 +68,46 @@ fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp, count assert_eq!(count(app), before, "nor into the one it was asked in"); } +/// A drag of the art of the document assigned Display P3 into the active one asks as Paste does: +/// Cancel drops nothing, and OK drops it as chosen. When the source document's profile changes while +/// the question is open, OK drops nothing and asks again about the new profile. `count` counts the +/// active document's objects. +fn drop_asks_as_paste_does(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { + let p3 = Some(cms::DISPLAY_P3); + let docs = app.session.documents(); + let at = docs.iter().position(|st| vectorcraft_engine::cmd::colormgmt::doc_profiles(&st.doc).0.as_deref() == p3).unwrap(); + let source = &docs[at]; + let ids: Vec = source.doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let n = ids.len(); + let drop = json!({"sourceDocument": source.uid, "ids": ids, "grab": [0, 0], "at": [50, 50]}); + let before = count(app); + assert_eq!(app.run(DROP, drop.clone()).unwrap(), json!({ "dialog": PASTE_KIND })); + assert_eq!(count(app), before, "nothing dropped yet"); + super::super::cancel(app); + assert_eq!(count(app), before, "Cancel drops nothing"); + assert_eq!(app.run(DROP, drop).unwrap(), json!({ "dialog": PASTE_KIND })); + // The source document is assigned another profile before OK. + let asked_in = app.session.active_index().unwrap(); + app.run("document.activate", json!({ "index": at })).unwrap(); + app.session.execute("edit.assignProfile", &json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("document.activate", json!({ "index": asked_in })).unwrap(); + assert_eq!(super::super::confirm(app).unwrap(), json!({ "dialog": PASTE_KIND })); + assert_eq!(count(app), before, "nothing dropped under the old question"); + let asked = &app.ui.dialog.as_ref().unwrap().fields["mismatches"][0]["clipboard"]; + assert_eq!(asked, &json!(cms::WIDE_GAMUT_RGB), "asked again about the new profile"); + set(app, "choice", json!("convert")); + let r = super::super::confirm(app).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + assert!(app.ui.dialog.is_none()); + assert_eq!(count(app), before + n); +} + /// With Color Settings' Ask boxes on, File › Open asks about a document whose profile is not the /// working space, or that has none, and opens it as chosen; Cancel doesn't open it, and a refused -/// choice keeps the dialog. Paste asks about colors from another profile and pastes as chosen. With -/// the boxes off, nothing asks. An open asked under automation roots finishes under them, and a -/// paste asked in one document pastes nothing once another is active. +/// choice keeps the dialog. Paste, and a drag from another document, ask about colors from another +/// profile and paste or drop as chosen. With the boxes off, nothing asks. An open asked or confirmed +/// under automation roots finishes under them, and a paste asked in one document pastes nothing once +/// another is active. #[test] fn opening_and_pasting_ask_about_profiles() { const CHILD: &str = "VECTORCRAFT_TEST_PROFILE_PROMPTS"; @@ -119,6 +166,7 @@ fn opening_and_pasting_ask_about_profiles() { assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB), "kept, though the policy converts"); open_asked_under_roots(&mut app, &tagged); + open_confirmed_under_roots(&mut app, &tagged); // Missing Profiles: Ask When Opening, and a choice the file refuses. app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); @@ -160,6 +208,8 @@ fn opening_and_pasting_ask_about_profiles() { super::super::cancel(&mut app); assert_eq!(count(&app), before); paste_asked_before_another_document_is_active(&mut app, count); + drop_asks_as_paste_does(&mut app, count); + let before = count(&app); app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); let r = app.run("edit.paste", json!({})).unwrap(); assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 14e48d1f43..101c812ce9 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5085,6 +5085,7 @@ axis Both И двете Assign profile: Задаване на профил: Preserve the color numbers Запазване на цветовите стойности Convert to keep the colors' appearance Преобразуване със запазване на вида на цветовете +@msg `{path}` goes with `{key}`: "assign" only `{path}` се използва само с `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Поставените цветове идват от документ с {model} профил „{from}“; профилът на този документ е „{to}“. Texture Текстура Craquelure… Кракелюр… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index df82af1a3a..b5a94e4f5f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1008,6 +1008,7 @@ Assign profile: Dodijeli profil: Preserve the color numbers Zadrži brojeve boja Convert to keep the colors' appearance Pretvori da boje zadrže izgled +@msg `{path}` goes with `{key}`: "assign" only `{path}` ide samo uz `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Zalijepljene boje dolaze iz dokumenta čiji je {model} profil „{from}”; profil ovog dokumenta je „{to}”. CMYK CMYK Texture Tekstura diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 07fddd5206..d695701d8f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -787,6 +787,7 @@ antiAlias Sharp Nítid Assign profile: Assigna el perfil: Preserve the color numbers Conserva els valors dels colors Convert to keep the colors' appearance Converteix per conservar l’aspecte dels colors +@msg `{path}` goes with `{key}`: "assign" only `{path}` només va amb `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Els colors enganxats provenen d’un document amb el perfil {model} “{from}”; el d’aquest document és “{to}”. Coarse Dots Punts gruixuts Collapse Panel Group Replega el grup de panells diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 37a8b39b56..d4a951bc2e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1027,6 +1027,7 @@ Assign profile: Přiřadit profil: Preserve the color numbers Zachovat hodnoty barev Convert to keep the colors' appearance Převést a zachovat vzhled barev +@msg `{path}` goes with `{key}`: "assign" only `{path}` patří jen k `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Vložené barvy pocházejí z dokumentu s profilem {model} „{from}“; tento dokument má „{to}“. CMYK CMYK Texture Textura diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0dc7640ab7..e95462fcab 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1574,6 +1574,7 @@ Assign profile: Tildel profil: Preserve the color numbers Bevar farveværdierne Convert to keep the colors' appearance Konverter for at bevare farvernes udseende +@msg `{path}` goes with `{key}`: "assign" only `{path}` hører kun til `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. De indsatte farver kommer fra et dokument med {model}-profilen »{from}«; dette dokuments er »{to}«. CMYK CMYK Texture Tekstur diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 88154a2e81..58cab3780d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5413,6 +5413,7 @@ theme Appearance Erscheinungsbild Assign profile: Profil zuweisen: Preserve the color numbers Farbwerte beibehalten Convert to keep the colors' appearance Konvertieren, um das Aussehen der Farben zu erhalten +@msg `{path}` goes with `{key}`: "assign" only `{path}` gehört nur zu `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Die eingefügten Farben stammen aus einem Dokument mit dem {model}-Profil „{from}“; dieses Dokument hat „{to}“. # PSD files. @msg not a PSD file keine PSD-Datei diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b2468c11da..5b35d27536 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5397,6 +5397,7 @@ digits Malayalam Μαλαγιάλαμ Assign profile: Αντιστοίχιση προφίλ: Preserve the color numbers Διατήρηση των αριθμών των χρωμάτων Convert to keep the colors' appearance Μετατροπή με διατήρηση της εμφάνισης των χρωμάτων +@msg `{path}` goes with `{key}`: "assign" only το `{path}` συνδυάζεται μόνο με `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Τα χρώματα που επικολλήθηκαν προέρχονται από έγγραφο με προφίλ {model} «{from}»· το προφίλ αυτού του εγγράφου είναι «{to}». System Title Bar Γραμμή τίτλου συστήματος VectorCraft Title Bar on Every Desktop Γραμμή τίτλου του VectorCraft σε κάθε επιφάνεια εργασίας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 412a082e21..1495072b27 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5442,6 +5442,7 @@ axis Both Ambos Assign profile: Asignar perfil: Preserve the color numbers Conservar los valores de color Convert to keep the colors' appearance Convertir para conservar el aspecto de los colores +@msg `{path}` goes with `{key}`: "assign" only `{path}` solo va con `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Los colores pegados provienen de un documento con el perfil {model} “{from}”; el de este documento es “{to}”. Texture Textura Craquelure… Craquelado… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2183145810..2e5bae49f1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1011,6 +1011,7 @@ Assign profile: Määritä profiili: Preserve the color numbers Säilytä värien lukuarvot Convert to keep the colors' appearance Muunna ja säilytä värien ulkoasu +@msg `{path}` goes with `{key}`: "assign" only `{path}` annetaan vain, kun `{key}` on "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Liitetyt värit ovat asiakirjasta, jonka {model}-profiili on ”{from}”; tämän asiakirjan profiili on ”{to}”. CMYK CMYK Texture Tekstuuri diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 69ceeb13d7..3f0df8f515 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5437,6 +5437,7 @@ axis Both Les deux Assign profile: Attribuer le profil : Preserve the color numbers Conserver les valeurs des couleurs Convert to keep the colors' appearance Convertir pour conserver l’aspect des couleurs +@msg `{path}` goes with `{key}`: "assign" only `{path}` ne s’utilise qu’avec `{key}` : "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Les couleurs collées proviennent d’un document dont le profil {model} est « {from} » ; celui de ce document est « {to} ». Texture Texture Craquelure… Craquelure… diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 207016d86b..dde69aa3cf 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -494,6 +494,7 @@ Assign profile: પ્રોફાઇલ સોંપો: Preserve the color numbers રંગોની સંખ્યાઓ જાળવો Convert to keep the colors' appearance રંગોનો દેખાવ જાળવવા રૂપાંતરિત કરો +@msg `{path}` goes with `{key}`: "assign" only `{path}` ફક્ત `{key}`: "assign" સાથે જ વપરાય છે The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. પેસ્ટ કરેલા રંગો એવા દસ્તાવેજમાંથી આવે છે જેની {model} પ્રોફાઇલ “{from}” છે; આ દસ્તાવેજની “{to}” છે. CSS Properties CSS ગુણધર્મો Calligraphic Brush કેલિગ્રાફિક બ્રશ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index c7a2c50216..68bc521748 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -914,6 +914,7 @@ antiAlias Sharp शार्प Assign profile: प्रोफ़ाइल असाइन करें: Preserve the color numbers रंगों की संख्याएँ बनाए रखें Convert to keep the colors' appearance रंगों का रूप बनाए रखने के लिए बदलें +@msg `{path}` goes with `{key}`: "assign" only `{path}` केवल `{key}`: "assign" के साथ उपयोग होता है The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. पेस्ट किए गए रंग ऐसे दस्तावेज़ से आए हैं जिसकी {model} प्रोफ़ाइल "{from}" है; इस दस्तावेज़ की "{to}" है। Coarse Dots मोटे बिंदु Coincidence: संयोग: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index dcdfaf3046..b4bf7dc184 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -718,6 +718,7 @@ font-technology Variable Változó Assign profile: Profil hozzárendelése: Preserve the color numbers A színértékek megtartása Convert to keep the colors' appearance Konvertálás a színek megjelenésének megtartásával +@msg `{path}` goes with `{key}`: "assign" only `{path}` csak a(z) `{key}`: "assign" értékkel használható The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. A beillesztett színek olyan dokumentumból származnak, amelynek {model}-profilja „{from}”; ennek a dokumentumnak „{to}”. Coarse Dots Durva pontok Collapse Panels to Icons Panelek ikonná csukása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 86250b7445..12dae26cfa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -950,6 +950,7 @@ Assign profile: Tetapkan profil: Preserve the color numbers Pertahankan angka warna Convert to keep the colors' appearance Konversi agar tampilan warna tetap sama +@msg `{path}` goes with `{key}`: "assign" only `{path}` hanya dipakai dengan `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Warna yang ditempel berasal dari dokumen dengan profil {model} “{from}”; profil dokumen ini “{to}”. CMYK CMYK Texture Tekstur diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 104b96e1e6..95a3970c56 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5481,6 +5481,7 @@ axis Both Entrambi Assign profile: Assegna profilo: Preserve the color numbers Mantieni i valori dei colori Convert to keep the colors' appearance Converti per mantenere l'aspetto dei colori +@msg `{path}` goes with `{key}`: "assign" only `{path}` va solo con `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. I colori incollati provengono da un documento con profilo {model} “{from}”; quello di questo documento è “{to}”. Texture Texture Craquelure… Craquelé… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 967db8d3d3..965535cc3f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5523,6 +5523,7 @@ swatch Bright Violet ビビッドバイオレット Assign profile: プロファイルを割り当て: Preserve the color numbers カラーの数値を保持 Convert to keep the colors' appearance カラーの見た目を保つように変換 +@msg `{path}` goes with `{key}`: "assign" only `{path}` は `{key}`: "assign" のときだけ指定してください The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. ペーストしたカラーは {model} プロファイルが「{from}」のドキュメントのものです。このドキュメントのプロファイルは「{to}」です。 Texture テクスチャ Craquelure… クラッキング… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 81c5545219..9755f53d30 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3001,6 +3001,7 @@ Assign profile: პროფილის მინიჭება: Preserve the color numbers ფერების რიცხვების შენარჩუნება Convert to keep the colors' appearance გადაყვანა ფერების იერსახის შესანარჩუნებლად +@msg `{path}` goes with `{key}`: "assign" only `{path}` გამოიყენება მხოლოდ `{key}`: "assign"-თან The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. ჩასმული ფერები მოდის დოკუმენტიდან, რომლის {model} პროფილია „{from}“; ამ დოკუმენტის პროფილია „{to}“. CMYK CMYK Texture ტექსტურა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a6b20868b6..ed4551d3be 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5450,6 +5450,7 @@ theme Appearance 외관 Assign profile: 프로필 지정: Preserve the color numbers 색상 값 유지 Convert to keep the colors' appearance 색상의 모양을 유지하도록 변환 +@msg `{path}` goes with `{key}`: "assign" only `{path}`은(는) `{key}`: "assign"일 때만 씁니다 The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. 붙여넣은 색상은 {model} 프로필이 “{from}”인 문서에서 왔습니다. 이 문서의 프로필은 “{to}”입니다. Texture 텍스처 Craquelure… 크랙… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 62b5cfae5a..5a33757e91 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1470,6 +1470,7 @@ Assign profile: Profiel toewijzen: Preserve the color numbers Kleurwaarden behouden Convert to keep the colors' appearance Omzetten zodat de kleuren er hetzelfde uitzien +@msg `{path}` goes with `{key}`: "assign" only `{path}` hoort alleen bij `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. De geplakte kleuren komen uit een document met het {model}-profiel „{from}”; dat van dit document is „{to}”. CMYK CMYK Texture Textuur diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1dcb89322b..7d118d330b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -968,6 +968,7 @@ Assign profile: Przypisz profil: Preserve the color numbers Zachowaj wartości kolorów Convert to keep the colors' appearance Konwertuj, aby zachować wygląd kolorów +@msg `{path}` goes with `{key}`: "assign" only `{path}` łączy się tylko z `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Wklejone kolory pochodzą z dokumentu z profilem {model} „{from}”; profil tego dokumentu to „{to}”. CMYK CMYK Texture Tekstura diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 47264adf58..7e6d932354 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3538,6 +3538,7 @@ imageTrace Outline Contorno Assign profile: Atribuir perfil: Preserve the color numbers Preservar os valores das cores Convert to keep the colors' appearance Converter para manter a aparência das cores +@msg `{path}` goes with `{key}`: "assign" only `{path}` só acompanha `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. As cores coladas vêm de um documento com o perfil {model} “{from}”; o deste documento é “{to}”. Texture Textura Craquelure… Craquelê… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f3996b9c1e..2d6472cfa5 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5481,6 +5481,7 @@ axis Both Оба Assign profile: Назначить профиль: Preserve the color numbers Сохранить числовые значения цветов Convert to keep the colors' appearance Преобразовать, сохранив вид цветов +@msg `{path}` goes with `{key}`: "assign" only `{path}` используется только с `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Вставленные цвета взяты из документа с профилем {model} «{from}»; у этого документа профиль «{to}». Texture Текстура Craquelure… Кракелюры… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 057785be43..8ed16d5bda 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5350,6 +5350,7 @@ axis Both Båda Assign profile: Tilldela profil: Preserve the color numbers Behåll färgvärdena Convert to keep the colors' appearance Konvertera så att färgerna ser likadana ut +@msg `{path}` goes with `{key}`: "assign" only `{path}` hör bara ihop med `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. De inklistrade färgerna kommer från ett dokument med {model}-profilen ”{from}”; det här dokumentets är ”{to}”. Texture Textur Craquelure… Krakelering… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 074521e9cd..4ecc29acb8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5229,6 +5229,7 @@ axis Both Her İkisi Assign profile: Profil ata: Preserve the color numbers Renk değerlerini koru Convert to keep the colors' appearance Renklerin görünümünü korumak için dönüştür +@msg `{path}` goes with `{key}`: "assign" only `{path}` yalnızca `{key}`: "assign" ile kullanılır The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Yapıştırılan renkler {model} profili “{from}” olan bir belgeden geliyor; bu belgeninki “{to}”. Texture Doku Craquelure… Küçük çatlak… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3d08c7b1f9..746994832c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5465,6 +5465,7 @@ axis Both Обидві Assign profile: Призначити профіль: Preserve the color numbers Зберегти числові значення кольорів Convert to keep the colors' appearance Перетворити, зберігши вигляд кольорів +@msg `{path}` goes with `{key}`: "assign" only `{path}` використовується лише з `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Вставлені кольори взято з документа з профілем {model} «{from}»; профіль цього документа «{to}». Texture Текстура Craquelure… Кракелюри… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2abbb5d00e..c0027cd28a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -630,6 +630,7 @@ font-technology Variable Biến thiên Assign profile: Gán cấu hình: Preserve the color numbers Giữ giá trị số của màu Convert to keep the colors' appearance Chuyển đổi để giữ diện mạo của màu +@msg `{path}` goes with `{key}`: "assign" only `{path}` chỉ dùng với `{key}`: "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Màu đã dán đến từ tài liệu có cấu hình {model} “{from}”; cấu hình của tài liệu này là “{to}”. Coarse Dots Chấm thô Collapse Panels to Icons Thu gọn bảng thành biểu tượng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e24406449e..dc7985bb84 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5367,6 +5367,7 @@ imageTrace Outline 轮廓 Assign profile: 指定配置文件: Preserve the color numbers 保留颜色数值 Convert to keep the colors' appearance 转换以保持颜色外观 +@msg `{path}` goes with `{key}`: "assign" only `{path}` 只能与 `{key}`: "assign" 一起给出 The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. 粘贴的颜色来自 {model} 配置文件为“{from}”的文档;此文档的配置文件为“{to}”。 Art & Illustration 艺术和插画 Branding 品牌 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b931b5070a..789e3948db 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5600,6 +5600,7 @@ axis Both 兩者 Assign profile: 指定描述檔: Preserve the color numbers 保留色彩數值 Convert to keep the colors' appearance 轉換以保持色彩外觀 +@msg `{path}` goes with `{key}`: "assign" only `{path}` 只能與 `{key}`: "assign" 一起提供 The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. 貼上的色彩來自 {model} 描述檔為「{from}」的文件;此文件的描述檔為「{to}」。 Texture 紋理 Craquelure… 龜裂紋… diff --git a/docs/mcp.md b/docs/mcp.md index 64d95fe0d8..aa06360460 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1695,10 +1695,11 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR `convert`, `discard`; `leave`, `assignWorking`, `assign` with `assignProfile`) states the answer, else the policy applies, and the reply's `profileChoice` names the answer used. Copy remembers the profiles the colors showed through; pasting them into a document with another RGB or CMYK profile keeps their numbers or converts them, as - `profileMismatch` on the paste commands says, else as the model's policy does (`convert` converts, the others keep - the numbers; a profile that is not available keeps them). `clipboard.profileMismatch` lists the models that differ, only those whose colors the copied objects - use, and with `askMismatchPaste` on the desktop app's Paste asks first. New from Template, File › Revert and a drag - between documents follow the policies without asking. + `profileMismatch` on the paste commands and `edit.dropSelection` says, else as the model's policy does (`convert` + converts, the others keep the numbers; a profile that is not available keeps them). `clipboard.profileMismatch` + lists the models that differ, only those whose colors the copied objects use (with `sourceDocument` and `ids`, the + objects a drop brings), and with `askMismatchPaste` on the desktop app asks first on Paste and on a drag between + documents. New from Template and File › Revert follow the policies without asking. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0c12586f67..701c02ddb4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -766,7 +766,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. When a document tagged with a profile other than the working space is opened, reverted or opened as a template, the policy keeps the profile, takes it off with the color numbers kept, or converts that model's colors into the working space, with black point compensation as Color Settings set it, and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules; placed images are not covered. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `color/src/cms/tests_icc.rs`. -- **Profile Mismatches and Missing Profiles:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has Profile Mismatches: Ask When Opening and Ask When Pasting, and Missing Profiles: Ask When Opening, off by default and kept in `Color Settings.json`. With a box on, File › Open asks before a document opens whose color mode's profile is not the working space (use the embedded profile, convert the colors to the working space, or discard the profile) or that has none (leave it, assign the working space, or assign a profile), and Paste asks whether colors copied from a document with another profile keep their numbers or convert; each starts on what the policy does. `document.open {profileChoice}` and the paste commands' `profileMismatch` give the answer without a prompt, and `clipboard.profileMismatch` lists what a paste would ask about. Asking about the profile of the document's color mode only, the choice a missing profile starts on under Convert to Working Space, and pastes and drags following the policies when nothing asks are VectorCraft's own rules. Public reference: [About missing and mismatched color profiles and Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `dialogs/profile_mismatch/tests.rs`. +- **Profile Mismatches and Missing Profiles:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has Profile Mismatches: Ask When Opening and Ask When Pasting, and Missing Profiles: Ask When Opening, off by default and kept in `Color Settings.json`. With a box on, File › Open asks before a document opens whose color mode's profile is not the working space (use the embedded profile, convert the colors to the working space, or discard the profile) or that has none (leave it, assign the working space, or assign a profile), and Paste, and a drag of artwork from another document, ask whether colors from a document with another profile keep their numbers or convert; each starts on what the policy does. `document.open {profileChoice}` and `profileMismatch` on the paste commands and `edit.dropSelection` give the answer without a prompt, and `clipboard.profileMismatch` lists what a paste or a drop would ask about. Asking about the profile of the document's color mode only and the choice a missing profile starts on under Convert to Working Space are VectorCraft's own rules. Public reference: [About missing and mismatched color profiles and Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `dialogs/profile_mismatch/tests.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From 1f411c8fa162dfdbe4fa45a611b5b1fb5a8e62db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:25:18 -0800 Subject: [PATCH 04/10] Color Settings: the paste question has a choice for each model when both differ profileMismatch also takes {rgb?, cmyk?}, a choice for each model, a model left out following its policy, on the paste commands, edit.dropSelection and clipboard.conflicts. With colors of both models from other profiles, the paste question shows a choice under each model's line, each starting on its model's policy, so OK no longer gives the CMYK colors the RGB policy's choice. --- crates/engine/src/cmd/colormgmt.rs | 58 +++++++++--- crates/engine/src/cmd/edit.rs | 4 +- crates/engine/tests/color_settings.rs | 43 +++++++++ .../ui-egui/src/dialogs/profile_mismatch.rs | 89 +++++++++++++++---- .../src/dialogs/profile_mismatch/tests.rs | 33 +++++++ docs/mcp.md | 12 +-- docs/target-app-parity.md | 2 +- 7 files changed, 201 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 6afb68ef45..58b5a9e57c 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -982,16 +982,47 @@ impl PasteProfile { if policy == Policy::Convert { PasteProfile::Convert } else { PasteProfile::PreserveNumbers } } - /// The `profileMismatch` param of paste command `cmd` (`None` when left out). - pub(crate) fn param(p: &Value, cmd: &str) -> Result> { - match text_param(p, "profileMismatch", cmd)? { - None => Ok(None), - Some("preserveNumbers") => Ok(Some(PasteProfile::PreserveNumbers)), - Some("convert") => Ok(Some(PasteProfile::Convert)), - Some(_) => { - let key = "profileMismatch"; - Err(bad(cmd, format!("`{key}` must be one of {}", "preserveNumbers, convert"))) + /// The `profileMismatch` param of paste command `cmd` (`None` when left out): one choice for + /// both models, or `{rgb?, cmyk?}` with a choice for each (a model left out follows its policy). + pub(crate) fn param(p: &Value, cmd: &str) -> Result> { + let key = "profileMismatch"; + let refuse = || bad(cmd, format!("`{key}` must be one of {}", "preserveNumbers, convert, {rgb?, cmyk?} of those")); + let one = |v: &Value| match v.as_str() { + Some("preserveNumbers") => Ok(PasteProfile::PreserveNumbers), + Some("convert") => Ok(PasteProfile::Convert), + _ => Err(refuse()), + }; + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Object(o)) => { + if o.keys().any(|k| k != "rgb" && k != "cmyk") { + return Err(refuse()); + } + let model = |m: &str| o.get(m).map(&one).transpose(); + Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? })) } + Some(v) => { + let c = one(v)?; + Ok(Some(PasteChoice { rgb: Some(c), cmyk: Some(c) })) + } + } + } +} + +/// What Paste does with the mismatched colors of each model (`profileMismatch`); a model without a +/// choice follows its policy ([`PasteProfile::of`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PasteChoice { + pub rgb: Option, + pub cmyk: Option, +} + +impl PasteChoice { + /// The choice for the colors of `model`, if any. + pub fn of(&self, model: ColorMode) -> Option { + match model { + ColorMode::Rgb => self.rgb, + ColorMode::Cmyk => self.cmyk, } } } @@ -1044,14 +1075,15 @@ pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcra /// The clipboard `clip` as pasting it into `d` brings it: for each mismatched model /// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into -/// the destination's with the working intent, as `choice` says (default: each model's policy, -/// [`PasteProfile::of`]). A source or destination profile that is not available keeps the numbers. +/// the destination's with the working intent, as `choice` says for that model (default: the +/// model's policy, [`PasteProfile::of`]). A source or destination profile that is not available +/// keeps the numbers. /// → the converted clipboard (`None` when nothing converts; its resources paste as another /// document's) and a line for each mismatched model (`{model, clipboard, document, choice}`). pub(crate) fn paste_profiles( clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, - choice: Option, + choice: Option, ) -> (Option, Vec) { let mismatches = paste_mismatches(clip, d); let mut report = Vec::new(); @@ -1061,7 +1093,7 @@ pub(crate) fn paste_profiles( // Both profiles must be here to convert between them. let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); let available = here(&m.from) && here(&m.to); - let picked = if available { choice.unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; + let picked = if available { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; if picked == PasteProfile::Convert { match m.model { ColorMode::Rgb => rgb_on = true, diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index abf8dd7e4e..d6e376087f 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -114,7 +114,7 @@ pub fn specs() -> Vec { "Drop Artwork", [], None, - "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y], profileMismatch?: \"preserveNumbers\"|\"convert\"} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as profileMismatch says, else as edit.colorSettings' policy of their model says (as edit.paste; clipboard.profileMismatch {sourceDocument, ids} lists them, and with askMismatchPaste on the desktop app asks first) → {ids, added, merged, renamed, profileMismatch?}", + "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y], profileMismatch?: as edit.paste} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as profileMismatch says, else as edit.colorSettings' policy of their model says (as edit.paste; clipboard.profileMismatch {sourceDocument, ids} lists them, and with askMismatchPaste on the desktop app asks first) → {ids, added, merged, renamed, profileMismatch?}", has_doc, drop_selection ), @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent (default: as the model's policy of edit.colorSettings says; every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out: as the model's policy of edit.colorSettings says; any other value is an error; every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 6188001b06..e8c04a144f 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1427,3 +1427,46 @@ fn assign_profile_goes_with_assign_only() { let err = open_with(tagged, json!({"profileChoice": "discard", "assignProfile": cms::DISPLAY_P3})).0.unwrap_err(); assert!(err.contains("`assignProfile` goes with `profileChoice`: \"assign\" only"), "{err}"); } + +/// `profileMismatch: {rgb?, cmyk?}` gives each model its own choice, and a model left out follows +/// its policy; a key other than rgb and cmyk, or a value other than the two choices, is refused and +/// pastes nothing. +#[test] +fn paste_takes_a_choice_for_each_model() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let both = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [both.0], "color": "#3366cc"})); + exec(&mut s, "paint.setStroke", json!({"ids": [both.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + select(&mut s, &[both]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.colorSettings", json!({"cmykPolicy": "convert"})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + let pasted = |s: &mut Session, choice: serde_json::Value| { + let r = exec(s, "edit.paste", json!({ "profileMismatch": choice })); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + let picked = |model: &str| r["profileMismatch"].as_array().unwrap().iter().find(|m| m["model"] == model).map(|m| m["choice"].clone()); + (fill, picked("rgb"), picked("cmyk")) + }; + // The CMYK policy's own choice, as a paste that leaves both models to their policies makes it. + let (_, rgb_policy, cmyk_policy) = pasted(&mut s, serde_json::Value::Null); + assert_eq!(rgb_policy, Some(json!("preserveNumbers"))); + assert!(cmyk_policy.is_some(), "the stroke's CMYK color is a mismatch too"); + let (fill, rgb, cmyk) = pasted(&mut s, json!({"rgb": "convert"})); + assert_eq!((rgb, &cmyk), (Some(json!("convert")), &cmyk_policy), "CMYK follows its policy"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(fill != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&fill)) < 1.0, "{blue0:?} → {fill:?}"); + let (fill, rgb, cmyk) = pasted(&mut s, json!({"cmyk": "preserveNumbers"})); + assert_eq!((fill, rgb, cmyk), (blue0, Some(json!("preserveNumbers")), Some(json!("preserveNumbers")))); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = objects(&s); + for bad in [json!({"lab": "convert"}), json!({"rgb": "keep"}), json!({"rgb": 1}), json!([]), json!(true)] { + assert!(s.execute("edit.paste", &json!({ "profileMismatch": bad })).is_err(), "{bad}"); + assert!(s.execute("clipboard.conflicts", &json!({ "profileMismatch": bad })).is_err(), "{bad}"); + } + assert_eq!(objects(&s), before, "a refused choice pastes nothing"); +} diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index 10a1425a9e..324dd32249 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -13,7 +13,8 @@ //! Pasting ([`PASTE_KIND`]): colors copied, or dragged ([`DROP`]), from a document whose profile is //! not this document's ask whether to keep their numbers or convert them. OK runs the paste or the //! drop with `profileMismatch`; Cancel pastes or drops nothing. Fields: `mismatches` (as -//! `clipboard.profileMismatch` lists them), `choice` (`preserveNumbers` | `convert`), `__command` +//! `clipboard.profileMismatch` lists them), `choice` (`preserveNumbers` | `convert`, or with both +//! models `{rgb, cmyk}` of those, one for each), `__command` //! and `__params` (the paste or drop to run), and `__doc` (the uid of the document it was asked in). use serde_json::{Value, json}; @@ -202,8 +203,7 @@ pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Opt return None; } let mismatches = paste_mismatches(app, command, params).filter(|a| !a.is_empty())?; - // The policy of the first model starts chosen. - let choice = mismatches[0]["default"].as_str().unwrap_or("preserveNumbers").to_string(); + let choice = first_choice(&mismatches); let doc = app.session.active().map(|st| st.uid); let fields = json!({ "mismatches": mismatches, "choice": choice, "__command": command, "__params": params, DOC: doc }); // A deferred paste this dialog asked about gives way to the new one. @@ -222,25 +222,75 @@ fn paste_mismatches(app: &mut VectorcraftApp, command: &str, params: &Value) -> found["mismatches"].as_array().cloned() } +/// The choice the paste question starts on: the model's policy for one model, and for both a +/// choice for each (`{rgb, cmyk}`), each starting on its model's policy. +fn first_choice(mismatches: &[Value]) -> Value { + let default = |m: &Value| m["default"].as_str().unwrap_or("preserveNumbers").to_string(); + match mismatches { + [m] => json!(default(m)), + _ => Value::Object(mismatches.iter().filter_map(|m| Some((m["model"].as_str()?.to_string(), json!(default(m))))).collect()), + } +} + +/// What `choice` (one choice for every model, or `{rgb?, cmyk?}`) picks for the colors of `model`. +fn picked<'a>(choice: &'a Value, model: &str) -> &'a str { + choice.as_str().or_else(|| choice.get(model).and_then(Value::as_str)).unwrap_or_default() +} + +/// `choice` with `value` picked for the colors of `model`: with one model the value alone, with +/// both a choice for each in which the other model's stays as `choice` has it. +fn pick(choice: &Value, mismatches: &[Value], model: &str, value: &str) -> Value { + if mismatches.len() < 2 { + return json!(value); + } + let each = + mismatches.iter().filter_map(|m| m["model"].as_str()).map(|m| (m.to_string(), json!(if m == model { value } else { picked(choice, m) }))); + Value::Object(each.collect()) +} + +/// Is `choice` one choice for every model, or a choice for each of `mismatches`' models? +fn valid_choice(choice: &Value, mismatches: &[Value]) -> bool { + let known = |v: &str| paste_choices().iter().any(|(c, _)| *c == v); + match choice { + Value::String(s) => known(s), + Value::Object(o) => { + let models: Vec<&str> = mismatches.iter().filter_map(|m| m["model"].as_str()).collect(); + o.len() == models.len() && models.iter().all(|m| o.get(*m).and_then(Value::as_str).is_some_and(known)) + } + _ => false, + } +} + fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let mismatches = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); + let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); + // With both models, each has its own choice under its line; with one, the choice follows it. for m in &mismatches { - let model = m["model"].as_str().unwrap_or_default().to_ascii_uppercase(); + let id = m["model"].as_str().unwrap_or_default(); + let model = id.to_ascii_uppercase(); let (from, to) = (m["clipboard"].as_str().unwrap_or_default(), m["document"].as_str().unwrap_or_default()); let text = tl!("The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”."); ui.label(crate::i18n::fmt(text, &[("model", model.as_str()), ("from", from), ("to", to)])); - } - ui.add_space(10.0); - let choice = d.str("choice"); - grid(ui, |ui| { - for (value, text) in paste_choices() { - label(ui, ""); - if widgets::radio(ui, text, choice == value, true) { - d.fields.insert("choice".into(), json!(value)); - } - ui.end_row(); + ui.add_space(6.0); + let now = picked(&choice, id); + let clicked = ui.push_id(id, |ui| { + grid(ui, |ui| { + let mut clicked = None; + for (value, text) in paste_choices() { + label(ui, ""); + if widgets::radio(ui, text, now == value, true) { + clicked = Some(value); + } + ui.end_row(); + } + clicked + }) + }); + if let Some(value) = clicked.inner { + d.fields.insert("choice".into(), pick(&choice, &mismatches, id, value)); } - }); + ui.add_space(10.0); + } false } @@ -252,10 +302,11 @@ const DOC: &str = "__doc"; /// does and pastes nothing. When the profiles that paste or drop would bring have changed since it /// asked (the clipboard or the dragged objects' document changed), it asks again about the new ones. fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - let choice = d.str("choice"); - if !paste_choices().iter().any(|(v, _)| *v == choice) { + let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); + let asked = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); + if !valid_choice(&choice, &asked) { let key = "choice"; - return Err(format!("`{key}` must be one of {}", "preserveNumbers, convert")); + return Err(format!("`{key}` must be one of {}", "preserveNumbers, convert, {rgb, cmyk} of those")); } let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); if deferred.is_none() && d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) { @@ -273,7 +324,7 @@ fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { return r; } } - params["profileMismatch"] = json!(choice); + params["profileMismatch"] = choice; app.ui.dialog = None; // A paste that waited for its clipboard runs in the context it was given in. crate::placing::confirm_swatch_paste(app, &command, params, deferred) diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index e23f1a6f06..39e6910bee 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -102,6 +102,39 @@ fn drop_asks_as_paste_does(app: &mut VectorcraftApp, count: impl Fn(&Vectorcraft assert_eq!(count(app), before + n); } +/// A paste question about both models has a choice for each, starting on its model's policy, and +/// picking one model's choice in the dialog leaves the other's as it was; OK checks the choice. +#[test] +fn a_paste_question_about_both_models_has_a_choice_for_each() { + let both = [ + json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "preserveNumbers"}), + json!({"model": "cmyk", "clipboard": "Ink A", "document": "Ink B", "default": "convert"}), + ]; + assert_eq!(first_choice(&both), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); + assert_eq!(first_choice(&both[1..]), json!("convert"), "one model starts on its policy"); + for (choice, ok) in [ + (json!({"rgb": "convert", "cmyk": "preserveNumbers"}), true), + (json!("convert"), true), + (json!({"rgb": "convert"}), false), + (json!({"rgb": "convert", "cmyk": "keep"}), false), + (json!({"rgb": "convert", "cmyk": "convert", "lab": "convert"}), false), + (json!(""), false), + ] { + assert_eq!(valid_choice(&choice, &both), ok, "{choice}"); + } + // Picking CMYK's choice keeps RGB's, also when one choice was set for both. + let start = first_choice(&both); + assert_eq!(pick(&start, &both, "cmyk", "preserveNumbers"), json!({"rgb": "preserveNumbers", "cmyk": "preserveNumbers"})); + assert_eq!(pick(&json!("convert"), &both, "rgb", "preserveNumbers"), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); + assert_eq!(pick(&json!("convert"), &both[..1], "rgb", "preserveNumbers"), json!("preserveNumbers")); + // The dialog draws a pair of choices under each model's line. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let fields = json!({ "mismatches": both, "choice": start, "__command": "edit.paste", "__params": {} }); + app.ui.dialog = Some(Dialog::new(PASTE_KIND, fields)); + let text = frame(&mut app); + assert_eq!(text.matches("Preserve the color numbers").count(), 2, "{text}"); +} + /// With Color Settings' Ask boxes on, File › Open asks about a document whose profile is not the /// working space, or that has none, and opens it as chosen; Cancel doesn't open it, and a refused /// choice keeps the dialog. Paste, and a drag from another document, ask about colors from another diff --git a/docs/mcp.md b/docs/mcp.md index aa06360460..b91fa5e361 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1695,11 +1695,13 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR `convert`, `discard`; `leave`, `assignWorking`, `assign` with `assignProfile`) states the answer, else the policy applies, and the reply's `profileChoice` names the answer used. Copy remembers the profiles the colors showed through; pasting them into a document with another RGB or CMYK profile keeps their numbers or converts them, as - `profileMismatch` on the paste commands and `edit.dropSelection` says, else as the model's policy does (`convert` - converts, the others keep the numbers; a profile that is not available keeps them). `clipboard.profileMismatch` - lists the models that differ, only those whose colors the copied objects use (with `sourceDocument` and `ids`, the - objects a drop brings), and with `askMismatchPaste` on the desktop app asks first on Paste and on a drag between - documents. New from Template and File › Revert follow the policies without asking. + `profileMismatch` on the paste commands and `edit.dropSelection` says (`preserveNumbers` or `convert` for both + models, or `{rgb?, cmyk?}` with one for each), else as the model's policy does (`convert` converts, the others keep + the numbers; a profile that is not available keeps them). `clipboard.profileMismatch` lists the models that + differ, only those whose colors the copied objects use (with `sourceDocument` and `ids`, the objects a drop + brings), and with `askMismatchPaste` on the desktop app asks first on Paste and on a drag between documents. A + question about both models has a choice for each, each starting on its model's policy. New from Template and + File › Revert follow the policies without asking. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 701c02ddb4..198a379bd9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -766,7 +766,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. When a document tagged with a profile other than the working space is opened, reverted or opened as a template, the policy keeps the profile, takes it off with the color numbers kept, or converts that model's colors into the working space, with black point compensation as Color Settings set it, and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules; placed images are not covered. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `color/src/cms/tests_icc.rs`. -- **Profile Mismatches and Missing Profiles:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has Profile Mismatches: Ask When Opening and Ask When Pasting, and Missing Profiles: Ask When Opening, off by default and kept in `Color Settings.json`. With a box on, File › Open asks before a document opens whose color mode's profile is not the working space (use the embedded profile, convert the colors to the working space, or discard the profile) or that has none (leave it, assign the working space, or assign a profile), and Paste, and a drag of artwork from another document, ask whether colors from a document with another profile keep their numbers or convert; each starts on what the policy does. `document.open {profileChoice}` and `profileMismatch` on the paste commands and `edit.dropSelection` give the answer without a prompt, and `clipboard.profileMismatch` lists what a paste or a drop would ask about. Asking about the profile of the document's color mode only and the choice a missing profile starts on under Convert to Working Space are VectorCraft's own rules. Public reference: [About missing and mismatched color profiles and Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `dialogs/profile_mismatch/tests.rs`. +- **Profile Mismatches and Missing Profiles:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has Profile Mismatches: Ask When Opening and Ask When Pasting, and Missing Profiles: Ask When Opening, off by default and kept in `Color Settings.json`. With a box on, File › Open asks before a document opens whose color mode's profile is not the working space (use the embedded profile, convert the colors to the working space, or discard the profile) or that has none (leave it, assign the working space, or assign a profile), and Paste, and a drag of artwork from another document, ask whether colors from a document with another profile keep their numbers or convert; each starts on what the policy does, and a paste question about both models has a choice for each. `document.open {profileChoice}` and `profileMismatch` on the paste commands and `edit.dropSelection` give the answer without a prompt, and `clipboard.profileMismatch` lists what a paste or a drop would ask about. Asking about the profile of the document's color mode only, the choice a missing profile starts on under Convert to Working Space and a paste choice for each model are VectorCraft's own rules. Public reference: [About missing and mismatched color profiles and Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `dialogs/profile_mismatch/tests.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From 526eba3ad467d26d432a7f458711d928b444c2c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:40:28 -0800 Subject: [PATCH 05/10] Color Settings: a null profileMismatch asks as leaving it out does With Ask When Pasting on, a paste or drop given profileMismatch: null opened no question, though the command reads null as no choice. The desktop app now asks for it as for an omitted choice. --- crates/ui-egui/src/dialogs/profile_mismatch.rs | 3 ++- .../src/dialogs/profile_mismatch/tests.rs | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index 324dd32249..272f6877e4 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -199,7 +199,8 @@ pub(crate) fn settle(app: &mut VectorcraftApp) { /// pasted or dropped colors come from another profile, open the dialog instead and answer /// `{dialog}`. pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option { - if params.get("profileMismatch").is_some() || !cms::working_settings().ask_mismatch_paste { + // A null choice is no choice, as the paste commands read it. + if params.get("profileMismatch").is_some_and(|v| !v.is_null()) || !cms::working_settings().ask_mismatch_paste { return None; } let mismatches = paste_mismatches(app, command, params).filter(|a| !a.is_empty())?; diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index 39e6910bee..d62c56e431 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -53,6 +53,17 @@ fn open_confirmed_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the caller that confirmed"); } +/// Cancel on the paste question pastes nothing, and a null `profileMismatch` asks as leaving it out +/// does. `count` counts the active document's objects. +fn paste_canceled(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { + let before = count(app); + for params in [json!({}), json!({ "profileMismatch": null })] { + assert_eq!(app.run("edit.paste", params.clone()).unwrap(), json!({ "dialog": PASTE_KIND }), "{params} asks"); + super::super::cancel(app); + assert_eq!(count(app), before); + } +} + /// Another document becomes the active one while the paste question is open: OK pastes nothing, into /// neither document, and the document the paste was asked in is active again afterward. `count` /// counts the active document's objects. @@ -236,10 +247,7 @@ fn opening_and_pasting_ask_about_profiles() { assert!(app.ui.dialog.is_none()); // Cancel pastes nothing; with the box off nothing asks. let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); - let before = count(&app); - app.run("edit.paste", json!({})).unwrap(); - super::super::cancel(&mut app); - assert_eq!(count(&app), before); + paste_canceled(&mut app, count); paste_asked_before_another_document_is_active(&mut app, count); drop_asks_as_paste_does(&mut app, count); let before = count(&app); From b192b589caac0c67a7cb1d5ce26f9943ab4e40d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:30:53 -0800 Subject: [PATCH 06/10] Rerun CI From 49672c2ccd4bbc018af27eef973bdd7d35b940b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 06:03:14 -0800 Subject: [PATCH 07/10] Color Settings: French row for the assign-only error uses no plain space before a colon --- 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 d5f75276c0..7ab07898b2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5809,7 +5809,7 @@ variable-list-end {0}, {1} {0} et {1} Assign profile: Attribuer le profil : Preserve the color numbers Conserver les valeurs des couleurs Convert to keep the colors' appearance Convertir pour conserver l’aspect des couleurs -@msg `{path}` goes with `{key}`: "assign" only `{path}` ne s’utilise qu’avec `{key}` : "assign" +@msg `{path}` goes with `{key}`: "assign" only `{path}` ne s’utilise qu’avec `{key}` égal à "assign" The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”. Les couleurs collées proviennent d’un document dont le profil {model} est « {from} » ; celui de ce document est « {to} ». Texture Texture Craquelure… Craquelure… From 95ed13dd805cd741569333ee6edd2df3ae4755df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:42:03 -0800 Subject: [PATCH 08/10] Color Settings: answer the review of the profile prompts - An absolute-colorimetric conversion from CMYK starts from the source's absolute appearance. - An assigned profile that was removed counts as the working space when copied colors are compared. - Colors that can't convert are listed with convertible false, start on Preserve Numbers, and the dialog disables Convert for them. - Paste on All Artboards leaves the backgrounds of copied artboards out of the question (clipboard.profileMismatch allArtboards). - A converting paste into its own document keeps its image keys. - An open answer is refused once Color Settings change the question; the dialog asks the new question, or opens by the policy. - Files opened while a question is open ask their own questions in turn. - OK on the paste question and on Swatch Conflict checks again where the paste runs and asks again when the question changed. - docs/mcp.md and the command help describe these rules. --- crates/color/src/cms.rs | 15 +- crates/color/src/cms/tests.rs | 23 +++ crates/engine/src/cmd/clipboard.rs | 8 +- crates/engine/src/cmd/clipboard/resources.rs | 20 +- crates/engine/src/cmd/colormgmt.rs | 51 +++-- crates/engine/src/cmd/edit.rs | 14 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 27 ++- crates/engine/tests/color_settings.rs | 195 +++++++++++++++++- crates/ui-egui/src/app.rs | 1 + .../ui-egui/src/dialogs/profile_mismatch.rs | 163 +++++++++++---- .../src/dialogs/profile_mismatch/tests.rs | 182 ++++++++++++++-- crates/ui-egui/src/dialogs/swatch_conflict.rs | 27 ++- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/placing.rs | 37 +++- docs/mcp.md | 39 ++-- 16 files changed, 677 insertions(+), 130 deletions(-) diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index fb5b5d8605..a3c35db8ce 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -603,9 +603,9 @@ impl Cms { /// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to /// Working Space). RGB converts directly from profile to profile, with this context's /// black-point compensation. CMYK converts between two loaded profiles through ProPhoto RGB - /// ([`IccProfile::to_same_model_of`]), and through the Lab it displays as - /// ([`Self::cmyk_display_lab`]) when either space is built in. Grey and Lab colours stay as they - /// are. + /// ([`IccProfile::to_same_model_of`]), and through Lab when either space is built in: the Lab it + /// displays as ([`Self::cmyk_display_lab`]), or for Absolute Colorimetric its absolute Lab. Grey + /// and Lab colours stay as they are. pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color { match *c { Color::Rgb { r, g, b } => { @@ -625,9 +625,16 @@ impl Cms { (CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc), _ => None, }; + // Absolute colorimetry starts from the inks' absolute Lab, paper color included and + // without black-point compensation; the other intents from the Lab they display as. + let source_lab = || match (&self.cmyk, intent) { + (CmykSpace::Generic(g), Intent::AbsoluteColorimetric) => g.to_lab_abs(inks), + (_, Intent::AbsoluteColorimetric) => lab::srgb_to_lab(self.cmyk_to_srgb(inks, true)), + _ => self.cmyk_display_lab(inks), + }; let [c, m, y, k] = match direct.as_deref() { Some(&[c, m, y, k]) => [c, m, y, k], - _ => dest.lab_to_cmyk(self.cmyk_display_lab(inks), intent), + _ => dest.lab_to_cmyk(source_lab(), intent), }; Color::Cmyk { c, m, y, k } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index f3cdfefd33..836ff9fdb6 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -517,3 +517,26 @@ fn convert_into_keeps_compensated_dark_inks() { } } } + +/// Absolute Colorimetric converts CMYK out of Generic CMYK from the inks' absolute Lab (paper color +/// included, no black-point compensation): into another document whose CMYK space is also Generic +/// CMYK, the paper, dark inks and mid tones keep their absolute appearance. +#[test] +fn absolute_cmyk_conversion_keeps_the_absolute_appearance() { + let generic = cms(); + let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + let absolute = |c: &Cms, ink: &Color| match (&c.cmyk, ink) { + (CmykSpace::Generic(g), Color::Cmyk { c, m, y, k }) => g.to_lab_abs([*c, *m, *y, *k]), + _ => panic!("Generic CMYK inks expected, not {ink:?}"), + }; + for ink in [ + Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, + Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 }, + Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 }, + Color::Cmyk { c: 0.4, m: 0.1, y: 0.6, k: 0.1 }, + ] { + let moved = generic.convert_into(&other_generic, &ink, Intent::AbsoluteColorimetric); + let d = delta_e2000(absolute(&generic, &ink), absolute(&other_generic, &moved)); + assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}"); + } +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 4da417940d..c42289ccc7 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Paste Profile Mismatch", [], None, - "{sourceDocument?, ids?: as edit.dropSelection} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\"}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", + "{sourceDocument?, ids?: as edit.dropSelection, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\", convertible}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then; an assigned profile removed since: the working space) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). convertible: false when either profile is not available (removed with color.removeProfile): the colors then keep their numbers whatever the choice, and default is preserveNumbers. With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", has_doc, profile_mismatch ), @@ -561,7 +561,7 @@ fn conflicts(s: &mut Session, p: &Value) -> Result { // The swatches as the paste brings them: converted from another profile when it converts. let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; let st = s.doc()?; - let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile); + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); let list: Vec = converted .as_ref() .unwrap_or(&s.clipboard) @@ -577,7 +577,9 @@ fn profile_mismatch(s: &mut Session, p: &Value) -> Result { // With `sourceDocument` and `ids`, the objects a drop brings, else the clipboard's. let dropped = if p.get("sourceDocument").is_some() || p.get("ids").is_some() { Some(super::edit::drop_clip(s, p, CMD)?) } else { None }; let clip = dropped.as_ref().unwrap_or(&s.clipboard); - let list: Vec = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc).iter().map(|m| m.to_json()).collect(); + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; + let list: Vec = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc, !all_artboards).iter().map(|m| m.to_json()).collect(); Ok(json!({ "mismatches": list })) } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 0a98ddd9bc..594d4c9f5d 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1121,8 +1121,11 @@ impl Clipboard { /// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added /// under a free name ("Dots 2") is compared and added with that name. An error, with `d` /// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]). + /// `same_doc`: `d` is the document the objects were copied from. With colors converted for the + /// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another + /// document's are, while its image blobs are still the document's own under their keys. pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used(d, &self.used(), choices, same_doc) + self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc) } /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` @@ -1155,9 +1158,22 @@ impl Clipboard { /// other is matched on its own ([`loop_groups`]). Pasted back into its own document /// (`same_doc`), each definition of a loop is the document's of its name. fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result { + self.import_used_with_images(d, used, choices, same_doc, same_doc) + } + + /// [`Self::import_used`], with the image blobs matched as those of the document they came + /// from when `same_doc_images`. + fn import_used_with_images( + &self, + d: &mut Document, + used: &Used, + choices: &SwatchChoices, + same_doc: bool, + same_doc_images: bool, + ) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; - self.import_images(d, used, same_doc, &mut out); + self.import_images(d, used, same_doc_images, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); let mut defs: Vec> = vec![]; for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index bc3880b2e6..0ac4f8c3b0 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -950,11 +950,16 @@ pub(crate) fn convert_art_and_style_colors(d: &mut vectorcraft_doc::Document, co } /// The RGB and CMYK profiles the colors of `d` show through, by name: those it is assigned, else -/// the working spaces. +/// the working spaces. An assigned profile that is not available (removed since) is the working +/// space, as the document draws through it ([`cms::for_document`]). pub(crate) fn effective_profiles(d: &vectorcraft_doc::Document) -> [String; 2] { let working = cms::working_settings(); let (rgb, cmyk) = doc_profiles(d); - [rgb.unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()), cmyk.unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string())] + let available = |name: Option, kind: cms::ProfileKind| name.filter(|n| cms::profile(n).is_some_and(|p| p.kind == kind)); + [ + available(rgb, cms::ProfileKind::Rgb).unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()), + available(cmyk, cms::ProfileKind::Cmyk).unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string()), + ] } /// What Paste does with the colors of a model when the document they were copied from showed them @@ -1035,20 +1040,25 @@ pub struct PasteMismatch { pub from: String, /// The profile they show through in the document they go into. pub to: String, - /// What the model's policy does with them. + /// What the model's policy does with them; Preserve Numbers when they can't convert. pub default: PasteProfile, + /// Both profiles are available, so the colors can convert; otherwise they keep their numbers + /// whatever the choice. + pub convertible: bool, } impl PasteMismatch { pub fn to_json(&self) -> Value { let model = if self.model == ColorMode::Rgb { "rgb" } else { "cmyk" }; - json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id() }) + json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id(), "convertible": self.convertible }) } } /// The models whose colors pasting `clip` into `d` brings from another profile: RGB, CMYK or both, -/// each only when the copied objects or the resources they carry hold a color of that model. -pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document) -> Vec { +/// each only when the copied objects or the resources they carry hold a color of that model. The +/// background colors of copied artboards count only with `boards` (Paste on All Artboards doesn't +/// paste the artboards). +pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, boards: bool) -> Vec { let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return vec![] }; let [to_rgb, to_cmyk] = effective_profiles(d); let working = cms::working_settings(); @@ -1056,11 +1066,26 @@ pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcra [(ColorMode::Rgb, from_rgb, to_rgb, working.rgb_policy), (ColorMode::Cmyk, from_cmyk, to_cmyk, working.cmyk_policy)] .into_iter() .filter(|(_, from, to, _)| cms::canonical_name(from) != cms::canonical_name(to)) - .map(|(model, from, to, policy)| PasteMismatch { model, from: from.clone(), to, default: PasteProfile::of(policy) }) + .map(|(model, from, to, policy)| { + let kind = if model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + // Both profiles must be here to convert between them. + let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); + let convertible = here(from) && here(&to); + let default = if convertible { PasteProfile::of(policy) } else { PasteProfile::PreserveNumbers }; + PasteMismatch { model, from: from.clone(), to, default, convertible } + }) .collect(); if out.is_empty() { return out; } + // Without the artboards when their backgrounds don't paste. + let without_boards; + let clip = if !boards && !clip.artboards.is_empty() { + without_boards = super::clipboard::Clipboard { artboards: vec![], ..clip.clone() }; + &without_boards + } else { + clip + }; // Which models the pasted colors use. let seen = std::cell::Cell::new((false, false)); let _ = clip.with_colors(&|c: &Color| { @@ -1077,23 +1102,20 @@ pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcra /// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into /// the destination's with the working intent, as `choice` says for that model (default: the /// model's policy, [`PasteProfile::of`]). A source or destination profile that is not available -/// keeps the numbers. +/// keeps the numbers. `boards`: as [`paste_mismatches`]. /// → the converted clipboard (`None` when nothing converts; its resources paste as another /// document's) and a line for each mismatched model (`{model, clipboard, document, choice}`). pub(crate) fn paste_profiles( clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, choice: Option, + boards: bool, ) -> (Option, Vec) { - let mismatches = paste_mismatches(clip, d); + let mismatches = paste_mismatches(clip, d, boards); let mut report = Vec::new(); let (mut rgb_on, mut cmyk_on) = (false, false); for m in &mismatches { - let kind = if m.model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; - // Both profiles must be here to convert between them. - let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); - let available = here(&m.from) && here(&m.to); - let picked = if available { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; + let picked = if m.convertible { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; if picked == PasteProfile::Convert { match m.model { ColorMode::Rgb => rgb_on = true, @@ -1103,6 +1125,7 @@ pub(crate) fn paste_profiles( let mut line = m.to_json(); if let Some(o) = line.as_object_mut() { o.remove("default"); + o.remove("convertible"); o.insert("choice".into(), json!(picked.id())); } report.push(line); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 7f0db6dd87..5e0231228b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -180,7 +180,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out: as the model's policy of edit.colorSettings says; any other value is an error; every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -1293,7 +1293,7 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?; // Colors from another profile keep their numbers or convert, as `profileMismatch` says, else as // the policies say. - let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile); + let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile, true); let mut r = paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices); if let Ok(v) = &mut r && !report.is_empty() @@ -1361,9 +1361,10 @@ fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result { // Taken out of the session for the edit (and put back whatever happens). let clip = std::mem::take(&mut s.clipboard); // Colors copied from a document with other profiles keep their numbers or convert - // (Edit › Color Settings' policies, or `profileMismatch`). + // (Edit › Color Settings' policies, or `profileMismatch`). Paste on All Artboards leaves the + // copied artboards, and so their backgrounds, behind. let (converted, report) = match s.doc() { - Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile), + Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile, mode != PasteMode::AllArtboards), Err(_) => (None, vec![]), }; let mut r = paste_clip(s, p, mode, converted.as_ref().unwrap_or(&clip), &choices); @@ -1549,8 +1550,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho vec![Affine::IDENTITY] }; let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { - // Converted colors are compared with the document's resources, as another document's are. - let imported = clip.import_into(d, choices, same_doc && !clip.colors_converted)?; + // Converted colors are compared with the document's resources, as another document's are + // (`Clipboard::import_into`); its images are still the document's own. + let imported = clip.import_into(d, choices, same_doc)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; let artboards: Vec = boards diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 7b24fbdd24..a41831b200 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was used; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index b2827b5ccf..61b371bcd6 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -695,6 +695,9 @@ pub struct ReadFile { /// The answer that was used and the question it answered (`document.open`'s `profileChoice` /// reply). answered: Option, + /// The profile question as it was last asked ([`ReadFile::ask`]): an answer is taken only while + /// the question is still the same. + asked: Option, } /// The part of [`read_for_open`] a file waiting for a profile answer has left to do. @@ -768,8 +771,9 @@ pub fn read_for_open_asking( choice, rest: Some(Rest { update_links, low_res_proxy_eps, color_mode }), answered: None, + asked: None, }; - if ask && file.choice.is_none() && file.question().is_some() { + if ask && file.choice.is_none() && file.ask().is_some() { return Ok(file); } file.finish_read()?; @@ -791,11 +795,28 @@ impl ReadFile { crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &st).filter(|q| q.asked(&st)) } + /// [`Self::question`], kept as the question asked: [`Self::answer`] takes an answer only while + /// the question is still the same. The app calls it when it shows the question. + pub fn ask(&mut self) -> Option { + self.asked = self.question(); + self.asked.clone() + } + /// Answer the profile question with `choice` and do the rest of the read: the policies (the /// answer in place of the one of the document's color mode), the color mode, the linked files - /// and the type. An error (a profile to assign that is not one of that model) leaves the file - /// waiting. + /// and the type. An error leaves the file waiting: a profile to assign that is not one of that + /// model, or Color Settings changed since the question was asked ([`Self::ask`]) so that the + /// question, its model, the profile it is about or the working space differ. pub fn answer(&mut self, choice: crate::cmd::colormgmt::ProfileChoice) -> Result<()> { + if let Some(asked) = &self.asked + && self.rest.is_some() + { + let now = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let key = |q: &crate::cmd::colormgmt::ProfileQuestion| (q.issue, q.model, q.profile.clone(), q.working.clone()); + if now.as_ref().map(key) != Some(key(asked)) { + return Err(bad("document.open", "the profile question changed since it was asked: answer the question it asks now")); + } + } let before = self.choice.replace(choice); let r = self.finish_read(); if r.is_err() { diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index c63de94238..7c0aef252e 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1290,6 +1290,35 @@ fn a_read_waits_for_the_profile_answer() { assert_eq!(doc_profiles(&opened.doc().unwrap().doc).0, Some(cms::DISPLAY_P3.into())); } +/// An answer is taken only while the question it answers stands: once Color Settings change the +/// working space so that the question goes away or names another working space, the answer is +/// refused and the file keeps waiting. Asked again, it takes the answer to the question it asks now. +#[test] +fn a_profile_answer_waits_for_the_question_it_answers() { + let _g = settings(); + let ProfileFiles { tagged, blue, blue0, .. } = &profile_files("profile-changed"); + let (blue, blue0) = (*blue, *blue0); + let mut s = session(); + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true})); + let bytes = std::fs::read(tagged).unwrap(); + let name = tagged.to_str().unwrap(); + let mut waiting = vectorcraft_engine::cmd::fileio::read_for_open_asking(name, &bytes, Some(name.into()), &json!({}), false, false, true).unwrap(); + assert_eq!(waiting.question().unwrap().working, cms::canonical_name(cms::SRGB)); + // The working space becomes the file's profile: the question is gone. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); + assert!(waiting.answer(ProfileChoice::Discard).is_err(), "the question it answers is gone"); + // Another working space: the question names it. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})); + let err = waiting.answer(ProfileChoice::Discard).unwrap_err().to_string(); + assert!(err.contains("the profile question changed since it was asked"), "{err}"); + assert_eq!(waiting.ask().unwrap().working, cms::canonical_name(cms::DISPLAY_P3)); + waiting.answer(ProfileChoice::Discard).unwrap(); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(r["profileChoice"]["choice"], "discard"); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill_of(&opened, blue)), (None, blue0)); +} + /// Swatch conflicts are checked against the colors as the paste brings them: a global swatch whose /// name and color match the destination's conflicts once the paste converts it, and pasting back /// into its own document with conversion compares its swatches too. @@ -1384,9 +1413,10 @@ fn paste_keeps_or_converts_colors_from_another_profile() { exec(&mut s, "file.new", json!({"width": 100, "height": 100})); let r = exec(&mut s, "clipboard.profileMismatch", json!({})); // Only RGB: the objects use no CMYK color. + let srgb = cms::canonical_name(cms::SRGB); assert_eq!( r["mismatches"], - json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": cms::canonical_name(cms::SRGB), "default": "preserveNumbers"}]) + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) ); let pasted = |s: &mut Session, p: serde_json::Value| { let r = exec(s, "edit.paste", p); @@ -1440,9 +1470,10 @@ fn a_drop_takes_the_profile_mismatch_choice() { let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([]), "the clipboard is empty"); let dragged = json!({"sourceDocument": source, "ids": [blue.0]}); + let srgb = cms::canonical_name(cms::SRGB); assert_eq!( exec(&mut s, "clipboard.profileMismatch", dragged.clone())["mismatches"], - json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": cms::canonical_name(cms::SRGB), "default": "preserveNumbers"}]) + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) ); for bad in [json!({"sourceDocument": source}), json!({"ids": [blue.0]}), json!({"sourceDocument": 999_999, "ids": [blue.0]})] { assert!(s.execute("clipboard.profileMismatch", &bad).is_err(), "{bad}"); @@ -1491,6 +1522,10 @@ fn paste_takes_a_choice_for_each_model() { exec(&mut s, "paint.setFill", json!({"ids": [both.0], "color": "#3366cc"})); exec(&mut s, "paint.setStroke", json!({"ids": [both.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + let stroke_of = |s: &Session, id: vectorcraft_doc::NodeId| { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.stroke()).and_then(|f| f.paint.color()).unwrap() + }; + let ink0 = stroke_of(&s, both); select(&mut s, &[both]); exec(&mut s, "edit.copy", json!({})); exec(&mut s, "file.new", json!({"width": 100, "height": 100})); @@ -1501,18 +1536,21 @@ fn paste_takes_a_choice_for_each_model() { let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); let fill = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); let picked = |model: &str| r["profileMismatch"].as_array().unwrap().iter().find(|m| m["model"] == model).map(|m| m["choice"].clone()); - (fill, picked("rgb"), picked("cmyk")) + (fill, stroke_of(s, id), picked("rgb"), picked("cmyk")) }; - // The CMYK policy's own choice, as a paste that leaves both models to their policies makes it. - let (_, rgb_policy, cmyk_policy) = pasted(&mut s, serde_json::Value::Null); - assert_eq!(rgb_policy, Some(json!("preserveNumbers"))); - assert!(cmyk_policy.is_some(), "the stroke's CMYK color is a mismatch too"); - let (fill, rgb, cmyk) = pasted(&mut s, json!({"rgb": "convert"})); - assert_eq!((rgb, &cmyk), (Some(json!("convert")), &cmyk_policy), "CMYK follows its policy"); + // The CMYK policy (Convert to Working Space) converts the stroke from Device CMYK into the + // working CMYK space, as a paste that leaves both models to their policies does. + let (_, ink, rgb_policy, cmyk_policy) = pasted(&mut s, serde_json::Value::Null); + assert_eq!((rgb_policy, &cmyk_policy), (Some(json!("preserveNumbers")), &Some(json!("convert")))); + let device = cms::for_document(None, Some(cms::DEVICE_CMYK)); + assert!(ink != ink0 && cms::delta_e2000(device.lab(&ink0), cms::working().lab(&ink)) < 2.0, "{ink0:?} → {ink:?}"); + let converted_ink = ink; + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"rgb": "convert"})); + assert_eq!((rgb, &cmyk, ink), (Some(json!("convert")), &cmyk_policy, converted_ink), "CMYK follows its policy"); let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); assert!(fill != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&fill)) < 1.0, "{blue0:?} → {fill:?}"); - let (fill, rgb, cmyk) = pasted(&mut s, json!({"cmyk": "preserveNumbers"})); - assert_eq!((fill, rgb, cmyk), (blue0, Some(json!("preserveNumbers")), Some(json!("preserveNumbers")))); + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"cmyk": "preserveNumbers"})); + assert_eq!((fill, ink, rgb, cmyk), (blue0, ink0, Some(json!("preserveNumbers")), Some(json!("preserveNumbers"))), "the inks keep their values"); let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); let before = objects(&s); for bad in [json!({"lab": "convert"}), json!({"rgb": "keep"}), json!({"rgb": 1}), json!([]), json!(true)] { @@ -1521,3 +1559,138 @@ fn paste_takes_a_choice_for_each_model() { } assert_eq!(objects(&s), before, "a refused choice pastes nothing"); } + +/// The fill color of the first object a paste reply `r` names, in the active document. +#[allow(clippy::unwrap_used, reason = "a test helper: a reply without objects fails the test")] +fn pasted_fill(s: &Session, r: &serde_json::Value) -> vectorcraft_color::Color { + fill_of(s, vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())) +} + +/// A document assigned a profile that was removed since draws through the working space, and its +/// copied colors come from the working space too: pasted into a document with another profile, they +/// convert from it as `profileMismatch` says. +#[test] +fn a_removed_assigned_profile_pastes_as_the_working_space() { + const NAME: &str = "Removed Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["convertible"]), (&json!(cms::canonical_name(cms::SRGB)), &json!(true)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let (blue0, moved) = (vectorcraft_color::Color::from_hex("#3366cc").unwrap(), pasted_fill(&s, &r)); + let p3 = cms::for_document(Some(cms::DISPLAY_P3), None); + assert!(moved != blue0 && cms::delta_e2000(cms::working().lab(&blue0), p3.lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); +} + +/// Colors copied from a document whose profile was removed after the copy can't convert: the +/// mismatch says so (convertible false, and default preserveNumbers under a converting policy), and +/// a paste that asks to convert keeps their numbers. +#[test] +fn colors_from_a_profile_removed_after_the_copy_keep_their_numbers() { + const NAME: &str = "Copied Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert"})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["default"], &m["convertible"]), (&json!("convert"), &json!(true)), "both profiles are here: {m}"); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["default"], &m["convertible"]), (&json!(NAME), &json!("preserveNumbers"), &json!(false)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + assert_eq!(pasted_fill(&s, &r), vectorcraft_color::Color::from_hex("#3366cc").unwrap()); +} + +/// Paste on All Artboards leaves copied artboards behind, so their backgrounds raise no mismatch for +/// it: clipboard.profileMismatch with allArtboards lists none, and the paste reports none. A plain +/// paste, which brings the artboard, still lists the background's model. +#[test] +fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let models = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.profileMismatch", p)["mismatches"].as_array().unwrap().len(); + assert_eq!(models(&mut s, json!({})), 1, "a plain paste brings the RGB background"); + assert_eq!(models(&mut s, json!({"allArtboards": true})), 0); + assert!(s.execute("clipboard.profileMismatch", &json!({"allArtboards": "yes"})).is_err()); + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + +/// A converting paste back into the document the objects came from (its profile changed since the +/// copy) still takes its image blobs as the document's own: an image whose blob under its key +/// changed since keeps that key, and so shows the document's blob. +#[test] +fn a_converting_paste_into_its_own_document_keeps_its_image_keys() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + let blob = |b: u8| vectorcraft_doc::ImageBlob::png(vec![b; 8]); + let image = s + .edit("Place", |d, _| { + d.images.insert("pic".into(), blob(1)); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 4, + height: 4, + xf: Affine::translate((20.0, 0.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[blue, image]); + exec(&mut s, "edit.copy", json!({})); + s.edit("Replace Image", |d, _| { + d.images.insert("pic".into(), blob(2)); + Ok(()) + }) + .unwrap(); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let doc = &s.doc().unwrap().doc; + let keys: Vec = r["ids"] + .as_array() + .unwrap() + .iter() + .filter_map(|id| match &doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap()))?.kind { + vectorcraft_doc::NodeKind::Image(im) => Some(im.key.clone()), + _ => None, + }) + .collect(); + assert_eq!(keys, ["pic"]); + assert_eq!(doc.images.len(), 1, "no copy of the old blob"); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 252cfe34f1..d9b752c32c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -187,6 +187,7 @@ impl VectorcraftApp { synthetic_frame: false, pending_plugin_install: None, pending_profile_open: None, + queued_profile_opens: Default::default(), script_picked: Vec::new(), script_picked_left_out: false, pen_end: Default::default(), diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index 272f6877e4..f04fff2ba8 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -19,7 +19,7 @@ use serde_json::{Value, json}; use vectorcraft_color::cms::{self, ProfileKind}; -use vectorcraft_engine::cmd::colormgmt::ProfileChoice; +use vectorcraft_engine::cmd::colormgmt::{ProfileChoice, ProfileQuestion}; use vectorcraft_engine::cmd::fileio::{self, ReadFile}; use vectorcraft_engine::file_access::ScopeHandle; @@ -82,33 +82,60 @@ fn paste_choices() -> [(&'static str, &'static str); 2] { } /// Open `file`, read for File › Open from `path`, as `document.open` does, unless Edit › Color -/// Settings asks about its profile ([`ReadFile::question`]): then the dialog asks first, and the -/// result is `{dialog}`. Opened, the views follow and the file goes on the recent files -/// ([`crate::io::opened`]). +/// Settings asks about its profile ([`ReadFile::ask`]): then the dialog asks first, and the result +/// is `{dialog}`. A file read while another one's question is open waits for its own question +/// until that one is answered (`{dialog, queued: true}`). Opened, the views follow and the file +/// goes on the recent files ([`crate::io::opened`]). pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option) -> Result { - // One question at a time: a file read while another waits opens as its policy says. - if app.pending_profile_open.is_none() - && let Some(q) = file.question() - { - let fields = json!({ - "issue": q.issue.id(), - "name": file.name(), - "model": q.model_label(), - "profile": q.profile, - "working": q.working, - "choice": q.default.id(), - "assignProfile": q.working, + ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture() }) +} + +/// [`open_or_ask`] for a file that has its scope already. +fn ask_or_open(app: &mut VectorcraftApp, mut pending: PendingOpen) -> Result { + let Some(q) = pending.file.ask() else { + let PendingOpen { file, path, scope } = pending; + return scope.run(|| { + let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) }); - app.pending_profile_open = Some(PendingOpen { file, path, scope: ScopeHandle::capture() }); - app.ui.dialog = Some(Dialog::new(OPEN_KIND, fields)); - return Ok(json!({ "dialog": OPEN_KIND })); + }; + if app.pending_profile_open.is_some() { + app.queued_profile_opens.push_back(pending); + return Ok(json!({ "dialog": OPEN_KIND, "queued": true })); } - let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; - crate::io::opened(app, &r); - if let Some(p) = &path { - crate::io::note_recent(app, p); + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) +} + +/// The open dialog's fields for question `q` about the file named `name`. +fn question_fields(q: &ProfileQuestion, name: &str) -> Value { + json!({ + "issue": q.issue.id(), + "name": name, + "model": q.model_label(), + "profile": q.profile, + "working": q.working, + "choice": q.default.id(), + "assignProfile": q.working, + }) +} + +/// With no dialog open, the next file waiting for its profile question asks it, or opens as its +/// policy says when the question is gone (Color Settings changed meanwhile). A file that fails to +/// open is reported, and the next one comes. +pub(crate) fn ask_next(app: &mut VectorcraftApp) { + while app.pending_profile_open.is_none() && app.ui.dialog.is_none() { + let Some(next) = app.queued_profile_opens.pop_front() else { return }; + let name = next.file.name(); + if let Err(e) = ask_or_open(app, next) { + crate::io::report_open_error(app, &name, &e); + } } - Ok(r) } /// The `profileChoice` the open dialog's fields give. @@ -151,7 +178,10 @@ fn open_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool } /// OK: open the waiting file as chosen, under the automation roots of the open and those of the -/// caller that confirms both. A choice the file refuses keeps the dialog open. +/// caller that confirms both. A choice the file refuses keeps the dialog open. When Color Settings +/// changed the question since it was asked, the dialog asks the question as it stands now instead, +/// or the file opens as its policy says when there is no question any more. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = open_choice(d)?; let Some(mut pending) = app.pending_profile_open.take() else { @@ -160,10 +190,31 @@ fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { }; let scope = pending.scope.clone().within_current(); if let Err(e) = scope.clone().run(|| pending.file.answer(choice)) { - app.pending_profile_open = Some(pending); - return Err(e.to_string()); + // The question changed: ask it as it is now (or open by the policy when it is gone). + let now = |q: &ProfileQuestion| question_fields(q, ""); + let asked = |q: &ProfileQuestion| ["issue", "model", "profile", "working"].iter().all(|k| now(q).get(*k) == d.fields.get(*k)); + return match pending.file.ask() { + Some(q) if asked(&q) => { + app.pending_profile_open = Some(pending); + Err(e.to_string()) + } + Some(q) => { + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) + } + None => { + app.ui.dialog = None; + open_pending(app, pending, scope) + } + }; } app.ui.dialog = None; + open_pending(app, pending, scope) +} + +/// Open `pending`, answered or without a question, under `scope`; a failure is reported. +fn open_pending(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> DialogResult { let PendingOpen { file, path, .. } = pending; let name = file.name(); scope.run(|| match fileio::open_read(&mut app.session, file) { @@ -182,16 +233,19 @@ fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { }) } -/// Cancel, or the dialog closed some other way: the waiting file doesn't open. +/// Cancel, or the dialog closed some other way: the waiting file doesn't open. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). pub(crate) fn cancel_open(app: &mut VectorcraftApp) { app.pending_profile_open = None; } -/// A file still waiting once its dialog is gone (another dialog took its place) doesn't open. +/// A file still waiting once its dialog is gone (another dialog took its place) doesn't open; with +/// no dialog open, the next file waiting for its question asks it. pub(crate) fn settle(app: &mut VectorcraftApp) { if app.pending_profile_open.is_some() && !app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) { - cancel_open(app); + app.pending_profile_open = None; } + ask_next(app); } /// Before running paste `command` (or `edit.dropSelection`, a drag from another document) with @@ -216,13 +270,32 @@ pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Opt } /// The models whose profiles differ for paste `command` with `params` (`clipboard.profileMismatch`): -/// a drop brings the objects it names, a paste the clipboard's. `None` when they can't be listed. +/// a drop brings the objects it names, a paste the clipboard's, and Paste on All Artboards leaves the +/// backgrounds of copied artboards behind. `None` when they can't be listed. fn paste_mismatches(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { - let query = if command == DROP { json!({ "sourceDocument": params.get("sourceDocument"), "ids": params.get("ids") }) } else { json!({}) }; + let query = match command { + DROP => json!({ "sourceDocument": params.get("sourceDocument"), "ids": params.get("ids") }), + ALL_ARTBOARDS => json!({ "allArtboards": true }), + _ => json!({}), + }; let found = app.session.execute("clipboard.profileMismatch", &query).ok()?; found["mismatches"].as_array().cloned() } +/// Paste on All Artboards, which leaves copied artboards behind. +const ALL_ARTBOARDS: &str = "edit.pasteOnAllArtboards"; + +/// Can the colors of mismatch `m` convert (both profiles are available)? +fn convertible(m: &Value) -> bool { + m["convertible"].as_bool().unwrap_or(true) +} + +/// May the colors of mismatch `m` take `value`? Preserve Numbers always; Convert only when they can +/// convert. +fn allowed(m: &Value, value: &str) -> bool { + value != "convert" || convertible(m) +} + /// The choice the paste question starts on: the model's policy for one model, and for both a /// choice for each (`{rgb, cmyk}`), each starting on its model's policy. fn first_choice(mismatches: &[Value]) -> Value { @@ -249,7 +322,8 @@ fn pick(choice: &Value, mismatches: &[Value], model: &str, value: &str) -> Value Value::Object(each.collect()) } -/// Is `choice` one choice for every model, or a choice for each of `mismatches`' models? +/// Is `choice` one choice for every model, or a choice for each of `mismatches`' models? (Convert +/// for a model whose colors can't convert keeps their numbers, as the paste commands do.) fn valid_choice(choice: &Value, mismatches: &[Value]) -> bool { let known = |v: &str| paste_choices().iter().any(|(c, _)| *c == v); match choice { @@ -279,7 +353,8 @@ fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool let mut clicked = None; for (value, text) in paste_choices() { label(ui, ""); - if widgets::radio(ui, text, now == value, true) { + // Colors whose profile is not available can only keep their numbers. + if widgets::radio(ui, text, now == value, allowed(m, value)) { clicked = Some(value); } ui.end_row(); @@ -301,7 +376,9 @@ const DOC: &str = "__doc"; /// OK: run the paste with the choice; any Swatch Conflict question comes next. When another /// document has become the active one since a paste that runs at once asked, it closes as Cancel /// does and pastes nothing. When the profiles that paste or drop would bring have changed since it -/// asked (the clipboard or the dragged objects' document changed), it asks again about the new ones. +/// asked (the clipboard, the dragged objects' document or the destination's profile changed), it +/// asks again about the new ones; a paste that waited for its clipboard is checked in the document +/// and with the clipboard it runs with. fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); let asked = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); @@ -316,19 +393,15 @@ fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { } let command = d.str("__command"); let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); - if deferred.is_none() - && let Some(now) = paste_mismatches(app, &command, ¶ms).filter(|a| !a.is_empty()) - && d.fields.get("mismatches").and_then(Value::as_array) != Some(&now) - { - app.ui.dialog = None; - if let Some(r) = ask_paste(app, &command, ¶ms) { - return r; - } - } params["profileMismatch"] = choice; app.ui.dialog = None; + // Without the answer, the paste asks again about what it brings now. + let changed = |app: &mut VectorcraftApp, command: &str, params: &Value| { + paste_mismatches(app, command, params).is_some_and(|now| !now.is_empty() && now != asked) + }; + let recheck = crate::placing::Recheck { key: "profileMismatch", changed: &changed }; // A paste that waited for its clipboard runs in the context it was given in. - crate::placing::confirm_swatch_paste(app, &command, params, deferred) + crate::placing::confirm_swatch_paste(app, &command, params, deferred, Some(&recheck)) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index d62c56e431..358c6f428e 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -27,6 +27,19 @@ fn rgb_profile(app: &VectorcraftApp) -> Option { vectorcraft_engine::cmd::colormgmt::doc_profiles(&app.session.doc().unwrap().doc).0 } +/// OK on the open question, run by `confirm`, opens one document, installed with `roots`. +fn confirm_opens_one_under( + app: &mut VectorcraftApp, + roots: Option<&std::sync::Arc>, + confirm: impl FnOnce(&mut VectorcraftApp) -> Value, +) { + let docs = app.session.documents().len(); + let r = confirm(app); + assert_eq!(app.session.documents().len(), docs + 1, "{r}"); + let opened = &app.session.documents()[r["index"].as_u64().unwrap() as usize]; + assert_eq!(opened.opened_by.as_ref().map(|o| o.describe()), roots.map(|o| o.describe())); +} + /// An open asked under automation roots finishes under them, though OK is pressed outside them: its /// linked files are read, and the document is installed, with the roots of the open. `tagged` asks /// with the settings in force. @@ -37,8 +50,7 @@ fn open_asked_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None)).unwrap(); assert_eq!(r, json!({ "dialog": OPEN_KIND })); assert!(file_access::current().is_none(), "OK is pressed outside the roots"); - super::super::confirm(app).unwrap(); - assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the open"); + confirm_opens_one_under(app, roots.as_ref(), |app| super::super::confirm(app).unwrap()); } /// An open asked outside automation roots and confirmed by a caller under them finishes under that @@ -49,8 +61,122 @@ fn open_confirmed_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); let r = crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); assert_eq!(r, json!({ "dialog": OPEN_KIND })); - file_access::confine(roots.as_ref(), || super::super::confirm(app)).unwrap(); - assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the caller that confirmed"); + confirm_opens_one_under(app, roots.as_ref(), |app| file_access::confine(roots.as_ref(), || super::super::confirm(app)).unwrap()); +} + +/// A PNG of one color, 8 × 8. +fn png(rgb: [u8; 3]) -> Vec { + let [r, g, b] = rgb; + let layout = (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8); + let img = craft_image_codecs::Image::from_raw(8, 8, layout.0, layout.1, [r, g, b, 255].repeat(64)).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The linked files of a document asked about under automation roots, and confirmed outside them, +/// are read under those roots, apart from where the document is installed: of two linked files +/// changed since the save, the one inside the roots updates, and the one outside keeps the picture +/// the document holds. The Ask When Opening box for a mismatch is on. +fn links_read_under_the_roots_of_the_open(app: &mut VectorcraftApp) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-links"); + let (inside, outside) = (dir.join("inside"), dir.join("outside")); + let (a, b) = (inside.join("in.png"), outside.join("out.png")); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for p in [&a, &b] { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, png([200, 40, 40])).unwrap(); + s.execute("file.place", &json!({"path": p.to_str().unwrap(), "at": [50, 50]})).unwrap(); + } + s.execute("edit.assignProfile", &json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + let r = s.execute("document.serialize", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + // The profiles in use are the process's: back to the working spaces. + s.execute("edit.assignProfile", &json!({ "rgb": null })).unwrap(); + for p in [&a, &b] { + let stamp = std::fs::metadata(p).unwrap().modified().unwrap(); + std::fs::write(p, png([40, 40, 200])).unwrap(); + // Link stamps use milliseconds: the new file is dated 2 s later. + let later = std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2)); + std::fs::OpenOptions::new().write(true).open(p).unwrap().set_times(later).unwrap(); + } + let update = std::mem::replace(&mut app.session.prefs.update_links, "automatically".into()); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[]).unwrap(); + let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "linked.vectorcraft", &bytes, None)).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + let r = super::super::confirm(app).unwrap(); + let updated: Vec<&str> = r["updatedLinks"].as_array().map(|a| a.iter().filter_map(|l| l["name"].as_str()).collect()).unwrap_or_default(); + assert_eq!(updated, ["in.png"], "{r}"); + app.session.prefs.update_links = update; + // A question about the link outside the roots is not part of this check. + if app.ui.dialog.is_some() { + super::super::cancel(app); + } +} + +/// A file read while another one's question is open waits and asks its own question in turn, and +/// each opens only after its own answer: Cancel on the first leaves it closed and asks about the +/// second. `tagged` asks with the settings in force. +fn files_opened_together_ask_in_turn(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + assert_eq!(crate::io::open_bytes(app, "first.vectorcraft", tagged, None).unwrap(), json!({ "dialog": OPEN_KIND })); + let r = crate::io::open_bytes(app, "second.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true })); + assert_eq!(app.queued_profile_opens.len(), 1); + super::super::cancel(app); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "the second asks"); + assert!(app.queued_profile_opens.is_empty()); + assert_eq!(app.session.documents().len(), docs, "neither is open"); + super::super::confirm(app).unwrap(); + assert_eq!(app.session.documents().len(), docs + 1); + assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); +} + +/// Color Settings change the open question while it is open: OK asks the question as it is now +/// (another working space) instead of opening, and opens by the policy once there is no question +/// (the working space is the file's profile). `tagged` (Wide Gamut RGB) asks with the settings in +/// force, the working space sRGB. +fn an_answer_waits_for_the_question_it_answers(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert_eq!(super::super::confirm(app).unwrap(), json!({ "dialog": OPEN_KIND })); + assert_eq!(app.session.documents().len(), docs, "not opened under the old question"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("working"), cms::canonical_name(cms::DISPLAY_P3), "asked again"); + app.run("edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert!(r.get("index").is_some() && app.ui.dialog.is_none(), "{r}"); + assert_eq!(app.session.documents().len(), docs + 1); +} + +/// Swatch Conflict asks again when the conflicts a converting paste raises change while it is open: +/// the destination is assigned another profile, so the pasted swatch converts to another color. OK +/// then pastes nothing and asks about the new conflict; OK on that one pastes as chosen. +fn swatch_conflicts_are_asked_again_when_they_change(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + let swatch = json!({"name": "Brand", "color": "#3366cc", "global": true}); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch.clone()).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch).unwrap(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = count(app); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + let asked = app.ui.dialog.as_ref().unwrap().fields["conflicts"].clone(); + set(app, "choice", json!("add")); + app.run("edit.assignProfile", json!({ "rgb": cms::DISPLAY_P3 })).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "asked again: {r}"); + assert_eq!(count(app), before, "nothing pasted under the old list"); + assert_ne!(app.ui.dialog.as_ref().unwrap().fields["conflicts"], asked); + set(app, "choice", json!("add")); + let r = super::super::confirm(app).unwrap(); + assert_eq!((count(app), r["renamed"].as_array().map(Vec::len)), (before + 1, Some(1)), "{r}"); } /// Cancel on the paste question pastes nothing, and a null `profileMismatch` asks as leaving it out @@ -65,18 +191,18 @@ fn paste_canceled(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> u } /// Another document becomes the active one while the paste question is open: OK pastes nothing, into -/// neither document, and the document the paste was asked in is active again afterward. `count` -/// counts the active document's objects. -fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { - let (asked_in, before) = (app.session.active_index().unwrap(), count(app)); +/// neither document, whichever is active. +fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) { + let counts = |app: &VectorcraftApp| -> Vec<(u64, usize)> { + app.session.documents().iter().map(|st| (st.uid, st.doc.layers[0].children().map_or(0, |c| c.len()))).collect() + }; + let (asked_in, before) = (app.session.active_index().unwrap(), counts(app)); assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND })); app.run("document.activate", json!({"index": 0})).unwrap(); - let other = count(app); super::super::confirm(app).unwrap(); assert!(app.ui.dialog.is_none()); - assert_eq!(count(app), other, "nothing pasted into the document now active"); + assert_eq!(counts(app), before, "nothing pasted into any document"); app.run("document.activate", json!({ "index": asked_in })).unwrap(); - assert_eq!(count(app), before, "nor into the one it was asked in"); } /// A drag of the art of the document assigned Display P3 into the active one asks as Paste does: @@ -118,8 +244,8 @@ fn drop_asks_as_paste_does(app: &mut VectorcraftApp, count: impl Fn(&Vectorcraft #[test] fn a_paste_question_about_both_models_has_a_choice_for_each() { let both = [ - json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "preserveNumbers"}), - json!({"model": "cmyk", "clipboard": "Ink A", "document": "Ink B", "default": "convert"}), + json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "preserveNumbers", "convertible": true}), + json!({"model": "cmyk", "clipboard": "Ink A", "document": "Ink B", "default": "convert", "convertible": true}), ]; assert_eq!(first_choice(&both), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); assert_eq!(first_choice(&both[1..]), json!("convert"), "one model starts on its policy"); @@ -211,6 +337,8 @@ fn opening_and_pasting_ask_about_profiles() { open_asked_under_roots(&mut app, &tagged); open_confirmed_under_roots(&mut app, &tagged); + links_read_under_the_roots_of_the_open(&mut app); + files_opened_together_ask_in_turn(&mut app, &tagged); // Missing Profiles: Ask When Opening, and a choice the file refuses. app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); @@ -248,11 +376,37 @@ fn opening_and_pasting_ask_about_profiles() { // Cancel pastes nothing; with the box off nothing asks. let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); paste_canceled(&mut app, count); - paste_asked_before_another_document_is_active(&mut app, count); + paste_asked_before_another_document_is_active(&mut app); drop_asks_as_paste_does(&mut app, count); let before = count(&app); app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); let r = app.run("edit.paste", json!({})).unwrap(); assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); assert_eq!(count(&app), before + 1); + swatch_conflicts_are_asked_again_when_they_change(&mut app); + all_artboards_leaves_backgrounds_out(&mut app); + // It changes the working space: last. + app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); + an_answer_waits_for_the_question_it_answers(&mut app, &tagged); +} + +/// Convert is offered only for a model whose colors can convert (`convertible`). +#[test] +fn convert_needs_both_profiles() { + let stuck = json!({"model": "rgb", "clipboard": "Gone", "document": "sRGB", "default": "preserveNumbers", "convertible": false}); + let free = json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "convert", "convertible": true}); + assert!(allowed(&stuck, "preserveNumbers") && !allowed(&stuck, "convert")); + assert!(allowed(&free, "convert") && allowed(&json!({"model": "rgb"}), "convert")); +} + +/// Paste on All Artboards asks about what it brings, without the backgrounds of copied artboards. +fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let listed = |app: &mut VectorcraftApp, command: &str| paste_mismatches(app, command, &json!({})).map(|m| m.len()); + assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); + assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); } diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index b525b82c7c..96ff733c42 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -36,13 +36,7 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option DialogResult { } let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); params["swatchConflict"] = Value::Object(choices); + // When the conflicts the paste raises have changed meanwhile (another profile converts the + // pasted swatches), it asks again about them instead. + let asked = list.to_vec(); app.ui.dialog = None; - crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, d.fields.get("__deferredPaste").and_then(Value::as_u64)) + let changed = |app: &mut VectorcraftApp, _: &str, params: &Value| found(app, params).is_some_and(|now| now != asked); + let recheck = crate::placing::Recheck { key: "swatchConflict", changed: &changed }; + let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); + crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, deferred, Some(&recheck)) +} + +/// The swatch conflicts pasting with `params` raises (`clipboard.conflicts`), with the swatches as +/// the paste brings them: converted from another profile when it converts. +fn found(app: &mut VectorcraftApp, params: &Value) -> Option> { + let mut q = json!({}); + if let Some(m) = params.get("profileMismatch") { + q["profileMismatch"] = m.clone(); + } + let found = app.session.execute("clipboard.conflicts", &q).ok()?; + found["swatches"].as_array().cloned() } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8d0a355b52..b0d408285c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -352,6 +352,9 @@ pub struct VectorcraftApp { /// The file File › Open read that waits for the answer to its profile question /// ([`dialogs::profile_mismatch`]), kept out of the dialog's fields. pub(crate) pending_profile_open: Option, + /// Files File › Open read while another one's profile question was open, each asking its own + /// question in turn. + pub(crate) queued_profile_opens: std::collections::VecDeque, /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) script_picked: Vec, diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 0743918568..cdb35e7419 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -668,14 +668,41 @@ fn pastes_inside(id: &str) -> bool { !matches!(id, "edit.pasteInFront" | "edit.pasteInBack") } +/// The answer a paste question gave, checked again where the paste runs (in the document and with +/// the clipboard it was given with): `key` is the param that holds the answer, and `changed` tells +/// whether the question the paste command `id` with those params would ask now differs from the one +/// answered. The paste then runs without the answer, and so asks again. +pub(crate) struct Recheck<'a> { + pub key: &'static str, + pub changed: &'a dyn Fn(&mut VectorcraftApp, &str, &Value) -> bool, +} + +/// `params` without the answer `recheck` names when the question it answered has changed. +fn rechecked(app: &mut VectorcraftApp, id: &str, mut params: Value, recheck: Option<&Recheck<'_>>) -> Value { + if let Some(r) = recheck + && (r.changed)(app, id, ¶ms) + && let Some(o) = params.as_object_mut() + { + o.remove(r.key); + } + params +} + /// Run the command confirmed by the deferred paste's Swatch Conflict or Paste Profile Mismatch -/// dialog. -pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: Value, token: Option) -> Result { +/// dialog, asking again first when `recheck` finds that the question has changed. +pub(crate) fn confirm_swatch_paste( + app: &mut VectorcraftApp, + id: &str, + params: Value, + token: Option, + recheck: Option<&Recheck<'_>>, +) -> Result { if !app.placing.swatch_paste.as_ref().is_some_and(|waiting| Some(waiting.chain) == token) { if token.is_some() || app.placing.swatch_paste.is_some() { cancel_swatch_paste(app); return Err("the deferred paste is no longer available".into()); } + let params = rechecked(app, id, params, recheck); return app.run(id, params); } let Some(waiting) = app.placing.swatch_paste.take() else { return app.run(id, params) }; @@ -701,11 +728,13 @@ pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: V } let insertion = waiting.insertion.clone().or_now(changed.as_ref(), app, pastes_inside(id)); insertion.clone().set(app); + // The question checked again with the clipboard and document the paste runs with. + let params = rechecked(app, id, params, recheck); app.placing.adopted = true; let result = app.run(id, params); app.placing.adopted = false; - // The paste asked again (Swatch Conflict after Paste Profile Mismatch): it stays deferred, in - // the context it was given in. + // The paste asked again (Swatch Conflict after Paste Profile Mismatch, or the same question + // about what changed): it stays deferred, in the context it was given in. let asked_again = app.ui.dialog.as_mut().filter(|d| asks_before_paste(&d.kind) && !d.fields.contains_key("__deferredPaste")); if let Some(d) = asked_again && let Ok(st) = app.session.doc() diff --git a/docs/mcp.md b/docs/mcp.md index 5f56c15f13..8e5ab0b0da 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1874,21 +1874,30 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel, the Color Picker, Swatch Options and New Swatch check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. - **Profile Mismatches and Missing Profiles** (`edit.colorSettings {askMismatchOpen, askMismatchPaste, - askMissingOpen}`, all off by default and kept in `Color Settings.json`): with `askMismatchOpen` or - `askMissingOpen` on, the desktop app's File › Open asks before a document opens when the profile of its color mode - is not the working space (use the embedded profile, convert the colors to the working space, or discard the - profile) or when it has none (leave it, assign the working space, or assign a profile), starting on what the - model's policy does; Cancel leaves the file closed. `document.open` never asks: `profileChoice` (`useEmbedded`, - `convert`, `discard`; `leave`, `assignWorking`, `assign` with `assignProfile`) states the answer, else the policy - applies, and the reply's `profileChoice` names the answer used. Copy remembers the profiles the colors showed - through; pasting them into a document with another RGB or CMYK profile keeps their numbers or converts them, as - `profileMismatch` on the paste commands and `edit.dropSelection` says (`preserveNumbers` or `convert` for both - models, or `{rgb?, cmyk?}` with one for each), else as the model's policy does (`convert` converts, the others keep - the numbers; a profile that is not available keeps them). `clipboard.profileMismatch` lists the models that - differ, only those whose colors the copied objects use (with `sourceDocument` and `ids`, the objects a drop - brings), and with `askMismatchPaste` on the desktop app asks first on Paste and on a drag between documents. A - question about both models has a choice for each, each starting on its model's policy. New from Template and - File › Revert follow the policies without asking. + askMissingOpen}`, all off by default and kept in `Color Settings.json`): with `askMismatchOpen` on, the desktop + app's File › Open asks before a document opens when the profile of its color mode is not the working space (use + the embedded profile, convert the colors to the working space, or discard the profile); with `askMissingOpen` on, + it asks when the document has no profile of its color mode (leave it, assign the working space, or assign a + profile). Each question starts on what the model's policy does, and Cancel leaves the file closed. Files opened + together ask one at a time, each opening only after its own answer. When Color Settings change the question + while it is open (another working space), OK asks the new question instead of opening. `document.open` never + asks: `profileChoice` (`useEmbedded`, `convert`, `discard`; `leave`, `assignWorking`, `assign` with + `assignProfile`) states the answer, else the policy applies. The reply's `profileChoice` names the choice given + for the document's question, not what it did: `convert` from a profile that is not available keeps the profile, + and a warning says the colors were not converted. Copy remembers the profiles the colors showed through (a + document's assigned profile that was removed since counts as the working space it draws through); pasting them + into a document with another RGB or CMYK profile keeps their numbers or converts them, as `profileMismatch` on the + paste commands and `edit.dropSelection` says (`preserveNumbers` or `convert` for both models, or `{rgb?, cmyk?}` + with one for each; `null` is the same as leaving it out), else as the model's policy does (`convert` converts, the + others keep the numbers). Colors whose source or destination profile is not available keep their numbers, also + with `convert`. `clipboard.profileMismatch` lists the models that differ, only those whose colors the copied + objects use (with `sourceDocument` and `ids`, the objects a drop brings; with `allArtboards: true`, without the + background colors of copied artboards, which Paste on All Artboards leaves behind), and gives `convertible: false` + for a model whose colors can't convert. With `askMismatchPaste` on, the desktop app asks first on Paste and on a + drag between documents, and offers only Preserve Numbers for a model that can't convert. A question about both + models has a choice for each, each starting on its model's policy. When the profiles a paste brings or the swatch + conflicts it raises change while the paste question or Swatch Conflict is open, OK asks again about them. New from + Template and File › Revert follow the policies without asking. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or From 6c5e10fd6438beda863ad312f28c577dadea3520 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:46:24 -0800 Subject: [PATCH 09/10] Color Settings: keep script gates and background reads after a profile answer - A scope narrowed to the confirming caller keeps the script gates of both, and reads are exempt from them only where both scopes exempt them. - A file read off the UI thread does the rest of its read after its profile answer (linked files and type) off the UI thread too; an open a caller asked for by path still finishes before OK returns. --- crates/engine/src/cmd/fileio/load.rs | 43 +++++++++++---- crates/engine/src/file_access.rs | 53 ++++++++++++++++--- crates/engine/src/script/files.rs | 2 +- .../ui-egui/src/dialogs/profile_mismatch.rs | 31 ++++++++--- crates/ui-egui/src/io/open.rs | 2 +- crates/ui-egui/src/opening.rs | 33 +++++++++++- 6 files changed, 136 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 61b371bcd6..d63f296bdc 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -698,6 +698,9 @@ pub struct ReadFile { /// The profile question as it was last asked ([`ReadFile::ask`]): an answer is taken only while /// the question is still the same. asked: Option, + /// Update Links and the low-resolution EPS proxy setting, while the linked files and the type + /// are left to do after the answer ([`ReadFile::finish_read`]). + links_left: Option<(bool, bool)>, } /// The part of [`read_for_open`] a file waiting for a profile answer has left to do. @@ -772,6 +775,7 @@ pub fn read_for_open_asking( rest: Some(Rest { update_links, low_res_proxy_eps, color_mode }), answered: None, asked: None, + links_left: None, }; if ask && file.choice.is_none() && file.ask().is_some() { return Ok(file); @@ -802,11 +806,12 @@ impl ReadFile { self.asked.clone() } - /// Answer the profile question with `choice` and do the rest of the read: the policies (the - /// answer in place of the one of the document's color mode), the color mode, the linked files - /// and the type. An error leaves the file waiting: a profile to assign that is not one of that - /// model, or Color Settings changed since the question was asked ([`Self::ask`]) so that the - /// question, its model, the profile it is about or the working space differ. + /// Answer the profile question with `choice` and apply it: the policies (the answer in place of + /// the one of the document's color mode) and the color mode. The linked files and the type are + /// left for [`Self::finish_read`] or [`open_read`]. An error leaves the file waiting: a profile + /// to assign that is not one of that model, or Color Settings changed since the question was + /// asked ([`Self::ask`]) so that the question, its model, the profile it is about or the working + /// space differ. pub fn answer(&mut self, choice: crate::cmd::colormgmt::ProfileChoice) -> Result<()> { if let Some(asked) = &self.asked && self.rest.is_some() @@ -818,7 +823,7 @@ impl ReadFile { } } let before = self.choice.replace(choice); - let r = self.finish_read(); + let r = self.apply_answer(); if r.is_err() { self.choice = before; } @@ -826,8 +831,26 @@ impl ReadFile { } /// The rest of [`read_for_open_asking`], once: the color management policies with the profile - /// answer, the color mode `colorMode` asks for, the linked files and the type. - fn finish_read(&mut self) -> Result<()> { + /// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked + /// files and the type. The app runs it off the UI thread once the question is answered. + pub fn finish_read(&mut self) -> Result<()> { + self.apply_answer()?; + self.finish_links(); + Ok(()) + } + + /// Read the linked files and lay out the type of a file whose profile answer is applied + /// ([`Self::answer`]), once. A file still waiting for its answer is left as it is. + fn finish_links(&mut self) { + let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return }; + let base = crate::cmd::links::LinkBase::file(self.path.as_deref()); + self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps); + Session::refresh_text_bounds(&mut self.loaded.doc); + } + + /// The policies with the profile answer and the color mode `colorMode` asks for, once; the + /// linked files and the type are left for [`Self::finish_read`]. + fn apply_answer(&mut self) -> Result<()> { if self.rest.is_none() { return Ok(()); } @@ -850,9 +873,7 @@ impl ReadFile { super::super::colormgmt::set_color_mode(doc, mode, true, None, grays); }); } - let base = crate::cmd::links::LinkBase::file(self.path.as_deref()); - self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, rest.update_links, rest.low_res_proxy_eps); - Session::refresh_text_bounds(&mut self.loaded.doc); + self.links_left = Some((rest.update_links, rest.low_res_proxy_eps)); Ok(()) } } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c170c14c27..6a46b8f3cc 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -253,17 +253,24 @@ impl ScopeHandle { } /// The captured scope narrowed to what the calling thread may reach as well: the roots of both - /// are in force ([`AutomationRoots::intersect`]), and without roots in either, none are. + /// are in force ([`AutomationRoots::intersect`]), and without roots in either, none are. The + /// script gates of both are in force too, and reads are exempt from them only where both are. pub fn within_current(self) -> Self { let here = Self::capture(); - let roots = match (self.roots(), here.roots()) { - (None, None) => return self, - (Some(r), None) | (None, Some(r)) => r, - (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => a, - (Some(a), Some(b)) => a.intersect(&b), + let gate = match (self.1.clone(), here.1.clone()) { + (None, None) => None, + (Some(g), None) | (None, Some(g)) => Some(g), + (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Some(a), + (Some(a), Some(b)) => Some(Arc::new(ScriptGate { also: Some(b), ..(*a).clone() })), }; - let Self(_, gate, exempt) = self; - Self(Some(Scope::Confined(roots)), gate, exempt) + let exempt = self.2 && here.2; + let scope = match (self.roots(), here.roots()) { + (None, None) => self.0, + (Some(r), None) | (None, Some(r)) => Some(Scope::Confined(r)), + (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Some(Scope::Confined(a)), + (Some(a), Some(b)) => Some(Scope::Confined(a.intersect(&b))), + }; + Self(scope, gate, exempt) } } @@ -277,10 +284,15 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). + pub(crate) also: Option>, } impl ScriptGate { fn check(&self, path: &str, access: Access) -> Result<(), String> { + if let Some(also) = &self.also { + also.check(path, access)?; + } let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { @@ -889,6 +901,31 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A scope narrowed to the calling thread keeps the script gate of both: a script command that + /// carries on work saved without a gate reads only what its gate allows, and with a gate saved + /// too, only what both allow; reads are exempt only where both scopes exempt them. + #[test] + fn a_narrowed_scope_keeps_the_script_gates_of_both() { + let (base, _) = folders("narrowed-gate"); + let gate = + |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); + let reads = |saved: ScopeHandle, gate_here: Option| { + let narrowed = match gate_here { + Some(g) => with_script_gate(g, || saved.within_current()), + None => saved.within_current(), + }; + narrowed.run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())) + }; + let plain = ScopeHandle(None, None, false); + assert_eq!(reads(plain.clone(), Some(gate("in"))), (true, false), "the confirming command's gate"); + assert_eq!(reads(ScopeHandle(None, Some(Arc::new(gate("in"))), false), None), (true, false), "the saved gate"); + assert_eq!(reads(ScopeHandle(None, Some(Arc::new(gate("in"))), false), Some(gate("outside"))), (false, false), "both gates"); + assert_eq!(reads(ScopeHandle(None, None, true), Some(gate("in"))), (true, false), "exempt only where both are"); + assert_eq!(reads(plain, None), (true, true)); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 6eecfeabf8..c0694bbd81 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -457,7 +457,7 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, and the files of /// the open documents, `documents`. pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents } + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } } /// The files written since this was last asked, to name in the report. diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index f04fff2ba8..a0f447277e 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -61,6 +61,10 @@ pub(crate) struct PendingOpen { /// The automation roots in force where the open was asked for: its linked files are read, and /// the document is installed, under them and those of the caller that confirms. scope: ScopeHandle, + /// It was read off the UI thread ([`crate::opening`]): the rest of its read is done there too + /// once the question is answered. An open that answers at once (a path a caller asked for) + /// finishes before OK returns. + background: bool, } /// The choices of a mismatch (`missing`: of a missing profile), as (`choice`, label). @@ -85,15 +89,16 @@ fn paste_choices() -> [(&'static str, &'static str); 2] { /// Settings asks about its profile ([`ReadFile::ask`]): then the dialog asks first, and the result /// is `{dialog}`. A file read while another one's question is open waits for its own question /// until that one is answered (`{dialog, queued: true}`). Opened, the views follow and the file -/// goes on the recent files ([`crate::io::opened`]). -pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option) -> Result { - ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture() }) +/// goes on the recent files ([`crate::io::opened`]). `background`: the file was read off the UI +/// thread, and the rest of its read after an answer is done there too. +pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option, background: bool) -> Result { + ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture(), background }) } /// [`open_or_ask`] for a file that has its scope already. fn ask_or_open(app: &mut VectorcraftApp, mut pending: PendingOpen) -> Result { let Some(q) = pending.file.ask() else { - let PendingOpen { file, path, scope } = pending; + let PendingOpen { file, path, scope, .. } = pending; return scope.run(|| { let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; crate::io::opened(app, &r); @@ -213,10 +218,24 @@ fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { open_pending(app, pending, scope) } -/// Open `pending`, answered or without a question, under `scope`; a failure is reported. +/// Open `pending`, answered or without a question, under `scope`; a failure is reported. A file read +/// off the UI thread does the rest of its read (its linked files and type) there too +/// ([`crate::opening::finish_answered`]). fn open_pending(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> DialogResult { - let PendingOpen { file, path, .. } = pending; + let PendingOpen { file, path, background, .. } = pending; let name = file.name(); + let file = match &path { + Some(p) if background && crate::opening::available() => match crate::opening::finish_answered(app, p, file, scope.clone()) { + Ok(r) => return Ok(r), + Err(Some(file)) => *file, + Err(None) => { + let e = "the file stopped being read (please report this bug)".to_string(); + crate::io::report_open_error(app, &name, &e); + return Err(e); + } + }, + _ => file, + }; scope.run(|| match fileio::open_read(&mut app.session, file) { Ok(r) => { crate::io::opened(app, &r); diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index f6fa57f28e..b0a037804f 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -138,7 +138,7 @@ pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: O let update_links = app.session.prefs.update_links == "automatically"; let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; let file = fileio::read_for_open_asking(name, bytes, path.clone(), p, update_links, low_res_proxy_eps, true).map_err(|e| e.to_string())?; - dialogs::profile_mismatch::open_or_ask(app, file, path) + dialogs::profile_mismatch::open_or_ask(app, file, path, false) } /// Did an open answer that it asks a question first (`{dialog}`), so the file isn't open yet? diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 06dd2b6a0a..5b4c8619ee 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -113,6 +113,37 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec, params: Ok(json!({ "background": true, "status": status })) } +/// Do the rest of the read of `file`, read for File › Open from `path` once its profile question +/// is answered or gone (its linked files and type, [`ReadFile::finish_read`]), on a thread of its +/// own under `scope`; it then opens as a file read off the UI thread does → `{background: true, +/// status}`, or the file back when no thread could start (the caller opens it at once). +pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFile, scope: ScopeHandle) -> Result>> { + let (tx, done) = channel(); + let slot = Arc::new(std::sync::Mutex::new(Some(file))); + let taken = slot.clone(); + let run = scope.clone(); + let spawned = std::thread::Builder::new().name("vectorcraft-open".into()).spawn(move || { + let Some(mut file) = taken.lock().ok().and_then(|mut f| f.take()) else { return }; + let r = run + .run(|| vectorcraft_engine::guard::catch_panic(|| file.finish_read().map_err(|e| e.to_string()))) + .unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)"))); + let r = r.map(|()| file); + // The app may have quit meanwhile: nothing to hand it to. + let _ = tx.send(r); + }); + if spawned.is_err() { + return Err(slot.lock().ok().and_then(|mut f| f.take()).map(Box::new)); + } + let label = format!("Opening {}", fileio::file_name(path)); + app.opening.next_id += 1; + let id = app.opening.next_id; + let token = CancelToken::new(); + app.opening.pending.push(Pending { id, path: path.to_string(), label: label.clone(), done, scope, token, hidden: false }); + let status = format!("{label}…"); + app.status(status.clone()); + Ok(json!({ "background": true, "status": status })) +} + /// May the active document change now ([`poll`])? pub(crate) fn may_switch(app: &VectorcraftApp) -> bool { let s = &app.session; @@ -240,7 +271,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { /// after the profile question Edit › Color Settings asks about it, if any /// ([`crate::dialogs::profile_mismatch::open_or_ask`]). fn finish(app: &mut VectorcraftApp, path: &str, r: Result) { - let opened = r.and_then(|file| crate::dialogs::profile_mismatch::open_or_ask(app, file, Some(path.to_string()))); + let opened = r.and_then(|file| crate::dialogs::profile_mismatch::open_or_ask(app, file, Some(path.to_string()), true)); if let Err(e) = opened { crate::io::report_open_error(app, &fileio::file_name(path), &e); } From e506b7ed74ad4c4dd417de0e8fe1567e9a0135bd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:20:18 -0800 Subject: [PATCH 10/10] Color Settings: a scope narrowed several times keeps every script gate Narrowing a scope that already carried two composed gates replaced the earlier gate's chain with the new gate, so a path only that earlier gate refused could be read. The new gate is now added at the end of the chain. --- crates/engine/src/file_access.rs | 33 +++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 6a46b8f3cc..c5ecee374e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -261,7 +261,7 @@ impl ScopeHandle { (None, None) => None, (Some(g), None) | (None, Some(g)) => Some(g), (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Some(a), - (Some(a), Some(b)) => Some(Arc::new(ScriptGate { also: Some(b), ..(*a).clone() })), + (Some(a), Some(b)) => Some(Arc::new(a.followed_by(b))), }; let exempt = self.2 && here.2; let scope = match (self.roots(), here.roots()) { @@ -289,6 +289,17 @@ pub(crate) struct ScriptGate { } impl ScriptGate { + /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every + /// gate already in the chain as well as `next`. + fn followed_by(&self, next: Arc) -> ScriptGate { + let also = match &self.also { + None => next, + Some(also) if Arc::ptr_eq(also, &next) => next, + Some(also) => Arc::new(also.followed_by(next)), + }; + ScriptGate { also: Some(also), ..self.clone() } + } + fn check(&self, path: &str, access: Access) -> Result<(), String> { if let Some(also) = &self.also { also.check(path, access)?; @@ -926,6 +937,26 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A scope narrowed again and again keeps every gate it was narrowed by: a gate an earlier + /// narrowing joined to the chain still refuses what it refused before. + #[test] + fn a_scope_narrowed_several_times_keeps_every_gate() { + let (base, _) = folders("narrowed-thrice"); + let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); + let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); + let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); + let first = narrow(ScopeHandle(None, None, false), gate(&base)); + assert_eq!(reads(&first), (true, true)); + let second = narrow(first, gate(&base.join("in"))); + assert_eq!(reads(&second), (true, false), "the second gate refuses the outside file"); + let third = narrow(second, gate(&base)); + assert_eq!(reads(&third), (true, false), "the second gate is kept after a third narrowing"); + let fourth = narrow(third, gate(&base)); + assert_eq!(reads(&fourth), (true, false), "and after a fourth"); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] {