diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index fb5b5d8605..a3c35db8ce 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -603,9 +603,9 @@ impl Cms { /// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to /// Working Space). RGB converts directly from profile to profile, with this context's /// black-point compensation. CMYK converts between two loaded profiles through ProPhoto RGB - /// ([`IccProfile::to_same_model_of`]), and through the Lab it displays as - /// ([`Self::cmyk_display_lab`]) when either space is built in. Grey and Lab colours stay as they - /// are. + /// ([`IccProfile::to_same_model_of`]), and through Lab when either space is built in: the Lab it + /// displays as ([`Self::cmyk_display_lab`]), or for Absolute Colorimetric its absolute Lab. Grey + /// and Lab colours stay as they are. pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color { match *c { Color::Rgb { r, g, b } => { @@ -625,9 +625,16 @@ impl Cms { (CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc), _ => None, }; + // Absolute colorimetry starts from the inks' absolute Lab, paper color included and + // without black-point compensation; the other intents from the Lab they display as. + let source_lab = || match (&self.cmyk, intent) { + (CmykSpace::Generic(g), Intent::AbsoluteColorimetric) => g.to_lab_abs(inks), + (_, Intent::AbsoluteColorimetric) => lab::srgb_to_lab(self.cmyk_to_srgb(inks, true)), + _ => self.cmyk_display_lab(inks), + }; let [c, m, y, k] = match direct.as_deref() { Some(&[c, m, y, k]) => [c, m, y, k], - _ => dest.lab_to_cmyk(self.cmyk_display_lab(inks), intent), + _ => dest.lab_to_cmyk(source_lab(), intent), }; Color::Cmyk { c, m, y, k } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index f3cdfefd33..836ff9fdb6 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -517,3 +517,26 @@ fn convert_into_keeps_compensated_dark_inks() { } } } + +/// Absolute Colorimetric converts CMYK out of Generic CMYK from the inks' absolute Lab (paper color +/// included, no black-point compensation): into another document whose CMYK space is also Generic +/// CMYK, the paper, dark inks and mid tones keep their absolute appearance. +#[test] +fn absolute_cmyk_conversion_keeps_the_absolute_appearance() { + let generic = cms(); + let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + let absolute = |c: &Cms, ink: &Color| match (&c.cmyk, ink) { + (CmykSpace::Generic(g), Color::Cmyk { c, m, y, k }) => g.to_lab_abs([*c, *m, *y, *k]), + _ => panic!("Generic CMYK inks expected, not {ink:?}"), + }; + for ink in [ + Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, + Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 }, + Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 }, + Color::Cmyk { c: 0.4, m: 0.1, y: 0.6, k: 0.1 }, + ] { + let moved = generic.convert_into(&other_generic, &ink, Intent::AbsoluteColorimetric); + let d = delta_e2000(absolute(&generic, &ink), absolute(&other_generic, &moved)); + assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}"); + } +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 4da417940d..c42289ccc7 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Paste Profile Mismatch", [], None, - "{sourceDocument?, ids?: as edit.dropSelection} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\"}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", + "{sourceDocument?, ids?: as edit.dropSelection, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\", convertible}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then; an assigned profile removed since: the working space) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). convertible: false when either profile is not available (removed with color.removeProfile): the colors then keep their numbers whatever the choice, and default is preserveNumbers. With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", has_doc, profile_mismatch ), @@ -561,7 +561,7 @@ fn conflicts(s: &mut Session, p: &Value) -> Result { // The swatches as the paste brings them: converted from another profile when it converts. let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; let st = s.doc()?; - let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile); + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); let list: Vec = converted .as_ref() .unwrap_or(&s.clipboard) @@ -577,7 +577,9 @@ fn profile_mismatch(s: &mut Session, p: &Value) -> Result { // With `sourceDocument` and `ids`, the objects a drop brings, else the clipboard's. let dropped = if p.get("sourceDocument").is_some() || p.get("ids").is_some() { Some(super::edit::drop_clip(s, p, CMD)?) } else { None }; let clip = dropped.as_ref().unwrap_or(&s.clipboard); - let list: Vec = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc).iter().map(|m| m.to_json()).collect(); + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; + let list: Vec = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc, !all_artboards).iter().map(|m| m.to_json()).collect(); Ok(json!({ "mismatches": list })) } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 0a98ddd9bc..594d4c9f5d 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1121,8 +1121,11 @@ impl Clipboard { /// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added /// under a free name ("Dots 2") is compared and added with that name. An error, with `d` /// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]). + /// `same_doc`: `d` is the document the objects were copied from. With colors converted for the + /// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another + /// document's are, while its image blobs are still the document's own under their keys. pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used(d, &self.used(), choices, same_doc) + self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc) } /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` @@ -1155,9 +1158,22 @@ impl Clipboard { /// other is matched on its own ([`loop_groups`]). Pasted back into its own document /// (`same_doc`), each definition of a loop is the document's of its name. fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result { + self.import_used_with_images(d, used, choices, same_doc, same_doc) + } + + /// [`Self::import_used`], with the image blobs matched as those of the document they came + /// from when `same_doc_images`. + fn import_used_with_images( + &self, + d: &mut Document, + used: &Used, + choices: &SwatchChoices, + same_doc: bool, + same_doc_images: bool, + ) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; - self.import_images(d, used, same_doc, &mut out); + self.import_images(d, used, same_doc_images, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); let mut defs: Vec> = vec![]; for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index bc3880b2e6..0ac4f8c3b0 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -950,11 +950,16 @@ pub(crate) fn convert_art_and_style_colors(d: &mut vectorcraft_doc::Document, co } /// The RGB and CMYK profiles the colors of `d` show through, by name: those it is assigned, else -/// the working spaces. +/// the working spaces. An assigned profile that is not available (removed since) is the working +/// space, as the document draws through it ([`cms::for_document`]). pub(crate) fn effective_profiles(d: &vectorcraft_doc::Document) -> [String; 2] { let working = cms::working_settings(); let (rgb, cmyk) = doc_profiles(d); - [rgb.unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()), cmyk.unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string())] + let available = |name: Option, kind: cms::ProfileKind| name.filter(|n| cms::profile(n).is_some_and(|p| p.kind == kind)); + [ + available(rgb, cms::ProfileKind::Rgb).unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()), + available(cmyk, cms::ProfileKind::Cmyk).unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string()), + ] } /// What Paste does with the colors of a model when the document they were copied from showed them @@ -1035,20 +1040,25 @@ pub struct PasteMismatch { pub from: String, /// The profile they show through in the document they go into. pub to: String, - /// What the model's policy does with them. + /// What the model's policy does with them; Preserve Numbers when they can't convert. pub default: PasteProfile, + /// Both profiles are available, so the colors can convert; otherwise they keep their numbers + /// whatever the choice. + pub convertible: bool, } impl PasteMismatch { pub fn to_json(&self) -> Value { let model = if self.model == ColorMode::Rgb { "rgb" } else { "cmyk" }; - json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id() }) + json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id(), "convertible": self.convertible }) } } /// The models whose colors pasting `clip` into `d` brings from another profile: RGB, CMYK or both, -/// each only when the copied objects or the resources they carry hold a color of that model. -pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document) -> Vec { +/// each only when the copied objects or the resources they carry hold a color of that model. The +/// background colors of copied artboards count only with `boards` (Paste on All Artboards doesn't +/// paste the artboards). +pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, boards: bool) -> Vec { let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return vec![] }; let [to_rgb, to_cmyk] = effective_profiles(d); let working = cms::working_settings(); @@ -1056,11 +1066,26 @@ pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcra [(ColorMode::Rgb, from_rgb, to_rgb, working.rgb_policy), (ColorMode::Cmyk, from_cmyk, to_cmyk, working.cmyk_policy)] .into_iter() .filter(|(_, from, to, _)| cms::canonical_name(from) != cms::canonical_name(to)) - .map(|(model, from, to, policy)| PasteMismatch { model, from: from.clone(), to, default: PasteProfile::of(policy) }) + .map(|(model, from, to, policy)| { + let kind = if model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + // Both profiles must be here to convert between them. + let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); + let convertible = here(from) && here(&to); + let default = if convertible { PasteProfile::of(policy) } else { PasteProfile::PreserveNumbers }; + PasteMismatch { model, from: from.clone(), to, default, convertible } + }) .collect(); if out.is_empty() { return out; } + // Without the artboards when their backgrounds don't paste. + let without_boards; + let clip = if !boards && !clip.artboards.is_empty() { + without_boards = super::clipboard::Clipboard { artboards: vec![], ..clip.clone() }; + &without_boards + } else { + clip + }; // Which models the pasted colors use. let seen = std::cell::Cell::new((false, false)); let _ = clip.with_colors(&|c: &Color| { @@ -1077,23 +1102,20 @@ pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcra /// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into /// the destination's with the working intent, as `choice` says for that model (default: the /// model's policy, [`PasteProfile::of`]). A source or destination profile that is not available -/// keeps the numbers. +/// keeps the numbers. `boards`: as [`paste_mismatches`]. /// → the converted clipboard (`None` when nothing converts; its resources paste as another /// document's) and a line for each mismatched model (`{model, clipboard, document, choice}`). pub(crate) fn paste_profiles( clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, choice: Option, + boards: bool, ) -> (Option, Vec) { - let mismatches = paste_mismatches(clip, d); + let mismatches = paste_mismatches(clip, d, boards); let mut report = Vec::new(); let (mut rgb_on, mut cmyk_on) = (false, false); for m in &mismatches { - let kind = if m.model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; - // Both profiles must be here to convert between them. - let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); - let available = here(&m.from) && here(&m.to); - let picked = if available { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; + let picked = if m.convertible { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; if picked == PasteProfile::Convert { match m.model { ColorMode::Rgb => rgb_on = true, @@ -1103,6 +1125,7 @@ pub(crate) fn paste_profiles( let mut line = m.to_json(); if let Some(o) = line.as_object_mut() { o.remove("default"); + o.remove("convertible"); o.insert("choice".into(), json!(picked.id())); } report.push(line); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 7f0db6dd87..5e0231228b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -180,7 +180,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out: as the model's policy of edit.colorSettings says; any other value is an error; every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -1293,7 +1293,7 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?; // Colors from another profile keep their numbers or convert, as `profileMismatch` says, else as // the policies say. - let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile); + let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile, true); let mut r = paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices); if let Ok(v) = &mut r && !report.is_empty() @@ -1361,9 +1361,10 @@ fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result { // Taken out of the session for the edit (and put back whatever happens). let clip = std::mem::take(&mut s.clipboard); // Colors copied from a document with other profiles keep their numbers or convert - // (Edit › Color Settings' policies, or `profileMismatch`). + // (Edit › Color Settings' policies, or `profileMismatch`). Paste on All Artboards leaves the + // copied artboards, and so their backgrounds, behind. let (converted, report) = match s.doc() { - Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile), + Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile, mode != PasteMode::AllArtboards), Err(_) => (None, vec![]), }; let mut r = paste_clip(s, p, mode, converted.as_ref().unwrap_or(&clip), &choices); @@ -1549,8 +1550,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho vec![Affine::IDENTITY] }; let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { - // Converted colors are compared with the document's resources, as another document's are. - let imported = clip.import_into(d, choices, same_doc && !clip.colors_converted)?; + // Converted colors are compared with the document's resources, as another document's are + // (`Clipboard::import_into`); its images are still the document's own. + let imported = clip.import_into(d, choices, same_doc)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; let artboards: Vec = boards diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 7b24fbdd24..a41831b200 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was used; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index b2827b5ccf..61b371bcd6 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -695,6 +695,9 @@ pub struct ReadFile { /// The answer that was used and the question it answered (`document.open`'s `profileChoice` /// reply). answered: Option, + /// The profile question as it was last asked ([`ReadFile::ask`]): an answer is taken only while + /// the question is still the same. + asked: Option, } /// The part of [`read_for_open`] a file waiting for a profile answer has left to do. @@ -768,8 +771,9 @@ pub fn read_for_open_asking( choice, rest: Some(Rest { update_links, low_res_proxy_eps, color_mode }), answered: None, + asked: None, }; - if ask && file.choice.is_none() && file.question().is_some() { + if ask && file.choice.is_none() && file.ask().is_some() { return Ok(file); } file.finish_read()?; @@ -791,11 +795,28 @@ impl ReadFile { crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &st).filter(|q| q.asked(&st)) } + /// [`Self::question`], kept as the question asked: [`Self::answer`] takes an answer only while + /// the question is still the same. The app calls it when it shows the question. + pub fn ask(&mut self) -> Option { + self.asked = self.question(); + self.asked.clone() + } + /// Answer the profile question with `choice` and do the rest of the read: the policies (the /// answer in place of the one of the document's color mode), the color mode, the linked files - /// and the type. An error (a profile to assign that is not one of that model) leaves the file - /// waiting. + /// and the type. An error leaves the file waiting: a profile to assign that is not one of that + /// model, or Color Settings changed since the question was asked ([`Self::ask`]) so that the + /// question, its model, the profile it is about or the working space differ. pub fn answer(&mut self, choice: crate::cmd::colormgmt::ProfileChoice) -> Result<()> { + if let Some(asked) = &self.asked + && self.rest.is_some() + { + let now = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let key = |q: &crate::cmd::colormgmt::ProfileQuestion| (q.issue, q.model, q.profile.clone(), q.working.clone()); + if now.as_ref().map(key) != Some(key(asked)) { + return Err(bad("document.open", "the profile question changed since it was asked: answer the question it asks now")); + } + } let before = self.choice.replace(choice); let r = self.finish_read(); if r.is_err() { diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index c63de94238..7c0aef252e 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1290,6 +1290,35 @@ fn a_read_waits_for_the_profile_answer() { assert_eq!(doc_profiles(&opened.doc().unwrap().doc).0, Some(cms::DISPLAY_P3.into())); } +/// An answer is taken only while the question it answers stands: once Color Settings change the +/// working space so that the question goes away or names another working space, the answer is +/// refused and the file keeps waiting. Asked again, it takes the answer to the question it asks now. +#[test] +fn a_profile_answer_waits_for_the_question_it_answers() { + let _g = settings(); + let ProfileFiles { tagged, blue, blue0, .. } = &profile_files("profile-changed"); + let (blue, blue0) = (*blue, *blue0); + let mut s = session(); + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true})); + let bytes = std::fs::read(tagged).unwrap(); + let name = tagged.to_str().unwrap(); + let mut waiting = vectorcraft_engine::cmd::fileio::read_for_open_asking(name, &bytes, Some(name.into()), &json!({}), false, false, true).unwrap(); + assert_eq!(waiting.question().unwrap().working, cms::canonical_name(cms::SRGB)); + // The working space becomes the file's profile: the question is gone. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); + assert!(waiting.answer(ProfileChoice::Discard).is_err(), "the question it answers is gone"); + // Another working space: the question names it. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})); + let err = waiting.answer(ProfileChoice::Discard).unwrap_err().to_string(); + assert!(err.contains("the profile question changed since it was asked"), "{err}"); + assert_eq!(waiting.ask().unwrap().working, cms::canonical_name(cms::DISPLAY_P3)); + waiting.answer(ProfileChoice::Discard).unwrap(); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(r["profileChoice"]["choice"], "discard"); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill_of(&opened, blue)), (None, blue0)); +} + /// Swatch conflicts are checked against the colors as the paste brings them: a global swatch whose /// name and color match the destination's conflicts once the paste converts it, and pasting back /// into its own document with conversion compares its swatches too. @@ -1384,9 +1413,10 @@ fn paste_keeps_or_converts_colors_from_another_profile() { exec(&mut s, "file.new", json!({"width": 100, "height": 100})); let r = exec(&mut s, "clipboard.profileMismatch", json!({})); // Only RGB: the objects use no CMYK color. + let srgb = cms::canonical_name(cms::SRGB); assert_eq!( r["mismatches"], - json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": cms::canonical_name(cms::SRGB), "default": "preserveNumbers"}]) + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) ); let pasted = |s: &mut Session, p: serde_json::Value| { let r = exec(s, "edit.paste", p); @@ -1440,9 +1470,10 @@ fn a_drop_takes_the_profile_mismatch_choice() { let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([]), "the clipboard is empty"); let dragged = json!({"sourceDocument": source, "ids": [blue.0]}); + let srgb = cms::canonical_name(cms::SRGB); assert_eq!( exec(&mut s, "clipboard.profileMismatch", dragged.clone())["mismatches"], - json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": cms::canonical_name(cms::SRGB), "default": "preserveNumbers"}]) + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) ); for bad in [json!({"sourceDocument": source}), json!({"ids": [blue.0]}), json!({"sourceDocument": 999_999, "ids": [blue.0]})] { assert!(s.execute("clipboard.profileMismatch", &bad).is_err(), "{bad}"); @@ -1491,6 +1522,10 @@ fn paste_takes_a_choice_for_each_model() { exec(&mut s, "paint.setFill", json!({"ids": [both.0], "color": "#3366cc"})); exec(&mut s, "paint.setStroke", json!({"ids": [both.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + let stroke_of = |s: &Session, id: vectorcraft_doc::NodeId| { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.stroke()).and_then(|f| f.paint.color()).unwrap() + }; + let ink0 = stroke_of(&s, both); select(&mut s, &[both]); exec(&mut s, "edit.copy", json!({})); exec(&mut s, "file.new", json!({"width": 100, "height": 100})); @@ -1501,18 +1536,21 @@ fn paste_takes_a_choice_for_each_model() { let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); let fill = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); let picked = |model: &str| r["profileMismatch"].as_array().unwrap().iter().find(|m| m["model"] == model).map(|m| m["choice"].clone()); - (fill, picked("rgb"), picked("cmyk")) + (fill, stroke_of(s, id), picked("rgb"), picked("cmyk")) }; - // The CMYK policy's own choice, as a paste that leaves both models to their policies makes it. - let (_, rgb_policy, cmyk_policy) = pasted(&mut s, serde_json::Value::Null); - assert_eq!(rgb_policy, Some(json!("preserveNumbers"))); - assert!(cmyk_policy.is_some(), "the stroke's CMYK color is a mismatch too"); - let (fill, rgb, cmyk) = pasted(&mut s, json!({"rgb": "convert"})); - assert_eq!((rgb, &cmyk), (Some(json!("convert")), &cmyk_policy), "CMYK follows its policy"); + // The CMYK policy (Convert to Working Space) converts the stroke from Device CMYK into the + // working CMYK space, as a paste that leaves both models to their policies does. + let (_, ink, rgb_policy, cmyk_policy) = pasted(&mut s, serde_json::Value::Null); + assert_eq!((rgb_policy, &cmyk_policy), (Some(json!("preserveNumbers")), &Some(json!("convert")))); + let device = cms::for_document(None, Some(cms::DEVICE_CMYK)); + assert!(ink != ink0 && cms::delta_e2000(device.lab(&ink0), cms::working().lab(&ink)) < 2.0, "{ink0:?} → {ink:?}"); + let converted_ink = ink; + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"rgb": "convert"})); + assert_eq!((rgb, &cmyk, ink), (Some(json!("convert")), &cmyk_policy, converted_ink), "CMYK follows its policy"); let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); assert!(fill != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&fill)) < 1.0, "{blue0:?} → {fill:?}"); - let (fill, rgb, cmyk) = pasted(&mut s, json!({"cmyk": "preserveNumbers"})); - assert_eq!((fill, rgb, cmyk), (blue0, Some(json!("preserveNumbers")), Some(json!("preserveNumbers")))); + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"cmyk": "preserveNumbers"})); + assert_eq!((fill, ink, rgb, cmyk), (blue0, ink0, Some(json!("preserveNumbers")), Some(json!("preserveNumbers"))), "the inks keep their values"); let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); let before = objects(&s); for bad in [json!({"lab": "convert"}), json!({"rgb": "keep"}), json!({"rgb": 1}), json!([]), json!(true)] { @@ -1521,3 +1559,138 @@ fn paste_takes_a_choice_for_each_model() { } assert_eq!(objects(&s), before, "a refused choice pastes nothing"); } + +/// The fill color of the first object a paste reply `r` names, in the active document. +#[allow(clippy::unwrap_used, reason = "a test helper: a reply without objects fails the test")] +fn pasted_fill(s: &Session, r: &serde_json::Value) -> vectorcraft_color::Color { + fill_of(s, vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())) +} + +/// A document assigned a profile that was removed since draws through the working space, and its +/// copied colors come from the working space too: pasted into a document with another profile, they +/// convert from it as `profileMismatch` says. +#[test] +fn a_removed_assigned_profile_pastes_as_the_working_space() { + const NAME: &str = "Removed Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["convertible"]), (&json!(cms::canonical_name(cms::SRGB)), &json!(true)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let (blue0, moved) = (vectorcraft_color::Color::from_hex("#3366cc").unwrap(), pasted_fill(&s, &r)); + let p3 = cms::for_document(Some(cms::DISPLAY_P3), None); + assert!(moved != blue0 && cms::delta_e2000(cms::working().lab(&blue0), p3.lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); +} + +/// Colors copied from a document whose profile was removed after the copy can't convert: the +/// mismatch says so (convertible false, and default preserveNumbers under a converting policy), and +/// a paste that asks to convert keeps their numbers. +#[test] +fn colors_from_a_profile_removed_after_the_copy_keep_their_numbers() { + const NAME: &str = "Copied Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert"})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["default"], &m["convertible"]), (&json!("convert"), &json!(true)), "both profiles are here: {m}"); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["default"], &m["convertible"]), (&json!(NAME), &json!("preserveNumbers"), &json!(false)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + assert_eq!(pasted_fill(&s, &r), vectorcraft_color::Color::from_hex("#3366cc").unwrap()); +} + +/// Paste on All Artboards leaves copied artboards behind, so their backgrounds raise no mismatch for +/// it: clipboard.profileMismatch with allArtboards lists none, and the paste reports none. A plain +/// paste, which brings the artboard, still lists the background's model. +#[test] +fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let models = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.profileMismatch", p)["mismatches"].as_array().unwrap().len(); + assert_eq!(models(&mut s, json!({})), 1, "a plain paste brings the RGB background"); + assert_eq!(models(&mut s, json!({"allArtboards": true})), 0); + assert!(s.execute("clipboard.profileMismatch", &json!({"allArtboards": "yes"})).is_err()); + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + +/// A converting paste back into the document the objects came from (its profile changed since the +/// copy) still takes its image blobs as the document's own: an image whose blob under its key +/// changed since keeps that key, and so shows the document's blob. +#[test] +fn a_converting_paste_into_its_own_document_keeps_its_image_keys() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + let blob = |b: u8| vectorcraft_doc::ImageBlob::png(vec![b; 8]); + let image = s + .edit("Place", |d, _| { + d.images.insert("pic".into(), blob(1)); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 4, + height: 4, + xf: Affine::translate((20.0, 0.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[blue, image]); + exec(&mut s, "edit.copy", json!({})); + s.edit("Replace Image", |d, _| { + d.images.insert("pic".into(), blob(2)); + Ok(()) + }) + .unwrap(); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let doc = &s.doc().unwrap().doc; + let keys: Vec = r["ids"] + .as_array() + .unwrap() + .iter() + .filter_map(|id| match &doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap()))?.kind { + vectorcraft_doc::NodeKind::Image(im) => Some(im.key.clone()), + _ => None, + }) + .collect(); + assert_eq!(keys, ["pic"]); + assert_eq!(doc.images.len(), 1, "no copy of the old blob"); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 252cfe34f1..d9b752c32c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -187,6 +187,7 @@ impl VectorcraftApp { synthetic_frame: false, pending_plugin_install: None, pending_profile_open: None, + queued_profile_opens: Default::default(), script_picked: Vec::new(), script_picked_left_out: false, pen_end: Default::default(), diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index 272f6877e4..f04fff2ba8 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -19,7 +19,7 @@ use serde_json::{Value, json}; use vectorcraft_color::cms::{self, ProfileKind}; -use vectorcraft_engine::cmd::colormgmt::ProfileChoice; +use vectorcraft_engine::cmd::colormgmt::{ProfileChoice, ProfileQuestion}; use vectorcraft_engine::cmd::fileio::{self, ReadFile}; use vectorcraft_engine::file_access::ScopeHandle; @@ -82,33 +82,60 @@ fn paste_choices() -> [(&'static str, &'static str); 2] { } /// Open `file`, read for File › Open from `path`, as `document.open` does, unless Edit › Color -/// Settings asks about its profile ([`ReadFile::question`]): then the dialog asks first, and the -/// result is `{dialog}`. Opened, the views follow and the file goes on the recent files -/// ([`crate::io::opened`]). +/// Settings asks about its profile ([`ReadFile::ask`]): then the dialog asks first, and the result +/// is `{dialog}`. A file read while another one's question is open waits for its own question +/// until that one is answered (`{dialog, queued: true}`). Opened, the views follow and the file +/// goes on the recent files ([`crate::io::opened`]). pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option) -> Result { - // One question at a time: a file read while another waits opens as its policy says. - if app.pending_profile_open.is_none() - && let Some(q) = file.question() - { - let fields = json!({ - "issue": q.issue.id(), - "name": file.name(), - "model": q.model_label(), - "profile": q.profile, - "working": q.working, - "choice": q.default.id(), - "assignProfile": q.working, + ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture() }) +} + +/// [`open_or_ask`] for a file that has its scope already. +fn ask_or_open(app: &mut VectorcraftApp, mut pending: PendingOpen) -> Result { + let Some(q) = pending.file.ask() else { + let PendingOpen { file, path, scope } = pending; + return scope.run(|| { + let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) }); - app.pending_profile_open = Some(PendingOpen { file, path, scope: ScopeHandle::capture() }); - app.ui.dialog = Some(Dialog::new(OPEN_KIND, fields)); - return Ok(json!({ "dialog": OPEN_KIND })); + }; + if app.pending_profile_open.is_some() { + app.queued_profile_opens.push_back(pending); + return Ok(json!({ "dialog": OPEN_KIND, "queued": true })); } - let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; - crate::io::opened(app, &r); - if let Some(p) = &path { - crate::io::note_recent(app, p); + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) +} + +/// The open dialog's fields for question `q` about the file named `name`. +fn question_fields(q: &ProfileQuestion, name: &str) -> Value { + json!({ + "issue": q.issue.id(), + "name": name, + "model": q.model_label(), + "profile": q.profile, + "working": q.working, + "choice": q.default.id(), + "assignProfile": q.working, + }) +} + +/// With no dialog open, the next file waiting for its profile question asks it, or opens as its +/// policy says when the question is gone (Color Settings changed meanwhile). A file that fails to +/// open is reported, and the next one comes. +pub(crate) fn ask_next(app: &mut VectorcraftApp) { + while app.pending_profile_open.is_none() && app.ui.dialog.is_none() { + let Some(next) = app.queued_profile_opens.pop_front() else { return }; + let name = next.file.name(); + if let Err(e) = ask_or_open(app, next) { + crate::io::report_open_error(app, &name, &e); + } } - Ok(r) } /// The `profileChoice` the open dialog's fields give. @@ -151,7 +178,10 @@ fn open_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool } /// OK: open the waiting file as chosen, under the automation roots of the open and those of the -/// caller that confirms both. A choice the file refuses keeps the dialog open. +/// caller that confirms both. A choice the file refuses keeps the dialog open. When Color Settings +/// changed the question since it was asked, the dialog asks the question as it stands now instead, +/// or the file opens as its policy says when there is no question any more. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = open_choice(d)?; let Some(mut pending) = app.pending_profile_open.take() else { @@ -160,10 +190,31 @@ fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { }; let scope = pending.scope.clone().within_current(); if let Err(e) = scope.clone().run(|| pending.file.answer(choice)) { - app.pending_profile_open = Some(pending); - return Err(e.to_string()); + // The question changed: ask it as it is now (or open by the policy when it is gone). + let now = |q: &ProfileQuestion| question_fields(q, ""); + let asked = |q: &ProfileQuestion| ["issue", "model", "profile", "working"].iter().all(|k| now(q).get(*k) == d.fields.get(*k)); + return match pending.file.ask() { + Some(q) if asked(&q) => { + app.pending_profile_open = Some(pending); + Err(e.to_string()) + } + Some(q) => { + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) + } + None => { + app.ui.dialog = None; + open_pending(app, pending, scope) + } + }; } app.ui.dialog = None; + open_pending(app, pending, scope) +} + +/// Open `pending`, answered or without a question, under `scope`; a failure is reported. +fn open_pending(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> DialogResult { let PendingOpen { file, path, .. } = pending; let name = file.name(); scope.run(|| match fileio::open_read(&mut app.session, file) { @@ -182,16 +233,19 @@ fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { }) } -/// Cancel, or the dialog closed some other way: the waiting file doesn't open. +/// Cancel, or the dialog closed some other way: the waiting file doesn't open. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). pub(crate) fn cancel_open(app: &mut VectorcraftApp) { app.pending_profile_open = None; } -/// A file still waiting once its dialog is gone (another dialog took its place) doesn't open. +/// A file still waiting once its dialog is gone (another dialog took its place) doesn't open; with +/// no dialog open, the next file waiting for its question asks it. pub(crate) fn settle(app: &mut VectorcraftApp) { if app.pending_profile_open.is_some() && !app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) { - cancel_open(app); + app.pending_profile_open = None; } + ask_next(app); } /// Before running paste `command` (or `edit.dropSelection`, a drag from another document) with @@ -216,13 +270,32 @@ pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Opt } /// The models whose profiles differ for paste `command` with `params` (`clipboard.profileMismatch`): -/// a drop brings the objects it names, a paste the clipboard's. `None` when they can't be listed. +/// a drop brings the objects it names, a paste the clipboard's, and Paste on All Artboards leaves the +/// backgrounds of copied artboards behind. `None` when they can't be listed. fn paste_mismatches(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { - let query = if command == DROP { json!({ "sourceDocument": params.get("sourceDocument"), "ids": params.get("ids") }) } else { json!({}) }; + let query = match command { + DROP => json!({ "sourceDocument": params.get("sourceDocument"), "ids": params.get("ids") }), + ALL_ARTBOARDS => json!({ "allArtboards": true }), + _ => json!({}), + }; let found = app.session.execute("clipboard.profileMismatch", &query).ok()?; found["mismatches"].as_array().cloned() } +/// Paste on All Artboards, which leaves copied artboards behind. +const ALL_ARTBOARDS: &str = "edit.pasteOnAllArtboards"; + +/// Can the colors of mismatch `m` convert (both profiles are available)? +fn convertible(m: &Value) -> bool { + m["convertible"].as_bool().unwrap_or(true) +} + +/// May the colors of mismatch `m` take `value`? Preserve Numbers always; Convert only when they can +/// convert. +fn allowed(m: &Value, value: &str) -> bool { + value != "convert" || convertible(m) +} + /// The choice the paste question starts on: the model's policy for one model, and for both a /// choice for each (`{rgb, cmyk}`), each starting on its model's policy. fn first_choice(mismatches: &[Value]) -> Value { @@ -249,7 +322,8 @@ fn pick(choice: &Value, mismatches: &[Value], model: &str, value: &str) -> Value Value::Object(each.collect()) } -/// Is `choice` one choice for every model, or a choice for each of `mismatches`' models? +/// Is `choice` one choice for every model, or a choice for each of `mismatches`' models? (Convert +/// for a model whose colors can't convert keeps their numbers, as the paste commands do.) fn valid_choice(choice: &Value, mismatches: &[Value]) -> bool { let known = |v: &str| paste_choices().iter().any(|(c, _)| *c == v); match choice { @@ -279,7 +353,8 @@ fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool let mut clicked = None; for (value, text) in paste_choices() { label(ui, ""); - if widgets::radio(ui, text, now == value, true) { + // Colors whose profile is not available can only keep their numbers. + if widgets::radio(ui, text, now == value, allowed(m, value)) { clicked = Some(value); } ui.end_row(); @@ -301,7 +376,9 @@ const DOC: &str = "__doc"; /// OK: run the paste with the choice; any Swatch Conflict question comes next. When another /// document has become the active one since a paste that runs at once asked, it closes as Cancel /// does and pastes nothing. When the profiles that paste or drop would bring have changed since it -/// asked (the clipboard or the dragged objects' document changed), it asks again about the new ones. +/// asked (the clipboard, the dragged objects' document or the destination's profile changed), it +/// asks again about the new ones; a paste that waited for its clipboard is checked in the document +/// and with the clipboard it runs with. fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); let asked = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); @@ -316,19 +393,15 @@ fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { } let command = d.str("__command"); let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); - if deferred.is_none() - && let Some(now) = paste_mismatches(app, &command, ¶ms).filter(|a| !a.is_empty()) - && d.fields.get("mismatches").and_then(Value::as_array) != Some(&now) - { - app.ui.dialog = None; - if let Some(r) = ask_paste(app, &command, ¶ms) { - return r; - } - } params["profileMismatch"] = choice; app.ui.dialog = None; + // Without the answer, the paste asks again about what it brings now. + let changed = |app: &mut VectorcraftApp, command: &str, params: &Value| { + paste_mismatches(app, command, params).is_some_and(|now| !now.is_empty() && now != asked) + }; + let recheck = crate::placing::Recheck { key: "profileMismatch", changed: &changed }; // A paste that waited for its clipboard runs in the context it was given in. - crate::placing::confirm_swatch_paste(app, &command, params, deferred) + crate::placing::confirm_swatch_paste(app, &command, params, deferred, Some(&recheck)) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index d62c56e431..358c6f428e 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -27,6 +27,19 @@ fn rgb_profile(app: &VectorcraftApp) -> Option { vectorcraft_engine::cmd::colormgmt::doc_profiles(&app.session.doc().unwrap().doc).0 } +/// OK on the open question, run by `confirm`, opens one document, installed with `roots`. +fn confirm_opens_one_under( + app: &mut VectorcraftApp, + roots: Option<&std::sync::Arc>, + confirm: impl FnOnce(&mut VectorcraftApp) -> Value, +) { + let docs = app.session.documents().len(); + let r = confirm(app); + assert_eq!(app.session.documents().len(), docs + 1, "{r}"); + let opened = &app.session.documents()[r["index"].as_u64().unwrap() as usize]; + assert_eq!(opened.opened_by.as_ref().map(|o| o.describe()), roots.map(|o| o.describe())); +} + /// An open asked under automation roots finishes under them, though OK is pressed outside them: its /// linked files are read, and the document is installed, with the roots of the open. `tagged` asks /// with the settings in force. @@ -37,8 +50,7 @@ fn open_asked_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None)).unwrap(); assert_eq!(r, json!({ "dialog": OPEN_KIND })); assert!(file_access::current().is_none(), "OK is pressed outside the roots"); - super::super::confirm(app).unwrap(); - assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the open"); + confirm_opens_one_under(app, roots.as_ref(), |app| super::super::confirm(app).unwrap()); } /// An open asked outside automation roots and confirmed by a caller under them finishes under that @@ -49,8 +61,122 @@ fn open_confirmed_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); let r = crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); assert_eq!(r, json!({ "dialog": OPEN_KIND })); - file_access::confine(roots.as_ref(), || super::super::confirm(app)).unwrap(); - assert!(app.session.doc().unwrap().opened_by.is_some(), "installed under the roots of the caller that confirmed"); + confirm_opens_one_under(app, roots.as_ref(), |app| file_access::confine(roots.as_ref(), || super::super::confirm(app)).unwrap()); +} + +/// A PNG of one color, 8 × 8. +fn png(rgb: [u8; 3]) -> Vec { + let [r, g, b] = rgb; + let layout = (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8); + let img = craft_image_codecs::Image::from_raw(8, 8, layout.0, layout.1, [r, g, b, 255].repeat(64)).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The linked files of a document asked about under automation roots, and confirmed outside them, +/// are read under those roots, apart from where the document is installed: of two linked files +/// changed since the save, the one inside the roots updates, and the one outside keeps the picture +/// the document holds. The Ask When Opening box for a mismatch is on. +fn links_read_under_the_roots_of_the_open(app: &mut VectorcraftApp) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-links"); + let (inside, outside) = (dir.join("inside"), dir.join("outside")); + let (a, b) = (inside.join("in.png"), outside.join("out.png")); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for p in [&a, &b] { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, png([200, 40, 40])).unwrap(); + s.execute("file.place", &json!({"path": p.to_str().unwrap(), "at": [50, 50]})).unwrap(); + } + s.execute("edit.assignProfile", &json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + let r = s.execute("document.serialize", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + // The profiles in use are the process's: back to the working spaces. + s.execute("edit.assignProfile", &json!({ "rgb": null })).unwrap(); + for p in [&a, &b] { + let stamp = std::fs::metadata(p).unwrap().modified().unwrap(); + std::fs::write(p, png([40, 40, 200])).unwrap(); + // Link stamps use milliseconds: the new file is dated 2 s later. + let later = std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2)); + std::fs::OpenOptions::new().write(true).open(p).unwrap().set_times(later).unwrap(); + } + let update = std::mem::replace(&mut app.session.prefs.update_links, "automatically".into()); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[]).unwrap(); + let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "linked.vectorcraft", &bytes, None)).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + let r = super::super::confirm(app).unwrap(); + let updated: Vec<&str> = r["updatedLinks"].as_array().map(|a| a.iter().filter_map(|l| l["name"].as_str()).collect()).unwrap_or_default(); + assert_eq!(updated, ["in.png"], "{r}"); + app.session.prefs.update_links = update; + // A question about the link outside the roots is not part of this check. + if app.ui.dialog.is_some() { + super::super::cancel(app); + } +} + +/// A file read while another one's question is open waits and asks its own question in turn, and +/// each opens only after its own answer: Cancel on the first leaves it closed and asks about the +/// second. `tagged` asks with the settings in force. +fn files_opened_together_ask_in_turn(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + assert_eq!(crate::io::open_bytes(app, "first.vectorcraft", tagged, None).unwrap(), json!({ "dialog": OPEN_KIND })); + let r = crate::io::open_bytes(app, "second.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true })); + assert_eq!(app.queued_profile_opens.len(), 1); + super::super::cancel(app); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "the second asks"); + assert!(app.queued_profile_opens.is_empty()); + assert_eq!(app.session.documents().len(), docs, "neither is open"); + super::super::confirm(app).unwrap(); + assert_eq!(app.session.documents().len(), docs + 1); + assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); +} + +/// Color Settings change the open question while it is open: OK asks the question as it is now +/// (another working space) instead of opening, and opens by the policy once there is no question +/// (the working space is the file's profile). `tagged` (Wide Gamut RGB) asks with the settings in +/// force, the working space sRGB. +fn an_answer_waits_for_the_question_it_answers(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert_eq!(super::super::confirm(app).unwrap(), json!({ "dialog": OPEN_KIND })); + assert_eq!(app.session.documents().len(), docs, "not opened under the old question"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("working"), cms::canonical_name(cms::DISPLAY_P3), "asked again"); + app.run("edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert!(r.get("index").is_some() && app.ui.dialog.is_none(), "{r}"); + assert_eq!(app.session.documents().len(), docs + 1); +} + +/// Swatch Conflict asks again when the conflicts a converting paste raises change while it is open: +/// the destination is assigned another profile, so the pasted swatch converts to another color. OK +/// then pastes nothing and asks about the new conflict; OK on that one pastes as chosen. +fn swatch_conflicts_are_asked_again_when_they_change(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + let swatch = json!({"name": "Brand", "color": "#3366cc", "global": true}); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch.clone()).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch).unwrap(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = count(app); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + let asked = app.ui.dialog.as_ref().unwrap().fields["conflicts"].clone(); + set(app, "choice", json!("add")); + app.run("edit.assignProfile", json!({ "rgb": cms::DISPLAY_P3 })).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "asked again: {r}"); + assert_eq!(count(app), before, "nothing pasted under the old list"); + assert_ne!(app.ui.dialog.as_ref().unwrap().fields["conflicts"], asked); + set(app, "choice", json!("add")); + let r = super::super::confirm(app).unwrap(); + assert_eq!((count(app), r["renamed"].as_array().map(Vec::len)), (before + 1, Some(1)), "{r}"); } /// Cancel on the paste question pastes nothing, and a null `profileMismatch` asks as leaving it out @@ -65,18 +191,18 @@ fn paste_canceled(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> u } /// Another document becomes the active one while the paste question is open: OK pastes nothing, into -/// neither document, and the document the paste was asked in is active again afterward. `count` -/// counts the active document's objects. -fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { - let (asked_in, before) = (app.session.active_index().unwrap(), count(app)); +/// neither document, whichever is active. +fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) { + let counts = |app: &VectorcraftApp| -> Vec<(u64, usize)> { + app.session.documents().iter().map(|st| (st.uid, st.doc.layers[0].children().map_or(0, |c| c.len()))).collect() + }; + let (asked_in, before) = (app.session.active_index().unwrap(), counts(app)); assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND })); app.run("document.activate", json!({"index": 0})).unwrap(); - let other = count(app); super::super::confirm(app).unwrap(); assert!(app.ui.dialog.is_none()); - assert_eq!(count(app), other, "nothing pasted into the document now active"); + assert_eq!(counts(app), before, "nothing pasted into any document"); app.run("document.activate", json!({ "index": asked_in })).unwrap(); - assert_eq!(count(app), before, "nor into the one it was asked in"); } /// A drag of the art of the document assigned Display P3 into the active one asks as Paste does: @@ -118,8 +244,8 @@ fn drop_asks_as_paste_does(app: &mut VectorcraftApp, count: impl Fn(&Vectorcraft #[test] fn a_paste_question_about_both_models_has_a_choice_for_each() { let both = [ - json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "preserveNumbers"}), - json!({"model": "cmyk", "clipboard": "Ink A", "document": "Ink B", "default": "convert"}), + json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "preserveNumbers", "convertible": true}), + json!({"model": "cmyk", "clipboard": "Ink A", "document": "Ink B", "default": "convert", "convertible": true}), ]; assert_eq!(first_choice(&both), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); assert_eq!(first_choice(&both[1..]), json!("convert"), "one model starts on its policy"); @@ -211,6 +337,8 @@ fn opening_and_pasting_ask_about_profiles() { open_asked_under_roots(&mut app, &tagged); open_confirmed_under_roots(&mut app, &tagged); + links_read_under_the_roots_of_the_open(&mut app); + files_opened_together_ask_in_turn(&mut app, &tagged); // Missing Profiles: Ask When Opening, and a choice the file refuses. app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); @@ -248,11 +376,37 @@ fn opening_and_pasting_ask_about_profiles() { // Cancel pastes nothing; with the box off nothing asks. let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); paste_canceled(&mut app, count); - paste_asked_before_another_document_is_active(&mut app, count); + paste_asked_before_another_document_is_active(&mut app); drop_asks_as_paste_does(&mut app, count); let before = count(&app); app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); let r = app.run("edit.paste", json!({})).unwrap(); assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); assert_eq!(count(&app), before + 1); + swatch_conflicts_are_asked_again_when_they_change(&mut app); + all_artboards_leaves_backgrounds_out(&mut app); + // It changes the working space: last. + app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); + an_answer_waits_for_the_question_it_answers(&mut app, &tagged); +} + +/// Convert is offered only for a model whose colors can convert (`convertible`). +#[test] +fn convert_needs_both_profiles() { + let stuck = json!({"model": "rgb", "clipboard": "Gone", "document": "sRGB", "default": "preserveNumbers", "convertible": false}); + let free = json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "convert", "convertible": true}); + assert!(allowed(&stuck, "preserveNumbers") && !allowed(&stuck, "convert")); + assert!(allowed(&free, "convert") && allowed(&json!({"model": "rgb"}), "convert")); +} + +/// Paste on All Artboards asks about what it brings, without the backgrounds of copied artboards. +fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let listed = |app: &mut VectorcraftApp, command: &str| paste_mismatches(app, command, &json!({})).map(|m| m.len()); + assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); + assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); } diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index b525b82c7c..96ff733c42 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -36,13 +36,7 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option DialogResult { } let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); params["swatchConflict"] = Value::Object(choices); + // When the conflicts the paste raises have changed meanwhile (another profile converts the + // pasted swatches), it asks again about them instead. + let asked = list.to_vec(); app.ui.dialog = None; - crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, d.fields.get("__deferredPaste").and_then(Value::as_u64)) + let changed = |app: &mut VectorcraftApp, _: &str, params: &Value| found(app, params).is_some_and(|now| now != asked); + let recheck = crate::placing::Recheck { key: "swatchConflict", changed: &changed }; + let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); + crate::placing::confirm_swatch_paste(app, &d.str("__command"), params, deferred, Some(&recheck)) +} + +/// The swatch conflicts pasting with `params` raises (`clipboard.conflicts`), with the swatches as +/// the paste brings them: converted from another profile when it converts. +fn found(app: &mut VectorcraftApp, params: &Value) -> Option> { + let mut q = json!({}); + if let Some(m) = params.get("profileMismatch") { + q["profileMismatch"] = m.clone(); + } + let found = app.session.execute("clipboard.conflicts", &q).ok()?; + found["swatches"].as_array().cloned() } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8d0a355b52..b0d408285c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -352,6 +352,9 @@ pub struct VectorcraftApp { /// The file File › Open read that waits for the answer to its profile question /// ([`dialogs::profile_mismatch`]), kept out of the dialog's fields. pub(crate) pending_profile_open: Option, + /// Files File › Open read while another one's profile question was open, each asking its own + /// question in turn. + pub(crate) queued_profile_opens: std::collections::VecDeque, /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) script_picked: Vec, diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 0743918568..cdb35e7419 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -668,14 +668,41 @@ fn pastes_inside(id: &str) -> bool { !matches!(id, "edit.pasteInFront" | "edit.pasteInBack") } +/// The answer a paste question gave, checked again where the paste runs (in the document and with +/// the clipboard it was given with): `key` is the param that holds the answer, and `changed` tells +/// whether the question the paste command `id` with those params would ask now differs from the one +/// answered. The paste then runs without the answer, and so asks again. +pub(crate) struct Recheck<'a> { + pub key: &'static str, + pub changed: &'a dyn Fn(&mut VectorcraftApp, &str, &Value) -> bool, +} + +/// `params` without the answer `recheck` names when the question it answered has changed. +fn rechecked(app: &mut VectorcraftApp, id: &str, mut params: Value, recheck: Option<&Recheck<'_>>) -> Value { + if let Some(r) = recheck + && (r.changed)(app, id, ¶ms) + && let Some(o) = params.as_object_mut() + { + o.remove(r.key); + } + params +} + /// Run the command confirmed by the deferred paste's Swatch Conflict or Paste Profile Mismatch -/// dialog. -pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: Value, token: Option) -> Result { +/// dialog, asking again first when `recheck` finds that the question has changed. +pub(crate) fn confirm_swatch_paste( + app: &mut VectorcraftApp, + id: &str, + params: Value, + token: Option, + recheck: Option<&Recheck<'_>>, +) -> Result { if !app.placing.swatch_paste.as_ref().is_some_and(|waiting| Some(waiting.chain) == token) { if token.is_some() || app.placing.swatch_paste.is_some() { cancel_swatch_paste(app); return Err("the deferred paste is no longer available".into()); } + let params = rechecked(app, id, params, recheck); return app.run(id, params); } let Some(waiting) = app.placing.swatch_paste.take() else { return app.run(id, params) }; @@ -701,11 +728,13 @@ pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: V } let insertion = waiting.insertion.clone().or_now(changed.as_ref(), app, pastes_inside(id)); insertion.clone().set(app); + // The question checked again with the clipboard and document the paste runs with. + let params = rechecked(app, id, params, recheck); app.placing.adopted = true; let result = app.run(id, params); app.placing.adopted = false; - // The paste asked again (Swatch Conflict after Paste Profile Mismatch): it stays deferred, in - // the context it was given in. + // The paste asked again (Swatch Conflict after Paste Profile Mismatch, or the same question + // about what changed): it stays deferred, in the context it was given in. let asked_again = app.ui.dialog.as_mut().filter(|d| asks_before_paste(&d.kind) && !d.fields.contains_key("__deferredPaste")); if let Some(d) = asked_again && let Ok(st) = app.session.doc() diff --git a/docs/mcp.md b/docs/mcp.md index 5f56c15f13..8e5ab0b0da 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1874,21 +1874,30 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel, the Color Picker, Swatch Options and New Swatch check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. - **Profile Mismatches and Missing Profiles** (`edit.colorSettings {askMismatchOpen, askMismatchPaste, - askMissingOpen}`, all off by default and kept in `Color Settings.json`): with `askMismatchOpen` or - `askMissingOpen` on, the desktop app's File › Open asks before a document opens when the profile of its color mode - is not the working space (use the embedded profile, convert the colors to the working space, or discard the - profile) or when it has none (leave it, assign the working space, or assign a profile), starting on what the - model's policy does; Cancel leaves the file closed. `document.open` never asks: `profileChoice` (`useEmbedded`, - `convert`, `discard`; `leave`, `assignWorking`, `assign` with `assignProfile`) states the answer, else the policy - applies, and the reply's `profileChoice` names the answer used. Copy remembers the profiles the colors showed - through; pasting them into a document with another RGB or CMYK profile keeps their numbers or converts them, as - `profileMismatch` on the paste commands and `edit.dropSelection` says (`preserveNumbers` or `convert` for both - models, or `{rgb?, cmyk?}` with one for each), else as the model's policy does (`convert` converts, the others keep - the numbers; a profile that is not available keeps them). `clipboard.profileMismatch` lists the models that - differ, only those whose colors the copied objects use (with `sourceDocument` and `ids`, the objects a drop - brings), and with `askMismatchPaste` on the desktop app asks first on Paste and on a drag between documents. A - question about both models has a choice for each, each starting on its model's policy. New from Template and - File › Revert follow the policies without asking. + askMissingOpen}`, all off by default and kept in `Color Settings.json`): with `askMismatchOpen` on, the desktop + app's File › Open asks before a document opens when the profile of its color mode is not the working space (use + the embedded profile, convert the colors to the working space, or discard the profile); with `askMissingOpen` on, + it asks when the document has no profile of its color mode (leave it, assign the working space, or assign a + profile). Each question starts on what the model's policy does, and Cancel leaves the file closed. Files opened + together ask one at a time, each opening only after its own answer. When Color Settings change the question + while it is open (another working space), OK asks the new question instead of opening. `document.open` never + asks: `profileChoice` (`useEmbedded`, `convert`, `discard`; `leave`, `assignWorking`, `assign` with + `assignProfile`) states the answer, else the policy applies. The reply's `profileChoice` names the choice given + for the document's question, not what it did: `convert` from a profile that is not available keeps the profile, + and a warning says the colors were not converted. Copy remembers the profiles the colors showed through (a + document's assigned profile that was removed since counts as the working space it draws through); pasting them + into a document with another RGB or CMYK profile keeps their numbers or converts them, as `profileMismatch` on the + paste commands and `edit.dropSelection` says (`preserveNumbers` or `convert` for both models, or `{rgb?, cmyk?}` + with one for each; `null` is the same as leaving it out), else as the model's policy does (`convert` converts, the + others keep the numbers). Colors whose source or destination profile is not available keep their numbers, also + with `convert`. `clipboard.profileMismatch` lists the models that differ, only those whose colors the copied + objects use (with `sourceDocument` and `ids`, the objects a drop brings; with `allArtboards: true`, without the + background colors of copied artboards, which Paste on All Artboards leaves behind), and gives `convertible: false` + for a model whose colors can't convert. With `askMismatchPaste` on, the desktop app asks first on Paste and on a + drag between documents, and offers only Preserve Numbers for a model that can't convert. A question about both + models has a choice for each, each starting on its model's policy. When the profiles a paste brings or the swatch + conflicts it raises change while the paste question or Swatch Conflict is open, OK asks again about them. New from + Template and File › Revert follow the policies without asking. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or