diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 96640b5508..a3c35db8ce 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, } } } @@ -589,10 +601,11 @@ impl Cms { /// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s /// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to - /// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded - /// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's - /// black-point compensation; CMYK goes through Lab when either space is built in. Grey and - /// Lab colours stay as they are. + /// 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: 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 } => { @@ -612,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_to_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 95e465b623..836ff9fdb6 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. @@ -478,3 +495,48 @@ 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}"); + } + } +} + +/// 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 4e086569ae..c42289ccc7 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, + "{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 + ), ]; 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() { @@ -486,17 +556,33 @@ 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, true); + 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, 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); + // 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 })) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 6290ccd3b4..3977d8dd01 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1129,8 +1129,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` @@ -1163,9 +1166,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 18374f8302..0ac4f8c3b0 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.newFromTemplate, 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 bpc 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.newFromTemplate, 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 bpc 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,259 @@ 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(_)) { + let path = "assignProfile"; + return Err(bad(cmd, format!("`{path}` goes with `{key}`: \"assign\" only"))); + } + 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 +939,214 @@ 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. 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); + 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 +/// 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): 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, + } + } +} + +/// 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; 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(), "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. 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(); + 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)| { + 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| { + 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 for that model (default: the +/// model's policy, [`PasteProfile::of`]). A source or destination profile that is not available +/// 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, boards); + let mut report = Vec::new(); + let (mut rgb_on, mut cmyk_on) = (false, false); + for m in &mismatches { + 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, + ColorMode::Cmyk => cmyk_on = true, + } + } + 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); + } + 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 +1159,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 f126ac78ec..5e0231228b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -115,7 +115,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], 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 ), @@ -180,7 +180,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; 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\"}. 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) ), @@ -189,7 +189,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) ), @@ -198,7 +198,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) ), @@ -207,7 +207,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) ), @@ -216,7 +216,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) ), @@ -1278,26 +1278,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() { @@ -1305,7 +1291,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"}))?; - paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, &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, 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() + { + 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)] @@ -1340,10 +1357,23 @@ 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`). 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, mode != PasteMode::AllArtboards), + 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 } @@ -1520,6 +1550,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| { + // 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()?; diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index f9031f3204..ba5555f9d2 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -84,7 +84,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 0969adb5a2..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), 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}]}; 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 8249fe6b71..d63f296bdc 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -686,6 +686,29 @@ 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 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. +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 @@ -714,36 +737,145 @@ 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, + asked: None, + links_left: None, + }; + if ask && file.choice.is_none() && file.ask().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)) + } + + /// [`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 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() + { + 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.apply_answer(); + if r.is_err() { + self.choice = before; + } + r + } + + /// The rest of [`read_for_open_asking`], once: the color management policies with the profile + /// 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(()); + } + // 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); + }); + } + self.links_left = Some((rest.update_links, rest.low_res_proxy_eps)); + Ok(()) + } } /// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents @@ -757,8 +889,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/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index f9c6471812..e9c316157f 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -147,7 +147,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 b824bebce2..c5ecee374e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -48,7 +48,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, @@ -128,6 +128,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]| { @@ -223,6 +242,36 @@ impl ScopeHandle { let Self(scope, gate, exempt) = self; with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, 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. 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 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(a.followed_by(b))), + }; + 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) + } } /// What a command a running script runs (`vc.run`) may read and write: the places the script's @@ -235,10 +284,26 @@ 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 { + /// 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)?; + } 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 { @@ -824,6 +889,74 @@ 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), None, false); + 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, false), None), Some(roots.describe()), "the saved roots stay"); + assert_eq!(within(ScopeHandle(Some(Scope::Confined(roots.clone())), None, false), Some(&narrow)), Some(both.describe())); + assert!(unconfined.run(|| current().is_none())); + 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); + } + + /// 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"] { 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/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index a7d516f8eb..7c0aef252e 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}; @@ -1082,3 +1082,615 @@ 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())); +} + +/// 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. +#[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. + let srgb = cms::canonical_name(cms::SRGB); + assert_eq!( + r["mismatches"], + 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); + 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); +} + +/// 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]}); + 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": 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}"); + } + 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}"); +} + +/// `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})); + 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})); + 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, stroke_of(s, id), picked("rgb"), picked("cmyk")) + }; + // 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, 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)] { + 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"); +} + +/// 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 1f29608088..ec5f77662b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -187,6 +187,8 @@ impl VectorcraftApp { automation_roots: None, 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/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 701c0f5ffc..5a9e7f7b28 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -214,10 +214,20 @@ 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; } } + // 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.rs b/crates/ui-egui/src/dialogs.rs index fb85fe1458..6797657fad 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -102,6 +102,7 @@ pub mod plugin; mod png_options; pub mod print; pub mod print_presets; +pub mod profile_mismatch; pub mod psd_import; mod psd_options; pub mod raster_effects; @@ -397,6 +398,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, @@ -745,6 +748,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; } @@ -818,6 +827,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 bedd3387c2..5be31baebd 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -297,7 +297,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..a0f447277e --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -0,0 +1,427 @@ +//! 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, 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`, 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}; +use vectorcraft_color::cms::{self, ProfileKind}; +use vectorcraft_engine::cmd::colormgmt::{ProfileChoice, ProfileQuestion}; +use vectorcraft_engine::cmd::fileio::{self, ReadFile}; +use vectorcraft_engine::file_access::ScopeHandle; + +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"; +/// 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(), + 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 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). +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::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`]). `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; + 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) + }); + }; + if app.pending_profile_open.is_some() { + app.queued_profile_opens.push_back(pending); + return Ok(json!({ "dialog": OPEN_KIND, "queued": true })); + } + 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); + } + } +} + +/// 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, under the automation roots of the open and those of the +/// 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 { + app.ui.dialog = None; + return Ok(Value::Null); + }; + let scope = pending.scope.clone().within_current(); + if let Err(e) = scope.clone().run(|| pending.file.answer(choice)) { + // 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. 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, 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); + 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. 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; 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) { + app.pending_profile_open = None; + } + ask_next(app); +} + +/// 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 { + // 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())?; + 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. + 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 }))) +} + +/// The models whose profiles differ for paste `command` with `params` (`clipboard.profileMismatch`): +/// 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 = 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 { + 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? (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 { + 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 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(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, ""); + // 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(); + } + clicked + }) + }); + if let Some(value) = clicked.inner { + d.fields.insert("choice".into(), pick(&choice, &mismatches, id, value)); + } + ui.add_space(10.0); + } + false +} + +/// 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. When the profiles that paste or drop would bring have changed since it +/// 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(); + if !valid_choice(&choice, &asked) { + let key = "choice"; + 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) { + 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!({})); + 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, Some(&recheck)) +} + +#[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..358c6f428e --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -0,0 +1,412 @@ +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 +} + +/// 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. +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"); + 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 +/// 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 })); + 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 +/// 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, 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(); + super::super::confirm(app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(counts(app), before, "nothing pasted into any document"); + app.run("document.activate", json!({ "index": asked_in })).unwrap(); +} + +/// 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); +} + +/// 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", "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"); + 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 +/// 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"; + 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"); + + 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(); + 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()); + paste_canceled(&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 fb8b528b01..96ff733c42 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -36,8 +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/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0355ab892c..9eec08b5d5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5402,6 +5402,25 @@ axis Both И двете Preserve Embedded Profiles Запазване на вградените профили Convert to Working Space Преобразуване в работното пространство Preserve Numbers Запазване на числата + Profile Mismatches: Несъответствия на профила: + Ask When Opening Питане при отваряне + Ask When Pasting Питане при поставяне + Missing Profiles: Липсващи профили: + Embedded Profile Mismatch Несъответствие с вградения профил + Missing Profile Липсващ профил + Paste Profile Mismatch Несъответствие на профила при поставяне + “{name}” is not tagged with a {model} profile. „{name}“ няма {model} профил. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“ има {model} профил „{profile}“, който не е {model} работното пространство „{working}“. + Use the embedded profile Използване на вградения профил + Convert the colors to the working space Преобразуване на цветовете в работното пространство + Discard the embedded profile Отхвърляне на вградения профил + Leave as is Оставяне без промяна + Assign the working space Задаване на работното пространство + 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… Кракелюр… Grain… Зърнистост… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a31af682a1..0232a0ec74 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1054,6 +1054,25 @@ Preserve Embedded Profiles Zadrži ugrađene profile Convert to Working Space Pretvori u radni prostor Preserve Numbers Zadrži brojeve + Profile Mismatches: Neusklađenost profila: + Ask When Opening Pitaj pri otvaranju + Ask When Pasting Pitaj pri lijepljenju + Missing Profiles: Nedostajući profili: + Embedded Profile Mismatch Neusklađenost ugrađenog profila + Missing Profile Nedostaje profil + Paste Profile Mismatch Neusklađenost profila pri lijepljenju + “{name}” is not tagged with a {model} profile. „{name}” nema {model} profil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” ima {model} profil „{profile}”, koji nije {model} radni prostor „{working}”. + Use the embedded profile Koristi ugrađeni profil + Convert the colors to the working space Pretvori boje u radni prostor + Discard the embedded profile Odbaci ugrađeni profil + Leave as is Ostavi kako jeste + Assign the working space Dodijeli radni prostor + 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 Craquelure… Krakelura… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 10c9c8e17a..b53fb7b0cf 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -793,6 +793,25 @@ antiAlias Sharp Nítid Preserve Embedded Profiles Conserva els perfils incrustats Convert to Working Space Converteix a l'espai de treball Preserve Numbers Conserva els números + Profile Mismatches: Discrepàncies de perfil: + Ask When Opening Pregunta en obrir + Ask When Pasting Pregunta en enganxar + Missing Profiles: Perfils que falten: + Embedded Profile Mismatch Discrepància del perfil incrustat + Missing Profile Falta el perfil + Paste Profile Mismatch Discrepància de perfil en enganxar + “{name}” is not tagged with a {model} profile. “{name}” no té cap perfil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” té el perfil {model} “{profile}”, que no és l’espai de treball {model} “{working}”. + Use the embedded profile Utilitza el perfil incrustat + Convert the colors to the working space Converteix els colors a l’espai de treball + Discard the embedded profile Descarta el perfil incrustat + Leave as is Deixa-ho tal com està + Assign the working space Assigna l’espai de treball + 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 Cycle Display Sizes Alterna les mides de visualització diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2edf932ad3..18d811aac2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1072,6 +1072,25 @@ Preserve Embedded Profiles Zachovat vložené profily Convert to Working Space Převést do pracovního prostoru Preserve Numbers Zachovat čísla + Profile Mismatches: Nesoulad profilů: + Ask When Opening Ptát se při otevírání + Ask When Pasting Ptát se při vkládání + Missing Profiles: Chybějící profily: + Embedded Profile Mismatch Nesoulad vloženého profilu + Missing Profile Chybějící profil + Paste Profile Mismatch Nesoulad profilu při vkládání + “{name}” is not tagged with a {model} profile. „{name}“ nemá přiřazen profil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“ má profil {model} „{profile}“, který není pracovním prostorem {model} „{working}“. + Use the embedded profile Použít vložený profil + Convert the colors to the working space Převést barvy do pracovního prostoru + Discard the embedded profile Zahodit vložený profil + Leave as is Ponechat beze změny + Assign the working space Přiřadit pracovní prostor + 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 Craquelure… Krakelování… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1d7719fe95..190d67bafc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3727,6 +3727,25 @@ liquify-list-end {0}, {1} {0} og {1} Preserve Embedded Profiles Bevar indlejrede profiler Convert to Working Space Konverter til arbejdsfarverum Preserve Numbers Bevar tal + Profile Mismatches: Profiluoverensstemmelser: + Ask When Opening Spørg ved åbning + Ask When Pasting Spørg ved indsætning + Missing Profiles: Manglende profiler: + Embedded Profile Mismatch Uoverensstemmelse med indlejret profil + Missing Profile Manglende profil + Paste Profile Mismatch Profiluoverensstemmelse ved indsætning + “{name}” is not tagged with a {model} profile. »{name}« har ingen {model}-profil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. »{name}« har {model}-profilen »{profile}«, som ikke er {model}-arbejdsfarverummet »{working}«. + Use the embedded profile Brug den indlejrede profil + Convert the colors to the working space Konverter farverne til arbejdsfarverummet + Discard the embedded profile Kassér den indlejrede profil + Leave as is Lad være som den er + Assign the working space Tildel arbejdsfarverummet + 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 Craquelure… Krakelering… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 753bd97a37..1e245da022 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5855,6 +5855,25 @@ variable-list-end {0}, {1} {0} und {1} Preserve Embedded Profiles Eingebettete Profile beibehalten Convert to Working Space In Arbeitsfarbraum konvertieren Preserve Numbers Werte beibehalten + Profile Mismatches: Profilabweichungen: + Ask When Opening Beim Öffnen fragen + Ask When Pasting Beim Einfügen fragen + Missing Profiles: Fehlende Profile: + Embedded Profile Mismatch Abweichung vom eingebetteten Profil + Missing Profile Fehlendes Profil + Paste Profile Mismatch Profilabweichung beim Einfügen + “{name}” is not tagged with a {model} profile. „{name}“ ist mit keinem {model}-Profil versehen. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“ ist mit dem {model}-Profil „{profile}“ versehen, das nicht der {model}-Arbeitsfarbraum „{working}“ ist. + Use the embedded profile Eingebettetes Profil verwenden + Convert the colors to the working space Farben in den Arbeitsfarbraum konvertieren + Discard the embedded profile Eingebettetes Profil verwerfen + Leave as is Unverändert lassen + Assign the working space Arbeitsfarbraum zuweisen + 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 @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode PSD-Dateien im Mehrkanalmodus können nicht gelesen werden: Speichern Sie die Datei im RGB-, CMYK- oder Graustufenmodus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 25c8467dc1..73086e6626 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5851,6 +5851,25 @@ variable-list-end {0}, {1} {0} και {1} Preserve Embedded Profiles Διατήρηση ενσωματωμένων προφίλ Convert to Working Space Μετατροπή στον χώρο εργασίας Preserve Numbers Διατήρηση αριθμών + Profile Mismatches: Αναντιστοιχίες προφίλ: + Ask When Opening Ερώτηση κατά το άνοιγμα + Ask When Pasting Ερώτηση κατά την επικόλληση + Missing Profiles: Προφίλ που λείπουν: + Embedded Profile Mismatch Αναντιστοιχία ενσωματωμένου προφίλ + Missing Profile Λείπει προφίλ + Paste Profile Mismatch Αναντιστοιχία προφίλ κατά την επικόλληση + “{name}” is not tagged with a {model} profile. Το «{name}» δεν έχει προφίλ {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. Το «{name}» έχει το προφίλ {model} «{profile}», που δεν είναι ο χώρος εργασίας {model} «{working}». + Use the embedded profile Χρήση του ενσωματωμένου προφίλ + Convert the colors to the working space Μετατροπή των χρωμάτων στον χώρο εργασίας + Discard the embedded profile Απόρριψη του ενσωματωμένου προφίλ + Leave as is Διατήρηση ως έχει + Assign the working space Αντιστοίχιση του χώρου εργασίας + 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 σε κάθε επιφάνεια εργασίας The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. Όσο είναι ορισμένη, η μεταβλητή περιβάλλοντος VECTORCRAFT_TITLEBAR επιλέγει τη γραμμή τίτλου. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7cfea26cdf..3e8ac96865 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5904,6 +5904,25 @@ variable-list-end {0}, {1} {0} y {1} Preserve Embedded Profiles Conservar perfiles incrustados Convert to Working Space Convertir en espacio de trabajo Preserve Numbers Conservar números + Profile Mismatches: Discrepancias de perfil: + Ask When Opening Preguntar al abrir + Ask When Pasting Preguntar al pegar + Missing Profiles: Perfiles que faltan: + Embedded Profile Mismatch Discrepancia del perfil incrustado + Missing Profile Falta el perfil + Paste Profile Mismatch Discrepancia de perfil al pegar + “{name}” is not tagged with a {model} profile. “{name}” no tiene un perfil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” tiene el perfil {model} “{profile}”, que no es el espacio de trabajo {model} “{working}”. + Use the embedded profile Usar el perfil incrustado + Convert the colors to the working space Convertir los colores al espacio de trabajo + Discard the embedded profile Descartar el perfil incrustado + Leave as is Dejar como está + Assign the working space Asignar el espacio de trabajo + 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… Grain… Granulado… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 573dbbf2dd..cc33135a4e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1051,6 +1051,25 @@ Preserve Embedded Profiles Säilytä upotetut profiilit Convert to Working Space Muunna työväriavaruuteen Preserve Numbers Säilytä lukuarvot + Profile Mismatches: Profiilien ristiriidat: + Ask When Opening Kysy avattaessa + Ask When Pasting Kysy liitettäessä + Missing Profiles: Puuttuvat profiilit: + Embedded Profile Mismatch Upotetun profiilin ristiriita + Missing Profile Profiili puuttuu + Paste Profile Mismatch Profiiliristiriita liitettäessä + “{name}” is not tagged with a {model} profile. Kohteella ”{name}” ei ole {model}-profiilia. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. Kohteella ”{name}” on {model}-profiili ”{profile}”, joka ei ole {model}-työväriavaruus ”{working}”. + Use the embedded profile Käytä upotettua profiilia + Convert the colors to the working space Muunna värit työväriavaruuteen + Discard the embedded profile Hylkää upotettu profiili + Leave as is Jätä ennalleen + Assign the working space Määritä työväriavaruus + 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 Craquelure… Krakelyyri… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e8d81e61ef..44c7cc7601 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5881,6 +5881,25 @@ variable-list-end {0}, {1} {0} et {1} Preserve Embedded Profiles Conserver les profils incorporés Convert to Working Space Convertir en espace de travail Preserve Numbers Conserver les valeurs numériques + Profile Mismatches: Non-concordance des profils : + Ask When Opening Demander à l’ouverture + Ask When Pasting Demander au collage + Missing Profiles: Profils manquants : + Embedded Profile Mismatch Non-concordance du profil incorporé + Missing Profile Profil manquant + Paste Profile Mismatch Non-concordance de profil au collage + “{name}” is not tagged with a {model} profile. « {name} » n’a pas de profil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. « {name} » a le profil {model} « {profile} », qui n’est pas l’espace de travail {model} « {working} ». + Use the embedded profile Utiliser le profil incorporé + Convert the colors to the working space Convertir les couleurs dans l’espace de travail + Discard the embedded profile Supprimer le profil incorporé + Leave as is Laisser tel quel + Assign the working space Attribuer l’espace de travail + 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}` é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… Grain… Grain… diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ffa6262d10..693e93ba15 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -492,6 +492,25 @@ Preserve Embedded Profiles એમ્બેડ કરેલી પ્રોફાઇલ જાળવો Convert to Working Space કાર્યકારી સ્પેસમાં રૂપાંતરિત કરો Preserve Numbers સંખ્યાઓ જાળવો + Profile Mismatches: પ્રોફાઇલ મેળ ન ખાવા: + Ask When Opening ખોલતી વખતે પૂછો + Ask When Pasting પેસ્ટ કરતી વખતે પૂછો + Missing Profiles: ખૂટતી પ્રોફાઇલ: + Embedded Profile Mismatch એમ્બેડ કરેલી પ્રોફાઇલ મેળ ખાતી નથી + Missing Profile પ્રોફાઇલ ખૂટે છે + Paste Profile Mismatch પેસ્ટ કરતી વખતે પ્રોફાઇલ મેળ ખાતી નથી + “{name}” is not tagged with a {model} profile. “{name}” પાસે કોઈ {model} પ્રોફાઇલ નથી. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” પાસે {model} પ્રોફાઇલ “{profile}” છે, જે {model} કાર્યકારી સ્પેસ “{working}” નથી. + Use the embedded profile એમ્બેડ કરેલી પ્રોફાઇલ વાપરો + Convert the colors to the working space રંગોને કાર્યકારી સ્પેસમાં રૂપાંતરિત કરો + Discard the embedded profile એમ્બેડ કરેલી પ્રોફાઇલ કાઢી નાખો + Leave as is જેમ છે તેમ રહેવા દો + Assign the working space કાર્યકારી સ્પેસ સોંપો + 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 કેલિગ્રાફિક બ્રશ Calligraphic Brush Options કેલિગ્રાફિક બ્રશ વિકલ્પો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0f39979732..31db4a06b0 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1172,6 +1172,25 @@ antiAlias Sharp शार्प Preserve Embedded Profiles एम्बेड की गई प्रोफ़ाइल बनाए रखें Convert to Working Space वर्किंग स्पेस में बदलें Preserve Numbers संख्याएँ बनाए रखें + Profile Mismatches: प्रोफ़ाइल बेमेल: + Ask When Opening खोलते समय पूछें + Ask When Pasting पेस्ट करते समय पूछें + Missing Profiles: अनुपलब्ध प्रोफ़ाइल: + Embedded Profile Mismatch एम्बेड की गई प्रोफ़ाइल बेमेल + Missing Profile प्रोफ़ाइल अनुपलब्ध + Paste Profile Mismatch पेस्ट करते समय प्रोफ़ाइल बेमेल + “{name}” is not tagged with a {model} profile. "{name}" में कोई {model} प्रोफ़ाइल नहीं है। + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. "{name}" में {model} प्रोफ़ाइल "{profile}" है, जो {model} वर्किंग स्पेस "{working}" नहीं है। + Use the embedded profile एम्बेड की गई प्रोफ़ाइल का उपयोग करें + Convert the colors to the working space रंगों को वर्किंग स्पेस में बदलें + Discard the embedded profile एम्बेड की गई प्रोफ़ाइल हटाएं + Leave as is जैसा है वैसा रहने दें + Assign the working space वर्किंग स्पेस असाइन करें + 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: संयोग: Collapse Panel Group पैनल समूह संक्षिप्त करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c2c4fd26c3..4692d9fb69 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -724,6 +724,25 @@ font-technology Variable Változó Preserve Embedded Profiles Beágyazott profilok megtartása Convert to Working Space Konvertálás a munkaszíntérbe Preserve Numbers Számértékek megtartása + Profile Mismatches: Profileltérések: + Ask When Opening Kérdezzen megnyitáskor + Ask When Pasting Kérdezzen beillesztéskor + Missing Profiles: Hiányzó profilok: + Embedded Profile Mismatch Eltérő beágyazott profil + Missing Profile Hiányzó profil + Paste Profile Mismatch Profileltérés beillesztéskor + “{name}” is not tagged with a {model} profile. „{name}” nem rendelkezik {model}-profillal. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” {model}-profilja „{profile}”, amely nem a(z) „{working}” {model}-munkaszíntér. + Use the embedded profile A beágyazott profil használata + Convert the colors to the working space A színek konvertálása a munkaszíntérbe + Discard the embedded profile A beágyazott profil elvetése + Leave as is Változatlanul hagyás + Assign the working space A munkaszíntér hozzárendelése + 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 Collapse to Icons Ikonná csukás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0d64cad035..4d8b184cf0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -991,6 +991,25 @@ Preserve Embedded Profiles Pertahankan Profil Tersemat Convert to Working Space Konversi ke Ruang Kerja Preserve Numbers Pertahankan Angka + Profile Mismatches: Ketidakcocokan Profil: + Ask When Opening Tanya Saat Membuka + Ask When Pasting Tanya Saat Menempel + Missing Profiles: Profil yang Hilang: + Embedded Profile Mismatch Ketidakcocokan Profil Tersemat + Missing Profile Profil Hilang + Paste Profile Mismatch Ketidakcocokan Profil Saat Menempel + “{name}” is not tagged with a {model} profile. “{name}” tidak memiliki profil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” memiliki profil {model} “{profile}”, yang bukan ruang kerja {model} “{working}”. + Use the embedded profile Gunakan profil tersemat + Convert the colors to the working space Konversi warna ke ruang kerja + Discard the embedded profile Buang profil tersemat + Leave as is Biarkan apa adanya + Assign the working space Tetapkan ruang kerja + 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 Craquelure… Craquelure… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a8f4a401c5..bd99a37916 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5926,6 +5926,25 @@ variable-list-end {0}, {1} {0} e {1} Preserve Embedded Profiles Mantieni profili incorporati Convert to Working Space Converti nello spazio di lavoro Preserve Numbers Mantieni valori numerici + Profile Mismatches: Mancata corrispondenza profili: + Ask When Opening Chiedi all'apertura + Ask When Pasting Chiedi quando si incolla + Missing Profiles: Profili mancanti: + Embedded Profile Mismatch Profilo incorporato non corrispondente + Missing Profile Profilo mancante + Paste Profile Mismatch Profilo non corrispondente nell'incollare + “{name}” is not tagged with a {model} profile. “{name}” non ha un profilo {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” ha il profilo {model} “{profile}”, che non è lo spazio di lavoro {model} “{working}”. + Use the embedded profile Usa il profilo incorporato + Convert the colors to the working space Converti i colori nello spazio di lavoro + Discard the embedded profile Elimina il profilo incorporato + Leave as is Lascia invariato + Assign the working space Assegna lo spazio di lavoro + 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é… Grain… Granulosità… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 030f9c52e6..b8dcc113e6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5974,6 +5974,25 @@ liquify-list-end {0}, {1} {0}、{1} Preserve Embedded Profiles 埋め込まれたプロファイルを保持 Convert to Working Space 作業用スペースに変換 Preserve Numbers カラー値を保持 + Profile Mismatches: プロファイルの不一致: + Ask When Opening 開くときに確認 + Ask When Pasting ペーストするときに確認 + Missing Profiles: プロファイルの欠落: + Embedded Profile Mismatch 埋め込まれたプロファイルの不一致 + Missing Profile プロファイルの欠落 + Paste Profile Mismatch ペースト時のプロファイルの不一致 + “{name}” is not tagged with a {model} profile. 「{name}」には {model} プロファイルがありません。 + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. 「{name}」の {model} プロファイルは「{profile}」で、{model} 作業用スペース「{working}」ではありません。 + Use the embedded profile 埋め込まれたプロファイルを使用 + Convert the colors to the working space カラーを作業用スペースに変換 + Discard the embedded profile 埋め込まれたプロファイルを破棄 + Leave as is そのままにする + Assign the working space 作業用スペースを割り当て + 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… クラッキング… Grain… 粒状… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 95afd990db..45f17d131b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3159,6 +3159,25 @@ Preserve Embedded Profiles ჩაშენებული პროფილების შენარჩუნება Convert to Working Space სამუშაო სივრცეში გადაყვანა Preserve Numbers რიცხვების შენარჩუნება + Profile Mismatches: პროფილების შეუსაბამობა: + Ask When Opening გახსნისას კითხვა + Ask When Pasting ჩასმისას კითხვა + Missing Profiles: დაკარგული პროფილები: + Embedded Profile Mismatch ჩაშენებული პროფილის შეუსაბამობა + Missing Profile პროფილი არ არის + Paste Profile Mismatch პროფილის შეუსაბამობა ჩასმისას + “{name}” is not tagged with a {model} profile. „{name}“-ს არ აქვს {model} პროფილი. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}“-ს აქვს {model} პროფილი „{profile}“, რომელიც არ არის {model} სამუშაო სივრცე „{working}“. + Use the embedded profile ჩაშენებული პროფილის გამოყენება + Convert the colors to the working space ფერების სამუშაო სივრცეში გადაყვანა + Discard the embedded profile ჩაშენებული პროფილის უგულებელყოფა + Leave as is უცვლელად დატოვება + Assign the working space სამუშაო სივრცის მინიჭება + 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 ტექსტურა Craquelure… კრაკელიური… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cbd72b88f2..e1e07b49a3 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5903,6 +5903,25 @@ liquify-list-end {0}, {1} {0} 및 {1} Preserve Embedded Profiles 포함된 프로필 유지 Convert to Working Space 작업 공간으로 변환 Preserve Numbers 숫자 유지 + Profile Mismatches: 프로필 불일치: + Ask When Opening 열 때 묻기 + Ask When Pasting 붙여넣을 때 묻기 + Missing Profiles: 누락된 프로필: + Embedded Profile Mismatch 포함된 프로필 불일치 + Missing Profile 프로필 없음 + Paste Profile Mismatch 붙여넣기 프로필 불일치 + “{name}” is not tagged with a {model} profile. “{name}”에 {model} 프로필이 없습니다. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}”의 {model} 프로필은 “{profile}”이며, {model} 작업 공간 “{working}”이(가) 아닙니다. + Use the embedded profile 포함된 프로필 사용 + Convert the colors to the working space 색상을 작업 공간으로 변환 + Discard the embedded profile 포함된 프로필 버리기 + Leave as is 그대로 두기 + Assign the working space 작업 공간 지정 + 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… 크랙… Grain… 그레인… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 8ff7f8b660..af7a1af990 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1596,6 +1596,25 @@ liquify-list-end {0}, {1} {0} en {1} Preserve Embedded Profiles Ingesloten profielen behouden Convert to Working Space Omzetten naar werkruimte Preserve Numbers Waarden behouden + Profile Mismatches: Profielverschillen: + Ask When Opening Vragen bij openen + Ask When Pasting Vragen bij plakken + Missing Profiles: Ontbrekende profielen: + Embedded Profile Mismatch Ingesloten profiel komt niet overeen + Missing Profile Ontbrekend profiel + Paste Profile Mismatch Profielverschil bij plakken + “{name}” is not tagged with a {model} profile. „{name}” heeft geen {model}-profiel. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” heeft het {model}-profiel „{profile}”, dat niet de {model}-werkruimte „{working}” is. + Use the embedded profile Ingesloten profiel gebruiken + Convert the colors to the working space Kleuren omzetten naar de werkruimte + Discard the embedded profile Ingesloten profiel negeren + Leave as is Laten zoals het is + Assign the working space Werkruimte toewijzen + 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 Craquelure… Craquelure… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4dc9bb9382..11af7a9677 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1013,6 +1013,25 @@ Preserve Embedded Profiles Zachowaj osadzone profile Convert to Working Space Konwertuj do przestrzeni roboczej Preserve Numbers Zachowaj wartości liczbowe + Profile Mismatches: Niezgodność profili: + Ask When Opening Pytaj przy otwieraniu + Ask When Pasting Pytaj przy wklejaniu + Missing Profiles: Brakujące profile: + Embedded Profile Mismatch Niezgodność osadzonego profilu + Missing Profile Brak profilu + Paste Profile Mismatch Niezgodność profilu przy wklejaniu + “{name}” is not tagged with a {model} profile. „{name}” nie ma profilu {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. „{name}” ma profil {model} „{profile}”, który nie jest przestrzenią roboczą {model} „{working}”. + Use the embedded profile Użyj osadzonego profilu + Convert the colors to the working space Konwertuj kolory do przestrzeni roboczej + Discard the embedded profile Odrzuć osadzony profil + Leave as is Pozostaw bez zmian + Assign the working space Przypisz przestrzeń roboczą + 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 Craquelure… Spękania… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a845506226..0730cffa08 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3827,6 +3827,25 @@ imageTrace Outline Contorno Preserve Embedded Profiles Preservar perfis incorporados Convert to Working Space Converter para espaço de trabalho Preserve Numbers Preservar números + Profile Mismatches: Incompatibilidades de perfil: + Ask When Opening Perguntar ao abrir + Ask When Pasting Perguntar ao colar + Missing Profiles: Perfis ausentes: + Embedded Profile Mismatch Incompatibilidade do perfil incorporado + Missing Profile Perfil ausente + Paste Profile Mismatch Incompatibilidade de perfil ao colar + “{name}” is not tagged with a {model} profile. “{name}” não tem um perfil {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” tem o perfil {model} “{profile}”, que não é o espaço de trabalho {model} “{working}”. + Use the embedded profile Usar o perfil incorporado + Convert the colors to the working space Converter as cores para o espaço de trabalho + Discard the embedded profile Descartar o perfil incorporado + Leave as is Deixar como está + Assign the working space Atribuir o espaço de trabalho + 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ê… Grain… Granulação… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 30a8318cf1..e0b055fa80 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5925,6 +5925,25 @@ variable-list-end {0}, {1} {0} и {1} Preserve Embedded Profiles Сохранять встроенные профили Convert to Working Space Преобразовывать в рабочее пространство Preserve Numbers Сохранять числа + Profile Mismatches: Несоответствие профилей: + Ask When Opening Спрашивать при открытии + Ask When Pasting Спрашивать при вставке + Missing Profiles: Отсутствующие профили: + Embedded Profile Mismatch Несоответствие встроенного профиля + Missing Profile Отсутствует профиль + Paste Profile Mismatch Несоответствие профиля при вставке + “{name}” is not tagged with a {model} profile. У «{name}» нет профиля {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. У «{name}» профиль {model} «{profile}», который не является рабочим пространством {model} «{working}». + Use the embedded profile Использовать встроенный профиль + Convert the colors to the working space Преобразовать цвета в рабочее пространство + Discard the embedded profile Отбросить встроенный профиль + Leave as is Оставить как есть + Assign the working space Назначить рабочее пространство + 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… Кракелюры… Grain… Зерно… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 32dd0ca577..3453449c78 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5798,6 +5798,25 @@ variable-list-end {0}, {1} {0} och {1} Preserve Embedded Profiles Behåll inbäddade profiler Convert to Working Space Konvertera till arbetsfärgrymd Preserve Numbers Behåll värden + Profile Mismatches: Profilavvikelser: + Ask When Opening Fråga vid öppning + Ask When Pasting Fråga vid inklistring + Missing Profiles: Profiler som saknas: + Embedded Profile Mismatch Avvikande inbäddad profil + Missing Profile Profil saknas + Paste Profile Mismatch Profilavvikelse vid inklistring + “{name}” is not tagged with a {model} profile. ”{name}” har ingen {model}-profil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. ”{name}” har {model}-profilen ”{profile}”, som inte är {model}-arbetsfärgrymden ”{working}”. + Use the embedded profile Använd den inbäddade profilen + Convert the colors to the working space Konvertera färgerna till arbetsfärgrymden + Discard the embedded profile Ignorera den inbäddade profilen + Leave as is Lämna som det är + Assign the working space Tilldela arbetsfärgrymden + 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… Grain… Korn… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9875997597..a645603ae4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5660,6 +5660,25 @@ liquify-list-end {0}, {1} {0} ve {1} Preserve Embedded Profiles Gömülü Profilleri Koru Convert to Working Space Çalışma Alanına Dönüştür Preserve Numbers Sayıları Koru + Profile Mismatches: Profil Uyuşmazlıkları: + Ask When Opening Açarken Sor + Ask When Pasting Yapıştırırken Sor + Missing Profiles: Eksik Profiller: + Embedded Profile Mismatch Gömülü Profil Uyuşmazlığı + Missing Profile Eksik Profil + Paste Profile Mismatch Yapıştırma Profili Uyuşmazlığı + “{name}” is not tagged with a {model} profile. “{name}” bir {model} profiline sahip değil. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}”, {model} çalışma alanı “{working}” olmayan “{profile}” {model} profiline sahip. + Use the embedded profile Gömülü profili kullan + Convert the colors to the working space Renkleri çalışma alanına dönüştür + Discard the embedded profile Gömülü profili at + Leave as is Olduğu gibi bırak + Assign the working space Çalışma alanını ata + 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… Grain… Tahıl… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 025596795a..3ec0f8248a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5910,6 +5910,25 @@ variable-list-end {0}, {1} {0} і {1} Preserve Embedded Profiles Зберігати вбудовані профілі Convert to Working Space Перетворювати в робочий простір Preserve Numbers Зберігати числа + Profile Mismatches: Невідповідність профілів: + Ask When Opening Питати під час відкриття + Ask When Pasting Питати під час вставлення + Missing Profiles: Відсутні профілі: + Embedded Profile Mismatch Невідповідність вбудованого профілю + Missing Profile Відсутній профіль + Paste Profile Mismatch Невідповідність профілю під час вставлення + “{name}” is not tagged with a {model} profile. «{name}» не має профілю {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. «{name}» має профіль {model} «{profile}», який не є робочим простором {model} «{working}». + Use the embedded profile Використати вбудований профіль + Convert the colors to the working space Перетворити кольори в робочий простір + Discard the embedded profile Відкинути вбудований профіль + Leave as is Залишити як є + Assign the working space Призначити робочий простір + 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… Кракелюри… Grain… Зерно… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e8c6a31600..0f3b1c894b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -638,6 +638,25 @@ font-technology Variable Biến thiên Preserve Embedded Profiles Giữ cấu hình nhúng Convert to Working Space Chuyển sang không gian làm việc Preserve Numbers Giữ giá trị số + Profile Mismatches: Cấu hình không khớp: + Ask When Opening Hỏi khi mở + Ask When Pasting Hỏi khi dán + Missing Profiles: Cấu hình bị thiếu: + Embedded Profile Mismatch Cấu hình nhúng không khớp + Missing Profile Thiếu cấu hình + Paste Profile Mismatch Cấu hình không khớp khi dán + “{name}” is not tagged with a {model} profile. “{name}” không có cấu hình {model}. + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}” có cấu hình {model} “{profile}”, không phải không gian làm việc {model} “{working}”. + Use the embedded profile Dùng cấu hình nhúng + Convert the colors to the working space Chuyển màu sang không gian làm việc + Discard the embedded profile Bỏ cấu hình nhúng + Leave as is Giữ nguyên + Assign the working space Gán không gian làm việc + 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 Collapse to Icons Thu gọn 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 4b1d1e8327..b841fcce8a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5807,6 +5807,25 @@ liquify-list-end {0}, {1} {0}和{1} Preserve Embedded Profiles 保留嵌入的配置文件 Convert to Working Space 转换为工作空间 Preserve Numbers 保留数值 + Profile Mismatches: 配置文件不匹配: + Ask When Opening 打开时询问 + Ask When Pasting 粘贴时询问 + Missing Profiles: 缺少配置文件: + Embedded Profile Mismatch 嵌入的配置文件不匹配 + Missing Profile 缺少配置文件 + Paste Profile Mismatch 粘贴时配置文件不匹配 + “{name}” is not tagged with a {model} profile. “{name}”没有 {model} 配置文件。 + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. “{name}”的 {model} 配置文件为“{profile}”,不是 {model} 工作空间“{working}”。 + Use the embedded profile 使用嵌入的配置文件 + Convert the colors to the working space 将颜色转换为工作空间 + Discard the embedded profile 放弃嵌入的配置文件 + Leave as is 保持原样 + Assign the working space 指定工作空间 + 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 品牌 Film & Video 影片和视频 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d58f9af010..e185b07a7e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6053,6 +6053,25 @@ axis Both 兩者 Preserve Embedded Profiles 保留內嵌描述檔 Convert to Working Space 轉換為工作空間 Preserve Numbers 保留數值 + Profile Mismatches: 描述檔不符: + Ask When Opening 開啟時詢問 + Ask When Pasting 貼上時詢問 + Missing Profiles: 遺失的描述檔: + Embedded Profile Mismatch 內嵌描述檔不符 + Missing Profile 遺失描述檔 + Paste Profile Mismatch 貼上時描述檔不符 + “{name}” is not tagged with a {model} profile. 「{name}」沒有 {model} 描述檔。 + “{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”. 「{name}」的 {model} 描述檔為「{profile}」,不是 {model} 工作空間「{working}」。 + Use the embedded profile 使用內嵌描述檔 + Convert the colors to the working space 將色彩轉換為工作空間 + Discard the embedded profile 捨棄內嵌描述檔 + Leave as is 保持原狀 + Assign the working space 指定工作空間 + 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… 龜裂紋… Grain… 顆粒… diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index fb8d655feb..73dd82dd02 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -26,6 +26,7 @@ pub(crate) use export::{ EXPORT_SELECTION, export_files, exported_with_notes, file_url, open_in_app, open_original, reveal_path, run_to_file, save_command_output_named, selection_path, take_selection, }; +pub(crate) use open::asks_first; pub(crate) use open::report_installed; pub(crate) use open::{EXPORT_PRESETS, import_presets, open_notes, open_with_on, opened, opened_after_notice, show_opened}; pub use open::{ diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 11c02ca139..b0a037804f 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -131,11 +131,19 @@ pub fn opens_as(name: &str) -> 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, false) +} + +/// 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 @@ -402,9 +410,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); @@ -570,7 +577,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 f9ed18f945..f23cb5927a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -353,6 +353,12 @@ 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, + /// 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/opening.rs b/crates/ui-egui/src/opening.rs index 99e0e9d6b6..5b4c8619ee 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()) }) }) }) @@ -111,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; @@ -234,15 +267,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()), true)); + 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 2b3e112c5f..8d5dd13890 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -109,8 +109,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")); @@ -151,6 +151,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 3ff8159407..a644c91ce9 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -742,8 +742,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 c43ad596b4..cdb35e7419 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -589,7 +589,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 { @@ -643,12 +643,19 @@ 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); @@ -661,13 +668,41 @@ fn pastes_inside(id: &str) -> bool { !matches!(id, "edit.pasteInFront" | "edit.pasteInBack") } -/// Run the command confirmed by the deferred paste's Swatch Conflict dialog. -pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: Value, token: Option) -> Result { +/// 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, 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) }; @@ -693,9 +728,32 @@ 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, 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() + { + 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 4f948702c5..11ccc45bd9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1876,6 +1876,31 @@ 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, 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` 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1fe63f4770..a4841fc843 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -864,7 +864,8 @@ 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`. - **Swatch Options and New Swatch color warnings:** both dialogs show the out-of-gamut triangle and the out-of-web-color cube under the color, each with its correction beside it, and a click on the icon or the correction shifts the color to the closest printable or web-safe color ([the archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=236), Swatch options; [the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)). The icons in the Color panel and the Color Picker correct the color too. VectorCraft's own rules: the triangle shows in RGB, HSB and Lab and the cube in every mode but Web Safe RGB, both can show at once, a web correction of a Grayscale, Lab or CMYK color is edited in RGB, a gamut correction keeps the CMYK equivalent and is edited in CMYK, and a correction keeps the name, the color type and Global and changes the dialog's fields only, so OK records one undo step. Tests: `swatch_options_shows_and_corrects_both_warnings` and `swatch_warnings_follow_the_mode` in `dialogs/swatch_options.rs`, `a_warning_corrects_the_new_colour_only_until_ok` in `dialogs/new_swatch.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 and the Profile Mismatches and Missing Profiles prompts 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`. +- **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, 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 units:** the dialog opens in Preferences › Units › General, also on a Recent entry made in other units (an entry in pixels, or a saved preset in the units it was saved in, keeps its units), so File › New and New Without Dialog make documents in the General unit. Units chosen in the Units menu stay when another tab or preset is chosen and when a card is clicked or double-clicked; without such a choice, clicking another Recent or Saved card brings back the units that card was made in (#7944). These are VectorCraft's own rules. Tests: `the_dialog_opens_in_the_general_units_over_a_recent_entry`, `a_recent_saved_preset_keeps_its_units_and_name`, `units_chosen_in_the_menu_survive_tabs_and_presets` and `units_set_over_a_popup_stay_chosen` in `dialogs/new_document.rs`; `a_recent_card_keeps_the_units_chosen_in_the_menu` and `a_double_clicked_card_keeps_the_units_chosen_in_the_menu` in `panels/tests_units.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`.