diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index f65fa1fd10..0544ac1972 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -196,6 +196,15 @@ impl Unit { } parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite()) } + + /// Parse a measurement with decimal points or commas and no input locale. Refuse a + /// number that looks like a grouped integer, even when it is part of an expression. + pub fn parse_with_decimal_comma(self, text: &str) -> Option { + if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) { + return None; + } + self.parse(&decimal_point(text)) + } /// The value naming this unit in the Units preferences (`points`, `millimeters`, /// `feetInches`). pub const fn key(self) -> &'static str { @@ -397,6 +406,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } +/// Does the operand contain a thousands comma? Check both parts of a compact pica value and +/// read a percentage's number without its percent sign. +fn thousands_operand(operand: &str) -> bool { + let operand = operand.trim(); + if let Some((picas, points)) = operand.split_once('p') + && !points.trim().is_empty() + && points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b',')) + { + return thousands(picas) || thousands(points); + } + thousands(operand.strip_suffix('%').unwrap_or(operand)) +} + /// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or /// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at /// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs index 4da4f68b79..c79f42919c 100644 --- a/crates/engine/src/cmd/addons/units.rs +++ b/crates/engine/src/cmd/addons/units.rs @@ -1,6 +1,6 @@ //! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. -//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and -//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives +//! it in each unit of Preferences › Units › East Asian Type //! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). //! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform //! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the @@ -10,7 +10,7 @@ mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit}; +use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit}; use vectorcraft_render::effects; use super::super::{CommandSpec, always, bad, cmd, has_selection}; @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Convert Units", [], None, - "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + "{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", always, convert ), @@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result { return Err(bad(CONVERT, "missing `value`")); }; let pt = match v { - Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s), Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), _ => None, }; diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 802fb5dfdf..2557ea3a6c 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() { } #[test] -fn values_read_as_number_fields_read_them() { +fn values_accept_units_arithmetic_and_decimal_commas() { let mut s = session(); let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); @@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() { assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); // Each number of a sum reads its own separator. assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); - // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. - assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); + assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25)); + assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5)); + assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); // x, X and × multiply as * does, and each counts toward the 128 signs. @@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() { assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err()); } +#[test] +fn a_thousands_comma_in_an_arithmetic_operand_is_refused() { + let mut s = session(); + for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] { + let result = s.execute("addon.units.convert", &json!({"value": value})); + assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}"); + } +} + #[test] fn keys_the_commands_do_not_take_are_refused() { let s = session(); diff --git a/crates/engine/src/cmd/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs index 7e6c3f2184..e67bc5e3bd 100644 --- a/crates/engine/src/cmd/colormgmt/proof_file.rs +++ b/crates/engine/src/cmd/colormgmt/proof_file.rs @@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec { pub(super) fn save(s: &mut Session, p: &Value) -> Result { const C: &str = "view.proofSetup.save"; let (path, named) = file_path(s, p, C)?; - let mut setup = proof::view().setup; - setup_params(p, &mut setup, C)?; - check_device(&setup.target).map_err(|e| bad(C, e))?; - // A file `view.proofSetup.load` would refuse is not written (a device with a very long name). - let bytes = encode(&setup); - if bytes.len() > MAX_FILE { - return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes"))); - } + let (setup, bytes) = encode_options(p, &path)?; if named && let Some(dir) = std::path::Path::new(&path).parent() && !dir.is_dir() @@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { Ok(Value::Object(r)) } +/// Serialize the Customize dialog's draft without committing it or writing a path. +pub fn draft_bytes(p: &Value) -> Result> { + encode_options(p, "Proof Setup").map(|(_, bytes)| bytes) +} + +fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec)> { + const C: &str = "view.proofSetup.save"; + let mut setup = proof::view().setup; + setup_params(p, &mut setup, C)?; + check_device(&setup.target).map_err(|e| bad(C, e))?; + let bytes = encode(&setup); + if bytes.len() > MAX_FILE { + return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes"))); + } + Ok((setup, bytes)) +} + /// The file `p` names for `cmd` and the usable proof setup in it. fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> { let (path, _) = file_path(s, p, cmd)?; // One byte past the limit shows a file over it, which is not read further. let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?; - if bytes.len() > MAX_FILE { - return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes"))); - } - let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + let setup = checked_setup(&bytes, &path, cmd)?; Ok((path, setup)) } +/// Read a picked proof setup's validated settings without applying them to the view. +pub fn draft_fields(bytes: &[u8], name: &str) -> Result { + let setup = checked_setup(bytes, name, "view.proofSetup.read")?; + Ok(Value::Object(setup_json(&setup))) +} + +fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result { + if bytes.len() > MAX_FILE { + return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes"))); + } + let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + Ok(setup) +} + pub(super) fn read(s: &mut Session, p: &Value) -> Result { let (path, setup) = read_setup(s, p, "view.proofSetup.read")?; let mut r = setup_json(&setup); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 1115c7e917..5a77b6d780 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -76,6 +76,15 @@ pub fn specs() -> Vec { has_doc, relink ), + cmd!( + "links.replaceEmbedded", + "Replace Image", + [], + None, + "{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}", + has_doc, + replace_embedded + ), cmd!( query "links.list", "Links", @@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } +/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement. +fn replace_embedded(s: &mut Session, p: &Value) -> Result { + const C: &str = "links.replaceEmbedded"; + let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?; + let doc = &s.doc()?.doc; + let mut seen = BTreeSet::new(); + for id in &ids { + if !seen.insert(*id) { + return Err(bad(C, format!("image {} is listed twice", id.0))); + } + if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) { + return Err(bad(C, format!("object {} is not an image", id.0))); + } + } + let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?; + let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?; + let mut img = fileio::raster_image(&bytes)?; + img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?; + s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?; + Ok(json!({ "replaced": ids_json(&ids) })) +} + /// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels /// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the /// transform still gives it its old size. Its Placement Options do not apply. The result is what @@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ /// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it: /// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a /// distort maps a path's. -fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { +fn refill_distorted( + n: &mut Node, + old_clip: Option<&FileClip>, + link: Option<&LinkInfo>, + img: &RasterImage, + held: Option<(&PathData, FillRule)>, +) -> ClipTo { let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); if let NodeKind::Image(im) = &mut n.kind { if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); } - (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); + (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned()); } let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule))); placed_clip_to(old.as_ref(), None, file, held) @@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option { /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that /// show that content. -fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { - install_with(d, ids, read, force, also, false) +fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { + install_with(d, ids, Some(&link), img, force, also, false) } /// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it @@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo { } } -/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`]. +/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes +/// through [`unembed_clip`]. fn install_with( d: &mut Document, ids: &[NodeId], - (link, img): FileRead, + link: Option<&LinkInfo>, + img: RasterImage, force: Option, also: Option<(&str, &str)>, unembed: bool, @@ -1341,7 +1380,7 @@ fn install_with( NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()), _ => None, }; - let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); + let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held); return (n, keep(clip, held.is_some())); } if let NodeKind::Image(im) = &mut n.kind { @@ -1353,7 +1392,7 @@ fn install_with( }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some()); - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } (n, clip) }; @@ -1367,7 +1406,7 @@ fn install_with( }; let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); if let Some(n) = d.node_mut(*id) { - let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); + let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); clips.push((*id, keep(clip, held.is_some()))); } continue; @@ -1384,12 +1423,12 @@ fn install_with( if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { - (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); + (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned()); } } // A DCS file's spot plates print on spot swatches of their inks. super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates()); - store_image(d, &img.key, img.blob, true); + store_image(d, &img.key, img.blob, link.is_some()); clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), @@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result { // Read before writing: pixels that can't be read leave no file behind. let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; - let read = (link_info(&path, &bytes), img); + let link = link_info(&path, &bytes); drop(doc); - s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?; + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re drop(doc); let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); let edited = s.edit("Unembed", |d, _| { - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true))) + editing_brush_art(d, |d| { + reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)) + }) }); if let Err(e) = edited { remove_written(&written); diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index d2e3f7b95a..4de3064182 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -406,6 +406,13 @@ fn edit_blends(s: &mut Session, label: &str, f: impl Fn(&mut Vec>, &mu ok() } +impl Session { + /// Whether Blend Options would operate on selected artwork rather than new-blend defaults. + pub fn has_selected_blend(&self) -> bool { + super::common::any_selected_of(self, is_blend, |_| true) + } +} + /// The first selected blend: its id, spec and key ids. fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec)> { let b = *selected_of(s, is_blend).first()?; diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index db1a641f2f..b863ec5edf 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -876,11 +876,17 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result { /// result is that command's, with `format` set to `csv` or `xml`. fn variable_import(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.import"; - let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; - let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let (name, input) = if let Some(path) = str_param(p, "path") { + (path, json!({"path": path})) + } else { + let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `path` or `name` with `dataBase64`"))?; + let bytes = str_param(p, "dataBase64").ok_or_else(|| bad(C, "missing `dataBase64`"))?; + (name, json!({"dataBase64": bytes})) + }; + let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); let (format, mut out) = match ext.as_deref() { - Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?), - Some("xml") => ("xml", load_library(s, &json!({"path": path}))?), + Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &input)?), + Some("xml") => ("xml", load_library(s, &input)?), _ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")), }; out["format"] = json!(format); @@ -1084,7 +1090,7 @@ pub fn specs() -> Vec { "Import…", ["Window", "Variables"], None, - "{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", + "{path | name | dataBase64 (a file's path, or its name with its bytes)} import a data source chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`", has_doc, variable_import ), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index a519986ed0..f2444bc019 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1096,7 +1096,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPicker", "Color Picker…", "", - "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", + "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard. Artboard preview and OK require the opening document to be active", ), ( "ui.sampleScreenColor", diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 7d000aa64f..90a35458cc 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -167,6 +167,8 @@ pub struct FrameStats { /// group or an effect's raster. A part of the frame rendered on its own can draw that art with /// other pixels than the whole frame does. pub view_sized: usize, + bounded_view_sized: usize, + view_sized_bounds: Option, /// How many threads composed the frame from its two ink planes, in a CMYK document that shows /// transparency; 0 for other frames. pub ink_threads: usize, @@ -183,10 +185,35 @@ pub struct FrameStats { pub micros: u64, } +impl FrameStats { + /// A conservative enclosure in the frame's output pixels, when every view-sized operation has + /// a known bound. `None` leaves the choice to render the whole frame. + pub fn view_sized_bounds(&self) -> Option { + self.view_sized_bounds.filter(|_| self.bounded_view_sized == self.view_sized) + } +} + +impl super::Renderer { + /// Records an operation bounded by its own output clip. A nested effect can affect more than + /// its own clip once an ancestor filters or composites it, so only bound direct RGB output. + pub(crate) fn note_view_sized_clip(&mut self, f: &Frame, clip: Rect) { + self.stats.view_sized += 1; + if self.nested == 0 && self.offscreen_live == 0 && f.view == f.output && f.doc.color_mode == vectorcraft_doc::ColorMode::Rgb { + let bound = f.output.transform_rect_bbox(clip).inflate(1.0, 1.0); + if bound.is_finite() { + self.stats.bounded_view_sized += 1; + self.stats.view_sized_bounds = vectorcraft_geom::union_opt(self.stats.view_sized_bounds, Some(bound)); + } + } + } +} + #[derive(Clone, Copy)] pub(crate) struct Frame<'a> { /// Drawing into a multithreaded context: vello filter layers must be rendered offscreen. pub(crate) mt: bool, + /// Set the flag if the incomplete paint would need a full render. + pub(crate) patch: Option<&'a std::cell::Cell>, pub(crate) doc: &'a Document, /// `doc`'s symbol art boxes, which culling measures symbol instances by ([`SymbolBoxes::quick`]). pub(crate) symbols: &'a SymbolBoxes<'a>, @@ -208,6 +235,17 @@ pub(crate) struct Frame<'a> { } impl Frame<'_> { + pub(crate) fn reject_patch(&self) -> bool { + self.patch.is_some_and(|hit| { + hit.set(true); + true + }) + } + + pub(crate) fn patch_rejected(&self) -> bool { + self.patch.is_some_and(std::cell::Cell::get) + } + /// Text space → device pixels when type is snapped to the pixel grid (Type anti-aliasing). pub(crate) fn text_snap(&self, t: &TextObject) -> Option { (self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf) diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index fe6933fea3..ceead2a01e 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -11,6 +11,12 @@ use super::{ RasterFx, Rect, RenderContext, Renderer, Shape, blend_mode, effects, fill_rule, paint, peniko, }; +/// The content to filter. An inner glow's output has an enclosing clip, while a shadow can spread beyond its content. +pub(super) enum FilterReach { + Clipped(Rect), + Spreads(Rect), +} + /// A hash of the names of `doc`'s swatches and patterns, of the paints and spot flags of its global /// swatches, and of the Spot Colors option those colors depend on. pub(crate) fn paint_names(doc: &Document) -> u64 { @@ -596,15 +602,25 @@ impl Renderer { &mut self, ctx: &mut RenderContext, f: &Frame, - reach: Rect, + reach: FilterReach, blur: f64, composite: Option<(vectorcraft_doc::color::BlendMode, f32)>, draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame, Option<(vectorcraft_doc::color::BlendMode, f32)>), ) { // A filter layer's coarser grid starts where its context does: at the corner of a context // drawn single-threaded, and at the frame's edge for a region cropped to the frame. + let (reach, clipped) = match reach { + FilterReach::Clipped(rect) => (rect, true), + FilterReach::Spreads(rect) => (rect, false), + }; let screen = Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); - self.stats.view_sized += usize::from(!f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen); + if !f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen { + if clipped { + self.note_view_sized_clip(f, reach); + } else { + self.stats.view_sized += 1; + } + } if !f.mt { return self.inside_layer(|r| draw(r, ctx, f, composite)); } diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index cafc8ec35b..1bc71d4626 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1,5 +1,6 @@ use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage}; use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry}; +use super::pixels::FilterReach; use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted}; use super::raster::{ DRAG_PIXEL_BUDGET, MAX_RASTERIZE, PIXEL_BUDGET, ViewCrop, content_changing, doc_raster_ppi, image_size, linear_key, pan_margin, pcolor, @@ -261,7 +262,7 @@ impl Renderer { let reach = reach + Vec2::new(dx, dy); #[cfg(test)] note_silhouette(); - self.with_filters(ctx, f, reach, blur, Some((mode, opacity)), |r, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Spreads(reach), blur, Some((mode, opacity)), |r, c, fr, comp| { c.set_transform(fr.view); c.push_layer(None, comp.map(|m| blend_mode(m.0)), comp.map(|m| m.1), None, Some(filter)); let ink = darkness.map_or(fr.ink, |d| fr.ink.darkened(d)); @@ -473,7 +474,7 @@ impl Renderer { let opacity = self.opacity_of(a); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_doc::color::BlendMode::Normal || a.isolate) { let blends = self.blends_through(a); - let bounds = if blends { self.bounds_of(f.symbols, a) } else { None }; + let bounds = if blends { self.frame_bounds_of(f, a) } else { None }; let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() }; self.group(ctx, f, comp, &mut |r, c, fr| r.draw_object_fx_art(c, fr, a, cache)); } else { @@ -819,6 +820,9 @@ impl Renderer { rfx: &[RasterFx], paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame), ) { + if !rfx.is_empty() && f.reject_patch() { + return; + } // Only the last MAX_RASTERIZE Rasterize effects are drawn. let count = rfx.iter().filter(|fx| matches!(fx, RasterFx::Rasterize(_))).count(); let capped: Vec; @@ -998,7 +1002,7 @@ impl Renderer { let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue }; let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color)); if pixels { - self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |r, c, fr, comp| { if let Some((m, o)) = comp { c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(blend_mode(m)), Some(o), None, None); @@ -1032,7 +1036,7 @@ impl Renderer { }); continue; } - self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| { + self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |_, c, fr, comp| { // The blend layer goes outside the clip: a clip layer is isolated, so a blend // inside it would mix with nothing instead of the content below. if let Some((m, o)) = comp { @@ -1131,6 +1135,7 @@ mod tests { let opts = RenderOptions::default(); let frame = Frame { mt: false, + patch: None, doc: &doc, symbols: &symbols, view: Affine::IDENTITY, diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 1090c937ad..39b6e951b8 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1530,6 +1530,78 @@ fn moved_objects_draw_their_effect_rasters_while_interacting() { /// 1600 × 1000 view near its corner needs more than the drag's budget. The /// frame after the drag, of the same document, is what a fresh renderer draws, as is a frame /// rendered while interacting without a drag (a dialog's preview). +#[test] +fn a_plain_patch_stops_at_a_raster_effect() { + let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("texture.texturizer", json!({}))]); + let plain = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(94.0, 3.0, 96.0, 6.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap(); + let (width, height) = (2000, 1600); + let view = Affine::scale(20.0); + let still = RenderOptions::default(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + renderer.render(&doc, width, height, view, &still); + let total_drawn = renderer.stats.drawn; + let mut scratch = Renderer::new(); + scratch.threads = 0; + let patch_view = Affine::translate((-1850.0, -50.0)) * view; + assert!(scratch.render_plain_patch(&doc, 100, 100, patch_view, &still).is_some(), "the distant patch does not draw the effect"); + assert!(scratch.render_plain_patch(&doc, width, height, view, &still).is_none(), "a patch that draws the effect needs the full render"); + assert!(scratch.stats.drawn < total_drawn, "the rejected patch does not draw the artwork after the effect"); +} + +#[test] +fn a_plain_patch_does_not_build_unrelated_3d_art_to_cull_it() { + let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("threeD.extrude", json!({"depth": 10}))]); + let plain = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(290.0, 10.0, 300.0, 20.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap(); + let opts = RenderOptions::default(); + let mut whole = Renderer::new(); + whole.threads = 0; + whole.render(&doc, 350, 150, Affine::IDENTITY, &opts); + assert!(whole.stats.three_d_built > 0, "the fixture generates 3D art"); + let mut scratch = Renderer::new(); + scratch.threads = 0; + let patch = Affine::translate((-280.0, 0.0)); + let result = scratch.render_plain_patch(&doc, 40, 30, patch, &opts); + assert_eq!(scratch.stats.three_d_built, 0, "fall back before rebuilding 3D art"); + assert!(result.is_none()); + + let layer = doc.layers[0].id; + let art = doc.layers[0].children().unwrap()[0].clone(); + doc.remove(art.id).unwrap(); + let mut group = Node::group(doc.alloc_id(), vec![art.clone()]); + group.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.innerGlow".into(), params: json!({"blur": 4}), visible: true }); + assert!(super::has_object_fx(&group), "this group uses the alternate bounds path"); + let group = doc.insert(Some(layer), 0, group).unwrap(); + assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "alternate group bounds also need the 3D child"); + doc.remove(group).unwrap(); + + let mut template = Node::layer(doc.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(0)); + if let vectorcraft_doc::NodeKind::Layer { template: flag, children, .. } = &mut template.kind { + *flag = true; + children.push(art.clone()); + } + let template = doc.insert(Some(layer), 0, template).unwrap(); + let hidden = RenderOptions { hide_templates: true, ..opts.clone() }; + assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &hidden).is_none(), "layer bounds conservatively include hidden templates"); + assert_eq!(scratch.stats.three_d_built, 0); + + doc.remove(template).unwrap(); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Solid".into(), art }); + let instance = Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Solid".into(), xf: Affine::IDENTITY }); + doc.insert(Some(layer), 0, instance).unwrap(); + assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "a symbol's definition also needs 3D bounds"); +} + #[test] fn a_drag_renders_raster_effects_within_the_drag_budget() { let effects = vec![("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 7, "opacity": 80})), ("texture.texturizer", json!({}))]; diff --git a/crates/render/src/group.rs b/crates/render/src/group.rs index 09509f58e7..12490eb308 100644 --- a/crates/render/src/group.rs +++ b/crates/render/src/group.rs @@ -114,6 +114,9 @@ impl Renderer { } fn group_offscreen(&mut self, ctx: &mut RenderContext, f: &Frame, c: Composite, r: Region, draw: &mut Content) { + if f.reject_patch() { + return; + } let Composite { clip, blend, opacity, mask, isolated, .. } = c; // A group that blends with its backdrop is drawn twice (over the backdrop, and alone for // its coverage), and so is everything in it, so such groups nested in each other cost 2ⁿ. @@ -309,7 +312,10 @@ impl Renderer { /// `c` over the backdrop and its shape are drawn offscreen over `c`'s bounds, and `c` is drawn /// as in the other knockout passes (groups in it can't copy their backdrop). pub(crate) fn knockout_over(&mut self, ctx: &mut RenderContext, f: &Frame, c: &Arc, backdrop: &Arc) { - let bounds = self.bounds_of(f.symbols, c); + let bounds = self.frame_bounds_of(f, c); + if f.patch_rejected() { + return; + } let Some(r) = region(ctx, f, bounds) else { return }; let view = Affine::translate((-(r.x as f64), -(r.y as f64))) * f.view; let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, r.w as f64, r.h as f64)); diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index cda46c8fc0..341aa22ff9 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -583,7 +583,7 @@ impl Renderer { let enclosing = std::mem::replace(&mut self.knockout, knockout); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) { let blends = self.blends_through(a); - let bounds = if blends { self.bounds_of(f.symbols, a) } else { None }; + let bounds = if blends { self.frame_bounds_of(f, a) } else { None }; let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() }; self.group(ctx, f, comp, &mut |r, c, fr| r.draw_live_body(c, fr, a, true)); } else { @@ -636,6 +636,10 @@ impl Renderer { if !m.is_valid() { return; } + // A cropped mesh may lose a covered neighbor that supplied a color at its fringe. + if f.reject_patch() { + return; + } if f.opts.outline { let bp = m.lines().to_bezpath(); self.hairline(ctx, f, &bp, [0, 0, 0, 255]); diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 94b8e8576e..5f4b5d71df 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -198,6 +198,7 @@ fn rasterize( let v = view * def.instance_xf(o); let frame = Frame { mt: false, + patch: None, doc, symbols: &symbols, view: v, diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1b9ba6db1a..3e34f4da9b 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -113,9 +113,32 @@ impl Renderer { /// set in one of the document's composite fonts draws in the document's definition, also when /// no session has registered it (a document that is not in front, or read from a file). pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered { + self.render_document(doc, width, height, view, opts, None) + } + + /// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen + /// group compositing require the full render. + pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option { + if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample { + return None; + } + let hit = std::cell::Cell::new(false); + let image = self.render_document(doc, width, height, view, opts, Some(&hit)); + (!hit.get()).then_some(image) + } + + fn render_document( + &mut self, + doc: &Document, + width: u32, + height: u32, + view: Affine, + opts: &RenderOptions, + patch: Option<&std::cell::Cell>, + ) -> Rendered { let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); - self.render_as(doc, width, height, view, opts, false, 1) + self.render_as(doc, width, height, view, opts, false, 1, patch) } /// [`Self::render`], or with `inks` the ink amounts in the working CMYK space instead of @@ -123,14 +146,24 @@ impl Renderer { /// pixel of the output in pixels of this render: the supersampling factor while an export /// draws its art at several times its size, else 1 ([`Frame::output`]). #[allow(clippy::too_many_arguments)] - fn render_as(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions, inks: bool, cell: u32) -> Rendered { + fn render_as( + &mut self, + doc: &Document, + width: u32, + height: u32, + view: Affine, + opts: &RenderOptions, + inks: bool, + cell: u32, + patch: Option<&std::cell::Cell>, + ) -> Rendered { let start = now(); if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() { let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE)); if let Some(k) = supersample_factor(w, h) { let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() }; let hairline = std::mem::replace(&mut self.hairline, f64::from(k)); - let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k); + let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch); self.hairline = hairline; let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize); self.stats.micros = now().saturating_sub(start); @@ -164,7 +197,7 @@ impl Renderer { let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); - let frame = Frame { mt: threads > 0, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) { @@ -199,7 +232,7 @@ impl Renderer { self.draw_frame(&frame, w, h) }; self.end_frame(); - if !inks { + if !inks && !pixels.is_empty() { proof::post(&mut pixels, opts); } self.stats.symbol_art = symbols.art_measured(); @@ -218,9 +251,8 @@ impl Renderer { self.placed_frame = None; } - /// End a frame: drop cache entries not used for a few frames (every render, thumbnails too, - /// so the nodes they hold go with them). - fn end_frame(&mut self) { + /// Drop stale bounds and paths, including old versions of edited nodes. + fn sweep_node_geometry(&mut self) { let g = self.stamp; // Swept however few the entries: each keeps its node alive, and an object dragged or // edited makes a new node (with its layer) in every frame. Kept until there were 1,024 of @@ -230,6 +262,23 @@ impl Renderer { // A kept path stays while its object is in `geom`, which keeps the objects still drawn. let geom = &self.geom; self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node))); + } + + /// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update. + /// Age the measurement caches and keep the previous draw's effect rasters available. + pub fn finish_measurement_only(&mut self) { + self.stamp += 1; + self.sweep_node_geometry(); + let g = self.stamp; + self.blends.retain(|_, e| g - e.2 <= 3); + self.let_go_of_measured(); + } + + /// End a frame: drop cache entries not used for a few frames (every render, thumbnails too, + /// so the nodes they hold go with them). + fn end_frame(&mut self) { + let g = self.stamp; + self.sweep_node_geometry(); if self.strokes.len() > 1024 { self.strokes.retain(|_, e| g - e.stamp <= 3); let strokes = &self.strokes; @@ -309,11 +358,17 @@ impl Renderer { } else { self.draw_page(&mut ctx, f); } - let pm = self.finish(&mut ctx, self.raster); + let pm = if f.patch_rejected() { + self.picture = None; + None + } else { + Some(self.finish(&mut ctx, self.raster)) + }; self.contexts.push((threads, ctx)); if self.contexts.len() > 2 { self.contexts.remove(0); } + let Some(pm) = pm else { return Vec::new() }; let mut pixels = pm.data_as_u8_slice().to_vec(); if let Some(bg) = opts.background { over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg))); @@ -370,7 +425,7 @@ impl Renderer { let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); let _frame = vectorcraft_text::KeptLayoutsFrame::begin(); - self.render_as(doc, w, h, view, opts, true, 1).pixels + self.render_as(doc, w, h, view, opts, true, 1, None).pixels } /// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels. @@ -427,7 +482,7 @@ impl Renderer { ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; - let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; + let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); self.begin_frame(); (self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index fd1218e0a8..1e47dcf70d 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -7,10 +7,33 @@ use super::{ use crate::kept_paths::{self, KeptPath}; use crate::node_checks::{holds_measured_three_d, measures_three_d}; +fn needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool { + measures_three_d(node) + || matches!(&node.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.symbol(symbol).is_some_and( + |s| holds_measured_three_d(&s.art) || holds_instance(&s.art) && symbols.has_effects(symbol) + )) +} + +fn subtree_needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool { + needs_three_d_bounds(symbols, node) + || node.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child))) +} + impl Renderer { /// Cached cull bounds of a node (containers union their cached children), symbol instances /// measured by their art box from `symbols`. pub(crate) fn bounds_of(&mut self, symbols: &SymbolBoxes, a: &Arc) -> Option { + self.bounds_with_patch(symbols, a, None) + } + + pub(crate) fn frame_bounds_of(&mut self, f: &Frame, a: &Arc) -> Option { + self.bounds_with_patch(f.symbols, a, f.patch.map(|_| f)) + } + + fn bounds_with_patch(&mut self, symbols: &SymbolBoxes, a: &Arc, patch: Option<&Frame<'_>>) -> Option { + if patch.is_some_and(Frame::patch_rejected) { + return None; + } let key = Arc::as_ptr(a) as usize; if let Some(e) = self.geom.get_mut(&key) && Arc::ptr_eq(&e.node, a) @@ -18,6 +41,11 @@ impl Renderer { e.stamp = self.stamp; return e.bounds; } + // The full renderer can reuse its 3D art. A cold scratch renderer may otherwise + // build it while calculating cull bounds, including bounds of symbol definitions. + if patch.is_some_and(|f| needs_three_d_bounds(symbols, a) && f.reject_patch()) { + return None; + } let b = match &a.kind { NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(a) => { let mut acc: Option = None; @@ -25,7 +53,10 @@ impl Renderer { let source = a.extras().trace.is_some().then(|| children.first()).flatten(); for c in children { if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) { - acc = vectorcraft_geom::union_opt(acc, self.bounds_of(symbols, c)); + acc = vectorcraft_geom::union_opt(acc, self.bounds_with_patch(symbols, c, patch)); + if patch.is_some_and(Frame::patch_rejected) { + return None; + } } } acc @@ -48,6 +79,14 @@ impl Renderer { let pad = brush_fx::pad(symbols, a); b.map(|b| fx::with_own_raster_reach(symbols, a, b).inflate(pad, pad)) } + // The fallback measures the whole subtree without going through the cached + // child traversal above. Reject cold measurement before entering it. + _ if patch.is_some_and(|f| { + a.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child))) && f.reject_patch() + }) => + { + return None; + } _ => self.kept_bounds(symbols, a).unwrap_or_else(|| brush_fx::cull_bounds(symbols, a)), }; self.geom.insert(key, GeomEntry { node: a.clone(), bounds: b, path: None, stamp: self.stamp }); @@ -227,7 +266,11 @@ impl Renderer { if crate::node_checks::left_out(f.opts, f.doc, a) { return true; } - match self.bounds_of(f.symbols, a) { + let bounds = self.frame_bounds_of(f, a); + if f.patch_rejected() { + return true; + } + match bounds { Some(b) => { let pad = f.px * 2.0; // Level of detail: leaves smaller than a quarter pixel are invisible. @@ -241,7 +284,7 @@ impl Renderer { } pub(crate) fn draw_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc) { - if self.skipped(f, a) { + if f.patch_rejected() || self.skipped(f, a) { return; } // An image masked by one white shape painted straight into the shape, as an image in a @@ -272,7 +315,10 @@ impl Renderer { let Some(m) = a.extras().mask.as_deref().filter(|m| !m.disabled && !f.opts.outline && !self.is_shape(a)) else { return false }; // A masked object is a non-isolated group of its own, drawn over its own pixels: the // mask is rendered over those only. - let bounds = self.bounds_of(f.symbols, a); + let bounds = self.frame_bounds_of(f, a); + if f.patch_rejected() { + return true; + } let Some((r, sub)) = group::area(ctx, f, bounds) else { return true }; let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return true }; let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a)); @@ -296,6 +342,9 @@ impl Renderer { /// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen, /// as luminance ([`mask_value`]). pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option> { + if f.reject_patch() { + return None; + } let mut mctx = f.offscreen_context(w, h); // Mask art is a picture of its own: it takes no part in a knockout group around the object, // and its luminance is that of its screen colours. @@ -393,7 +442,7 @@ impl Renderer { return; } // A cancelled export stops drawing; whoever asked for the picture drops it (see `cancel`). - if vectorcraft_doc::cancel::is_cancelled() { + if f.patch_rejected() || f.patch.is_some() && measures_three_d(n) && f.reject_patch() || vectorcraft_doc::cancel::is_cancelled() { return; } if force { @@ -679,7 +728,7 @@ impl Renderer { let inverse = im.xf.inverse(); let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h); for c in shapes { - if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) { + if let Some(b) = self.frame_bounds_of(f, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) { for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] { let p = inverse * kurbo::Point::new(q.0, q.1); if p.x.is_finite() && p.y.is_finite() { @@ -742,7 +791,11 @@ impl Renderer { if crate::node_checks::left_out(f.opts, f.doc, c) { return; } - match self.bounds_of(f.symbols, c) { + let bounds = self.frame_bounds_of(f, c); + if f.patch_rejected() { + return; + } + match bounds { Some(b) => { let pad = f.px * 2.0; if !rects_overlap(b.inflate(pad, pad), f.visible) { @@ -781,7 +834,7 @@ impl Renderer { self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n))); } } else { - for c in children { + for c in children.iter().take_while(|_| !f.patch_rejected()) { self.draw_arc(ctx, f, c); } } @@ -804,6 +857,9 @@ impl Renderer { /// over the elements below it (the art below the group when the group is non-isolated and /// drawn over a copy of it, see [`Self::group`] and [`Self::knockout_over`]). pub(crate) fn draw_knockout(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc]) { + if f.reject_patch() { + return; + } let backdrop = self.backdrop.take(); for c in Node::knockout_elements(children) { if self.skipped(f, c) { diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 01c73918e7..9e6851043f 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -327,6 +327,10 @@ impl Renderer { /// characters'. It also returns false for type whose offscreen drawing would be more than /// [`MAX_RASTER_SIDE`] pixels a side or more than [`fx::PIXEL_BUDGET`] pixels in all. fn draw_type_edges(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject, g: &Arc, geom_kept: bool) -> bool { + // A smaller frame can fit the offscreen type that a full frame draws as Sharp. + if f.reject_patch() { + return true; + } if proof::overprints(f.opts) && t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke) { return false; } diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 1b734b4522..7b68bc74d4 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -10,6 +10,30 @@ use crate::blobs::blob_key; use crate::tests_fontchange::fonts_steady; use crate::*; +#[test] +fn geometry_from_measurement_only_frames_releases_old_node_versions() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let oldest = Arc::downgrade(&doc.layers[0].children().unwrap()[0]); + let mut renderer = Renderer::new(); + let opts = RenderOptions::default(); + for _ in 0..12 { + let mut next = doc.clone(); + next.node_mut(id).unwrap().transform(Affine::translate((1.0, 0.0)), false); + assert!(matches!(renderer.changed(&doc, &next, &opts), Changed::Area(_))); + renderer.finish_measurement_only(); + doc = next; + } + assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw"); +} + /// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by /// the tests running alongside). fn png(w: u32, h: u32, seed: u8) -> Vec { diff --git a/crates/render/src/tests/typeedges.rs b/crates/render/src/tests/typeedges.rs index 3295342ce8..80c46edcc5 100644 --- a/crates/render/src/tests/typeedges.rs +++ b/crates/render/src/tests/typeedges.rs @@ -43,6 +43,17 @@ fn partial(a: &[u8]) -> usize { a.iter().filter(|v| **v > 0 && **v < 255).count() } +#[test] +fn a_plain_patch_defers_frame_sensitive_type_edges() { + let mut renderer = Renderer::new(); + renderer.threads = 0; + let opts = RenderOptions::default(); + let sharp = page(TypeAntiAlias::Sharp, None); + let crisp = page(TypeAntiAlias::Crisp, None); + assert!(renderer.render_plain_patch(&sharp, W, H, Affine::IDENTITY, &opts).is_some()); + assert!(renderer.render_plain_patch(&crisp, W, H, Affine::IDENTITY, &opts).is_none()); +} + /// The first pixels of `drawn` (type drawn with `m`) that are not the share `edge_coverage` gives /// the same pixel of `sharp` (the type drawn with Sharp), within a step of rounding: (pixel, /// Sharp, drawn). diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 7474772eae..0087c1a4a8 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -276,6 +276,10 @@ fn a_frame_counts_the_art_it_draws_by_its_size() { let mut r = Renderer::new(); r.render(&mesh(100.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default()); assert_eq!(r.stats.view_sized, 0, "a mesh within the mesh buffer"); + assert!( + r.render_plain_patch(&mesh(100.0), 60, 60, Affine::translate((-50.0, -50.0)), &RenderOptions::default()).is_none(), + "a patch through a mesh must fall back even when the full mesh fits" + ); r.render(&mesh(3000.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default()); assert!(r.stats.view_sized > 0, "a mesh past the mesh buffer"); } diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index d29066a126..6ddf340de4 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -4,7 +4,7 @@ use std::mem; -use craft::ui::dialog::{DialogResult, StackDialog}; +use craft::ui::dialog::{DialogId, DialogResult, StackDialog}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog}; use egui::Context; use serde_json::{Value, json}; @@ -32,13 +32,27 @@ pub(crate) struct Spec { /// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document. #[derive(Default)] pub(crate) struct AddonDialogs { - open: Option<(craft::ui::dialog::DialogId, &'static Spec)>, + open: Option, preview: LivePreview, } +#[derive(Clone, Copy)] +struct Open { + id: DialogId, + spec: &'static Spec, + document: Option, +} + +impl Open { + fn on_document(self, app: &VectorcraftApp) -> bool { + self.document == app.session.active().map(|state| state.uid) + } +} + /// Closes the open add-on dialog without an answer and rolls its preview back. fn close_open(app: &mut VectorcraftApp) { - let Some((id, _)) = app.addon_dialogs.open.take() else { return }; + let Some(open) = app.addon_dialogs.open.take() else { return }; + let id = open.id; if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { host.with(|h| { h.cancel_by_id(&ctx, id); @@ -46,7 +60,10 @@ fn close_open(app: &mut VectorcraftApp) { let _ = h.take_by_id::(id); }); } - mem::take(&mut app.addon_dialogs.preview).cancel(app); + let preview = mem::take(&mut app.addon_dialogs.preview); + if open.on_document(app) { + preview.cancel(app); + } } /// Opens the dialog `spec` describes over `fields`, built each pass by `build`. @@ -62,7 +79,7 @@ pub(crate) fn open( close_open(app); let id = dialog.id(); host.with(|h| h.open(dialog)); - app.addon_dialogs.open = Some((id, spec)); + app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) }); Ok(json!({ "dialog": spec.command })) } @@ -94,10 +111,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { } fn pump_commit(app: &mut VectorcraftApp) { - let Some((id, spec)) = app.addon_dialogs.open else { return }; + let Some(open) = app.addon_dialogs.open else { return }; let Some(host) = app.dialogs() else { return }; + let Open { id, spec, .. } = open; + let on_document = open.on_document(app); + if !on_document { + // Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing. + app.addon_dialogs.preview = LivePreview::default(); + } let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); - if let Some((previewing, params)) = &live { + if on_document && let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); @@ -115,7 +138,9 @@ fn pump_commit(app: &mut VectorcraftApp) { app.addon_dialogs.open = None; let preview = mem::take(&mut app.addon_dialogs.preview); // The dialog is closed already, so a refusal can only go to the status line. - if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { + if !on_document { + app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned()); + } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { app.status(error); } } diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index eb24e09c37..b7f648aa1e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -76,13 +76,29 @@ fn new_app() -> VectorcraftApp { /// Two rectangles without a stroke, both selected. fn two_rects() -> VectorcraftApp { let mut app = new_app(); + select_two_rects(&mut app); + app +} + +fn select_two_rects(app: &mut VectorcraftApp) { app.run("paint.setStroke", json!({"none": true})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap(); app.run("select.all", json!({})).unwrap(); +} + +fn two_drawings() -> VectorcraftApp { + let mut app = two_rects(); + app.run("file.new", json!({"width": 700, "height": 500})).unwrap(); + select_two_rects(&mut app); + activate(&mut app, 0); app } +fn activate(app: &mut VectorcraftApp, index: usize) { + app.run("document.activate", json!({"index": index})).unwrap(); +} + fn two_circles() -> VectorcraftApp { let mut app = new_app(); let ids: Vec = [100.0, 160.0] @@ -280,3 +296,68 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() assert_eq!(app.dialogs().unwrap().with(|h| h.open_dialogs().len()), 1); assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back"); } + +#[test] +fn an_add_on_preview_waits_for_its_opening_drawing() { + let mut app = two_drawings(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed in the opening drawing"); + + activate(&mut app, 1); + let undo = undo_len(&app); + frame(&mut app); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, undo), "the other drawing never shows the preview"); + assert!(!app.session.in_interaction()); + + activate(&mut app, 0); + assert_eq!(x0(&app, 1), 100.0, "the old preview rolled back when leaving the drawing"); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "the retained settings preview again on the original drawing"); + cancel(&app, id); + frame(&mut app); + assert_eq!(x0(&app, 1), 100.0); +} + +#[test] +fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() { + let mut app = two_drawings(); + let source_undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(false)); + assert!(confirm(&app, id)); + activate(&mut app, 1); + let target_undo = undo_len(&app); + frame(&mut app); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, target_undo), "the other drawing is never rearranged or given an undo step"); + assert_eq!(app.session.active_index(), Some(1)); + activate(&mut app, 0); + assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo)); +} + +#[test] +fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() { + let mut app = two_drawings(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0); + + activate(&mut app, 1); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + cancel(&app, id); + let context = ctx(&app); + super::pump(&mut app, &context); + let active = app.session.active().unwrap(); + assert_eq!(active.interaction.as_ref().map(|edit| edit.label.as_str()), Some("Other drawing's edit")); + assert_eq!(active.doc, other); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index aa844e53ca..2d8a078f2b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -121,6 +121,8 @@ impl VectorcraftApp { moved: false, from_worker: false, whole_frames: false, + view_sized_bounds: None, + web_patch_renderer: None, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 1be3cbe933..78bc288399 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -26,10 +26,15 @@ pub struct CanvasCache { /// ([`canvas::show`]). pub from_worker: bool, /// The frame shown drew art in a way that depends on its size, or a part of it drawn again on - /// this thread would not have matched the frame around it: until the next whole frame is shown, - /// edits of the frame shown render whole, on the worker when the frame is heavy - /// ([`canvas::show`]). + /// this thread would not have matched the frame around it. Edits that reach the affected area + /// render whole, on the worker when the frame is heavy ([`canvas::show`]). pub whole_frames: bool, + /// The shown web frame can still be patched outside this enclosure in its own raster pixels. + /// Present only when all frame-size-dependent output has a known bound. + pub view_sized_bounds: Option, + /// Draws for a patch against a web frame with bounded view-sensitive art. + /// The renderer of the whole frame keeps its raster and derived-art caches across these patches. + pub web_patch_renderer: Option>, /// The frame shown holds pixels the worker copied from its last frame, and when it was shown /// (seconds, egui's input time): it renders whole once it has been shown for /// [`canvas::STILL_SECS`] with the view unmoved. diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 709aee2c5c..e432b42759 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -353,7 +353,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } Payload::Style(_) => Ok(()), - Payload::Panel(PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => { + Payload::Panel(drag @ PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" && let Some((id, points)) = selected_mesh_drop(app, at, zoom) @@ -362,14 +362,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), return run(app, "object.mesh.setPointColor", params); } let Some(hit) = hit() else { return Ok(()) }; - let mut params = if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color) - && app.session.active().is_some_and(|st| st.uid != rows.document) - && let Some(color) = paint.color() - { - json!({"color": crate::panels::color_json(&color), "keepModel": true}) - } else { - params.clone() - }; + let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) else { return Ok(()) }; params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 1c1d17c00d..b96cb93038 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -57,9 +57,10 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// is at most 8 ms, and except when that frame drew raster effects from rasters made before their /// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame /// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects, -/// and this thread's doesn't. No frame that drew art in a way that depends on its size, or that a -/// part drawn again here since it was shown would have differed from, is drawn again in part -/// ([`crate::CanvasCache::whole_frames`]). A frame that drew nothing from moved rasters or at a +/// and this thread's doesn't. A web frame with known view-sensitive output bounds can still be +/// patched outside them, accounting for the patch's rounding. Otherwise view-sensitive art or +/// an earlier rejected patch requires a whole render ([`crate::CanvasCache::whole_frames`]). +/// A frame that drew nothing from moved rasters or at a /// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction /// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change. /// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what @@ -101,17 +102,32 @@ pub(super) fn changed_pixels( vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), - Some([x0, y0, x1, y1]) if !app.canvas.whole_frames => { + Some([x0, y0, x1, y1]) => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); + let patch = Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)); + if app.canvas.whole_frames && app.canvas.view_sized_bounds.is_none_or(|bounds| !bounds.intersect(patch).is_zero_area()) { + return None; + } + // A full draw can use 3D art measured here. Do not rebuild it in the scratch renderer. + if app.canvas.view_sized_bounds.is_some() && app.canvas.renderer.measured_bytes() > 0 { + return None; + } let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h)); (share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1])) } - Some(_) => None, }, vectorcraft_render::Changed::Everything => None, } } +fn web_patch_renderer(slot: &mut Option>) -> &mut vectorcraft_render::Renderer { + slot.get_or_insert_with(|| { + let mut renderer = vectorcraft_render::Renderer::new(); + renderer.threads = 0; + Box::new(renderer) + }) +} + /// `a..b` of `0..n`, grown to whole eighths of `n` and moved back into `0..n`: the parts of a /// frame rendered again come in few sizes, which keep the contexts the renderer keeps. fn in_steps(a: u32, b: u32, n: u32) -> (u32, u32) { @@ -608,6 +624,8 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: app.canvas.moved = done.moved > 0; app.canvas.from_worker = true; app.canvas.whole_frames = done.view_sized; + app.canvas.view_sized_bounds = None; + app.canvas.web_patch_renderer = None; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -707,15 +725,27 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let t0 = monotonic_ms(); if region.is_none() { // Nothing in view to draw again: what was made to measure the edit isn't drawn. - app.canvas.renderer.let_go_of_measured(); + app.canvas.renderer.finish_measurement_only(); } let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { - let renderer = &mut app.canvas.renderer; let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; - let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); + let plain_patch = app.canvas.view_sized_bounds.is_some(); + let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer }; + let part = effects.view(|| { + if plain_patch { + renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts) + } else { + Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)) + } + }); + let Some(mut part) = part else { + app.canvas.view_sized_bounds = None; + return false; + }; if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 { app.canvas.whole_frames = true; + app.canvas.view_sized_bounds = None; return false; } let width = part.width; @@ -723,7 +753,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let color = color_image(&part); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); - app.canvas.moved |= app.canvas.renderer.stats.moved > 0; + app.canvas.moved |= renderer.stats.moved > 0; + if plain_patch { + app.canvas.renderer.finish_measurement_only(); + } } app.canvas.key = Some((*key).clone()); app.canvas.shown = Some(((*doc).clone(), opts.clone())); @@ -779,6 +812,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a // part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]). let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); + if !same_doc { + app.canvas.web_patch_renderer = None; + } let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; // A document's first frame (opened, or its tab chosen) renders on the worker too: how long it @@ -802,7 +838,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { (Some(worker), true, false) => { // The worker draws the frame: what this thread's renderer made to measure the edit // isn't drawn here. - app.canvas.renderer.let_go_of_measured(); + app.canvas.renderer.finish_measurement_only(); let queued = worker.submit(crate::render_worker::Job { key: key.clone(), doc: doc.clone(), @@ -835,7 +871,12 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.perf.render_ms = monotonic_ms() - t0; app.canvas.last_ms = app.perf.render_ms; app.canvas.moved = app.canvas.renderer.stats.moved > 0; - app.canvas.whole_frames = app.canvas.renderer.stats.view_sized > 0 || app.canvas.renderer.stats.previewed > 0; + let stats = app.canvas.renderer.stats; + app.canvas.whole_frames = stats.view_sized > 0 || stats.previewed > 0; + app.canvas.view_sized_bounds = if app.canvas.waits_for_still && stats.previewed == 0 { stats.view_sized_bounds() } else { None }; + if app.canvas.view_sized_bounds.is_none() { + app.canvas.web_patch_renderer = None; + } app.canvas.from_worker = false; app.canvas.reused = None; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index c9e44fd207..04e367dce5 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1030,6 +1030,78 @@ fn an_edit_over_art_drawn_for_the_frames_size() { } } +#[test] +fn web_partial_redraws_skip_unchanged_view_sensitive_art() { + keeping_color_settings(|| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; + app.canvas.waits_for_still = true; + app.canvas.renderer.threads = 0; + let glow = app.run("shape.rectangle", json!({"x": 55, "y": 70, "width": 55, "height": 55})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"ids": [glow], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap(); + let large = app.run("shape.rectangle", json!({"x": -980, "y": -700, "width": 965, "height": 1010})).unwrap()["id"].clone(); + app.run("effect.apply", json!({"ids": [large], "effect": "texture.texturizer", "params": {}})).unwrap(); + let far = app.run("shape.rectangle", json!({"x": 300, "y": 200, "width": 12, "height": 12})).unwrap()["id"].clone(); + let near = app.run("shape.rectangle", json!({"x": 60, "y": 80, "width": 12, "height": 12})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + shapes(&mut app, &ctx); + if let Some(vm) = app.view_mut() { + (vm.zoom, vm.center) = (1.2, Point::new(200.0, 150.0)); + } + // Start from a full raster at the chosen view rather than waiting for the reprojected view to settle. + app.canvas.key = None; + let read = |app: &mut VectorcraftApp| { + let (_, mut delta) = frame_output(app, &ctx); + let tex = app.canvas.texture.as_ref().unwrap().id(); + delta.set.remove(&tex).and_then(|mut uploads| uploads.pop()).expect("the edit uploads canvas pixels") + }; + let first = read(&mut app); + assert!(first.pos.is_none()); + assert!(app.canvas.renderer.stats.view_sized > 0, "single-threaded filter layers depend on the frame size"); + let egui::ImageData::Color(first) = first.image; + let mut composed = (*first).clone(); + for color in ["#ff0000", "#00ff00"] { + app.run("paint.setFill", json!({"ids": [far], "color": color})).unwrap(); + let delta = read(&mut app); + let [x, y] = delta.pos.expect("an edit away from the glow uploads only a patch"); + let egui::ImageData::Color(patch) = delta.image; + for row in 0..patch.height() { + let start = (y + row) * composed.width() + x; + composed.pixels[start..start + patch.width()].copy_from_slice(&patch.pixels[row * patch.width()..(row + 1) * patch.width()]); + } + } + let key = app.canvas.key.as_ref().unwrap(); + let view = app.canvas_view().unwrap(); + let (w, h, view) = frame_view(key.pixel, (key.w, key.h), &view, key.ppp); + let (doc, still) = app.canvas.shown.as_ref().unwrap(); + let drag = vectorcraft_render::RenderOptions { interacting: true, dragging: true, ..still.clone() }; + let mut cold = vectorcraft_render::Renderer::new(); + cold.threads = 0; + cold.render(doc, w, h, view, &drag); + assert!(cold.stats.previewed > 0, "a cold renderer draws the large effect at drag resolution"); + app.canvas.renderer.render(doc, w, h, view, &drag); + assert_eq!(app.canvas.renderer.stats.previewed, 0, "distant canvas patches left the full-resolution effect available for the drag"); + + // The old glow's bounds survive successive partial renders, even though neither draws it. + app.run("paint.setFill", json!({"ids": [near], "color": "#0202ee"})).unwrap(); + let overlap = read(&mut app); + assert!(overlap.pos.is_none(), "editing inside the old glow's bounds renders the whole frame"); + app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap(); + let restored = read(&mut app); + assert!(restored.pos.is_none()); + let egui::ImageData::Color(restored) = restored.image; + assert_eq!(restored.size, composed.size); + assert!(restored.pixels == composed.pixels, "partial updates equal a full redraw: {}", differing(&composed.pixels, Some(&restored.pixels))); + app.run("effect.apply", json!({"ids": [far], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap(); + assert!(read(&mut app).pos.is_none(), "the new glow in the part also requires a whole frame"); + }); +} + /// A canvas more device pixels across than the largest texture side the display supports renders /// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel /// Preview's region of document pixels stays within it too. diff --git a/crates/ui-egui/src/dialogs/action_set_options.rs b/crates/ui-egui/src/dialogs/action_set_options.rs index 8bf20b57c9..29fe71991d 100644 --- a/crates/ui-egui/src/dialogs/action_set_options.rs +++ b/crates/ui-egui/src/dialogs/action_set_options.rs @@ -6,8 +6,8 @@ //! Options also holds the action's function key and color (`key`, `cmd`, `shift`, `color`, //! `automaticAlignTo`, see [`ActionOptions`]). OK adds the set and makes it the current one, //! renames the set, or changes the action's name, function key and color (`ui.action.options`). -//! An invalid `set`, `action` or function key is an error, and so is a name the list refuses. OK -//! then changes no set or action, and the dialog stays open. +//! An invalid `set`, `action` or function key is an error, as are a name the list refuses and a +//! library change while editing an existing set or action. The dialog stays open with the error. use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id}; @@ -67,12 +67,14 @@ pub struct SetOptionsDialog { pub set: Option, /// The index of the action in its set; only for Action Options. pub action: Option, + /// The action library revision these addresses described when Options opened. + revision: Option, form: Form, } impl SetOptionsDialog { - fn new(kind: SetOptionsKind, set: Option, action: Option, fields: SetOptionsFields) -> Self { - SetOptionsDialog { id: dialog_id(KEY), kind, set, action, form: Form::new(fields, check) } + fn new(kind: SetOptionsKind, set: Option, action: Option, revision: Option, fields: SetOptionsFields) -> Self { + SetOptionsDialog { id: dialog_id(KEY), kind, set, action, revision, form: Form::new(fields, check) } } } @@ -81,14 +83,15 @@ pub fn open_new(app: &mut VectorcraftApp) { let sets = app.ui.actions.sets(); let n = (1..).find(|n| !sets.contains(&format!("Set {n}").as_str())).unwrap_or(1); let fields = SetOptionsFields { name: format!("Set {n}"), ..SetOptionsFields::default() }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, fields)); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, None, fields)); } /// Open Set Options for the set at `set`, if there is one. pub fn open(app: &mut VectorcraftApp, set: usize) { if let Some(name) = model::set_name(&app.ui.actions, set) { let fields = SetOptionsFields { name: name.to_owned(), ..SetOptionsFields::default() }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, fields)); + let revision = app.ui.actions.revision(); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, Some(revision), fields)); } } @@ -105,22 +108,26 @@ pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) { automatic_align_to: model::automatic_align_to(a), }; let fields = SetOptionsFields { name: a.name.clone(), options }; - open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), fields)); + let revision = app.ui.actions.revision(); + open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), Some(revision), fields)); } impl ActionDialog for SetOptionsDialog { - /// What OK files, with the kind and place the dialog had. - type Answer = (SetOptionsKind, Option, Option, SetOptionsFields); + /// What OK files, with the kind, place and library revision the dialog had. + type Answer = (SetOptionsKind, Option, Option, Option, SetOptionsFields); fn take_ok(&mut self) -> Option { - self.form.take().map(|fields| (self.kind, self.set, self.action, fields)) + self.form.take().map(|fields| (self.kind, self.set, self.action, self.revision, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { self.form.answer(answer); } - fn run(app: &mut VectorcraftApp, (kind, set, action, fields): Self::Answer) -> Result<(), String> { + fn run(app: &mut VectorcraftApp, (kind, set, action, revision, fields): Self::Answer) -> Result<(), String> { + if revision.is_some_and(|revision| app.ui.actions.revision() != revision) { + return Err("The action library changed. Reopen Options to edit it.".into()); + } match kind { SetOptionsKind::NewSet => edits::new_set(app, &fields.name), SetOptionsKind::Set => { diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index cb1c6337e5..1e3013b69a 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -154,6 +154,7 @@ struct Setup { #[derive(Clone, Copy)] struct Target { document: u64, + reverts: u64, /// The current artboard's ID, or no ID while creating a new artboard. artboard: Option, } @@ -556,7 +557,7 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize { fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option) -> Result { let host = app.dialogs().ok_or("no window")?; let st = app.session.active().ok_or("no document")?; - let target = Target { document: st.uid, artboard }; + let target = Target { document: st.uid, reverts: st.reverts, artboard }; let artwork = vectorcraft_render::encode::art_bounds(&st.doc); let [(_, fade), (_, update_while_dragging)] = global_fields(app); (value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point); @@ -652,6 +653,9 @@ fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) - .active() .filter(|st| st.uid == target.document) .ok_or(tl!("Artboard Options can only change the document where it was opened."))?; + if st.reverts != target.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } let globals = global_changes(app, v); if v.new { let r = confirm_new(app, v)?; @@ -1063,4 +1067,39 @@ mod tests { assert!(!is_open(&app)); assert_eq!(*app.session.doc().unwrap().doc, *before); } + + #[test] + fn artboard_options_refuses_a_stale_draft_after_confirmed_revert() { + let file = std::env::temp_dir().join(format!("vectorcraft-artboard-options-revert-{}.vectorcraft", std::process::id())); + let path = file.to_string_lossy(); + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts, artboard) = (original.uid, original.reverts, original.doc.artboards[0].id); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + + open(&mut app).unwrap(); + set(&app, &[("name", json!("Stale Draft"))]).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(&file); + let reverted = app.session.active().unwrap(); + assert_eq!((reverted.uid, reverted.reverts, reverted.doc.artboards[0].id), (uid, reverts + 1, artboard)); + let undo = undo_len(&app); + + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1"); + assert_eq!(undo_len(&app), undo); + assert_eq!(answer, Err("The document was reverted. Reopen this dialog to continue.".into())); + assert!(is_open(&app)); + let host = app.dialogs().unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert_eq!(host.with(|h| h.get::().unwrap().value.name.clone()), "Stale Draft"); + host.with(|h| h.cancel_by_id(&ctx, id())); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Fresh Draft"))]).unwrap(); + ok(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Fresh Draft"); + } } diff --git a/crates/ui-egui/src/dialogs/blend_options.rs b/crates/ui-egui/src/dialogs/blend_options.rs index a03d7bbd37..fc4c90371b 100644 --- a/crates/ui-egui/src/dialogs/blend_options.rs +++ b/crates/ui-egui/src/dialogs/blend_options.rs @@ -130,7 +130,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let state = app .dialogs() .and_then(|d| d.with(|host| host.get_by_id::(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields()))))); - if let Some((previewing, p)) = state { + if let Some((previewing, p)) = state + && (!previewing || app.session.has_selected_blend()) + { + // With no blend selected, the command sets application defaults instead of previewing artwork. // The answer only reports the preview's status, which the preview itself shows. let _ = preview.run(app, previewing, PREVIEW_LABEL, CMD, &p); } @@ -139,8 +142,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// OK: keeps the preview as one undo step on a blend; sets the defaults otherwise. fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let on_blend = result.fields.text("__target") == Some("blend"); + if on_blend != app.session.has_selected_blend() { + let reason = if on_blend { + tl!("Select a blend before applying these options.") + } else { + tl!("Deselect any selected blends before applying the options for new blends.") + }; + return Err(reason.to_owned()); + } let p = params(&result.fields); - if result.fields.text("__target") != Some("blend") { + if !on_blend { return app.run(CMD, p).map(|_| ()); } let preview = app.object_dialogs.blend.take().unwrap_or_default(); @@ -212,6 +224,62 @@ mod tests { } } + fn app_with_smooth_blend() -> (VectorcraftApp, u64) { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + for x in [0, 200] { + app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + let id = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap(); + (app, id) + } + + #[test] + fn opening_blend_defaults_does_not_edit_a_later_selected_blend() { + let (mut app, id) = app_with_smooth_blend(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.blendOptions", json!({})).unwrap(); + assert_eq!(fields(&app).text("__target"), Some("defaults")); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + app.run("select.set", json!({"ids": [id]})).unwrap(); + + let undo = app.session.active().unwrap().history.undo.len(); + confirm(&mut app); + assert_eq!(spec(&app, id).spacing, BlendSpacing::SmoothColor, "a newly selected blend keeps its spacing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&app)); + + app.run("select.none", json!({})).unwrap(); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(app.session.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7)); + } + + #[test] + fn opening_blend_options_for_a_selection_does_not_write_defaults() { + let (mut app, id) = app_with_smooth_blend(); + let defaults = app.session.prefs.blend_options; + app.run("ui.blendOptions", json!({})).unwrap(); + assert_eq!(fields(&app).text("__target"), Some("blend")); + set(&app, "spacing", json!("steps")); + set(&app, "steps", json!(7)); + app.run("select.none", json!({})).unwrap(); + + frame(&mut app); + assert_eq!(app.session.prefs.blend_options, defaults, "the blend preview leaves new-blend defaults intact"); + assert!(!app.session.in_interaction()); + confirm(&mut app); + assert_eq!(app.session.prefs.blend_options, defaults); + assert!(is_open(&app)); + + app.run("select.set", json!({"ids": [id]})).unwrap(); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(spec(&app, id).spacing, BlendSpacing::Steps(7)); + } + #[test] fn opens_on_the_blend_previews_and_keeps_smooth_color() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index 4305eb1d4b..dd84950970 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -21,7 +21,7 @@ super::confirm::wrapped_dialog!(BrushDeleteQuestion, StandardPrompt, KIND); /// What the question is about: the document it was asked in, the `brush.delete` params and whether a /// stroke uses one of the brushes. struct BrushDeleteAsk { - doc: Option, + doc: Option<(u64, u64)>, params: Value, used: bool, } @@ -33,7 +33,7 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { return; }; let (message, yes, no) = words(used); - let doc = app.session.active().map(|d| d.uid); + let doc = app.session.active().map(|d| (d.uid, d.reverts)); let prompt = StandardPrompt::custom(message).button(PromptChoice::Proceed, yes).button(PromptChoice::Cancel, no).tag(BrushDeleteAsk { doc, params, used }); dialogs.with(|host| host.open(BrushDeleteQuestion(prompt))); @@ -89,7 +89,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Yes on brushes that a stroke has started to use since the question opened asks again with Remove /// Strokes and Cancel. When another document has become the active one, nothing is deleted. fn confirm(app: &mut VectorcraftApp, question: BrushDeleteAsk) { - if question.doc != app.session.active().map(|doc| doc.uid) { + if !confirmation_is_current(app, question.doc) { return; } if !question.used { @@ -111,5 +111,19 @@ pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, bool)> { Some((words(used).0.to_string(), used)) } +/// Whether the opening Brush confirmation still owns the active drawing's contents. +pub(super) fn confirmation_is_current(app: &mut VectorcraftApp, opening: Option<(u64, u64)>) -> bool { + let current = app.session.active().map(|st| (st.uid, st.reverts)); + if opening == current { + return true; + } + if let (Some((document, _)), Some((active, _))) = (opening, current) + && document == active + { + app.status(tl!("The document was reverted. Reopen this dialog to continue.")); + } + false +} + #[cfg(test)] pub(super) mod tests; diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index 2478b403bc..b712b589d9 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -10,6 +10,15 @@ pub(in crate::dialogs) fn app() -> VectorcraftApp { crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())) } +/// Writes a native file for the test to revert to. +pub(in crate::dialogs) fn save_for_revert(app: &mut VectorcraftApp, tag: &str) -> std::path::PathBuf { + let file = std::env::temp_dir().join(format!("vectorcraft-brush-{tag}-{}.vectorcraft", std::process::id())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap(); + file +} + /// Answers the open question `D` the way its button does (`Some(choice)`: the button of that choice, /// `None`: Cancel's close), then runs the module's `pump`. pub(in crate::dialogs) fn answer(app: &mut VectorcraftApp, choice: Option<&str>, pump: fn(&mut VectorcraftApp, &egui::Context)) { @@ -84,3 +93,36 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() { assert!(stroke.width > 0.0); } } + +#[test] +fn stale_delete_approval_keeps_the_saved_brush_after_revert() { + let mut app = app(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let slim = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 8})).unwrap()["id"].as_u64().unwrap(); + let tall = app.run("shape.rectangle", json!({"x": 10, "y": 30, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [slim]})).unwrap(); + let file = save_for_revert(&mut app, "delete-revert"); + let brush_height = |app: &mut VectorcraftApp| { + let brush = app.run("brush.get", json!({"name": "Bar"})).expect("the saved brush still exists"); + let art: vectorcraft_doc::Node = serde_json::from_value(brush["art"].clone()).unwrap(); + art.geometric_bounds().unwrap().height() + }; + let saved = brush_height(&mut app); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap(); + assert!((brush_height(&mut app) - saved).abs() > 1e-6); + ask(&mut app, json!({"names": ["Bar"]}), false); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert!((brush_height(&mut app) - saved).abs() < 1e-6); + + let undo = app.session.active().unwrap().history.undo.len(); + answer::(&mut app, Some("proceed"), pump); + assert!((brush_height(&mut app) - saved).abs() < 1e-6); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); +} diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs index 6d4379802c..f000758428 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -22,7 +22,7 @@ super::confirm::wrapped_dialog!(ReplaceArtQuestion, StandardPrompt, KIND); /// What the question is about: the document it was asked in, the brush and the art. struct ReplaceArtAsk { - doc: Option, + doc: Option<(u64, u64)>, name: String, ids: Vec, } @@ -59,7 +59,7 @@ pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { app.status("no window"); return; }; - let doc = app.session.active().map(|d| d.uid); + let doc = app.session.active().map(|d| (d.uid, d.reverts)); let prompt = StandardPrompt::custom(tl!( "Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?" )) @@ -86,7 +86,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Runs `brush.replaceArt`. When another document has become the active one, no brush changes. fn confirm(app: &mut VectorcraftApp, question: ReplaceArtAsk, apply: bool) { - if question.doc != app.session.active().map(|doc| doc.uid) { + if !super::brush_delete::confirmation_is_current(app, question.doc) { return; } let params = json!({"name": question.name, "ids": question.ids, "applyToStrokes": apply}); diff --git a/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs index 054e24a6b6..2b794c8a8c 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs @@ -1,7 +1,7 @@ use serde_json::json; use vectorcraft_doc::NodeId; -use super::super::brush_delete::tests::{answer, app}; +use super::super::brush_delete::tests::{answer, app, save_for_revert}; use super::*; fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 { @@ -95,3 +95,30 @@ fn a_button_changes_no_brush_after_another_document_became_active() { app.run("document.activate", json!({"index": 0})).unwrap(); assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); } + +#[test] +fn stale_replace_approval_keeps_the_saved_brush_art_after_revert() { + let mut app = app(); + let (_, tall) = used_brush(&mut app); + let thick = rect(&mut app, 10.0, 65.0, 40.0, 30.0); + let file = save_for_revert(&mut app, "replace-revert"); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap(); + assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6); + replace(&mut app, "Bar", &[thick]); + assert!(asks(&app)); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert!(st.doc.node(NodeId(thick)).is_some(), "the restored drawing shares the same local source ID"); + assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); + + let undo = app.session.active().unwrap().history.undo.len(); + answer::(&mut app, Some("proceed"), pump); + assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "the stale answer leaves the restored brush intact"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); +} diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index b371adb13b..2b85bb6394 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -25,18 +25,21 @@ //! . use std::borrow::Cow; +use std::sync::{Arc, Weak}; use craft::behavior::{Mixed, Selection, SelectionChange, keyed}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; -use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::pickers::Select; use craft::ui::primitives::{HAlign, IconSpec, TextRun}; -use craft::ui::runtime::env::{Env, LengthUnits}; +use craft::ui::runtime::env::{Env, Label, LengthUnits}; +use craft::ui::runtime::measure; +use craft::ui::runtime::overlay::CloseReason; use craft::ui::runtime::words::CommonWords; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::tabs::{Tab, TabKind, TabStrip}; @@ -44,11 +47,14 @@ use craft::ui::text::NumberField; use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid}; use egui::{Context, Ui}; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Selection as ArtworkSelection; use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; use crate::VectorcraftApp; use crate::panels::paragraph::BulletGlyph; +use super::preview::LivePreview; + /// The dialog kind of Bullets and Numbering. pub const KIND: &str = "bulletsAndNumbering"; @@ -122,9 +128,70 @@ pub(crate) struct BulletsDialog { hanging: bool, /// The General unit the indent fields show; the pump keeps it current. lengths: LengthUnits, + active_document: bool, + held: HeldAnswer>, open: bool, } +/// The preview from the opening drawing and the interaction that owns its undo snapshot. +pub(crate) struct Preview { + document: u64, + live: LivePreview, + selection: Option>, +} + +impl Preview { + fn owns_interaction(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.selection else { return false }; + app.session.active().is_some_and(|state| { + state.uid == self.document + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn update(&mut self, app: &mut VectorcraftApp, fields: Map) { + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return }; + if !self.owns_interaction(app) { + self.live = LivePreview::default(); + self.selection = None; + if state.interaction.is_some() { + return; + } + } + let on = changes(&fields); + let ran = self.live.run(app, on, tl!("Bullets and Numbering"), CMD, &Value::Object(fields)).is_some(); + if !on { + self.selection = None; + } else if ran { + self.selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } + } + + fn apply(&mut self, app: &mut VectorcraftApp, fields: Map) -> Result<(), String> { + if !changes(&fields) { + if self.owns_interaction(app) { + std::mem::take(&mut self.live).cancel(app); + self.selection = None; + } + return Ok(()); + } + if app.session.active().is_none_or(|state| state.uid != self.document) { + return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned()); + } + if app.session.in_interaction() && !self.owns_interaction(app) { + return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned()); + } + self.selection = None; + std::mem::take(&mut self.live).commit(app, CMD, Value::Object(fields)).map(drop) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.owns_interaction(app) { + self.live.cancel(app); + } + } +} + /// The kind of list `list` is, as the `list` field names it. fn kind(list: Option) -> &'static str { match list { @@ -144,8 +211,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?), }; crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document")?.uid; // A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own. - std::mem::take(&mut app.bullets_preview).cancel(app); + if let Some(old) = app.bullets_preview.take() { + old.cancel(app); + } // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { @@ -192,9 +262,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { targets, hanging: false, lengths: crate::canvas::general_lengths(app), + active_document: true, + held: HeldAnswer::default(), open: true, }; host.with(|h| h.open(dialog)); + app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None }); Ok(Value::Null) } @@ -468,8 +541,7 @@ fn changes(p: &Map) -> bool { } impl StackDialog for BulletsDialog { - /// The `text.setFormat` parameters OK runs. - type Result = Value; + type Result = (); fn id(&self) -> DialogId { dialog_id(KIND) @@ -479,20 +551,46 @@ impl StackDialog for BulletsDialog { Some(KIND) } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let common = Env::of(ui).words::(); - let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; + let finish = self.held.is_accepted(); + let refusal = self.held.refusal().map(|(reason, _)| reason.clone()); + let buttons = [ + FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(true).enabled(!self.held.is_waiting()), + FooterButton::new(common.cancel.clone(), DialogRole::Cancel), + ]; let mut open = self.open; - let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)); - let shown = dialog.show(ui, |ui, _| self.body(ui)); + let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone()); + let shown = dialog.show(ui, |ui, cx| { + if finish && !measure::active(ui.ctx()) { + cx.request_close_as(CloseReason::Activated); + } + self.body(ui); + }); self.open = open; let DialogOutput { closed, picked, .. } = shown.output; - closed?; - Some(if picked == Some(OK) { DialogResult::Ok(Value::Object(params(self))) } else { DialogResult::Cancel }) + if picked == Some(OK) && !self.held.is_waiting() { + self.held.file(params(self)); + } + match closed { + Some(CloseReason::Activated) if finish => self.held.finish().map(|_| DialogResult::Ok(())), + Some(_) => Some(DialogResult::Cancel), + None => None, + } } - fn confirm(&mut self, _: &Context) -> Option { - Some(Value::Object(params(self))) + fn confirm(&mut self, _: &Context) -> Option<()> { + if self.held.is_accepted() { + return self.held.finish().map(drop); + } + if !self.held.is_waiting() { + self.held.file(params(self)); + } + None + } + + fn held_state(&self) -> Option { + self.held.state() } fn json_fields(&self) -> Option { @@ -515,38 +613,41 @@ impl StackDialog for BulletsDialog { } } -/// Runs once per frame: keeps the indent fields' unit current, shows the dialog's values on the type while they change -/// something, and answers a finished dialog: OK keeps the preview as one undo step, Cancel (Escape and the close box -/// too) and an OK that changes nothing put the type back. +/// Shows the draft on its opening drawing and answers OK before the dialog closes. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { let Some(host) = app.dialogs() else { return }; - if let Some(result) = host.with(|h| h.take::()) { - let live = std::mem::take(&mut app.bullets_preview); - match result { - DialogResult::Ok(Value::Object(p)) if changes(&p) => { - if let Err(e) = live.commit(app, CMD, Value::Object(p)) { - app.status(e); - // The dialog is gone: a preview the refused OK left running goes with it. Nothing runs - // when the refusal came before the interaction began, which is the right outcome too. - let _ = app.session.cancel_interaction(); - } - } - _ => live.cancel(app), - } - } + let Some(mut preview) = app.bullets_preview.take() else { return }; + let active_document = app.session.active().is_some_and(|state| state.uid == preview.document); let lengths = crate::canvas::general_lengths(app); - // The host's lock is released before the preview runs: a command never runs inside `with`. - let Some(p) = host.with(|h| { + let Some((fields, answer)) = host.with(|h| { h.get_mut::().map(|d| { d.lengths = lengths; - params(d) + let fields = params(d); + if (active_document && !d.active_document) || d.held.refusal().is_some_and(|(_, at)| *at != fields) { + d.held.clear_refusal(); + } + d.active_document = active_document; + (fields, d.held.take()) }) }) else { + preview.cancel(app); return; }; - let mut live = std::mem::take(&mut app.bullets_preview); - let _ = live.run(app, changes(&p), tl!("Bullets and Numbering"), CMD, &Value::Object(p)); - app.bullets_preview = live; + if let Some(answer) = answer { + let result = preview.apply(app, answer).map_err(Label::from); + let accepted = result.is_ok(); + host.with(|h| { + if let Some(dialog) = h.get_mut::() { + dialog.held.answer(result); + } + }); + if accepted { + return; + } + } else { + preview.update(app, fields); + } + app.bullets_preview = Some(preview); } #[cfg(test)] @@ -618,13 +719,23 @@ mod tests { crate::dialogs::host::pump(app, &ctx); } - /// OK on the open dialog, as automation answers it, then the frame's pump. - fn ok(app: &mut VectorcraftApp) { + fn press_ok(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (window(app), top(app)); - assert!(app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)), "OK is enabled"); + let host = app.dialogs().unwrap(); + host.with(|h| { + assert!(!h.confirm_by_id(&ctx, id), "the app must accept the answer first"); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); frame(app); } + /// Files OK and closes with the accepted answer, as the view or automation does. + fn ok(app: &mut VectorcraftApp) { + press_ok(app); + let (ctx, (id, _)) = (window(app), top(app)); + assert!(app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)), "the app accepted OK"); + } + /// Cancel on the open dialog, as Esc gives it, then the frame's pump. fn cancel(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (window(app), top(app)); @@ -641,6 +752,97 @@ mod tests { with_dialog(app, |d| params(d)) } + fn other_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + id + } + + #[test] + fn bullets_preview_pauses_in_another_drawing() { + let (mut app, id) = app(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + let other = other_drawing(&mut app); + let before = first(&app, other); + + frame(&mut app); + + assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by preview"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + ok(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + } + + #[test] + fn bullets_ok_does_not_change_the_other_drawings_type() { + let (mut app, id) = app(); + let opening = first(&app, id); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "number", Some("arabic")); + let other = other_drawing(&mut app); + let before = first(&app, other); + let undo = app.session.doc().unwrap().history.undo.len(); + + press_ok(&mut app); + + assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by OK"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(with_dialog(&app, |d| matches!(d.held.state(), Some(HeldOk::Refused(_))))); + assert_eq!(fields(&app)["number"], "arabic"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(first(&app, id), opening); + frame(&mut app); + assert!(with_dialog(&app, |d| d.held.state().is_none())); + ok(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic))); + } + + #[test] + fn bullets_cancel_keeps_the_other_drawings_pending_edit() { + let (mut app, id) = app(); + let opening = first(&app, id); + let other = other_drawing(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + frame(&mut app); + assert!(app.session.in_interaction()); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other paragraph edit").unwrap(); + app.session.preview("text.setFormat", &json!({"ids": [other], "leftIndent": 41})).unwrap(); + let editing = first(&app, other); + assert_eq!(editing.1, 41.0); + cancel(&mut app); + + assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(first(&app, other), editing); + app.session.commit_interaction().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(first(&app, id), opening); + } + + #[test] + fn accepted_bullets_close_on_the_next_view_pass() { + let (mut app, id) = app(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + press_ok(&mut app); + let ctx = window(&app); + + crate::tests_synthetic::key_frame(&mut app, &ctx, vec![]); + + assert!(!is_open(&app)); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + } + /// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the /// indents show on the type at once, and OK keeps them as one `text.setFormat`, which one Undo /// takes back. diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index e0ad66addf..f9649382bf 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -3,7 +3,7 @@ //! as one undo step through `paint.setFill` / `paint.setStroke` and makes the colour the Color //! Guide's base colour; Cancel puts the art back. Opened for an artboard (Properties › Artboards › //! Fill), it shows the colour on the artboard's paper and OK keeps it through -//! `artboard.setProps {index, color}`. +//! `artboard.setProps {index, color}`. Preview and OK require the opening document to be active. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog //! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor @@ -43,11 +43,18 @@ pub(crate) enum Target { /// The stroke proxy. Stroke, /// The background colour of this artboard. - Artboard(usize), + Artboard { document: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, } +impl Target { + fn in_active_document(&self, app: &VectorcraftApp) -> bool { + let Self::Artboard { document, .. } = self else { return true }; + app.session.active().is_some_and(|st| st.uid == *document) + } +} + /// One open Color Picker: what the dialog itself does not know. pub(crate) struct Open { /// The dialog's id on the window's host. @@ -150,14 +157,17 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => { let index = v.as_u64().and_then(|i| usize::try_from(i).ok()); - let found = index.and_then(|i| Some((i, app.session.active()?.doc.artboards.get(i)?.color))); - let (i, color) = found.ok_or("no such artboard")?; - Some((i, color.unwrap_or(Color::WHITE))) + let found = index.and_then(|i| { + let st = app.session.active()?; + let color = st.doc.artboards.get(i)?.color.unwrap_or(Color::WHITE); + Some((st.uid, i, color)) + }); + Some(found.ok_or("no such artboard")?) } }; let color = match (p.get("color"), artboard) { (Some(v), _) => color_value(v).ok_or_else(|| format!("bad color {v}"))?, - (None, Some((_, c))) => c, + (None, Some((_, _, c))) => c, (None, None) => proxy_color(app, stroke), }; let dialogs = app.dialogs().ok_or("no window")?; @@ -184,9 +194,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { dialog = dialog.kept(model_values(&color)); } - // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. - if let Some((i, _)) = artboard { - dialog = dialog.instance(i); + // The host replaces a picker only for the same document and artboard. + if let Some((document, index, _)) = artboard { + dialog = dialog.instance((document, index)); } let id = dialogs.with(|h| h.open(dialog)); // A picker the open replaced leaves its preview behind: end it. @@ -196,7 +206,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let _ = app.session.cancel_interaction(); } let target = match artboard { - Some((i, _)) => Target::Artboard(i), + Some((document, index, _)) => Target::Artboard { document, index }, None if stroke => Target::Stroke, None => Target::Fill, }; @@ -274,6 +284,13 @@ fn finish( open: &mut Open, result: Option>, ) { + // Switching documents rolls back the source preview. Do not settle it against the new drawing. + if !open.target.in_active_document(app) { + if matches!(result, Some(DialogResult::Ok(_))) { + app.status("The active document changed while the Color Picker was open"); + } + return; + } let preview = std::mem::take(&mut open.preview); match (result, &open.target) { (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => { @@ -293,7 +310,7 @@ fn finish( /// The command that applies colour `c` to the picker's target, and its params. fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { - Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), + Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })), Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), } @@ -314,18 +331,18 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); let untouched = !app.session.in_interaction() && picked.color == open.start; - let artboard = matches!(open.target, Target::Artboard(_)); + let artboard = matches!(open.target, Target::Artboard { .. }); let selected = artboard || app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); if untouched || !selected { return; } let label = match open.target { - Target::Artboard(_) => "Artboard Options", + Target::Artboard { .. } => "Artboard Options", Target::Stroke => "Stroke Color", _ => "Fill Color", }; @@ -342,7 +359,7 @@ fn commit(app: &mut VectorcraftApp, open: &Open, preview: LivePreview, picked: & let (cmd, params) = paint_command(&open.target, c); preview.commit(app, cmd, params)?; // A color picked for the fill or stroke also becomes the Color Guide's base color. - if !matches!(open.target, Target::Artboard(_)) { + if !matches!(open.target, Target::Artboard { .. }) { crate::panels::color_guide::choose_base(app, c); } Ok(()) diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 47b1ad268f..26e3bf486b 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -52,6 +52,15 @@ fn artboard_color(app: &VectorcraftApp) -> Option { app.session.doc().unwrap().doc.artboards[1].color } +fn two_documents_with_artboards() -> (VectorcraftApp, egui::Context) { + let (mut app, ctx) = app(); + app.run("artboard.new", json!({})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("artboard.new", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, ctx) +} + /// The selected art takes each colour as it is picked; OK keeps the last as one undo step and /// Cancel puts the art back. #[test] @@ -101,6 +110,71 @@ fn an_artboard_shows_its_background_color_live() { assert!(app.run("ui.colorPicker", json!({"artboard": 9})).is_err()); } +#[test] +fn the_artboard_picker_previews_only_in_its_opening_document() { + let (mut app, ctx) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let before = undo_len(&app); + set_hex(&mut app, &ctx, "#00ff00"); + assert_eq!(artboard_color(&app), None, "the other document never previews the color"); + assert!(!app.session.in_interaction()); + assert_eq!(undo_len(&app), before); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(artboard_color(&app), None, "leaving the source rolled its preview back"); + let before = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#00ff00")); + assert_eq!(undo_len(&app), before + 1); +} + +#[test] +fn confirming_an_artboard_picker_in_another_document_leaves_both_unchanged() { + let (mut app, ctx) = two_documents_with_artboards(); + let source_undo = undo_len(&app); + app.run("ui.colorPicker", json!({"artboard": 1, "color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx); + app.run("document.activate", json!({"index": 1})).unwrap(); + let destination_undo = undo_len(&app); + ok(&mut app, &ctx); + assert_eq!(app.ui.status, "The active document changed while the Color Picker was open"); + assert_eq!(artboard_color(&app), None); + assert_eq!(undo_len(&app), destination_undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(artboard_color(&app), None); + assert_eq!(undo_len(&app), source_undo); +} + +#[test] +fn canceling_an_artboard_picker_preserves_the_other_documents_interaction() { + let (mut app, ctx) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#ff0000"); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("Other edit").unwrap(); + app.session.preview("artboard.setProps", &json!({"index": 1, "color": "#445566"})).unwrap(); + + cancel(&mut app, &ctx); + assert!(app.session.in_interaction(), "the current document keeps its own interaction"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#445566")); +} + +#[test] +fn artboard_pickers_for_the_same_index_in_different_documents_have_separate_instances() { + let (mut app, _) = two_documents_with_artboards(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + let first = id(&app); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + assert_ne!(id(&app), first); + assert_eq!(app.color_dialogs.pickers.len(), 2); +} + /// OK on an untouched picker for an artboard without a color leaves it without one and adds no /// undo step; a white the opener passes as `color` is set. #[test] diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 0142a0070f..d1f01049d3 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -26,6 +26,7 @@ use std::cell::RefCell; use std::ops::RangeInclusive; +use std::path::Path; use std::sync::Arc; use craft::behavior::{ColumnKey, ColumnWidth, Selection, SelectionChange, keyed}; @@ -135,6 +136,8 @@ enum PartEdit { /// The Composite Fonts dialog on the dialog host. OK files the fonts for [`pump`], which runs /// [`COMMAND`] and answers whether the dialog may close. pub struct CompositeFontsDialog { + /// The document whose fonts the draft edits. + document: u64, fonts: Vec, /// The index of the font picked. selected: usize, @@ -167,9 +170,9 @@ pub struct CompositeFontsDialog { /// Open Composite Fonts on the active document's composite fonts, the first one picked, with the /// custom character sets and the sample hidden and nothing typed. pub fn open(app: &mut VectorcraftApp) -> Result { - let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec(); + let document = app.session.active().ok_or("no document open")?; let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; - let dialog = CompositeFontsDialog::new(fonts, crate::font_menu::hold(app)); + let dialog = CompositeFontsDialog::new(document.uid, document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app)); dialogs.with(|host| host.open(dialog)); Ok(Value::Null) } @@ -241,10 +244,11 @@ fn part_mut(f: &mut CompositeFont, at: usize) -> Option<&mut CompositePart> { impl CompositeFontsDialog { /// The dialog over `fonts`, the first picked. - fn new(fonts: Vec, hold: PickerHold) -> Self { + fn new(document: u64, fonts: Vec, hold: PickerHold) -> Self { let mut sample = Map::new(); sample::defaults(&mut sample); CompositeFontsDialog { + document, fonts, selected: 0, set: 0, @@ -852,15 +856,18 @@ impl StackDialog for CompositeFontsDialog { /// file dialog a Load…, Replace… or Save… asked for. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { let Some((held, request)) = with_dialog(app, |d| { - let held = d.held.take(); + let held = d.held.take().map(|fonts| (d.document, fonts)); let request = d.file.take().map(|request| (request, Arc::clone(&d.file_owner))); (held, request) }) else { return; }; - if let Some(fonts) = held { - // A name two fonts share or a value out of range keeps the dialog open with the reason. - let answer = app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from); + if let Some((document, fonts)) = held { + let answer = if app.session.active().is_some_and(|active| active.uid == document) { + app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from) + } else { + Err(Label::from(tl!("Composite Fonts can only change the document where it was opened.").to_owned())) + }; with_dialog(app, |d| d.held.answer(answer)); } if let Some((request, owner)) = request { @@ -892,14 +899,19 @@ fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()> /// Reads the fonts of the file picked and gives them to the dialog (Load… or Replace…). fn load_file(app: &mut VectorcraftApp, request: &PresetFileRequest, replace: bool, picked: &Picked) -> Result { - // PLAN: assumed fl.A23 `file_asks::open_params(&Picked) -> Option>`; `None` is a cancelled pick. let Some(mut params) = open_params(picked) else { return Ok(Value::Null) }; + let browser_name = params.remove("name"); + let name = picked + .first_path() + .as_deref() + .or_else(|| browser_name.as_ref().and_then(Value::as_str).map(Path::new)) + .and_then(Path::file_name) + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); params.insert("apply".into(), json!(false)); let read = app.run(IMPORT, Value::Object(params))?; let fonts: Vec = serde_json::from_value(read["fonts"].clone()).map_err(|e| e.to_string())?; with_dialog(app, |d| d.load(fonts, replace)); - let name = picked.first_path().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default(); - // Only the file's name goes into the status line. if let Some(event) = request.loaded(name, Vec::new()) { report(app, event); } diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 04af573087..2db07b9344 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -97,6 +97,36 @@ fn delayed_load_and_replace_leave_the_reopened_composite_fonts_draft_alone() { } } +#[test] +fn load_and_replace_accept_a_browser_picked_file() { + let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["Draft", "From Web"]), (PresetCommands::Replace, &["From Web"])]; + for (command, expected) in choices { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = ctx(&app); + open(&mut app).unwrap(); + let bytes = dialog(&mut app, |d| { + d.new_font("From Web".into()); + file_bytes(&d.fonts).unwrap() + }); + cancel(&mut app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Draft".into())); + let dialogs = app.dialogs().unwrap(); + ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear(); + let step = steps(&app); + + request(&mut app, command, None); + picker.answer_contents(&[("picked.vccomposite", &bytes)]); + poll(&mut app, &ctx); + let draft_names = dialog(&mut app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::>()); + assert_eq!(draft_names, expected, "{}", app.ui.status); + assert!(app.ui.status.contains("picked.vccomposite"), "{}", app.ui.status); + assert!(names(&app).is_empty(), "picking a file edits only the draft"); + assert_eq!(steps(&app), step); + } +} + fn steps(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } @@ -169,6 +199,41 @@ fn composite_fonts_change_on_ok_as_one_undo_step() { assert!(names(&app).is_empty()); } +#[test] +fn a_held_composite_fonts_ok_keeps_the_draft_with_its_opening_document() { + let mut app = app(); + app.run("file.new", json!({"width": 440, "height": 440})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Destination only".into())); + ok(&mut app).unwrap(); + let destination = (names(&app), steps(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let source = (names(&app), steps(&app)); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("From the source".into())); + let ctx = ctx(&app); + let id = dialog_id(KIND); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + pump(&mut app, &ctx); + assert_eq!((names(&app), steps(&app)), destination, "the other document keeps its fonts and undo history"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + assert!(is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!((names(&app), steps(&app)), source); + ok(&mut app).unwrap(); + assert_eq!(names(&app), ["From the source"]); + assert_eq!(steps(&app), source.1 + 1); + assert!(!is_open(&app)); +} + /// New is based on the font picked and takes the next free name; a name two fonts share, or one /// left empty, keeps the dialog open and changes nothing. #[test] diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index b53bab2351..60ff63e67f 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -143,13 +143,15 @@ struct Edited { pick: Option, } -/// The Properties section's colour picker: the dialog it opened, the colour it answers for and the dimension it edits. +/// The Properties section's colour picker and the swatch, document and dimension it edits. #[derive(Clone, Debug)] pub(crate) struct Pick { /// The open colour picker. pub id: DialogId, /// The key of the swatch that asked. pub key: String, + /// The document that contains the dimension. + pub document: u64, /// The dimension the colour goes to. pub target: NodeId, } @@ -340,8 +342,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { let Some(pick) = app.object_dialogs.dimension.clone() else { return }; let Some(finished) = dialogs.with(|host| host.take_by_id::(pick.id)) else { return }; app.object_dialogs.dimension = None; - if let Some(ColorPickerResult { picked, .. }) = finished.ok() - && let Some(mut o) = options_of(app, pick.target) + let Some(ColorPickerResult { picked, .. }) = finished.ok() else { return }; + if app.session.active().map(|st| st.uid) != Some(pick.document) { + app.status("The active document changed while the Color Picker was open"); + return; + } + if let Some(mut o) = options_of(app, pick.target) && set_color(&mut o, &pick.key, picked.color) { update(app, pick.target.0, &o); @@ -715,12 +721,13 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { }); } if let Some(request) = edited.pick + && let Some(document) = app.session.active().map(|st| st.uid) && let Some(dialogs) = app.dialogs() { let key = request.key.clone(); let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app)); let picker = dialogs.with(|host| host.open(picker)); - app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) }); + app.object_dialogs.dimension = Some(Pick { id: picker, key, document, target: NodeId(id) }); } Row::new().show(ui, |ui, _| { if Button::new(tl!("Apply to All")).show(ui).clicked() @@ -775,6 +782,46 @@ mod tests { serde_json::from_value(app.borrow().session.tool_options_of("dimension")["style"].clone()).unwrap() } + #[test] + fn dimension_properties_picker_keeps_its_source_document() { + use crate::tests::panel_harness::Panel; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut add_dimension = |line_color: [u8; 3]| { + app.run("file.new", json!({"width":200,"height":200})).unwrap(); + let created = app.run("dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"lineColor":line_color}})).unwrap(); + let id = created["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids":[id]})).unwrap(); + NodeId(id) + }; + let source = add_dimension([17, 34, 51]); + let other = add_dimension([51, 34, 17]); + assert_eq!(source, other, "each drawing allocates its own object ids"); + app.run("document.activate", json!({"index":0})).unwrap(); + + let mut panel = Panel::new(app, properties_section); + let ctx = panel.ctx().clone(); + let host = WindowDialogs::of(&ctx, &WindowKey::main()); + panel.click("Line Color"); + let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap(); + panel.app().run("document.activate", json!({"index":1})).unwrap(); + assert!(host.with(|h| h.confirm_by_id(&ctx, picker))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), other).unwrap().line_color, [51, 34, 17]); + + panel.app().run("document.activate", json!({"index":0})).unwrap(); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]); + panel.click("Line Color"); + let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap(); + assert!(host.with(|h| h.confirm_by_id(&ctx, picker))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [18, 52, 86]); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]); + } + /// The Arrow Style rule of `ui.dialog.set` and the saved style: a head clears with `arrowStyle`, a built-in head /// sets its entry's two values, a name that is no built-in head is refused, and a draft that does not validate /// cannot be saved. diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index c3aa0ef099..0c6e1b5f56 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into())); fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into())); fields["convertColors"] = json!(true); - let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone()); + let (source, mode, setup) = ((st.uid, st.reverts), st.doc.color_mode, st.doc.setup.clone()); let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) }; let presets: Vec = app.session.flattener_presets().into_iter().map(|p| p.name).collect(); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); @@ -186,8 +186,12 @@ fn color_commands(app: &VectorcraftApp, fields: &Map) -> Result Result { - if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) { + let source = app.document_setup_source.and_then(|(uid, reverts)| app.session.active().filter(|st| st.uid == uid).map(|st| (st, reverts))); + let Some((doc, reverts)) = source else { return Err(tl!("Document Setup can only change the document where it was opened.").to_owned()); + }; + if doc.reverts != reverts { + return Err(tl!("Reopen Document Setup after reverting the drawing.").to_owned()); } let map = json_map(fields); let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect()); @@ -700,6 +704,46 @@ mod tests { check_source_document(true); } + #[test] + fn a_revert_refuses_a_stale_document_setup_for_both_confirmation_paths() { + for edit_artboards in [false, true] { + let (mut app, ctx) = new_app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("document-setup-revert"); + let path = dir.join("setup.vectorcraft"); + app.run("document.setup", json!({"bleed": [2, 2, 2, 2]})).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("document.setup", json!({"bleed": [7, 7, 7, 7]})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + let source = app.session.doc().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + let undo = reverted.history.undo.len(); + if edit_artboards { + set(&app, &ctx, "editArtboards", json!(true)); + super::pump(&mut app, &ctx); + } else { + assert!(!press_ok(&mut app, &ctx)); + } + assert!(is_open(&app)); + assert_eq!(app.session.tool_id(), "selection"); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.doc.setup.bleed, [2.0; 4]); + assert_eq!(reverted.history.undo.len(), undo); + + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([5, 5, 5, 5])); + assert!(press_ok(&mut app, &ctx)); + assert_eq!(app.session.doc().unwrap().doc.setup.bleed, [5.0; 4]); + } + } + #[test] fn edit_artboards_applies_settings_and_closes_the_dialog() { let (mut app, ctx) = setup_open(); diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 0f61119fc8..9f810b6117 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -11,7 +11,7 @@ //! applies and makes objects). What only the art of symbol instances holds needs Object on. use craft::ui::contract::SaveKey; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::memory::Lifetime; use serde_json::{Value, json}; use vectorcraft_engine::cmd::expand::{DEFAULT_STEPS, MAX_STEPS}; @@ -22,6 +22,7 @@ use crate::VectorcraftApp; pub const KIND: &str = "expand"; const CMD: &str = "object.expand"; +const OPENING_DRAWING: &str = "__openingDrawing"; /// Where the choices OK expanded with are kept for the rest of the app's run. const REMEMBER: SaveKey = SaveKey::new("vectorcraft.dialog.expand"); @@ -145,8 +146,11 @@ fn rows() -> Vec { /// every option on before that. fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result { let ctx = app.ui_ctx.as_ref().ok_or("no window")?; + let active = app.session.active().ok_or("no document open")?; + let mut fields = DialogFields::new(); + fields.set(OPENING_DRAWING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts}))); let rows = rows(); - Ok(HostedParamDialog::new(ctx, KIND, DialogFields::new(), move |fields| { + Ok(HostedParamDialog::new(ctx, KIND, fields, move |fields| { refresh(info, fields); ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run) })) @@ -154,10 +158,17 @@ fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result Result { - let document = app.session.active().ok_or("no document open")?.uid; - crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| { - if app.session.active().is_none_or(|st| st.uid != document) { + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { + let Some(FieldValue::Json(opening)) = result.fields.get(OPENING_DRAWING) else { return Err(tl!("Return to the original drawing to expand the artwork").into()); + }; + let active = app + .session + .active() + .filter(|st| Some(st.uid) == opening["uid"].as_u64()) + .ok_or_else(|| tl!("Return to the original drawing to expand the artwork").to_owned())?; + if Some(active.reverts) != opening["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); } ok(app, result) }) @@ -533,4 +544,33 @@ mod tests { app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); assert!(is_open(&app)); } + + #[test] + fn expand_approval_does_not_expand_artwork_restored_by_revert() { + let mut app = app(); + gradient_rectangle(&mut app); + let rectangle = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("expand-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap(); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [rectangle.0]})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(_)))); + assert_eq!(app.session.active().unwrap().doc, restored); + + close(&app); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + ok_and_close(&mut app); + let st = app.session.active().unwrap(); + let art = st.doc.node(st.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &art.kind else { panic!("expected a clip group") }; + assert!(matches!(children[1].kind, NodeKind::Mesh(_))); + } } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 6e8f8bc1d2..7894461e9a 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -19,7 +19,7 @@ use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; -use super::export_host::{self, After, Export, Open}; +use super::export_host::{self, After, Export}; use super::{dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export}; use crate::{VectorcraftApp, io}; @@ -111,7 +111,9 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let n = app.session.active().map_or(0, |s| s.doc.artboards.len()); + let source = app.session.active(); + let document = source.map(|source| source.uid); + let n = source.map_or(0, |source| source.doc.artboards.len()); let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); let format = match missing { Some((id, _)) => id, @@ -133,12 +135,21 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res }) .ok_label(Label::from("Export…")) }); - export_host::open(app, Export::As, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) + export_host::open(app, Export::As { document }, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) +} + +fn require_source(app: &VectorcraftApp, document: Option) -> Result<(), String> { + let document = document.ok_or_else(|| tl!("Open Export As from the drawing you want to export").to_owned())?; + if app.session.active().is_none_or(|source| source.uid != document) { + return Err(tl!("Return to the original drawing to export it").into()); + } + Ok(()) } /// Check the artboard range and that there is something to export; the save panel and the format's options or /// the file follow once the dialog has closed. -pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFields) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, document: Option, fields: &DialogFields) -> Result { + require_source(app, document)?; if let Some((_, hint)) = unavailable(fields) { return Err(hint.into()); } @@ -162,7 +173,10 @@ pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFie } let range = if all { "all".to_string() } else { range }; let pages = Pages { use_artboards, all, range, selection: false }; - Ok(Some(Box::new(move |app| io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages))))) + Ok(Some(Box::new(move |app| { + require_source(app, document)?; + io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages)) + }))) } /// `params` of an options dialog for [`io::export`]: with [`io::EXPORT_SELECTION`] when diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 0211830949..3011330cf5 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -45,6 +45,7 @@ use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize, ToggleCell, ToggleS use craft::ui::patterns::form_dialogs::{FormDialog, PathRow}; use craft::ui::primitives::{ContentPainterCx, fit_rect}; use craft::ui::runtime::env::Label; +use craft::ui::runtime::focus::Initial; use craft::ui::tabs::{Tab, TabKind, TabStrip}; use craft::ui::text::TextField; use craft::ui::tile_grid::{Tile, TileGrid, TilePartEvent}; @@ -958,6 +959,10 @@ impl StackDialog for ExportForScreensDialog { let mut held = std::mem::take(&mut self.held); let mut dialog = FormDialog::new(tl!("Export for Screens"), Bind::bound(&mut fields)).ok_label(ok).ok_enabled(chosen.is_none()).held(&mut held); + if self.web { + // Keep the first artboard visible when the web dialog opens in a short viewport. + dialog = dialog.shaped(|surface| surface.initial_focus(Initial::First)); + } if let Some(reason) = chosen { dialog = dialog.ok_reason(reason); } diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index efdc6c9f6d..fb68f64c51 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -21,7 +21,10 @@ pub(crate) type After = Option Result, + }, /// The options of the raster format `format`. Raster { /// The format's id. @@ -126,7 +129,7 @@ fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { match &open.kind { - Export::As => export_as::confirm(app, open, fields), + Export::As { document } => export_as::confirm(app, *document, fields), Export::Raster { .. } => png_options::confirm(app, open, fields), Export::Svg { .. } => svg_options::confirm(app, open, fields), Export::Eps => eps_options::confirm(app, open, fields), diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 560c64605a..61bba50596 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -293,6 +293,22 @@ fn shown_match(app: &VectorcraftApp, at: &Value, found: &Value) -> Option (bool, Option) { + let Some(last) = app.ui.last_find.as_ref() else { return (false, None) }; + let Some(found) = last.get("found") else { return (false, None) }; + let at = place(app, last, query); + let matched = at.is_some(); + if found["visible"].as_bool().unwrap_or(true) == matched { + return (matched, None); + } + let message = at.and_then(|at| shown_match(app, at, found)).unwrap_or_default(); + if let Some(found) = app.ui.last_find.as_mut().and_then(|last| last.get_mut("found")) { + found["visible"] = json!(matched); + } + (matched, Some(message)) +} + /// Runs the request the dialog made this frame, then tells the dialog its message and whether a /// match is current. The match is evaluated in every pump, so a changed Find text or switch /// disables Replace and Replace & Find at once; a pass that has no request only refreshes it. @@ -309,10 +325,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }; Some(ran.unwrap_or_else(|e| said(&e))) }); - let matched = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some()); + let (matched, match_message) = refresh_match(app, &form.query); dialogs.with(|host| { if let Some(d) = host.get_mut::() { - if let Some(message) = message { + if let Some(message) = message.or(match_message) { d.set_message(message); } d.set_matched(matched); diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 2f633e0d25..d773e5a99b 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -296,6 +296,37 @@ fn a_changed_search_starts_again() { assert_eq!(matched(&p), Some((bottom, 4, 7)), "the same search goes on"); } +#[test] +fn the_match_line_follows_the_active_drawing_and_find_query() { + let (app, _) = app_with(&["source cat match"]); + let mut p = Panel::new(app, draw); + p.app().run("file.new", json!({"width": 800, "height": 600})).unwrap(); + p.app().run("text.create", json!({"x": 50, "y": 50, "text": "destination dog match"})).unwrap(); + p.app().run("document.activate", json!({"index": 0})).unwrap(); + choose(&p); + set(&p, "find", json!("cat")); + p.click("Find Next"); + assert!(message(&p).contains("source cat match")); + + p.app().run("document.activate", json!({"index": 1})).unwrap(); + pump(&p); + assert_eq!(matched(&p), None); + assert_eq!(message(&p), "", "the line must not describe a match from another drawing"); + + p.app().run("document.activate", json!({"index": 0})).unwrap(); + pump(&p); + assert!(matched(&p).is_some()); + assert!(message(&p).contains("source cat match")); + + set(&p, "find", json!("dog")); + pump(&p); + assert_eq!(matched(&p), None); + assert_eq!(message(&p), "", "the line must not describe a match for the previous query"); + p.click("Find Next"); + pump(&p); + assert_eq!(message(&p), "No matches found", "refreshing the dialog leaves the search result visible"); +} + /// The place a search reached belongs to its document: in another document, Edit › Find Next and /// the dialog start at that document's first match, even where an object there has the same id. /// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ffcc511501..9cf40d3319 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -25,14 +25,16 @@ use craft::host::{PickRequest, Picked}; use craft::table::ui::{ CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions, }; +use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, PaintUi, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, PaintUi, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{ DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field, }; use craft::ui::display::Text; use craft::ui::layout_components::Row; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::FormDialog; use craft::ui::primitives::TextRun; use craft::ui::runtime::env::{Env, Label, Units}; @@ -48,6 +50,7 @@ use crate::file_asks::{self, Owner}; /// The dialog kind of Graph Data, the key of its dialog on the host. pub const KIND: &str = "graphData"; +const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet."; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its /// series; the least rows it shows. @@ -68,12 +71,13 @@ const ROW_H: f32 = 19.0; pub fn open(app: &mut VectorcraftApp) -> Result { // The query fails without a graph selected, with the engine's own message. let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?; + let document = app.session.active().ok_or("no document open")?.uid; let graph = app.session.active().and_then(|st| st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)).map(|id| (st, id))); let scatter = graph.is_some_and(|(st, id)| { st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter) }); let id = graph.map(|(_, id)| id.0); - let dialog = GraphDataDialog::new(grid_from_data(&v), id, scatter, can_import(app)); + let dialog = GraphDataDialog::new(grid_from_data(&v), document, id, scatter, can_import(app)); let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; dialogs.with(|host| host.open(dialog)); Ok(Value::Null) @@ -391,9 +395,10 @@ fn graph_grid(app: &mut VectorcraftApp, graph: Option) -> Result bool { - file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some() + file_asks::can(app, craft::host::PickKind::Open) + && (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some()) } /// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. @@ -431,6 +436,7 @@ fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result, import_owner: Arc<()>, apply: Option, @@ -442,18 +448,28 @@ struct Asks { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let can = can_import(app); + let active = app.session.active().map(|doc| doc.uid); let asked = dialogs.with(|host| { host.get_mut::().map(|d| { d.can_import = can; + if active == Some(d.document) { + d.held.clear_refusal(); + } d.take_asks() }) }); - let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return }; + let Some(Asks { document, graph, import_owner, apply: filed, actions }) = asked else { return }; + let same_document = active == Some(document); if let Some(sheet) = filed { - if let Err(e) = apply(app, &sheet, graph) { - app.status(e); - } - dialogs.with(|host| host.get_mut::().map(GraphDataDialog::applied)); + let answer = if same_document { + if let Err(e) = apply(app, &sheet, graph) { + app.status(e); + } + Ok(()) + } else { + Err(Label::from(tl!(WRONG_DOCUMENT))) + }; + dialogs.with(|host| host.get_mut::().map(|dialog| dialog.applied(answer))); } for action in actions { match action { @@ -473,6 +489,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { move |app, picked| import(app, &owner, picked), ); } + Action::Revert if !same_document => app.status(tl!(WRONG_DOCUMENT).to_owned()), Action::Revert => match graph_grid(app, graph) { Ok(grid) => { dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); @@ -657,6 +674,7 @@ pub(crate) struct GraphDataDialog { sheet: Sheet, state: GridState, entry: Entry, + document: u64, /// The graph the sheet opened on. graph: Option, scatter: bool, @@ -669,7 +687,7 @@ pub(crate) struct GraphDataDialog { impl GraphDataDialog { /// The window over `grid`, the data of `graph`; Switch x/y is on for a `scatter` graph. - fn new(grid: Grid, graph: Option, scatter: bool, can_import: bool) -> Self { + fn new(grid: Grid, document: u64, graph: Option, scatter: bool, can_import: bool) -> Self { let sheet = Sheet { grid, ..Sheet::default() }; let state = GridState::new(CellSelection::cell(CellAt::new(0, 1)), 1.0); let mut entry = Entry { text: String::new(), at: (0, 1) }; @@ -680,6 +698,7 @@ impl GraphDataDialog { sheet, state, entry, + document, graph, scatter, can_import, @@ -691,12 +710,18 @@ impl GraphDataDialog { /// Everything the window asked since the last call, once. fn take_asks(&mut self) -> Asks { - Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) } + Asks { + document: self.document, + graph: self.graph, + import_owner: self.import_owner.clone(), + apply: self.held.take(), + actions: std::mem::take(&mut self.actions), + } } /// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again. - fn applied(&mut self) { - self.held.answer(Ok(())); + fn applied(&mut self, answer: Result<(), Label>) { + self.held.answer(answer); self.held.finish(); } @@ -727,6 +752,7 @@ impl StackDialog for GraphDataDialog { fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { let GraphDataDialog { sheet, state, entry, scatter, can_import, lines, actions, held, .. } = self; let mut pane = Pane { state, entry, lines, actions, scatter: *scatter, can_import: *can_import }; + let refusal = held.refusal().map(|(reason, _)| reason.clone()); let shown = FormDialog::new(tl!("Graph Data"), Bind::bound(&mut *sheet)) .ok_label(tl!("Apply")) .ok_enabled(!held.is_waiting()) @@ -734,7 +760,12 @@ impl StackDialog for GraphDataDialog { // The sheet owns the scroll; the controls above it stay in view. .collection_body(true) .shaped(|dialog| dialog.initial_focus(Initial::Default)) - .show(ui, |ui, _, values| body(ui, values, &mut pane)); + .show(ui, |ui, _, values| { + if let Some(reason) = refusal.clone() { + Notice::new(Tone::Bad, reason).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui); + } + body(ui, values, &mut pane) + }); // The pass reports a press only in the pass that took the input, so a second pass of the frame files nothing. if shown.picked == Some(0) && !held.is_waiting() { commit_text(sheet, pane.entry); @@ -846,6 +877,51 @@ mod tests { pump(app, &ctx); } + fn sheet_with_matching_graphs() -> (VectorcraftApp, u64) { + let (mut app, id) = app_with("1,2\n3,4", "column"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "csv": "7,8\n9,10"})).unwrap(); + assert_eq!(other["id"], id); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + open(&mut app).unwrap(); + set_field(&app, "grid", json!([[""], ["", "5", "6"]])).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + (app, id) + } + + #[test] + fn graph_data_apply_cannot_change_the_other_drawings_graph() { + let (mut app, id) = sheet_with_matching_graphs(); + let other = data(&mut app, id); + let undo = app.session.active().unwrap().history.undo.len(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id), other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id)["rows"], json!([[5.0, 6.0]])); + } + + #[test] + fn graph_data_revert_keeps_the_draft_in_the_other_drawing() { + let (mut app, id) = sheet_with_matching_graphs(); + let draft = read(&app, |dialog| dialog.sheet.grid.clone()); + let revert = |app: &mut VectorcraftApp| { + edit(app, |dialog| dialog.actions.push(Action::Revert)); + pump(app, &crate::testing::ui_context()); + }; + revert(&mut app); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let expected = grid_from_data(&data(&mut app, id)); + revert(&mut app); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), expected); + } + /// The app with the window drawn each frame as the shell draws it. // PLAN: the shell's own frame (hub-w2) replaces `host.run` here, and runs `file_asks::poll` (files-w7) itself. fn harness(app: VectorcraftApp) -> Harness { @@ -978,6 +1054,27 @@ mod tests { assert_eq!(at(&h, 0, 1), "c"); } + #[test] + fn browser_graph_data_import_reads_picked_bytes_without_a_path_reader() { + let (mut app, _) = app_with(",original\nQ1,1", "column"); + app.services.read = None; + app.services.read_head = None; + let files = Arc::new(ScriptedFiles::held().in_browser()); + app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); + app.host = Arc::new(app.host.with_files(files.clone())); + open(&mut app).unwrap(); + let mut h = harness(app); + h.run_steps(4); + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert_eq!(files.open(), 1, "the browser can open the Import Data picker"); + files.answer(Picked::Contents(vec![("data.txt".into(), b"\timported\nQ2\t8".to_vec())])); + h.run_steps(4); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)), "imported"); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 0)), "Q2"); + assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 1)), "8"); + } + #[test] fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() { let (mut app, _) = app_with(",first\nQ1,1", "column"); diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 348287e7bd..04e5e7f0a8 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -251,9 +251,12 @@ pub(crate) enum Answer { impl Answer { /// Runs the command; the refusal is its error. - fn run(&self, app: &mut VectorcraftApp) -> Result<(), Label> { + fn run(&self, app: &mut VectorcraftApp, target: &GraphTarget) -> Result<(), Label> { + if !target.in_active_document(app) { + return Err(Label::from(tl!("This graph design belongs to the document that opened the dialog."))); + } let design = |d: &Option| json!({ "design": d.as_ref().map(|d| d.name.as_str()), "library": library_of(d.as_ref()) }); - let (command, params) = match self { + let (command, mut params) = match self { Answer::Column { design: d, options } => { let mut params = design(d); params["columnType"] = json!(options.column_type.as_str()); @@ -263,10 +266,38 @@ impl Answer { } Answer::Marker { design: d } => ("graph.marker", design(d)), }; + // When selection still describes the opening target, let the command keep its selected series highlighted. + let selected = vectorcraft_engine::graph_type_subject(&app.session).ok(); + if !selected.is_some_and(|selected| selected.id.0 == target.graph && selected.series == target.series) { + params["id"] = json!(target.graph); + if !target.series.is_empty() { + params["seriesIndexes"] = json!(target.series); + } + } app.run(command, params).map(|_| ()).map_err(Label::from) } } +/// The graph and picked series the Column or Marker form opened for. +#[derive(Clone)] +struct GraphTarget { + document: u64, + graph: u64, + series: Vec, +} + +impl GraphTarget { + fn selected(app: &VectorcraftApp) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; + let selected = vectorcraft_engine::graph_type_subject(&app.session).map_err(|error| error.to_string())?; + Ok(Self { document, graph: selected.id.0, series: selected.series }) + } + + fn in_active_document(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|active| active.uid == self.document) + } +} + /// A loaded library's document, for the thumbnails of its designs. struct LibraryDoc { id: String, @@ -361,6 +392,7 @@ impl Lists { pub(crate) struct GraphDesignDialog { id: DialogId, kind: Kind, + target: Option, lists: Lists, /// The selected rows: any number of designs in Graph Design; one design, or None, in Column and Marker. selection: Selection, @@ -376,14 +408,16 @@ pub(crate) struct GraphDesignDialog { /// What [`pump`] takes from the open dialog to run. struct Work { actions: Vec, - answer: Option, + answer: Option<(Answer, GraphTarget)>, + document: Option, } impl GraphDesignDialog { - fn new(kind: Kind, lists: Lists, chosen: Vec, column: ColumnOptions) -> Self { + fn new(kind: Kind, lists: Lists, chosen: Vec, column: ColumnOptions, target: Option) -> Self { let mut dialog = GraphDesignDialog { id: dialog_id(kind.key()), kind, + target, lists, selection: Selection::new(Vec::new(), None, None), name: String::new(), @@ -432,7 +466,9 @@ impl GraphDesignDialog { } fn take_work(&mut self) -> Work { - Work { actions: std::mem::take(&mut self.actions), answer: self.held.take() } + let answer = self.held.take().and_then(|answer| self.target.clone().map(|target| (answer, target))); + let document = self.target.as_ref().map(|target| target.document); + Work { actions: std::mem::take(&mut self.actions), answer, document } } /// What OK files. @@ -756,7 +792,7 @@ impl StackDialog for GraphDesignDialog { pub fn open_design(app: &mut VectorcraftApp) -> Result { let lists = Lists::read(app)?; let first = lists.designs.first().map(|n| DesignKey::document(n)); - open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default())) + open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default(), None)) } /// Open Column for the selected graph series, on the design and options they draw their columns with (None for plain @@ -769,14 +805,16 @@ pub fn open_column(app: &mut VectorcraftApp) -> Result { fractions: v["fractions"].as_str().and_then(Fractions::parse).unwrap_or_default(), }; let chosen = v["design"].as_str().map(DesignKey::document); - open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options)) + let target = GraphTarget::selected(app)?; + open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options, Some(target))) } /// Open Marker for the selected graph series, on the design they draw with (None for the default). pub fn open_marker(app: &mut VectorcraftApp) -> Result { let v = app.session.execute("graph.marker", &json!({})).map_err(|e| e.to_string())?; let chosen = v["design"].as_str().map(DesignKey::document); - open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default())) + let target = GraphTarget::selected(app)?; + open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default(), Some(target))) } fn open(app: &VectorcraftApp, dialog: GraphDesignDialog) -> Result { @@ -815,8 +853,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Err(e) => app.status(e), } } - let answered = work.answer.map(|answer| answer.run(app)); - let lists = Lists::read(app).ok(); + let answered = work.answer.map(|(answer, target)| answer.run(app, &target)); + let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| active.uid == document)); + let lists = if same_document { Lists::read(app).ok() } else { None }; dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { if let Some(lists) = lists { @@ -881,6 +920,42 @@ mod tests { assert!(!dialogs.with(|host| host.is_open::())); } + #[test] + fn graph_column_and_marker_keep_their_opening_graph() { + for (graph_kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_kind); + let graph = app.session.active().unwrap().selection.objects[0].0; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let r = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [r]})).unwrap(); + app.run("graph.design", json!({"new": true})).unwrap(); + select_graph(&mut app, graph_kind); + assert_eq!(app.session.active().unwrap().selection.objects[0].0, graph); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let design = |app: &mut VectorcraftApp, id| app.session.execute(command, &json!({"id": id})).unwrap()["design"].clone(); + + activate(&mut app, 0); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + activate(&mut app, 1); + let undo = app.session.active().unwrap().history.undo.len(); + app.dialogs().unwrap().with(|host| host.confirm::(&ctx)); + super::pump(&mut app, &ctx); + assert_eq!(design(&mut app, graph), Value::Null); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)["selected"], "New Design"); + + activate(&mut app, 0); + select_graph(&mut app, graph_kind); + let selected = app.session.active().unwrap().selection.objects[0].0; + assert_ne!(selected, graph); + ok(&mut app, &ctx); + assert_eq!(design(&mut app, graph), "New Design"); + assert_eq!(design(&mut app, selected), Value::Null); + } + } + #[test] fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { diff --git a/crates/ui-egui/src/dialogs/graphic_style_options.rs b/crates/ui-egui/src/dialogs/graphic_style_options.rs index f72fdbba21..6081982fb2 100644 --- a/crates/ui-egui/src/dialogs/graphic_style_options.rs +++ b/crates/ui-egui/src/dialogs/graphic_style_options.rs @@ -40,13 +40,19 @@ impl Target { /// Open the dialog with `name` in its field; OK runs `target`. fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let params = vec![Param::new("name", tl!("Style Name:").to_string(), ParamKind::text(name.clone()))]; let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::command(&ctx, KIND, DialogFields::from_pairs([("name", name)]), move |fields| { ParamDialog::command(KIND, tl!("Graphic Style Options").to_string(), params.clone()).values(Bind::bound(fields)) }); // An `Err` (a name another style has) keeps the dialog open with the reason. - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ()); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned()); + } + target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ()) + }; host::open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -132,4 +138,30 @@ mod tests { assert_eq!(names(&app).last().unwrap(), "Halo"); assert!(app.run("ui.graphicStyleOptions", json!({"name": "nope"})).is_err()); } + + #[test] + fn renaming_a_style_does_not_change_a_matching_name_in_another_drawing() { + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = names(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open(&mut app, Some("Twin")).unwrap(); + let id = options(&app); + set(&app, id, "name", json!("Source style")); + activate(&mut app, 1); + accept(&mut app, id); + assert_eq!(names(&app), other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(options(&app), id); + + activate(&mut app, 0); + accept(&mut app, id); + assert!(names(&app).iter().any(|name| name == "Source style")); + } } diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index d15f561816..c3a3fb0e6b 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -14,7 +14,7 @@ //! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked. use craft::behavior::{Selection, keyed}; -use craft::host::PickRequest; +use craft::host::{PickId, PickRequest, Picked}; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; @@ -61,6 +61,8 @@ struct Form { file: String, /// The linked file selected in the list, as linked or as the list shows it. selected: String, + /// The file chooser still waiting for its typed answer. + pick: Option, pending: Option, } @@ -217,12 +219,25 @@ fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { if selection.items.first() != selected { form.selected = selection.items.into_iter().next().unwrap_or_default(); } - Field::new(caption("File or URL:")).show(ui, |ui, _| { - let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); - let out = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).pick(request).show(ui); - // The answer is a path; the dialog links a `file:///` URL ([`crate::io::file_url`]). - if let Some(path) = out.picked { - form.file = crate::io::file_url(&path); + Field::new(caption("File or URL:")).show(ui, |ui, cx| { + if let Some(ticket) = form.pick + && let Some(answer) = cx.take_pick_answer(ticket) + { + form.pick = None; + // Browser picks supply the file's bytes and basename. Only a filesystem path can be linked. + if let Picked::Paths(paths) = answer + && let Some(path) = paths.first() + { + form.file = crate::io::file_url(&path.to_string_lossy()); + } + } + let row = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).show(ui); + if row.browse + && form.pick.is_none() + && let Some(host) = cx.env.host() + { + let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); + form.pick = Some(host.files().pick(request)); } }); let chosen = selected_row(files, &form.selected); @@ -242,7 +257,7 @@ mod tests { use std::rc::Rc; use std::sync::Arc; - use craft::host::{AppInfo, Host, Picked, ScriptedFiles}; + use craft::host::{AppInfo, Host, ScriptedFiles}; use craft::ui::testing::Fixture; use egui::{Key, Modifiers}; use vectorcraft_engine::Session; @@ -380,4 +395,21 @@ mod tests { let file = form.borrow().file.clone(); assert!(file.starts_with("file:///") && file.ends_with("/my%20menu.js") && !file.contains('\\'), "{file}"); } + + #[test] + fn a_browser_file_pick_does_not_invent_a_local_script_url() { + let files = Arc::new(ScriptedFiles::held()); + let form = Rc::new(RefCell::new(Form { file: "https://example.test/menu.js".into(), ..Default::default() })); + let shown = Rc::clone(&form); + let mut fixture = Fixture::new(move |ui| body(ui, &[], &mut shown.borrow_mut())); + fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build())); + fixture.settle(); + let choose = fixture.by_label(tl!("Choose…")).expect("the Choose button"); + fixture.click(&choose); + fixture.settle(); + let picked = Picked::Contents(vec![("menu.js".into(), b"// local script".to_vec())]); + assert!(files.answer(picked).is_some(), "Choose… filed a browser pick"); + fixture.idle(3); + assert_eq!(form.borrow().file, "https://example.test/menu.js"); + } } diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 378c5bbe21..5b97daaedd 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -36,6 +36,8 @@ const CMD: &str = "text.setFormat"; pub(crate) struct Open { /// The dialog on the host. pub id: DialogId, + /// The drawing that owns the text IDs and the preview. + document: u64, /// The preview on the canvas. pub preview: LivePreview, /// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on. @@ -47,6 +49,12 @@ pub(crate) struct Open { initial: DialogFields, } +impl Open { + fn in_opening_document(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| st.uid == self.document) + } +} + /// The three spacing rows: (`text.setFormat` key, field prefix, range). const ROWS: [(&str, &str, (f64, f64)); 3] = [ ("wordSpacing", "word", JustificationOptions::WORD_SPACING), @@ -108,6 +116,7 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> { /// Open Justification on the paragraph attributes the Paragraph panel shows. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document open")?.uid; // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; @@ -136,20 +145,24 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), |f| form(f)).preview_off(); let id = super::host::open_held(app, dialog, |app, result| { let Some(open) = app.justification.take() else { return Ok(()) }; + if !open.in_opening_document(app) { + app.justification = Some(open); + return Err(tl!("This dialog was opened in a different document.").to_owned()); + } let p = params(app, &result.fields, &open); if !changes(&p) { // Nothing to apply: end the preview as production's OK did. open.preview.cancel(app); return Ok(()); } - let Open { id, preview, targets, story, initial } = open; + let Open { id, document, preview, targets, story, initial } = open; preview.commit(app, CMD, Value::Object(p)).map(|_| ()).inspect_err(|_| { // The dialog stays open on the refusal, with a preview of its own again. - app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial }); + app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial }); }) }) .ok_or("no window")?; - app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial: fields }); + app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial: fields }); Ok(Value::Null) } @@ -200,6 +213,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.justification.take() else { return }; let shown = app.dialogs().and_then(|d| d.with(|h| h.get_mut_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); + // A document switch ends that document's preview. The active drawing may have started a different one. + if !open.in_opening_document(app) { + if shown.is_some() { + open.preview = LivePreview::default(); + app.justification = Some(open); + } + return; + } // The host lock is released: a command never runs inside `DialogHost::with`. let Some((on, fields)) = shown else { open.preview.cancel(app); @@ -433,4 +454,62 @@ mod tests { app.run("edit.undo", json!({})).unwrap(); assert!(auto_leadings(&app, c).iter().all(|l| *l == 150.0), "undo restores the hidden frame"); } + + fn two_drawings() -> (VectorcraftApp, u64) { + let (mut app, id) = app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(id, second, "local text IDs may match between drawings"); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, id) + } + + #[test] + fn justification_approval_leaves_text_in_the_other_drawing_unchanged() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::ok(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(driver::is_open(&app)); + assert_eq!(driver::fields(&app).number("autoLeading"), Some(180.0)); + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::ok(&mut app); + assert!(!driver::is_open(&app)); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + } + + #[test] + fn justification_preview_leaves_text_in_the_other_drawing_unchanged() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + driver::cancel(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + } + + #[test] + fn cancelling_justification_keeps_the_other_drawings_new_interaction() { + let (mut app, id) = two_drawings(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("New text edit").unwrap(); + app.session.preview("text.setFormat", &json!({"ids": [id], "autoLeading": 190})).unwrap(); + driver::cancel(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 190.0); + assert!(app.session.in_interaction()); + } } diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 944051cf7d..c25df0cf41 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -249,9 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { /// Opens the dialog on `value`. fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let st = app.session.active().ok_or("no document open")?; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value))); + dialogs.with(|host| host.open(LayerOptionsDialog::new(st.uid, st.reverts, value))); Ok(Value::Null) } @@ -412,6 +412,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { pub(crate) struct LayerOptionsDialog { id: DialogId, document: u64, + reverts: u64, open: bool, value: LayerOptionsValue, held: HeldAnswer, @@ -423,8 +424,17 @@ pub(crate) struct LayerOptionsDialog { impl LayerOptionsDialog { /// The dialog over `value`. - fn new(document: u64, value: LayerOptionsValue) -> Self { - LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + fn new(document: u64, reverts: u64, value: LayerOptionsValue) -> Self { + LayerOptionsDialog { + id: dialog_id(KEY), + document, + reverts, + open: true, + value, + held: HeldAnswer::new(), + refused_at: None, + color_request: None, + } } /// The OK filed by the user, once. @@ -573,9 +583,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; // The closed dialog's answer was run when OK was filed. let _ = dialogs.with(|host| host.take::()); - let Some((document, value)) = dialogs.with(|host| { + let Some((document, reverts, value)) = dialogs.with(|host| { let dialog = host.get_mut::()?; - Some((dialog.document, dialog.take_filed()?)) + Some((dialog.document, dialog.reverts, dialog.take_filed()?)) }) else { return; }; @@ -588,6 +598,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { // Isolation mode can start while the dialog is open. let answer = match app.session.active().filter(|st| st.uid == document) { None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))), + Some(st) if st.reverts != reverts => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))), Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { Err(Label::from("exit isolation mode first")) } @@ -935,4 +946,45 @@ mod tests { let n = app.session.doc().unwrap().doc.node(NodeId(rect)).unwrap().clone(); assert_eq!((n.display_name(), n.locked), ("Box".to_string(), true)); } + + #[test] + fn layer_options_refuses_a_stale_draft_after_confirmed_revert() { + let file = std::env::temp_dir().join(format!("vectorcraft-layer-options-revert-{}.vectorcraft", std::process::id())); + let path = file.to_string_lossy(); + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts, layer) = (original.uid, original.reverts, original.doc.layers[0].id); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + + app.run("ui.layerOptions", json!({"id": layer.0})).unwrap(); + set(&mut app, "name", json!("Stale Draft")); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(&file); + let reverted = app.session.active().unwrap(); + assert_eq!((reverted.uid, reverted.reverts, reverted.doc.layers[0].id), (uid, reverts + 1, layer)); + let undo = reverted.history.undo.len(); + + let ctx = app.ui_ctx.clone().unwrap(); + let id = open_id(&app); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + let reverted = app.session.active().unwrap(); + assert_eq!(reverted.doc.node(layer).unwrap().display_name(), "Layer 1"); + assert_eq!(reverted.history.undo.len(), undo); + assert!(app.any_dialog_open(), "the refused draft stays available to inspect or cancel"); + assert_eq!(fields(&app)["name"], "Stale Draft"); + assert_eq!( + dialogs.with(|host| host.held_state(id)), + Some(HeldOk::Refused("The document was reverted. Reopen this dialog to continue.".into())) + ); + dialogs.with(|host| host.cancel_by_id(&ctx, id)); + app.run("ui.layerOptions", json!({"id": layer.0})).unwrap(); + set(&mut app, "name", json!("Fresh Draft")); + ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft"); + } } diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 7fe468c4d2..60e7df2fb1 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -421,7 +421,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec, one: &str, other: &str) -> Opt return Some(changed_on_disk_status(ids.len())); } let detail = crate::i18n::tn(ids.len() as u64, one, other); - super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); + super::confirm::ask_in_document(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); None } @@ -984,4 +984,52 @@ mod tests { assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); let _ = std::fs::remove_dir_all(dir); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn accepting_a_modified_link_offer_does_not_update_another_drawing() { + let dir = std::env::temp_dir().join(format!("vectorcraft-modified-switch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = drive::app(); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.session.prefs.update_links = "askWhenModified".into(); + let mut ids = vec![]; + for name in ["first.png", "second.png"] { + let path = dir.join(name); + std::fs::write(&path, png([200, 0, 0])).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap(); + let links = app.run("links.list", json!({})).unwrap(); + ids.push(links["links"][0]["id"].as_u64().unwrap()); + let stamp = std::fs::metadata(&path).unwrap().modified().unwrap(); + std::fs::write(&path, png([0, 0, 200])).unwrap(); + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2))) + .unwrap(); + } + assert_eq!(ids[0], ids[1], "the same ID refers to different files"); + let answer = |app: &mut VectorcraftApp| { + let question = crate::tests::picks::open_dialogs(app).pop().unwrap().id; + crate::tests::picks::answer_dialog(app, question, &[], true); + }; + + app.run("document.activate", json!({"index": 0})).unwrap(); + ask_update_changed(&mut app, vec![json!(ids[0])]); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); + answer(&mut app); + let foreign_modified = app.run("links.check", json!({})).unwrap()["modified"].clone(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); + ask_update_changed(&mut app, vec![json!(ids[0])]); + answer(&mut app); + let original_modified = app.run("links.check", json!({})).unwrap()["modified"].clone(); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(foreign_modified, 1, "the second drawing's link still needs approval"); + assert_eq!(original_modified, 0, "approval updates the first drawing's link"); + } } diff --git a/crates/ui-egui/src/dialogs/new_color_group.rs b/crates/ui-egui/src/dialogs/new_color_group.rs index a832047188..421d3a3d59 100644 --- a/crates/ui-egui/src/dialogs/new_color_group.rs +++ b/crates/ui-egui/src/dialogs/new_color_group.rs @@ -18,6 +18,7 @@ pub const KIND: &str = "newColorGroup"; /// art is selected and no swatches are. pub fn open(app: &mut VectorcraftApp, swatches: Vec) -> Result { let st = app.session.active().ok_or("no document open")?; + let document = st.uid; let art = !st.selection.is_empty(); let mut fields = DialogFields::new(); fields.set("name", st.doc.free_swatch_name("Color Group")); @@ -37,6 +38,9 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec) -> Result Result<(), String> { + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("Create this color group in the document that opened the dialog.").to_owned()); + } app.run("swatch.newGroup", params(&answer.fields, &swatches)).map(|_| ()) }; super::host::open_held(app, dialog, ok).ok_or(NO_WINDOW)?; @@ -53,3 +57,45 @@ fn params(fields: &DialogFields, swatches: &[String]) -> Value { json!({"name": name, "swatches": swatches}) } } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::dialog_id; + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn color_group_does_not_convert_the_other_drawings_artwork() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + for color in ["#123456", "#446688"] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 25, "height": 25})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + activate(&mut app, 0); + open(&mut app, Vec::new()).unwrap(); + activate(&mut app, 1); + + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KIND); + let confirm = |app: &mut VectorcraftApp| { + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + crate::testing::app_frame(app, &ctx, Default::default()); + }; + confirm(&mut app); + let current = app.session.active().unwrap(); + assert_eq!(current.doc, other, "the other drawing keeps its swatches and process fills"); + assert_eq!(current.history.undo.len(), undo); + + activate(&mut app, 0); + confirm(&mut app); + assert!(app.session.active().unwrap().doc.swatch_groups.iter().any(|group| group.name == "Color Group")); + } +} diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 5580f9511c..39bbd6a984 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -55,7 +55,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ); return Ok(Value::Null); }; - let document = st.uid; + let document = (st.uid, st.reverts); let p = std::path::Path::new(&path); let stem = p.file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); @@ -107,9 +107,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } } -fn require_package_document(app: &VectorcraftApp, document: u64) -> Result<(), String> { - if app.session.active().is_none_or(|st| st.uid != document) { +fn require_package_document(app: &VectorcraftApp, (document, reverts): (u64, u64)) -> Result<(), String> { + let Some(active) = app.session.active().filter(|st| st.uid == document) else { return Err(tl!("Package can only save and collect the document where it was opened.").to_owned()); + }; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } Ok(()) } @@ -160,7 +163,7 @@ pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result return r; } } - // A completed background job may have changed the active document while Package waited. + // A completed background job may have changed the active document or its loaded contents while Package waited. require_package_document(app, document)?; let package = app.session.prepare_package(¶ms).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?; let label = format!("Packaging {}", text("name")); diff --git a/crates/ui-egui/src/dialogs/perspective_presets.rs b/crates/ui-egui/src/dialogs/perspective_presets.rs index 930c5fa0fc..481be9c0c7 100644 --- a/crates/ui-egui/src/dialogs/perspective_presets.rs +++ b/crates/ui-egui/src/dialogs/perspective_presets.rs @@ -9,6 +9,8 @@ //! //! Field: `selected` (a preset's name). +use std::sync::Arc; + use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::host::PickRequest; use craft::ui::buttons::Button; @@ -117,13 +119,22 @@ pub(super) struct PresetsDialog { names: Vec, /// The button pressed in the last pass, for [`pump`] to run outside the host's lock. action: Option, + /// Identifies the manager that opened an Import picker. + import_owner: Arc<()>, open: bool, } impl PresetsDialog { fn new(selected: &str, presets: Vec) -> Self { - let mut dialog = - PresetsDialog { id: dialog_id(KIND), selected: selected.to_owned(), presets: Vec::new(), names: Vec::new(), action: None, open: true }; + let mut dialog = PresetsDialog { + id: dialog_id(KIND), + selected: selected.to_owned(), + presets: Vec::new(), + names: Vec::new(), + action: None, + import_owner: Arc::new(()), + open: true, + }; dialog.set_presets(presets); dialog } @@ -296,13 +307,18 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul select(app, &next); } Action::Import => { + let Some(owner) = with_dialog(app, |manager| Arc::clone(&manager.import_owner)) else { return Ok(()) }; let request = PickRequest::open(KIND).filter("Perspective grid presets", PRESET_EXTS); - file_asks::ask(app, request, Owner::Free, |app, picked| { + file_asks::ask(app, request, Owner::Free, move |app, picked| { let mut params = file_asks::open_params(&picked).ok_or("cancelled")?; params.remove("name"); let r = app.run("perspective.presets.import", Value::Object(params))?; if let Some(first) = r["imported"].get(0).and_then(Value::as_str) { - select(app, first); + with_dialog(app, |manager| { + if Arc::ptr_eq(&manager.import_owner, &owner) { + manager.selected = first.to_owned(); + } + }); } Ok(r) }); diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index a5987f699b..cb0e6981d2 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -4,8 +4,8 @@ //! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and //! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save… //! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one -//! into the dialog (`view.proofSetup.read`). Both are desktop only. Their pickers start in the -//! Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below +//! into the dialog (`view.proofSetup.read`). The browser reads picked bytes and downloads a copy +//! when saving. Desktop pickers start in the Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below //! Customize… ([`saved_items`]): Save… makes the folder when it may be written, and Load…'s picker //! starts in its own default folder until the folder exists. //! @@ -116,15 +116,10 @@ fn rgb_device(device: &str) -> bool { /// The dialog over the host's values, made again every pass. fn build(fields: &mut DialogFields) -> ParamDialog<'_> { - // The web has no folder to keep setups in. - let footer = if cfg!(target_arch = "wasm32") { - Vec::new() - } else { - vec![ - (SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)), - (LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)), - ] - }; + let footer = vec![ + (SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)), + (LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)), + ]; ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer) } @@ -297,6 +292,29 @@ fn act(app: &mut VectorcraftApp, id: DialogId, fields: &DialogFields, action: &s /// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again. fn save(app: &mut VectorcraftApp, fields: &DialogFields) { + let mut request = + PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT); + let mut p = params(fields); + if let Some(o) = p.as_object_mut() { + o.remove("proof"); + } + if app.host.files().browser_saves() { + match proof_file::draft_bytes(&p) { + Ok(bytes) => { + crate::file_asks::save(app, request, bytes, Owner::Free, |app, picked| { + match picked { + Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())), + Picked::Downloaded(name) => app.status(format!("Saved {name}")), + Picked::Failed(error) => return Err(error), + _ => {} + } + Ok(Value::Null) + }); + } + Err(e) => app.status(e.to_string()), + } + return; + } // The picker opens in the folder, made for it when it may be written. [`list_saved`] removes // it again when the picker closes without a file in it. let dir = app.session.proof_setup_dir().map(Path::to_path_buf); @@ -307,15 +325,9 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) { if made.is_some() { saved().made = made; } - let mut request = - PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT); if let Some(dir) = dir { request = request.directory(dir); } - let mut p = params(fields); - if let Some(o) = p.as_object_mut() { - o.remove("proof"); - } ask(app, request, Owner::Free, move |app, picked| { let Picked::Saved { path, .. } = picked else { return Ok(Value::Null) }; let path = path.to_string_lossy().into_owned(); @@ -343,8 +355,16 @@ fn load(app: &mut VectorcraftApp, id: DialogId) { && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) }; ask_while(app, request, Owner::Free, is_live, move |app, picked| { - let Some(path) = picked.first_path() else { return Ok(Value::Null) }; - let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?; + let r = match picked { + Picked::Contents(files) => { + let Some((name, bytes)) = files.into_iter().next() else { return Ok(Value::Null) }; + proof_file::draft_fields(&bytes, &name).map_err(|e| e.to_string())? + } + other => { + let Some(path) = other.first_path() else { return Ok(Value::Null) }; + app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))? + } + }; let fields = [ ("device", "target"), ("intent", "intent"), @@ -817,6 +837,52 @@ mod tests { assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); } + #[test] + fn a_browser_pick_loads_a_proof_setup_into_the_draft() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let files = scripted(&mut app, ScriptedFiles::held().in_browser()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + set(&mut app, &ctx, "preview", json!(false)); + let before = proof::view(); + let mut source = before.setup.clone(); + source.intent = Intent::Saturation; + press(&mut app, &ctx, LOAD_BUTTON); + files.answer(Picked::Contents(vec![("browser.vcproof".into(), proof_file::encode(&source))])); + crate::file_asks::poll(&mut app); + assert_eq!(values(&app)["intent"], "saturation"); + assert_eq!(proof::view(), before); + + press(&mut app, &ctx, LOAD_BUTTON); + files.answer(Picked::Contents(vec![("oversized.vcproof".into(), vec![b' '; proof_file::MAX_FILE + 1])])); + crate::file_asks::poll(&mut app); + assert!(app.ui.status.contains("larger than")); + assert_eq!(values(&app)["intent"], "saturation"); + assert_eq!(proof::view(), before); + } + + #[test] + fn saving_a_browser_proof_setup_gives_the_file_service_the_draft_bytes() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let files = scripted(&mut app, ScriptedFiles::held().in_browser()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + for (k, v) in [("intent", json!("saturation")), ("preview", json!(false))] { + set(&mut app, &ctx, k, v); + } + let before = proof::view(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-browser-save"); + let path = dir.join("draft.vcproof"); + press(&mut app, &ctx, SAVE); + files.answer(Picked::Saved { path: path.clone(), file_type: None }); + crate::file_asks::poll(&mut app); + let bytes = files.file(&path).expect("the browser file service receives the draft bytes"); + assert_eq!(proof_file::parse(&bytes).unwrap().intent, Intent::Saturation); + assert_eq!(proof::view(), before); + assert_eq!(values(&app)["intent"], "saturation"); + assert!(!path.exists(), "the browser save does not write through the native path"); + } + #[test] fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() { let _view = DefaultProofView::new(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e872c841a7..a377869b5b 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -118,7 +118,7 @@ mod prominent; use std::borrow::Cow; use std::cell::RefCell; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use craft::behavior::edit_history::{EditHistory, Step}; use craft::behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed}; @@ -152,6 +152,7 @@ use serde_json::{Value, json}; use vectorcraft_color::harmony::{self, Harmony, move_on_wheel}; use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method}; use vectorcraft_color::{Color, keep_model}; +use vectorcraft_doc::Selection as ArtworkSelection; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::fileio::builtin_open_filters; use vectorcraft_engine::cmd::swatchlib; @@ -258,8 +259,44 @@ impl Fields { pub(crate) struct Open { /// The dialog on the window's host. pub id: DialogId, + document: u64, /// The preview the pump runs and OK commits. pub preview: LivePreview, + /// The selection snapshot identifies the interaction that ran the preview. + preview_selection: Option>, +} + +impl Open { + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.preview_selection else { return false }; + app.session.active().is_some_and(|state| { + state.uid == self.document + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn problem(&self, app: &VectorcraftApp) -> Option<&'static str> { + if app.session.active().is_none_or(|state| state.uid != self.document) { + Some("Return to the document where Recolor Artwork opened.") + } else if app.session.in_interaction() && !self.owns_preview(app) { + Some("Finish the active edit before applying Recolor Artwork.") + } else { + None + } + } + + fn take_preview(&mut self) -> LivePreview { + self.preview_selection = None; + std::mem::take(&mut self.preview) + } + + fn cancel(&mut self, app: &mut VectorcraftApp) { + let owns_preview = self.owns_preview(app); + let preview = self.take_preview(); + if owns_preview { + preview.cancel(app); + } + } } /// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?, preset?}`) on the selected @@ -284,7 +321,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // The group is looked for in the document without the preview of a Recolor Artwork this one // replaces (which can rename the group), as that dialog's rollback below leaves it. let unpreviewed = match &st.interaction { - Some(it) if app.color_dialogs.recolor.is_some() => &it.doc, + Some(it) if app.color_dialogs.recolor.as_ref().is_some_and(|open| open.owns_preview(app)) => &it.doc, _ => &st.doc, }; if let Some(g) = group @@ -301,6 +338,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // A Recolor Artwork still open is replaced: its preview goes before the group's colours are read. cancel_open(app); let st = app.session.active().ok_or("no document open")?; + let document = st.uid; let group_colors: Option> = match group { Some(g) => { let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?; @@ -339,7 +377,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let dialog = RecolorDialog::new(app, d); let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?; - app.color_dialogs.recolor = Some(Open { id, preview: LivePreview::default() }); + app.color_dialogs.recolor = Some(Open { id, document, preview: LivePreview::default(), preview_selection: None }); Ok(Value::Null) } @@ -349,8 +387,8 @@ fn cancelled(app: &mut VectorcraftApp) { if app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.is_open::())) { return; } - if let Some(open) = app.color_dialogs.recolor.take() { - open.preview.cancel(app); + if let Some(mut open) = app.color_dialogs.recolor.take() { + open.cancel(app); } } @@ -363,9 +401,9 @@ const NEW_GROUP: &str = "Color Group"; /// Ends an open Recolor Artwork as Cancel ends it: its preview is rolled back and it closes. pub(super) fn cancel_open(app: &mut VectorcraftApp) { - let Some(old) = app.color_dialogs.recolor.take() else { return }; + let Some(mut old) = app.color_dialogs.recolor.take() else { return }; let id = old.id; - old.preview.cancel(app); + old.cancel(app); if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { dialogs.with(|host| { host.cancel_by_id(&ctx, id); @@ -476,8 +514,9 @@ const SAVE_GROUP: &str = "__saveGroup"; /// Cancel the preview, so commands read the art's own colors; the pump runs it again afterwards. fn cancel_preview(app: &mut VectorcraftApp) { - if let Some(preview) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) { - preview.cancel(app); + if let Some(mut open) = app.color_dialogs.recolor.take() { + open.cancel(app); + app.color_dialogs.recolor = Some(open); } } @@ -1630,12 +1669,20 @@ pub(super) fn limit_to(dialogs: &craft::ui::shell::WindowDialogs, parent: Dialog /// Runs the open dialog's live preview with `(on, command, params)`. fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) { - let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return }; - // `run` reports a preview that fails on the status line itself. - let _ = live.run(app, on, TITLE, cmd, ¶ms); - if let Some(open) = app.color_dialogs.recolor.as_mut() { - open.preview = live; + let Some(mut open) = app.color_dialogs.recolor.take() else { return }; + if open.problem(app).is_none() { + if !open.owns_preview(app) { + open.take_preview(); + } + // `run` reports a preview that fails on the status line itself. + let ran = open.preview.run(app, on, TITLE, cmd, ¶ms).is_some(); + if !on { + open.preview_selection = None; + } else if ran { + open.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } } + app.color_dialogs.recolor = Some(open); } /// Feeds the open Recolor Artwork what it shows of the app, runs what its passes asked for, asks for @@ -1643,8 +1690,27 @@ fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, /// previews its recolour: once a frame, after the window's dialog host ran. // PLAN: hub-w2 adds the line `recolor::pump(app, ctx)` to `dialogs::host::pump` (co.A6 names this pump). pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some(id) = app.color_dialogs.recolor.as_ref().map(|open| open.id) else { return }; + let Some(open) = app.color_dialogs.recolor.as_ref() else { return }; + let id = open.id; let Some(dialogs) = app.dialogs() else { return }; + if let Some(reason) = open.problem(app) { + let requests = dialogs.with(|host| { + let d = host.get_mut_by_id::(id)?; + let group_action = d.fields.fields.remove(GROUP_ACTION).is_some(); + let save_group = d.fields.fields.remove(SAVE_GROUP).is_some(); + let library = std::mem::take(&mut d.filed.library).then(|| Arc::clone(&d.opening)); + Some((library, group_action || save_group)) + }); + if let Some((library, action_refused)) = requests { + if let Some(opening) = library { + pick_library(app, opening); + } + if action_refused { + app.status(reason); + } + } + return; + } // The colour the picker answered for a row reaches the row here, where the app can snap it to Limit to Library. dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) @@ -1681,7 +1747,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Artwork dialog → {changed, canUndo, canRedo}. pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result { const NOT_OPEN: &str = "Recolor Artwork is not open"; - let id = app.color_dialogs.recolor.as_ref().map(|open| open.id).ok_or(NOT_OPEN)?; + let open = app.color_dialogs.recolor.as_ref().ok_or(NOT_OPEN)?; + if let Some(reason) = open.problem(app) { + return Err(crate::i18n::msg(reason)); + } + let id = open.id; let dialogs = app.dialogs().ok_or(NOT_OPEN)?; let mut work = dialogs.with(|host| host.get_mut_by_id::(id).map(RecolorDialog::take_work)).ok_or(NOT_OPEN)?; // Fields set since the last frame take effect first, as the next frame would give them. @@ -1706,7 +1776,8 @@ pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result bool { - app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some_and(|d| d.steps.can(&d.fields, back)))) + app.color_dialogs.recolor.as_ref().is_some_and(|open| open.problem(app).is_none()) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some_and(|d| d.steps.can(&d.fields, back)))) } /// Row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -1725,6 +1796,10 @@ pub(super) fn with_new_color(app: &VectorcraftApp, d: &mut RecolorDialog, i: usi /// save colours opened alone as a new colour group). The dialog closes once this answers `Ok`; an /// `Err` keeps it open with the reason. fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { + let open = app.color_dialogs.recolor.as_ref().ok_or("Recolor Artwork is not open")?; + if let Some(reason) = open.problem(app) { + return Err(crate::i18n::msg(reason)); + } let mut d = fields.clone(); select_group(app, &mut d)?; sync(app, &mut d); @@ -1743,7 +1818,7 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { } r?; } - let preview = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)).unwrap_or_default(); + let preview = app.color_dialogs.recolor.as_mut().map(Open::take_preview).unwrap_or_default(); let committed = if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r) && to_color(r).is_some())); preview.commit(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})) @@ -3118,6 +3193,94 @@ mod tests { rc } + fn two_red_drawings() -> (Recolor, u64, u64) { + let mut app = app(120); + let opening = square(&mut app, 10.0, "#ff0000"); + app.run("select.set", json!({"ids": [opening]})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let other = square(&mut app, 60.0, "#ff0000"); + app.run("select.set", json!({"ids": [other]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}])).unwrap(); + (rc, opening, other) + } + + #[test] + fn recolor_preview_does_not_change_the_other_drawings_art() { + let (mut rc, opening, other) = two_red_drawings(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + rc.frame(); + + assert_eq!(fill_hex(&rc, other), "#ff0000", "preview leaves the other drawing's fill alone"); + assert!(!rc.app().session.in_interaction()); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + rc.frame(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + rc.confirm().unwrap(); + } + + #[test] + fn recolor_ok_keeps_the_draft_on_the_opening_drawing() { + let (mut rc, opening, other) = two_red_drawings(); + rc.set("preview", json!(false)).unwrap(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&rc.app()); + let confirmed = rc.confirm(); + + assert_eq!(fill_hex(&rc, other), "#ff0000", "OK leaves the other drawing's fill alone"); + assert_eq!(undo_len(&rc.app()), undo); + assert!(confirmed.is_err() && rc.is_open()); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(fill_hex(&rc, opening), "#ff0000"); + rc.confirm().unwrap(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + } + + #[test] + fn recolor_cancel_leaves_the_other_drawings_pending_edit() { + let (mut rc, opening, other) = two_red_drawings(); + rc.frame(); + assert_eq!(fill_hex(&rc, opening), "#00ff00"); + { + let mut app = rc.app(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.setFill", &json!({"ids": [other], "color": "#0000ff"})).unwrap(); + } + rc.cancel(); + + assert!(rc.app().session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(fill_hex(&rc, other), "#0000ff"); + rc.app().session.commit_interaction().unwrap(); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(fill_hex(&rc, opening), "#ff0000"); + } + + #[test] + fn recolor_delete_leaves_the_other_drawings_same_named_group() { + let mut app = app(120); + app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#00ff00"]})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#ff0000"]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut rc = opened(app, json!({"group": "Shared"})); + rc.frame(); + rc.app().run("document.activate", json!({"index": 1})).unwrap(); + let other = group_hex(&rc.app(), "Shared"); + + rc.act("delete").unwrap(); + + assert_eq!(group_hex(&rc.app(), "Shared"), other, "Delete leaves the other drawing's group alone"); + rc.app().run("document.activate", json!({"index": 0})).unwrap(); + rc.frame(); + assert!(group_hex(&rc.app(), "Shared").is_some(), "a refused action does not run after returning"); + rc.act("delete").unwrap(); + assert!(group_hex(&rc.app(), "Shared").is_none()); + } + #[test] fn recolor_dialog_keeps_the_default_model_without_an_extra_dropdown() { let rc = opened(app(100), json!({"colors": ["#ff8000"]})); diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs index 0d3020abb5..61dfc60d6f 100644 --- a/crates/ui-egui/src/dialogs/recolor_preset.rs +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -24,6 +24,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if st.selection.is_empty() { return Err("select artwork to recolor".into()); } + let document = st.uid; if p.get("group").is_some_and(|g| !g.is_null()) { return Err("`group` does not apply to a preset".into()); } @@ -39,6 +40,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false); // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("Open the original drawing to continue with Recolor with Preset.").to_owned()); + } let mut p = serde_json::Map::new(); if let Some(n) = colors { p.insert("colors".into(), json!(n)); @@ -59,3 +63,42 @@ fn count(v: Option<&Value>) -> Result, String> { Some(n) => n.as_u64().filter(|n| *n >= 1).map(Some).ok_or_else(|| "`colors` must be a count of at least 1".into()), } } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::{HeldOk, dialog_id}; + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn recolor_preset_does_not_open_artwork_in_another_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + for color in ["#ff0000", "#0000ff"] { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [shape], "color": color})).unwrap(); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + host.with(|h| h.set_json_field(&ctx, id, "limitTo", json!("document"))).unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the preset waits for the app"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let target_undo = app.session.active().unwrap().history.undo.len(); + super::super::host::pump(&mut app, &ctx); + assert!(app.color_dialogs.recolor.is_none(), "the held answer must not open Recolor Artwork on the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), target_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(super::super::tests::confirm(&mut app), "the original preset draft can open Recolor Artwork"); + assert!(app.color_dialogs.recolor.is_some()); + let limit = super::super::recolor::limit_to(&host, dialog_id(super::super::recolor::KIND)); + assert_eq!(limit.as_deref(), Some("document")); + } +} diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index 6eb9001c3b..4a633c0503 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -6,7 +6,7 @@ //! dialog opened on are held by its OK. use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use serde_json::{Value, json}; use super::host::open_held; @@ -15,12 +15,13 @@ use crate::VectorcraftApp; /// The command Rename answers for; the key of its dialog. pub(crate) const CMD: &str = "artboard.rename"; +const TARGET: &str = "__target"; + /// `artboard.rename` for the selected artboards: opens the dialog on the one artboard's name, or on an empty name /// for several. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?; - let document = st.uid; let selected: Vec<_> = crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect(); let name = match selected.as_slice() { @@ -30,21 +31,34 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let artboards: Vec<_> = selected.iter().map(|board| board.id).collect(); let mut fields = DialogFields::new(); fields.set("name", name); + // The held answer carries the target of the draft being confirmed, including after reopening. + fields.set(TARGET, FieldValue::Json(json!({"document": st.uid, "reverts": st.reverts, "artboards": artboards}))); let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { let rows = vec![Param::new("name", tl!("Name:"), ParamKind::text(""))]; ParamDialog::command(CMD, tl!("Rename"), rows).values(Bind::bound(fields)) }); - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let name = result.fields.text("name").unwrap_or_default(); // An empty name keeps the names as they are, as the Artboards panel's name field does. if name.trim().is_empty() { return Ok(()); } - let st = - app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; - let indices = artboards + let Some(FieldValue::Json(target)) = result.fields.get(TARGET) else { + return Err(tl!("The artboards being renamed could not be found.").to_owned()); + }; + let st = app + .session + .active() + .filter(|st| Some(st.uid) == target["document"].as_u64()) + .ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; + if Some(st.reverts) != target["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen the dialog to rename artboards.").to_owned()); + } + let indices = target["artboards"] + .as_array() + .ok_or_else(|| tl!("The artboards being renamed could not be found.").to_owned())? .iter() - .map(|id| st.doc.artboards.iter().position(|board| board.id == *id)) + .map(|id| st.doc.artboards.iter().position(|board| Some(u64::from(board.id)) == id.as_u64())) .collect::>>() .ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?; if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) { @@ -61,6 +75,14 @@ mod tests { use super::*; use vectorcraft_engine::Session; + struct SavedFile(std::path::PathBuf); + + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + fn app() -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); @@ -143,6 +165,48 @@ mod tests { assert!(!app.any_dialog_open()); } + #[test] + fn rename_cannot_use_a_draft_opened_before_file_revert() { + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-rename-artboards-revert-{}.vectorcraft", std::process::id()))); + let services = crate::Services { + read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))), + write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + app.select_tool("artboard"); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + let active = app.session.active().unwrap(); + let (document, reverts, artboard) = (active.uid, active.reverts, active.doc.artboards[0].id); + app.run(CMD, json!({"indices": [0], "name": "Temporary"})).unwrap(); + open(&mut app).unwrap(); + let (id, fields) = open_rename(&app); + assert_eq!(fields["name"], "Temporary"); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name", json!("Stale")).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + }); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!((active.uid, active.reverts, active.doc.artboards[0].id), (document, reverts + 1, artboard)); + let undo = active.history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"], "an older draft cannot rename the reloaded board"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + rename(&mut app, "Page"); + assert_eq!(names(&app), ["Page-1", "Artboard 2", "Page-2"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + #[test] fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index 0bbf1e89ea..ed586dcb5c 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -138,6 +138,7 @@ impl ItemSource for Shown<'_> {} pub(crate) struct SavedNamesDialog { id: DialogId, document: u64, + reverts: u64, names: SavedNames, draft: NamesDraft, /// The picked row, by its index in the draft; one at most. @@ -148,10 +149,10 @@ pub(crate) struct SavedNamesDialog { impl SavedNamesDialog { /// The dialog over `list`, with the first name picked. - fn new(document: u64, names: SavedNames, list: Vec) -> Self { + fn new(document: u64, reverts: u64, names: SavedNames, list: Vec) -> Self { let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); - SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + SavedNamesDialog { id: id_of(names.kind), document, reverts, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } } /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for @@ -327,9 +328,10 @@ impl StackDialog for SavedNamesDialog { /// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { list.truncate(names.max); - let document = app.session.active().ok_or("no document open")?.uid; + let active = app.session.active().ok_or("no document open")?; + let (document, reverts) = (active.uid, active.reverts); let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list))); + dialogs.with(|host| host.open(SavedNamesDialog::new(document, reverts, names, list))); Ok(()) } @@ -343,15 +345,15 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { .filter_map(|open| { let dialog = host.get_mut_by_id::(open.id)?; let edits = dialog.held.take()?; - Some((open.id, dialog.document, dialog.names.command, edits)) + Some((open.id, dialog.document, dialog.reverts, dialog.names.command, edits)) }) .collect() }); - for (id, document, command, edits) in filed { - let outcome = if app.session.active().is_some_and(|active| active.uid == document) { - app.run(command, json!({ "edits": edits })) - } else { - Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()) + for (id, document, reverts, command, edits) in filed { + let outcome = match app.session.active().filter(|active| active.uid == document) { + Some(active) if active.reverts != reverts => Err(tl!("The document was reverted. Reopen the dialog to edit saved names.").to_owned()), + Some(_) => app.run(command, json!({ "edits": edits })), + None => Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()), }; if let Err(reason) = &outcome { app.status(reason.clone()); @@ -368,6 +370,95 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { mod tests { use super::*; + struct SavedFile(std::path::PathBuf); + + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + #[test] + fn saved_selection_draft_does_not_edit_a_reverted_drawing() { + exercise_reverted_draft(false); + } + + #[test] + fn saved_views_draft_does_not_edit_a_reverted_drawing() { + exercise_reverted_draft(true); + } + + fn exercise_reverted_draft(is_view: bool) { + let path = SavedFile(std::env::temp_dir().join(format!("vc-saved-names-revert-{}-{is_view}.vectorcraft", std::process::id()))); + let services = crate::Services { + read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))), + write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); + let add_shape = |app: &mut VectorcraftApp, x| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + }; + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let open = |app: &mut VectorcraftApp| { + if is_view { + crate::dialogs::edit_views::open(app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(app).unwrap(); + crate::dialogs::edit_selection::KIND + } + }; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + add_shape(&mut app, 10); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + add_shape(&mut app, 40); + let old = app.session.active().unwrap(); + let (document, reverts) = (old.uid, old.reverts); + let kind = open(&mut app); + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Stale")).unwrap(); + host.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!((active.uid, active.reverts), (document, reverts + 1), "Revert preserves the tab's UID"); + assert_eq!(names(&mut app), json!(["Shared", "Spare"])); + let undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "{kind} cannot apply its old draft to the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + assert!(dialogs.with(|host| host.cancel_by_id(&ctx, id))); + assert_eq!(open(&mut app), kind); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + host.confirm_by_id(&ctx, id); + }); + pump(&mut app, &ctx); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised", "Spare"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + #[test] fn saved_names_edits_stay_with_their_document() { for is_view in [false, true] { diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index f85cdfe558..2ff5b5bf69 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -14,7 +14,7 @@ use std::sync::LazyLock; use craft::behavior::{ColumnWidth, IconId}; use craft::egui::{Response, Ui}; -use craft::host::{PickRequest, Picked}; +use craft::host::PickRequest; use craft::ui::buttons::{Button, IconButton}; use craft::ui::contract::overlay::Trigger; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; @@ -178,26 +178,16 @@ pub(crate) fn save_preset_row(ui: &mut Ui, fields: &mut Map) -> O } /// Import Preset…: the presets of a picked file are added to the saved ones; `then` gets the names -/// added, or the error (`cancelled` when no file was picked). On the web the picked file arrives -/// with its bytes and imports through `io::open_bytes`, which reports no names. +/// added, or the error (`cancelled` when no file was picked). Browser picks use the file's contents. pub(crate) fn import_presets(app: &mut VectorcraftApp, then: impl FnOnce(&mut VectorcraftApp, Result, String>) + 'static) { let request = PickRequest::open("export-presets").filter("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS); // `then` reports its own result, so the continuation never fails (a failure would reach the status line twice). let _ = file_asks::ask(app, request, Owner::Free, move |app, picked| { - let result: Result, String> = match picked { - Picked::Contents(files) => match files.first() { - Some((name, bytes)) => io::open_bytes(app, name, bytes, None).map(|_| Vec::new()), - None => Err("cancelled".into()), - }, - other => match other.first_path() { - Some(path) => { - let path = path.to_string_lossy().into_owned(); - io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, json!({ "path": path })) - .map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()) - } - None => Err("cancelled".into()), - }, - }; + let result = file_asks::open_params(&picked).ok_or_else(|| "cancelled".to_owned()).and_then(|mut params| { + params.remove("name"); + io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, Value::Object(params)) + .map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()) + }); then(app, result); Ok(Value::Null) }); @@ -488,7 +478,6 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map, mut menu: Optio } shown.output } - /// The format Format Settings opens on for format rows `rows`: the first row's format when it has /// settings of its own, else PNG. Row spellings (`jpeg`, `tif`) give the canonical id. pub(crate) fn settings_format(rows: &[Value]) -> &'static str { @@ -561,3 +550,39 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map, presets: &[ } shown.output } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_browser_preset_picker_routes_by_content_without_opening_drawings() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.services.download = Some(Box::new(|_, _| Ok(()))); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("document.exportPresets.save", json!({"name": "Fleet", "settings": {"formats": [{"format": "png"}]}})).unwrap(); + let export = app.run("document.exportPresets.export", json!({"names": ["Fleet"]})).unwrap(); + let bytes = export["data"].as_str().unwrap().as_bytes(); + app.run("document.exportPresets.delete", json!({"name": "Fleet"})).unwrap(); + let document = app.session.active().unwrap().uid; + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let picked = |app: &mut VectorcraftApp, name: &str, bytes: &[u8]| { + let answer = Rc::new(Cell::new(None)); + let report = Rc::clone(&answer); + import_presets(app, move |_, result| report.set(Some(result))); + picker.answer_contents(&[(name, bytes)]); + crate::tests::picks::poll(app, &ctx); + answer.take().unwrap() + }; + + let svg = br#""#; + let error = picked(&mut app, "drawing.svg", svg); + assert_eq!(app.session.documents().len(), 1, "Import Preset must not open a drawing"); + assert!(error.unwrap_err().contains("not an export presets file")); + + assert_eq!(picked(&mut app, "different-extension.svg", bytes), Ok(vec!["Fleet".to_string()])); + assert_eq!(app.ui.status, "Imported export presets: Fleet"); + assert_eq!(app.session.active().unwrap().uid, document); + } +} diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 488fb70e57..4804675d8d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -29,6 +29,7 @@ //! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder. use std::path::Path; +use std::sync::Arc; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; @@ -276,6 +277,7 @@ impl StackDialog for ScriptNotice { /// The dialog of a script's file dialog call: what the run asked for, read from the run's own /// request when the dialog opens, so no field of the dialog changes what the person reads. pub(crate) struct ScriptFiles { + opening: Arc<()>, kind: PickerKind, prompt: String, can_always: bool, @@ -290,6 +292,7 @@ pub(crate) struct ScriptFiles { impl ScriptFiles { fn new(p: ScriptPicker) -> Self { Self { + opening: Arc::new(()), kind: p.kind, prompt: p.prompt, can_always: p.can_always, @@ -719,8 +722,11 @@ pub(crate) fn settle_files(app: &mut VectorcraftApp, result: DialogResult().map(|dialog| Arc::clone(&dialog.opening))).flatten() else { + return; + }; let Some(p) = app.session.script_picker() else { return }; let several = p.multiple && p.kind == PickerKind::Open; let mut request = match p.kind { @@ -750,7 +756,11 @@ fn choose(app: &mut VectorcraftApp) { file_asks::ask(app, request, Owner::Free, move |app, picked| { let chosen = picked.paths().iter().map(|path| path.to_string_lossy().into_owned()).collect(); let automated = app.file_asks.automated(); - with_host(app, |host, _| host.get_mut::().map(|dialog| dialog.add(chosen, several, automated))); + with_host(app, |host, _| { + if let Some(dialog) = host.get_mut::().filter(|dialog| Arc::ptr_eq(&dialog.opening, &opening)) { + dialog.add(chosen, several, automated); + } + }); Ok(Value::Null) }); } diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index d031aac572..ccdf07a76e 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -35,6 +35,9 @@ pub(crate) const OPTION_TOOLS: [&str; 4] = ["rectangularGrid", "polarGrid", "arc /// link as the Transform panel's, and the next of these dialogs opens with it as this one left it. const SIZE_KINDS: [&str; 3] = ["rectangle", "roundedRectangle", "ellipse"]; +const CLICK_DOCUMENT: &str = "__clickDocument"; +const CLICK_ALT: &str = "__clickAlt"; + /// Where a shape tool was clicked: the dialog's shape is drawn there, and with `alt` held a box shape /// is centred on it. #[derive(Clone, Copy, Debug)] @@ -87,10 +90,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option) { if SIZE_KINDS.contains(&kind) { values.insert("constrain".into(), json!(app.object_dialogs.shape_link)); } - // The click is among the fields (no row shows it), where OK reads it. + // Keep the placement with the draft whose fields OK receives. if let Some(click) = click { + let Some(document) = app.session.active().map(|doc| doc.uid) else { + app.status(tl!("Open a document before drawing a shape").to_string()); + return; + }; values.insert("x".into(), json!(click.at.x)); values.insert("y".into(), json!(click.at.y)); + values.insert(CLICK_DOCUMENT.into(), json!(document.to_string())); + values.insert(CLICK_ALT.into(), json!(click.alt)); } let ink = (kind == "arc" && click.is_none()).then(|| ArcInk::of(&app.session)); let params = shape_params(kind, &values, lengths, ink); @@ -100,7 +109,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option) { ParamDialog::new(key.clone(), title, params.clone()).values(Bind::bound(fields)) }); let kind_owned = kind.to_owned(); - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, click, &result.fields); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, &result.fields); if open_held(app, dialog, ok).is_none() { app.status(format!("no window to show the {kind} dialog")); } @@ -470,18 +479,28 @@ fn option_values(kind: &str, fields: &DialogFields) -> Option /// OK of the `kind` dialog: Tool Options set the tool's options and draw nothing; a click dialog draws at the /// click, then keeps the options and General › Corner Radius. Every refusal comes before the draw, so a refused OK /// draws nothing and the dialog stays open for a second OK. -fn confirm(app: &mut VectorcraftApp, kind: &str, click: Option, fields: &DialogFields) -> Result<(), String> { +fn confirm(app: &mut VectorcraftApp, kind: &str, fields: &DialogFields) -> Result<(), String> { let options = option_values(kind, fields); - let Some(click) = click else { + let Some(document) = fields.text(CLICK_DOCUMENT) else { return match options { Some(options) if OPTION_TOOLS.contains(&kind) => set_options(app, kind, options), _ => Err(format!("the {kind} tool has no options")), }; }; + let document = document.parse::().map_err(|_| tl!("The shape click document is missing").to_string())?; + if app.session.active().is_none_or(|doc| doc.uid != document) { + let reason = if app.session.documents().iter().any(|doc| doc.uid == document) { + tl!("Switch back to the document where you clicked to draw the shape") + } else { + tl!("The document where you clicked to draw the shape has closed") + }; + return Err(reason.into()); + } + let (Some(x), Some(y)) = (fields.number("x"), fields.number("y")) else { + return Err(tl!("The shape click position is missing").into()); + }; + let click = Click { at: Point::new(x, y), alt: fields.bool(CLICK_ALT).unwrap_or(false) }; let corner_radius = if kind == "roundedRectangle" { Some(rounded_radius(app, fields)?) } else { None }; - let at = |key, clicked| fields.number(key).unwrap_or(clicked); - let click = Click { at: Point::new(at("x", click.at.x), at("y", click.at.y)), ..click }; - let (x, y) = (click.at.x, click.at.y); let (width, height) = (length_of(fields, "width", 100.0), length_of(fields, "height", 100.0)); let (bx, by) = box_origin(click, width, height); let (id, params) = match kind { @@ -658,6 +677,60 @@ mod tests { app.session.doc().unwrap().doc.layers[0].children().unwrap().len() } + #[test] + fn rectangle_click_waits_for_its_opening_document() { + let (mut app, mut fx) = shown(); + let opening = app.session.doc().unwrap().uid; + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0})); + set(&app, &fx, "rectangle", "width", json!(32.0)).unwrap(); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + assert_ne!(app.session.doc().unwrap().uid, opening); + + press_ok(&mut app, &mut fx, "rectangle"); + assert_eq!(drawn(&app), 0, "OK must leave the other document unchanged"); + assert!(is_open(&app, "rectangle")); + + app.run("document.activate", json!({"index": 0})).unwrap(); + press_ok(&mut app, &mut fx, "rectangle"); + assert!(!is_open(&app, "rectangle")); + let doc = &app.session.doc().unwrap().doc; + let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((bounds.x0 - 40.0).abs() < 1e-6 && (bounds.y0 - 60.0).abs() < 1e-6); + assert!((bounds.width() - 32.0).abs() < 1e-6); + } + + #[test] + fn a_reopened_rectangle_uses_the_replacement_click_and_modifier() { + let (mut app, mut fx) = shown(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0})); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 120.0, "y": 130.0, "alt": true})); + set(&app, &fx, "rectangle", "width", json!(20.0)).unwrap(); + set(&app, &fx, "rectangle", "height", json!(30.0)).unwrap(); + + press_ok(&mut app, &mut fx, "rectangle"); + + assert!(!is_open(&app, "rectangle")); + assert_eq!(drawn(&app), 1); + let doc = &app.session.doc().unwrap().doc; + let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert!((bounds.center().x - 120.0).abs() < 1e-6 && (bounds.center().y - 130.0).abs() < 1e-6); + } + + #[test] + fn tool_options_can_be_confirmed_after_switching_documents() { + let (mut app, mut fx) = shown(); + open_options(&mut app, "lineSegment").unwrap(); + set(&app, &fx, "lineSegment", "length", json!(72.0)).unwrap(); + app.run("file.new", json!({"width": 350, "height": 200})).unwrap(); + + press_ok(&mut app, &mut fx, "lineSegment"); + + assert!(!is_open(&app, "lineSegment")); + assert_eq!(drawn(&app), 0); + assert_eq!(app.session.tool_options_of("lineSegment")["length"], json!(72.0)); + } + #[test] fn spiral_click_dialog_uses_and_updates_tool_options() { let (mut app, mut fx) = shown(); diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index e0040bb228..cb58f856a7 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -85,6 +85,8 @@ impl StripKind { pub(crate) struct Strip { /// Which command the strip previews. pub kind: StripKind, + /// The drawing whose selection and preview the strip uses. + document: Option<(u64, u64)>, /// The slider's value, 0 to 100. pub level: f64, /// The selection's document bounds when the strip opened, so the strip stays put while the @@ -99,6 +101,18 @@ pub(crate) struct Strip { } impl Strip { + fn in_source(&self, app: &VectorcraftApp) -> bool { + self.document == app.session.active().map(|doc| (doc.uid, doc.reverts)) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.in_source(app) + && app.session.active().and_then(|doc| doc.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == self.kind.cmd()) + { + self.preview.cancel(app); + } + } + /// The slider's level, a whole number from 0 to 100. fn level(&self) -> f64 { if self.level.is_finite() { self.level.round().clamp(0.0, 100.0) } else { self.kind.default_level() } @@ -124,10 +138,17 @@ pub(crate) fn opening_level(app: &VectorcraftApp, kind: StripKind) -> f64 { /// Opens the strip of `kind`, replacing (and cancelling the preview of) one that is open. pub(crate) fn open(app: &mut VectorcraftApp, kind: StripKind) { if let Some(old) = app.object_dialogs.strip.take() { - old.preview.cancel(app); + old.cancel(app); } - let strip = - Strip { kind, level: opening_level(app, kind), bounds: app.selection_bounds(), open: true, auto: None, preview: LivePreview::default() }; + let strip = Strip { + kind, + document: app.session.active().map(|doc| (doc.uid, doc.reverts)), + level: opening_level(app, kind), + bounds: app.selection_bounds(), + open: true, + auto: None, + preview: LivePreview::default(), + }; app.object_dialogs.strip = Some(strip); } @@ -158,6 +179,9 @@ pub(super) fn auto_of(app: &mut VectorcraftApp, kind: StripKind) -> Result Result { return Err(not_open(StripKind::Simplify)); } let Some(strip) = app.object_dialogs.strip.take() else { return Err(not_open(StripKind::Simplify)) }; + if !strip.in_source(app) { + return Err(not_open(StripKind::Simplify)); + } let tolerance = simplify_level_tolerance(strip.level()); - strip.preview.cancel(app); + strip.cancel(app); // PLAN: assumed `path_ops::open_simplify(app: &mut VectorcraftApp, tolerance: f64)` returning `()`. super::path_ops::open_simplify(app, tolerance); Ok(json!({ "tolerance": tolerance })) @@ -202,6 +229,9 @@ fn anchor_rect(view: &CanvasView, bounds: Option) -> ScreenRect { /// the canvas body. pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasView) { let Some(mut strip) = app.object_dialogs.strip.take() else { return }; + if !strip.in_source(app) { + return; + } let kind = strip.kind; let anchor = anchor_rect(view, strip.bounds); let (mut level, mut open) = (strip.level, strip.open); @@ -226,7 +256,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasVie strip.open = open; let result = match shown.output.closed { Some(CloseReason::Escape) => { - strip.preview.cancel(app); + strip.cancel(app); return; } Some(_) => { diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index c916cc46d0..aaf3021f6d 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -16,6 +16,8 @@ //! `__list` (the filters listed, pushed by [`pump`]), and with an applied effect `__index`, //! `__item` and `missing` (the name of a deleted filter the effect names). +use std::sync::Arc; + use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::host::{PickRequest, Picked}; use craft::ui::buttons::Button; @@ -47,6 +49,32 @@ const LISTING: &str = "__list"; /// The rows the filter list shows before it scrolls. const LIST_ROWS: u16 = 7; +struct Opening { + document: u64, + reverts: u64, +} + +impl Opening { + fn check(&self, app: &VectorcraftApp) -> Result<(), String> { + let Some(doc) = app.session.active().filter(|doc| doc.uid == self.document) else { + return Err(tl!("Return to the original drawing to edit its SVG filters").into()); + }; + if doc.reverts != self.reverts { + return Err(tl!("Reopen Apply SVG Filter after reverting the drawing").into()); + } + Ok(()) + } +} + +fn opening_id() -> egui::Id { + egui::Id::unique((KIND, "opening")) +} + +fn opening(app: &VectorcraftApp) -> Option> { + with_dialog(app, |_| ())?; + app.ui_ctx.as_ref()?.data(|d| d.get_temp(opening_id())) +} + /// The dialog's heading. fn heading() -> String { tl!("Apply SVG Filter…").trim_end_matches('…').to_string() @@ -252,9 +280,8 @@ fn code_row(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut craft::ui::p /// the default's code or with nothing; when neither has its name, the name shown above the list if /// the filter was deleted, or else its code open as a new filter. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - if app.session.active().is_none() { - return Err("no document open".into()); - } + let doc = app.session.active().ok_or("no document open")?; + let source = Arc::new(Opening { document: doc.uid, reverts: doc.reverts }); let mut fields = json!({ "selected": "", "code": "", "editing": "", "__action": "" }); if let Some(k) = p.get("index").and_then(Value::as_u64) { let mut q = json!({}); @@ -289,7 +316,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let pairs = fields.as_object().into_iter().flatten().map(|(k, v)| (k.clone(), field_value(v.clone()))); let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::from_pairs(pairs), build); - crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields)).ok_or("no window")?; + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { + let source = opening(app).ok_or("the SVG Filter dialog is gone")?; + source.check(app)?; + confirm(app, &result.fields) + }) + .ok_or("no window")?; + ctx.data_mut(|d| d.insert_temp(opening_id(), source)); Ok(Value::Null) } @@ -337,6 +370,15 @@ fn set(app: &mut VectorcraftApp, fields: &[(&str, Value)]) { /// Each frame: pushes the listed filters into the dialog (the build closure has no app) and runs the /// button pressed, once. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(source) = opening(app) else { return }; + if let Err(error) = source.check(app) { + let has_action = with_dialog(app, |d| !text(d.fields(), ACTION).is_empty()).unwrap_or_default(); + if has_action { + set(app, &[(ACTION, json!(""))]); + app.status(error); + } + return; + } let listing = listing(app); let taken = with_dialog(app, |d| { if json_field(d.fields(), LISTING).as_ref() != Some(&listing) { @@ -374,7 +416,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Ok(()) } "import" => { - ask_import(app); + ask_import(app, Some(source)); Ok(()) } _ => Ok(()), @@ -407,7 +449,7 @@ pub(crate) fn menu_items(names: &[String]) -> Vec { /// `ui.importSvgFilter {}`: add the filters of an SVG file the user picks to the active document. /// The answer is `{pending: "fileDialog"}`; the continuation runs the import. pub fn import_file(app: &mut VectorcraftApp) -> Result { - Ok(ask_import(app)) + Ok(ask_import(app, None)) } /// The extensions of the SVG files Import… reads. @@ -420,24 +462,33 @@ pub(crate) fn pick() -> PickRequest { /// Asks for an SVG file; once picked, its filters are added to the document and the first one /// added is selected in the dialog when it is open. -fn ask_import(app: &mut VectorcraftApp) -> Value { - file_asks::ask(app, pick(), Owner::Document, |app, picked| { - let params = match picked { - // The browser answers with the file's contents, not a path. - Picked::Contents(files) => { - let (_, bytes) = files.first().ok_or("cancelled")?; - json!({ "svg": String::from_utf8_lossy(bytes) }) +fn ask_import(app: &mut VectorcraftApp, source: Option>) -> Value { + let dialog = source.clone().or_else(|| opening(app).filter(|opening| opening.check(app).is_ok())); + file_asks::ask_while( + app, + pick(), + Owner::Document, + move |app| source.is_none_or(|source| source.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &source))), + move |app, picked| { + let params = match picked { + // The browser answers with the file's contents, not a path. + Picked::Contents(files) => { + let (_, bytes) = files.first().ok_or("cancelled")?; + json!({ "svg": String::from_utf8_lossy(bytes) }) + } + other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }), + }; + let r = app.run("svgFilter.import", params)?; + let added = r["added"].as_array().map_or(0, Vec::len); + app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[])); + if let Some(first) = r["added"].get(0) + && dialog.is_some_and(|dialog| dialog.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(¤t, &dialog))) + { + set(app, &[(SELECTED, first.clone())]); } - other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }), - }; - let r = app.run("svgFilter.import", params)?; - let added = r["added"].as_array().map_or(0, Vec::len); - app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[])); - if let Some(first) = r["added"].get(0) { - set(app, &[(SELECTED, first.clone())]); - } - Ok(r) - }) + Ok(r) + }, + ) } #[cfg(test)] @@ -493,6 +544,78 @@ mod tests { assert!(open_dialogs(&app).is_empty()); } + #[test] + fn svg_filter_ok_leaves_the_other_drawings_artwork_alone() { + let mut app = self::app(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let id = rect(&mut app); + app.run("file.new", json!({"width": 120, "height": 120})).unwrap(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + assert_eq!(rect(&mut app), id); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open(&mut app, &json!({})).unwrap(); + activate(&mut app, 1); + let dialog = dialog_id(KIND); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert!(effects(&app, id).is_empty()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)[SELECTED], "Shift"); + + activate(&mut app, 0); + answer_dialog(&mut app, dialog, &[], true); + assert_eq!(effects(&app, id)[0].params["name"], "Shift"); + } + + #[test] + fn reopened_svg_filter_uses_the_replacement_openings_drawing() { + let mut app = self::app(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let first = rect(&mut app); + open(&mut app, &json!({})).unwrap(); + app.run("file.new", json!({"width": 120, "height": 120})).unwrap(); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let second = rect(&mut app); + open(&mut app, &json!({})).unwrap(); + answer_dialog(&mut app, dialog_id(KIND), &[(SELECTED, json!("Shift"))], true); + assert_eq!(effects(&app, second).first().map(|f| f.params["name"].clone()), Some(json!("Shift"))); + assert!(open_dialogs(&app).is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(effects(&app, first).is_empty()); + } + + #[test] + fn an_svg_filter_draft_cannot_apply_after_reverting_its_drawing() { + let mut app = self::app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("svg-filter-drawing-revert"); + let path = dir.join("drawing.vectorcraft"); + app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap(); + let object = rect(&mut app); + app.run("file.saveAs", json!({"path": path})).unwrap(); + rect(&mut app); + app.run("select.set", json!({"ids": [object]})).unwrap(); + let original = app.session.doc().unwrap(); + let (uid, generation) = (original.uid, original.reverts); + open(&mut app, &json!({})).unwrap(); + let dialog = dialog_id(KIND); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.doc().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + app.run("select.set", json!({"ids": [object]})).unwrap(); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert!(effects(&app, object).is_empty()); + + open(&mut app, &json!({})).unwrap(); + answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true); + assert_eq!(effects(&app, object).first().map(|effect| effect.params["name"].clone()), Some(json!("Shift"))); + } + #[test] fn the_dialog_draws_its_filters_and_buttons() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 61c702c3e3..470f78e55e 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -100,10 +100,14 @@ fn rows(name: &str) -> Vec { /// edited), applies the fields to it; `keep_art` leaves the selection as ordinary art for a new one; /// `opened` are the guides the dialog opened with. fn open_dialog(app: &mut VectorcraftApp, fields: DialogFields, edit: Option, keep_art: bool, opened: [f64; 4]) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let ctx = app.ui_ctx.clone().ok_or("no window")?; let name = fields.text("name").unwrap_or_default().to_string(); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name))); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> { + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("This symbol belongs to the document that opened the dialog.").to_owned()); + } let f = &result.fields; let name = f.text("name").unwrap_or_default().trim().to_string(); if name.is_empty() { @@ -187,3 +191,38 @@ fn merge(into: &mut Value, extra: Value) { a.extend(b); } } + +#[cfg(test)] +mod document_tests { + use craft::ui::dialog::dialog_id; + use vectorcraft_engine::Session; + + use super::super::tests_warp::{accept, set, windowed}; + use super::*; + + #[test] + fn editing_symbol_options_does_not_rename_another_drawings_symbol() { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + for side in [30, 50] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": side, "height": side})).unwrap(); + app.run("symbol.new", json!({"name": "Badge"})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + open_edit(&mut app, Some("Badge")).unwrap(); + let id = dialog_id(KIND); + set(&app, id, "name", json!("Source badge")); + activate(&mut app, 1); + accept(&mut app, id); + assert_eq!(app.session.active().unwrap().doc, other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + activate(&mut app, 0); + accept(&mut app, id); + assert!(app.session.active().unwrap().doc.symbols.iter().any(|symbol| symbol.name == "Source badge")); + } +} diff --git a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs index 8111cfe239..edb0fb5bf6 100644 --- a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs +++ b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs @@ -38,6 +38,7 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Tate-chu-yoko Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document")?.uid; let (up, right) = crate::panels::character::shared_tcy_offsets(app); let mut fields = DialogFields::new(); for (key, v) in KEYS.into_iter().zip([up, right]) { @@ -52,6 +53,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if p.is_empty() { return Ok(()); } + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned()); + } crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) }) .ok_or("no window")?; @@ -133,6 +137,42 @@ mod tests { assert_eq!(offsets(&app, id), [(0.0, 0.0)]); } + #[test] + fn tate_chu_yoko_settings_refuses_confirmation_in_another_drawing() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, source_id) = app(); + let source_before = offsets(&app, source_id); + let source_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyUpDown", json!(7)); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the edit waits for the app"); + + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let target_id = app.run("text.create", json!({"x": 10, "y": 50, "text": "other"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [target_id]})).unwrap(); + let target_before = offsets(&app, target_id); + let target_undo = app.session.active().unwrap().history.undo.len(); + driver::pump(&mut app); + assert_eq!( + (offsets(&app, target_id), app.session.active().unwrap().history.undo.len()), + (target_before, target_undo), + "the other drawing's text and undo history stay untouched" + ); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(driver::fields(&app).number("tcyUpDown"), Some(7.0)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [source_id]})).unwrap(); + assert_eq!(offsets(&app, source_id), source_before); + assert!(crate::dialogs::tests::confirm(&mut app), "confirm the retained edit on its original drawing"); + assert_eq!(offsets(&app, source_id), [(7.0, 0.0)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1); + } + /// While the Type tool edits text, OK sets the selected characters. #[test] fn tate_chu_yoko_settings_dialog_sets_the_range_the_type_tool_selects() { diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 016cf865aa..7ab85da4ae 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -344,6 +344,40 @@ fn a_bad_range_keeps_export_as_open() { assert!(written.borrow().is_empty()); } +#[test] +fn export_as_opened_without_a_drawing_does_not_take_a_later_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + save_panel(&mut app, |_| Some("/out/untitled.png".into())); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["format"], "png"); + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let error = try_confirm(&mut app).expect_err("the old Export As draft has no source drawing"); + assert!(error.contains("Open Export As from the drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty())); +} + +#[test] +fn export_as_waits_for_the_drawing_that_opened_it() { + let (mut app, written) = app(2); + app.run("file.exportAs", json!({"format": "png", "useArtboards": true, "range": "1"})).unwrap(); + app.run("file.new", json!({ "width": 200, "height": 100 })).unwrap(); + let error = try_confirm(&mut app).expect_err("Export As must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["range"], "1"); + PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty())); + app.run("document.activate", json!({ "index": 0 })).unwrap(); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + confirm(&mut app); + assert_eq!(written.borrow().len(), 1); + assert_eq!(&written.borrow()[0].1[16..20], 60u32.to_be_bytes()); +} + /// Each format's Export As continues in its options dialog, writes nothing before that dialog's OK, and then /// writes its files: (case, artboards, Export As params, the options' key, the files, the pages of a PDF, the /// page size of a PDF of the art's bounds). diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index e551e71627..e9a2166fa7 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -179,6 +179,34 @@ fn simplify_slider_escape_puts_the_paths_back() { assert_eq!(anchor_count(&app), 20); } +#[test] +fn path_sliders_close_on_a_drawing_switch() { + for (kind, command) in + [(simplify_slider::StripKind::Simplify, "object.path.simplify"), (simplify_slider::StripKind::Smooth, "object.path.smooth")] + { + let mut app = app_with_dense_path(); + let original = app.session.doc().unwrap().doc.clone(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": 120.0 + (i % 2) as f64 * 0.2})).collect(); + let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 19]]})).unwrap(); + let second = app.session.doc().unwrap().doc.clone(); + app.run("document.activate", json!({"index": 0})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + + app.run("document.activate", json!({"index": 1})).unwrap(); + assert!(simplify_slider::auto_of(&mut app, kind).is_err(), "Auto must not use the second drawing"); + frame(&mut app, vec![]); + assert!(!simplify_slider::showing_of(&app, kind)); + assert!(!app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc, second); + assert_eq!(app.session.documents()[0].doc, original); + } +} + /// The Simplify slider stays where it opened, under the paths as they were, while the preview changes their bounds, so a /// drag doesn't move the rail under the pointer. #[test] @@ -265,3 +293,36 @@ fn simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path() assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len + 1); kept(&app, "the dialog"); } + +#[test] +fn path_sliders_close_when_file_revert_restores_the_artwork() { + for (kind, command) in + [(simplify_slider::StripKind::Simplify, "object.path.simplify"), (simplify_slider::StripKind::Smooth, "object.path.smooth")] + { + let mut app = app_with_dense_path(); + let id = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("path-slider-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap(); + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 19]]})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 19]]})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + frame(&mut app, vec![]); + assert!(!simplify_slider::showing_of(&app, kind), "{command}"); + assert!(!app.session.in_interaction()); + assert_eq!(app.session.active().unwrap().doc, restored); + + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + assert!(simplify_slider::showing_of(&app, kind)); + assert!(app.session.in_interaction()); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 5dec578456..392e77a4ed 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -665,3 +665,31 @@ fn package_save_first_does_not_save_a_different_drawing() { crate::tests::picks::poll(&mut app, &ctx); assert_eq!(picker.requests().len(), 1, "approval in the opening drawing starts Save As"); } + +#[test] +fn held_package_approval_does_not_write_output_after_revert() { + let dir = Folder::new("package-revert"); + let mut app = saved(&dir); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.session.execute("prefs.set", &json!({"values": {"backgroundExport": false, "backgroundSave": false}})).unwrap(); + let before = std::fs::read(dir.path("card.vectorcraft")).unwrap(); + let out = dir.path("out"); + let output = std::path::Path::new(&out).join("card Folder"); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + package_dialog(&mut app, &out); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, package_id()))); + assert_eq!(held_state(&app), Some(HeldOk::Waiting)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(!output.exists(), "the old approval writes no output"); + assert_eq!(std::fs::read(dir.path("card.vectorcraft")).unwrap(), before); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + close_all(&app); + package_dialog(&mut app, &out); + assert!(press_ok(&mut app)); + assert!(output.join("card.vectorcraft").exists()); +} diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index d7d5249f6a..abbd37dfb7 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -311,6 +311,33 @@ fn the_presets_manager_imports_browser_contents_and_desktop_paths() { assert_eq!(field(&app, "selected"), json!("Desktop")); } +#[test] +fn a_late_perspective_import_leaves_the_reopened_managers_selection_alone() { + use super::perspective_presets::{self, Action, KIND}; + use vectorcraft_engine::cmd::perspgrid::PRESET_FORMAT; + + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + let ctx = window(&app); + let preset = |name: &str| json!({"format": PRESET_FORMAT, "presets": [{"name": name}]}).to_string(); + app.run("ui.perspectivePresetsDialog", json!({})).unwrap(); + perspective_presets::run(&mut app, Action::Import, "[1P-Normal View]").unwrap(); + assert_eq!(picker.requests().len(), 1); + assert!(host(&app, |h| h.cancel_by_id(&ctx, dialog_id(KIND)))); + let selected = "[2P-Normal View]"; + app.run("ui.perspectivePresetsDialog", json!({"selected": selected})).unwrap(); + picker.answer_contents(&[("First.vcperspective", preset("First").as_bytes())]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("First").is_some(), "the file still imports into saved presets"); + assert_eq!(field(&app, "selected"), json!(selected), "the reopened manager keeps its choice"); + + perspective_presets::run(&mut app, Action::Import, selected).unwrap(); + picker.answer_contents(&[("Second.vcperspective", preset("Second").as_bytes())]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("Second").is_some()); + assert_eq!(field(&app, "selected"), json!("Second"), "the current manager selects its own import"); +} + #[test] fn perspective_preset_menus_list_the_views_of_each_type() { let app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index af68809f46..1648e86648 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -61,6 +61,51 @@ fn open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn the_first_artboard_is_clickable_on_open_in_a_short_web_viewport() { + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for view in ["grid", "list"] { + let (mut app, log) = app(2, true); + app.run("artboard.rename", json!({"indices": [0], "name": "First audit board"})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 500.0)); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.2; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + open(&mut app); + set(&mut app, "view", json!(view)); + for _ in 0..5 { + draw(&mut app, vec![]); + } + let out = draw(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let bounds = nodes + .iter() + .find_map(|(_, node)| { + if node.role() == Role::CheckBox && node.label().is_some_and(|label| label.contains("First audit board")) { + node.bounds() + } else { + None + } + }) + .expect("the first artboard has a checkbox"); + let pos = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + + assert_eq!(field(&app, "boards"), json!([true, true])); + draw(&mut app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + assert_eq!(field(&app, "boards"), json!([false, true]), "the first {view} checkbox should be clickable without scrolling"); + assert!(log.borrow().is_empty()); + } +} + /// Presses OK, which the dialog refuses or does not offer: it stays open. fn stays_open(app: &mut VectorcraftApp) { let _ = try_confirm(app); diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index f6e3503592..d97375e034 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -66,6 +66,7 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool app.status(tl!("no document").to_string()); return true; }; + let document = st.uid; let vars = st.doc.variables.clone(); let mut fields = DialogFields::new(); match id { @@ -128,18 +129,19 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool let rows = params(&vars, &build_id, fields); ParamDialog::command(KEY, Label::from(title.clone()), rows) }); - crate::dialogs::host::open_held(app, dialog, move |app, result| ok(app, &command, result)); + crate::dialogs::host::open_held(app, dialog, move |app, result| ok(app, document, &command, result)); true } /// Runs `command` with what the confirmed `result` says. A data set dialog answers the error, which /// keeps it open with what was typed (a taken or empty name); any other command's error goes to the /// status line and the dialog closes. -fn ok(app: &mut VectorcraftApp, command: &str, result: &ParamResult) -> Result<(), String> { - let Some(vars) = app.session.active().map(|st| st.doc.variables.clone()) else { - return Err(tl!("no document").to_string()); +fn ok(app: &mut VectorcraftApp, document: u64, command: &str, result: &ParamResult) -> Result<(), String> { + let Some(st) = app.session.active().filter(|st| st.uid == document) else { + return Err(tl!("These changes belong to the document this dialog was opened for.").to_owned()); }; - let Err(e) = app.run(command, params_of(command, result, &vars)) else { return Ok(()) }; + let params = params_of(command, result, &st.doc.variables); + let Err(e) = app.run(command, params) else { return Ok(()) }; if matches!(command, "dataset.new" | "dataset.set") { return Err(e); } @@ -440,6 +442,37 @@ mod tests { assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true})); } + #[test] + fn a_data_set_edit_stays_with_the_drawing_that_opened_it() { + let mut app = app_with_variables(); + app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Source"}})).unwrap(); + app.run("file.new", json!({"width": 240, "height": 220})).unwrap(); + app.run("variable.define", json!({"name": "Title", "kind": "text"})).unwrap(); + app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Other"}})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = app.run("dataset.list", json!({})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + assert!(open(&mut app, "dataset.set", None)); + set(&mut app, "name", json!("Revised")); + set(&mut app, &value_key("Title"), json!("New value")); + activate(&mut app, 1); + ok(&mut app); + + assert_eq!(app.run("dataset.list", json!({})).unwrap(), other); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&app)); + assert_eq!(fields(&app)[value_key("Title")], "New value"); + + activate(&mut app, 0); + ok(&mut app); + assert!(!is_open(&app)); + let source = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(source["datasets"][0]["name"], "Revised"); + assert_eq!(source["datasets"][0]["values"]["Title"], json!({"text": "New value"})); + } + #[test] fn edit_data_sets_name_field_renames_the_row_it_edits() { let mut app = app_with_variables(); diff --git a/crates/ui-egui/src/dialogs/warichu.rs b/crates/ui-egui/src/dialogs/warichu.rs index cbce874539..123d52f407 100644 --- a/crates/ui-egui/src/dialogs/warichu.rs +++ b/crates/ui-egui/src/dialogs/warichu.rs @@ -68,6 +68,7 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Warichu Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let document = app.session.active().ok_or("no document")?.uid; let shared = crate::panels::character::shared_warichu(app); let mut fields = DialogFields::new(); set_shared(&mut fields, KEYS[0], shared.lines.map(i64::from)); @@ -83,6 +84,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if p.is_empty() { return Ok(()); } + if !app.session.active().is_some_and(|active| active.uid == document) { + return Err(tl!("Warichu Settings can only change the document where it was opened.").to_owned()); + } crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) }) .ok_or("no window")?; @@ -260,6 +264,42 @@ mod tests { assert_eq!(params(&fields, &initial).get("warichuGap"), Some(&json!(MAX_WARICHU_GAP))); } + #[test] + fn warichu_settings_refuses_confirmation_in_another_drawing() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, source_id) = app(); + let source_before = settings(&app, source_id); + let source_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.warichuSettings", json!({})).unwrap(); + driver::set(&mut app, "warichuLines", json!(4)); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the edit waits for the app"); + + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let target_id = app.run("text.create", json!({"x": 10, "y": 50, "text": "other"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [target_id]})).unwrap(); + let target_before = settings(&app, target_id); + let target_undo = app.session.active().unwrap().history.undo.len(); + driver::pump(&mut app); + assert_eq!( + (settings(&app, target_id), app.session.active().unwrap().history.undo.len()), + (target_before, target_undo), + "the other drawing's text and undo history stay untouched" + ); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(driver::fields(&app).number("warichuLines"), Some(4.0)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [source_id]})).unwrap(); + assert_eq!(settings(&app, source_id), source_before); + assert!(crate::dialogs::tests::confirm(&mut app), "confirm the retained edit on its original drawing"); + assert_eq!(settings(&app, source_id), [(false, 4, 0.0, 50.0, WarichuAlign::Auto)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1); + } + /// While the Type tool edits text, OK sets the selected characters. #[test] fn warichu_settings_dialog_sets_the_range_the_type_tool_selects() { diff --git a/crates/ui-egui/src/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index 1165d68845..4deae1af89 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -354,8 +354,8 @@ impl Target { struct Form { /// The path whose stroke carries the points. path: u64, - /// The uid of the document the dialog opened in. - doc: Option, + /// The document's UID and revert count when the dialog opened. + doc: Option<(u64, u64)>, /// Adjust Adjoining Width Points. adjust: bool, target: Target, @@ -684,8 +684,9 @@ impl StackDialog for WidthPointDialog { /// Adjoining adjustment defaults to false. Either half of a discontinuous point opens both. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_u64).ok_or("give the path `id`")?; - let doc = &app.session.active().ok_or("no document")?.doc; - let id = vectorcraft_tools::distort::stroke_owner(doc, NodeId(id)).0; + let active = app.session.active().ok_or("no document")?; + let document = (active.uid, active.reverts); + let id = vectorcraft_tools::distort::stroke_owner(&active.doc, NodeId(id)).0; let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); let mut index = match p.get("index").filter(|v| !v.is_null()) { Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("no such width point")?), @@ -695,7 +696,6 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { return Err("give only one of `index`, `indices` and `t`".into()); } let adjust = p.get("adjustAdjoining").and_then(Value::as_bool).unwrap_or(false); - let uid = app.session.active().map(|st| st.uid); let mut several = None; if let Some(indices) = p.get("indices").filter(|v| !v.is_null()) { match target(app, id, indices)? { @@ -711,7 +711,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } None => one_point(app, id, index, p)?, }; - let dialog = WidthPointDialog::new(Form { path: id, doc: uid, adjust, target }, stroke_lengths(app)); + let dialog = WidthPointDialog::new(Form { path: id, doc: Some(document), adjust, target }, stroke_lengths(app)); app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(Value::Null) } @@ -749,10 +749,11 @@ fn one_point(app: &VectorcraftApp, id: u64, index: Option, p: &Value) -> Ok(Target::One { index, t, at, sides: Sides::of(l, r), out, single: Single::None }) } -/// Whether the document the dialog opened in (`doc`) is still the active one. -fn same_document(app: &VectorcraftApp, doc: Option) -> Result<(), String> { +/// Whether the document the dialog opened in is active and has not been reloaded by Revert. +fn same_document(app: &VectorcraftApp, doc: Option<(u64, u64)>) -> Result<(), String> { match (doc, app.session.active()) { - (Some(uid), Some(st)) if st.uid == uid => Ok(()), + (Some((uid, reverts)), Some(st)) if (st.uid, st.reverts) == (uid, reverts) => Ok(()), + (Some((uid, _)), Some(st)) if st.uid == uid => Err(tl!("The document was reverted. Reopen Width Point Edit.").to_owned()), _ => Err("no such width point".into()), } } diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index 1c9522319a..5400a3449a 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -851,6 +851,57 @@ fn second_document(app: &mut VectorcraftApp, id: u64) { app.run("stroke.widthProfile.set", json!({"ids": [other], "points": points})).unwrap(); } +struct SavedFile(std::path::PathBuf); + +impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +fn exercise_reverted_point(prospective: bool) { + let (mut app, id) = if prospective { creation_app() } else { app() }; + app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-width-point-revert-{}-{prospective}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + let saved = points(&app, id); + let state = app.session.active().unwrap(); + let (document, reverts) = (state.uid, state.reverts); + app.run("shape.rectangle", json!({"x": 30, "y": 30, "width": 10, "height": 10})).unwrap(); + let target = if prospective { json!({"id": id, "t": 0.4}) } else { json!({"id": id, "index": 1}) }; + app.run("ui.widthPointEdit", target.clone()).unwrap(); + set(&app, "side1", json!(7)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (document, reverts + 1)); + assert_eq!(points(&app, id), saved, "the reloaded path still looks like the original target"); + let undo = state.history.undo.len(); + let accepted = ok(&mut app); + + assert_eq!(points(&app, id), saved, "the old Width Point draft leaves the reloaded path alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(accepted.is_err() && is_open(&app)); + cancel(&app); + app.run("ui.widthPointEdit", target).unwrap(); + set(&app, "side1", json!(7)); + ok(&mut app).unwrap(); + assert_ne!(points(&app, id), saved); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); +} + +#[test] +fn existing_width_point_draft_cannot_edit_a_reverted_path() { + exercise_reverted_point(false); +} + +#[test] +fn prospective_width_point_draft_cannot_edit_a_reverted_path() { + exercise_reverted_point(true); +} + #[test] fn ok_and_delete_act_only_in_the_document_the_dialog_opened_in() { for opened in [json!({"indices": [1, 3]}), json!({"index": 2})] { diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 98464ba721..d3712ed83a 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -646,13 +646,25 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va } /// File → New from Template…: a template (or any readable file) as a new untitled document. Without -/// a path the open dialog starts in the Templates folder. On the web the browser's file picker -/// opens it (`.vctemplate`, `.ait` and template files open untitled there too). +/// a path the open dialog starts in the Templates folder. The browser supplies the picked file's +/// name and bytes for the same template loader. pub fn new_from_template(app: &mut VectorcraftApp, path: Option) -> Result { let Some(path) = path else { let filters = std::iter::once(("Templates", TEMPLATE_EXTS)).chain(fileio::builtin_open_filters()); let request = open_request("template", fileio::templates_dialog_folder(&app.session.prefs), filters); - return ask_open(app, request, Owner::Free, new_from_path); + return Ok(file_asks::ask(app, request, Owner::Free, |app, picked| match picked { + Picked::Contents(files) => { + let (name, bytes) = files.into_iter().next().ok_or("cancelled")?; + if let Err(error) = open_template(app, &name, &bytes, None) { + report_open_error(app, &name, &error); + } + Ok(Value::Null) + } + picked => { + let path = picked.first_path().ok_or("cancelled")?; + new_from_path(app, path.to_string_lossy().into_owned()) + } + })); }; new_from_path(app, path) } @@ -660,7 +672,11 @@ pub fn new_from_template(app: &mut VectorcraftApp, path: Option) -> Resu /// [`new_from_template`] for the file at `path`. fn new_from_path(app: &mut VectorcraftApp, path: String) -> Result { let bytes = read(app, &path)?; - let r = fileio::open_template(&mut app.session, &path, &bytes, Some(&path)).map_err(|e| e.to_string())?; + open_template(app, &path, &bytes, Some(&path)) +} + +fn open_template(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<&str>) -> Result { + let r = fileio::open_template(&mut app.session, name, bytes, path).map_err(|e| e.to_string())?; opened(app, &r); Ok(r) } diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 98f082b312..1c82a3a7d7 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -877,7 +877,7 @@ pub(super) fn ask_before_losing(app: &mut VectorcraftApp, path: &str, command: & if command != "file.save" { params["path"] = json!(path); } - dialogs::confirm::ask(app, &message, &detail, command, params); + dialogs::confirm::ask_in_document(app, &message, &detail, command, params); Some(json!({ "pending": dialogs::confirm::KIND })) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d675cec18d..2df90dba90 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -274,7 +274,7 @@ pub struct VectorcraftApp { /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, /// The document whose settings the open Document Setup dialog edits. - pub(crate) document_setup_source: Option, + pub(crate) document_setup_source: Option<(u64, u64)>, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one /// step however many values it sets. pub(crate) edit_scopes: HashMap, @@ -290,8 +290,8 @@ pub struct VectorcraftApp { pub(crate) export_dialogs: dialogs::export_host::ExportDialogs, /// The document and selection used by each open slice dialog. pub(crate) slice_dialogs: dialogs::slices::SliceDialogs, - /// The drawing the open Package dialog saves and collects. - pub(crate) package_document: Option, + /// The drawing and loaded contents the open Package dialog saves and collects. + pub(crate) package_document: Option<(u64, u64)>, /// Save for Web's renders and colour table. pub(crate) web_export: dialogs::save_for_web::WebExport, /// The Flattener Preview panel's model. @@ -321,7 +321,7 @@ pub struct VectorcraftApp { /// The Justification dialog, while it is open. pub(crate) justification: Option, /// The Bullets and Numbering dialog's live preview. - pub(crate) bullets_preview: dialogs::preview::LivePreview, + pub(crate) bullets_preview: Option, /// The paste that waits for the answer to its colour profile question. pub(crate) pending_paste: Option, /// The missing links' questions, while they are asked. diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4da3dcdc16..e4d6d5d1c1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1097,7 +1097,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorPicker", "Color Picker…", "", - "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", + "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard. Artboard preview and OK require the opening document to be active", ), ( "ui.sampleScreenColor", diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 8407b87dd8..7cc1efffd5 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -1,5 +1,6 @@ //! What panels drag onto art and onto each other. +use serde_json::{Value, json}; use vectorcraft_color::Paint; /// What panels drag onto art and onto each other. One payload type, so the canvas has one drop @@ -70,4 +71,20 @@ impl PanelDrag { _ => None, } } + + /// A named process swatch follows the source drawing's swatch. In another drawing its + /// captured process color applies without using a same-name swatch there. + pub(crate) fn paint_drop_params(&self, destination: Option) -> Option { + let Self::Paint { paint, params, rows, .. } = self else { return None }; + if params.is_null() { + return None; + } + if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color) + && destination.is_some_and(|uid| uid != rows.document) + && let Some(color) = paint.color() + { + return Some(json!({"color": crate::panels::color_json(&color), "keepModel": true})); + } + Some(params.clone()) + } } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index fe36fca6df..cbbd43bd93 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -790,9 +790,9 @@ fn takes_drop(mixed: (bool, bool), well: Well, drag: &PanelDrag) -> bool { /// Paints the fill (the primary well) or the stroke with the paint `drag` carries. fn drop_paint(app: &mut VectorcraftApp, well: Well, drag: &PanelDrag) { - if let PanelDrag::Paint { params, .. } = drag { + if let Some(params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) { let cmd = if well == Well::Primary { "paint.setFill" } else { "paint.setStroke" }; - app.run(cmd, params.clone()).ok(); + app.run(cmd, params).ok(); } } @@ -1085,6 +1085,33 @@ mod tests { assert_eq!(current_paints(&app).0.color().map(|c| c.to_hex()), Some("#00ff00".into())); } + #[test] + fn proxy_drops_keep_the_dragged_process_color_after_switching_documents() { + use crate::panel_drag::SwatchRows; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let name = "Shared Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap(); + let paint = source.doc.swatch(name).unwrap().paint.clone(); + let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let drag = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; + app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); + drop_paint(&mut app, Well::Primary, &drag); + assert_eq!(current_paints(&app).0, app.session.active().unwrap().doc.swatch(name).unwrap().paint); + + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + drop_paint(&mut app, Well::Primary, &drag); + drop_paint(&mut app, Well::Secondary, &drag); + assert_eq!(current_paints(&app), (paint.clone(), paint)); + assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination); + } + #[test] fn paint_params_roundtrip_shapes() { assert_eq!(paint_params(&Paint::None), json!({"none": true})); diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index 9672ee1c64..dd6981c763 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -20,7 +20,7 @@ //! `actionSet.read`), a Set Selection step as a Select Object step. use craft::automation::actions::{Action, ActionColor, ActionStep, ActionsFile}; -use craft::host::{PickKind, PickRequest}; // PLAN: assumed path of the host's picker types in the app's `craft` facade +use craft::host::{PickKind, PickRequest, Picked}; // PLAN: assumed path of the host's picker types in the app's `craft` facade use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -577,15 +577,20 @@ fn read_path(app: &mut VectorcraftApp, path: &str) -> Result { (None, Some(read)) => read(path)?, (None, None) => return Err("no file reader".into()), }; + read_bytes(app, path, &bytes) +} + +/// A desktop or browser file's contents, with its name used only as the unnamed set's fallback. +fn read_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8]) -> Result { if bytes.len() > MAX_SET_FILE { return Err("the action set file is larger than 8 MiB".into()); } - if is_aia(&bytes) { - return read_aia(app, json!({ "name": path, "dataBase64": vectorcraft_format::base64_encode(&bytes) })); + if is_aia(bytes) { + return read_aia(app, json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) })); } - let stem = std::path::Path::new(path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - let text = String::from_utf8(bytes).map_err(|_| "not an action set file")?; - let (name, actions) = read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?; + let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let text = std::str::from_utf8(bytes).map_err(|_| "not an action set file")?; + let (name, actions) = read_set(text, if stem.is_empty() { "Actions" } else { &stem })?; Ok(FileRead { name, actions, aia: None }) } @@ -613,8 +618,16 @@ fn read_file( let exts = [&[ACTIONS_EXT], vectorcraft_engine::cmd::actionset::EXTS].concat(); let request = PickRequest::open("actions").filter("Action sets", &exts); Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| { - let path = picked.first_path().ok_or("cancelled")?; - let read = read_path(app, &path.to_string_lossy())?; + let read = match picked { + Picked::Contents(files) => { + let (name, bytes) = files.into_iter().next().ok_or("cancelled")?; + read_bytes(app, &name, &bytes)? + } + other => { + let path = other.first_path().ok_or("cancelled")?; + read_path(app, &path.to_string_lossy())? + } + }; then(app, read) })) } diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index a2f5247c91..d83e306f05 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -203,6 +203,29 @@ fn options_with_a_field_that_is_not_an_index_change_nothing() { } } +#[test] +fn stale_action_options_do_not_rename_the_copy_that_took_its_index() { + let mut app = app_with_sets(); + crate::dialogs::action_set_options::open_action(&mut app, 1, 1); + set_dialog::(&mut app, "name", json!("Wrong target")); + assert_eq!(app.run(DUPLICATE, json!({"set": 1, "action": 0})).unwrap(), json!({"set": 1, "action": 1})); + let before = action_names(&app, 1); + assert!(confirm_dialog::(&mut app).is_err(), "an index taken by a copy must refuse OK"); + assert!(is_open::(&app)); + assert_eq!(action_names(&app, 1), before); +} + +#[test] +fn stale_set_options_do_not_rename_the_set_that_took_its_index() { + let mut app = app_with_sets(); + crate::dialogs::action_set_options::open(&mut app, 1); + set_dialog::(&mut app, "name", json!("Wrong target")); + app.ui.actions.delete_set("Mine").unwrap(); + assert!(confirm_dialog::(&mut app).is_err(), "an index taken by the next set must refuse OK"); + assert!(is_open::(&app)); + assert_eq!(set_names(&app), ["Default Actions", "Other"]); +} + /// `ui.actionSet.delete` moves the panel's selected action down with its set, and clears it /// when its set is deleted. #[test] diff --git a/crates/ui-egui/src/panels/actions/tests_files.rs b/crates/ui-egui/src/panels/actions/tests_files.rs index 79bad2c42e..a88cbc36fe 100644 --- a/crates/ui-egui/src/panels/actions/tests_files.rs +++ b/crates/ui-egui/src/panels/actions/tests_files.rs @@ -7,6 +7,52 @@ use super::tests_support::*; use super::*; use crate::dialogs::action_batch::BatchDialog; +#[test] +fn browser_picks_load_and_replace_action_sets_without_a_file_reader() { + let native = json!({ + "format": "vcactions", "version": 1, "name": "Browser", + "actions": [{"name": "Group", "steps": [{"command": "object.group", "params": {}}]}] + }) + .to_string(); + let mut aia = aia_text("", &[("Group", &[("group", true)])]).into_bytes(); + // AIA's text encoding is not required to be UTF-8. + aia.extend(b"/note (\xFF)\n"); + for command in [LOAD_SET, REPLACE_SET] { + for (name, bytes) in [("Browser.vcactions", native.as_bytes()), ("Browser.aia", aia.as_slice())] { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let picker = crate::tests::picks::scripted(&mut app); + app.services.read = None; + app.services.read_head = None; + let before = saved_sets(&app); + let undo = undo_steps(&app); + app.run(command, json!({})).unwrap(); + picker.cancel(); + crate::file_asks::poll(&mut app); + assert_eq!(saved_sets(&app), before, "cancel keeps the sets"); + for invalid in [vec![0xff], vec![b' '; files::MAX_SET_FILE + 1]] { + app.run(command, json!({})).unwrap(); + picker.answer_contents(&[(name, &invalid)]); + crate::file_asks::poll(&mut app); + assert_eq!(saved_sets(&app), before, "invalid picked bytes keep the sets"); + assert!(!app.ui.status.is_empty(), "a rejected file reports why"); + } + app.run(command, json!({})).unwrap(); + picker.answer_contents(&[(name, bytes)]); + crate::file_asks::poll(&mut app); + let names = set_names(&app); + assert_eq!(names.last().map(String::as_str), Some("Browser")); + if command == REPLACE_SET { + assert_eq!(names, ["Browser"]); + } else { + assert!(names.len() > 1, "Load keeps existing sets"); + } + assert_eq!(set_actions(&app, names.len() - 1)[0].steps, [ActionStep::new("object.group", json!({}))]); + assert_eq!(undo_steps(&app), undo, "loading actions does not edit the drawing"); + } + } +} + #[test] fn defaults_are_valid_commands() { for a in default_sets().actions { diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 3311617585..6f670ae2fd 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -944,7 +944,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { let filters = library_panel::library_pick_filters(BrushLibraries::KIND); - library_panel::pick_library_file(app, path, filters, |app, path| load_library(app, json!({ "path": path }))) + library_panel::pick_library_file(app, path, filters, load_library) } /// The id prefix of the Window → Brush Libraries → User Defined slots. diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 1d089378d3..cf42d21f00 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1041,7 +1041,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { let filters = library_panel::library_pick_filters(GraphicStyleLibraries::KIND); - library_panel::pick_library_file(app, path, filters, |app, path| load_library(app, json!({ "path": path }))) + library_panel::pick_library_file(app, path, filters, load_library) } /// The id prefix of the Window → Graphic Style Libraries → User Defined slots. diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 472a6f5d83..4a782235e2 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -90,8 +90,10 @@ fn mono(ui: &mut Ui, s: &str) { Text::new(s.to_string()).role(TypeRole::Mono).show(ui); } -/// One paint's row: its tile, its values and its note. A mixed paint keeps the tile's room empty. +/// One paint's tile and readout. A solid tint's name sits below its channel values. +/// A mixed paint keeps the tile's room empty. fn paint_block(ui: &mut Ui, p: &PaintLines) { + let (inline_note, tint_name) = if p.values.is_empty() { (p.note.as_ref(), None) } else { (None, p.note.as_ref()) }; Row::new().show(ui, |ui, _| { Picture::painter("", ThumbAspect::SQUARE, |cx, rect| { if !p.mixed { @@ -102,10 +104,13 @@ fn paint_block(ui: &mut Ui, p: &PaintLines) { for v in &p.values { mono(ui, v); } - if let Some(note) = &p.note { + if let Some(note) = inline_note { Text::new(note.clone()).shade(Shade::Muted).show(ui); } }); + if let Some(name) = tint_name { + Text::new(name.clone()).shade(Shade::Muted).show(ui); + } } /// What the panel reads from the document and the tool for its rows of numbers ([`Rows::of`]). @@ -408,4 +413,29 @@ mod tests { g.swatch = Some("Sunset".into()); assert_eq!(paint_name(&Paint::Gradient(Box::new(g))), Some("Sunset".into())); } + + #[test] + fn a_solid_tint_and_its_channels_fit_in_the_narrowest_info_panel() { + use crate::panel_docking::PANEL_MIN_WIDTH; + use crate::tests::panel_harness::{Place, floated}; + + const SWATCH: &str = "Signal Red Coated"; + const TINT: &str = "Signal Red Coated 40%"; + let mut app = app_with_rect(); + let color = json!({"model": "cmyk", "c": 0.1, "m": 0.8, "y": 0.6, "k": 0.2}); + run(&mut app, "swatch.new", json!({"name": SWATCH, "color": color, "spot": true})); + run(&mut app, "paint.setFill", json!({"swatch": SWATCH, "tint": 40})); + let paint = lines(&mut app, &crate::testing::ui_context()).fill; + assert_eq!(paint.note.as_deref(), Some(TINT)); + assert_eq!(paint.values.len(), 4, "the fixture has four CMYK channels"); + let names: Vec<_> = paint.values.iter().map(String::as_str).chain([TINT]).collect(); + let panel = floated(app, "info", "en", Place::Floating(PANEL_MIN_WIDTH), &names); + assert!((panel.body.width() - PANEL_MIN_WIDTH).abs() < 1.0, "the Info panel is at its minimum width"); + let past = panel.past_named(&names); + assert!(past.is_empty(), "the readout extends past the Info panel: {past:?}"); + let tint = panel.rects(TINT)[0]; + for name in &paint.values { + assert!(panel.rects(name)[0].center().y < tint.top(), "the tint follows the color channels on its own line"); + } + } } diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index f0eb4a72e2..4ed813fb6a 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -20,7 +20,7 @@ use std::cell::RefCell; use std::collections::HashMap; use craft::behavior::{IconId, Selection, SelectionModel}; -use craft::host::{PickRequest, Picked}; +use craft::host::PickRequest; use craft::theme::variant::Tone; use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; @@ -113,7 +113,7 @@ pub(crate) trait LibraryKind { const OPEN: &'static str; /// The engine command listing the libraries, for error messages. const LIST: &'static str; - /// The engine command loading a library from a file (`{path}` → `{library}`). + /// The engine command loading a library by path or by file name and contents (`{library}`). const LOAD: &'static str; /// The libraries menu's tooltip ("Swatch Libraries Menu"). const MENU: &'static str; @@ -502,13 +502,13 @@ pub(crate) fn locate(app: &mut VectorcraftApp, p: &Value) -> Result Result { +/// Locate Library… answered with the chosen file for missing library panel `given`. +fn located(app: &mut VectorcraftApp, given: &str, params: Value) -> Result { let (k, id) = parse(given).ok_or_else(|| format!("`{given}` isn't a library panel (see window.swatchLibrary)"))?; - let r = app.run(k.load, json!({ "path": path }))?; + let r = app.run(k.load, params)?; let next = r["library"].as_str().unwrap_or_default().to_string(); let to = panel_id(k.kind, &next); if to != given && is_open(&app.ui, &to) { @@ -543,25 +543,21 @@ pub(crate) fn library_pick_filters(kind: &str) -> Vec<(&'static str, &'static [& } } -/// Other Library… and Locate Library…: `then` loads the library file at `path`, else one picked in -/// an open dialog. The pick is asked of the app (`file_asks`) and answers on a later pass, which -/// runs `then` with the picked file; until then this returns what `file_asks::ask` returns. +/// Other Library… and Locate Library…: `then` gets the load command parameters for the file at +/// `path`, or for the picked file. A browser pick supplies the name and contents. pub(crate) fn pick_library_file( app: &mut VectorcraftApp, path: Option, filters: Vec<(&'static str, &'static [&'static str])>, - then: impl FnOnce(&mut VectorcraftApp, String) -> Result + 'static, + then: impl FnOnce(&mut VectorcraftApp, Value) -> Result + 'static, ) -> Result { if let Some(path) = path { - return then(app, path); + return then(app, json!({ "path": path })); } let request = filters.into_iter().fold(PickRequest::open("library"), |r, (name, exts)| r.filter(name, exts)); - Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| match picked { - Picked::Paths(paths) => match paths.into_iter().next() { - Some(path) => then(app, path.to_string_lossy().into_owned()), - None => Ok(Value::Null), - }, - _ => Ok(Value::Null), + Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| match file_asks::open_params(&picked) { + Some(params) => then(app, Value::Object(params)), + None => Ok(Value::Null), })) } diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index 68fc0cf0de..af1b38d9ae 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -262,6 +262,45 @@ fn saving_to_a_file_and_opening_a_palette_file() { assert!(!builtin_library(&open.id) && builtin_library(vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES)); } +fn browser_library(filename: &str, bytes: &[u8], entry: &str) -> Option { + let mut app = app(); + app.services.download = Some(Box::new(|_, _| Ok(()))); + let picker = scripted(&mut app); + let undo = undo_len(&app); + crate::tests::picks::asks(&mut app, &format!("{}.other", K::OPEN)); + picker.answer_contents(&[(filename, bytes)]); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + assert_eq!((app.session.documents().len(), undo_len(&app)), (1, undo), "loading a library does not change the drawing"); + let open = last_open(&app.ui)?; + assert_eq!(open.kind, K::KIND); + assert!(is_open(&app.ui, &open.panel())); + let (name, library) = K::get(&app, &open.id)?; + assert!(K::rows(&library, &open.id).iter().any(|row| row.name == entry && row.item.is_some()), "{entry} is in the {name} library"); + Some(name) +} + +#[test] +fn other_library_opens_browser_pick_contents_for_each_panel_kind() { + use crate::panels::{brushes::BrushLibraries, graphic_styles::GraphicStyleLibraries, symbols::SymbolLibraries}; + + let mut source = app(); + source.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + source.run("graphicStyle.new", json!({"name": "Studio Style"})).unwrap(); + source.run("symbol.new", json!({"name": "Studio Symbol"})).unwrap(); + source.run("brush.new", json!({"type": "bristle", "name": "Studio Brush"})).unwrap(); + let encoded = source.run("document.serialize", json!({})).unwrap(); + let document = vectorcraft_format::base64_decode(encoded["dataBase64"].as_str().unwrap()).unwrap(); + let palette = b"GIMP Palette\nName: Browser Palette\n#\n255 0 0\tBrowser Red\n"; + let loaded = [ + browser_library::("Browser Palette.gpl", palette, "Browser Red"), + browser_library::("Browser Studio.vectorcraft", &document, "Studio Brush"), + browser_library::("Browser Studio.vectorcraft", &document, "Studio Symbol"), + browser_library::("Browser Studio.vectorcraft", &document, "Studio Style"), + ]; + assert_eq!(loaded.map(|name| name.unwrap_or_default()), ["Browser Palette", "Browser Studio", "Browser Studio", "Browser Studio"]); +} + #[test] fn the_save_dialog_writes_swatch_exchange_files() { let written = std::rc::Rc::new(std::cell::RefCell::new(vec![])); @@ -503,6 +542,32 @@ fn a_persistent_panel_whose_file_is_gone_is_listed_as_missing_until_located() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn locate_library_loads_browser_contents_into_the_missing_panel() { + let path = std::env::temp_dir().join(format!("vc-browser-locate-{}.gpl", std::process::id())); + let palette = b"GIMP Palette\nName: Replacement\n#\n255 0 0\tNew Red\n"; + std::fs::write(&path, palette).unwrap(); + let mut app = app(); + let missing = panel_of(app.run("window.swatchLibrary.other", json!({"path": path})).unwrap()); + app.run("ui.libraryPanel", json!({"panel": missing, "persistent": true, "view": "smallList"})).unwrap(); + std::fs::remove_file(&path).unwrap(); + + let mut app = restarted(&app); + tidy(&mut app); + app.services.download = Some(Box::new(|_, _| Ok(()))); + let picker = scripted(&mut app); + assert_eq!(app.run("ui.libraryPanel.locate", json!({"panel": missing})), Ok(json!({"pending": "fileDialog"}))); + picker.answer_contents(&[("Replacement.gpl", palette)]); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + + assert!(!is_open(&app.ui, &missing), "the missing panel has been recovered"); + let panel = last_open(&app.ui).unwrap(); + assert!(is_open(&app.ui, &panel.panel())); + assert_eq!((panel.persistent, panel.view), (true, Some(View::SmallList))); + assert!(SwatchLibraries::get(&app, &panel.id).is_some_and(|(_, lib)| lib.swatch("New Red").is_some())); +} + #[test] fn locating_a_library_open_in_its_own_panel_brings_that_panel_forward() { let dir = std::env::temp_dir().join(format!("vc-locate-open-library-{}", std::process::id())); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 80f69b1179..d2765a0af9 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -23,7 +23,7 @@ use std::collections::HashMap; use std::sync::Arc; use craft::behavior::{IconId, Selection, keyed}; -use craft::host::{PickKind, PickRequest}; +use craft::host::{PickKind, PickRequest, Picked}; use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; @@ -364,12 +364,26 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest, then: impl FnOnce(&mut Ve /// say. pub(crate) fn replace(app: &mut VectorcraftApp, ids: Vec) { let request = vectorcraft_engine::cmd::fileio::place_filters().fold(PickRequest::open("links"), |r, (name, exts)| r.filter(name, exts)); - ask(app, request, move |app, path| { - let r = app.run("links.relink", json!({ "ids": ids, "path": path, "preserve": "fit" })); - report(app, r, |v| crate::i18n::msg_n(v["relinked"].as_array().map_or(0, Vec::len) as u64, "Replaced {n} image", "Replaced {n} images", &[])); + file_asks::ask(app, request, Owner::Document, move |app, picked| { + if let Picked::Contents(files) = picked { + if let Some((name, bytes)) = files.into_iter().next() { + let result = app + .run("links.replaceEmbedded", json!({ "ids": ids, "dataBase64": vectorcraft_format::base64_encode(&bytes) })) + .map_err(|err| format!("{name}: {err}")); + report(app, result, |v| replaced_status(v["replaced"].as_array().map_or(0, Vec::len))); + } + } else if let Some(path) = picked.first_path() { + let r = app.run("links.relink", json!({ "ids": ids, "path": path.to_string_lossy(), "preserve": "fit" })); + report(app, r, |v| replaced_status(v["relinked"].as_array().map_or(0, Vec::len))); + } + Ok(Value::Null) }); } +fn replaced_status(n: usize) -> String { + crate::i18n::msg_n(n as u64, "Replaced {n} image", "Replaced {n} images", &[]) +} + /// Relink images `ids` (none: every missing one) to the files of their names in a picked folder. fn relink_to_folder(app: &mut VectorcraftApp, ids: Vec) { ask(app, PickRequest::folder("links"), move |app, folder| { diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 1a3e0fefd1..6da7bcfb54 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -270,6 +270,7 @@ fn load_profile(app: &mut VectorcraftApp) { Some(path) => app.run("color.loadProfile", json!({ "path": path })), None => Ok(Value::Null), }, + Picked::Contents(files) if !files.is_empty() => Err("loading profiles from disk isn't available in the browser".into()), _ => Ok(Value::Null), }); } @@ -457,6 +458,24 @@ mod tests { use crate::tests::panel_harness::Panel; use vectorcraft_engine::Session; + #[test] + fn browser_profile_pick_reports_why_it_cannot_load() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let picker = crate::tests::picks::scripted(&mut app); + app.status("Previous status"); + + load_profile(&mut app); + picker.cancel(); + crate::file_asks::poll(&mut app); + assert_eq!(app.ui.status, "Previous status"); + + load_profile(&mut app); + assert_eq!(picker.requests().len(), 2); + picker.answer_contents(&[("proof.icc", b"test profile")]); + crate::file_asks::poll(&mut app); + assert_eq!(app.ui.status, "loading profiles from disk isn't available in the browser"); + } + /// The panel's Proof Setup list offers the targets of View › Proof Setup, in the same order and /// with the same labels, and each one is a target `view.proofSetup` accepts. #[test] diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index e255b6757d..4f16980b9a 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -200,12 +200,9 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { - library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SwatchLibraries::KIND), |app, path| { - load_library(app, json!({ "path": path })) - }) + library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SwatchLibraries::KIND), load_library) } /// The id prefix of the Window → Swatch Libraries → User Defined slots. diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 7143c2d88e..321a0a7c6d 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -1037,9 +1037,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result) -> Result { - library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SymbolLibraries::KIND), |app, path| { - load_library(app, json!({ "path": path })) - }) + library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SymbolLibraries::KIND), load_library) } /// The id prefix of the Window → Symbol Libraries → User Defined slots. diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 2dc86c3775..5c54fe7ef2 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -653,6 +653,61 @@ fn properties_shows_the_selected_image_and_its_link_actions() { assert!(text.contains("Linked File") && text.contains("Edit Original") && text.contains("Embed"), "{text}"); } +#[test] +fn replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step() { + use crate::tests::picks::{poll, scripted}; + use vectorcraft_doc::{NodeId, NodeKind}; + use vectorcraft_geom::Rect; + + let dir = Folder::new("replace-browser-bytes"); + let (mut app, linked, _) = app(&dir); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + let journal = app.session.journal.len(); + let picker = scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let bytes = png(10, 20); + + super::links::replace(&mut app, vec![linked]); + assert_eq!(picker.requests().len(), 1); + picker.answer_contents(&[("replacement.png", &bytes)]); + poll(&mut app, &ctx); + + let state = app.session.doc().unwrap(); + let NodeKind::Image(image) = &state.doc.node(NodeId(linked)).unwrap().kind else { panic!("replacement must keep the image's id") }; + assert_eq!((image.width, image.height), (10, 20)); + assert!(image.link.is_none(), "browser file contents are embedded"); + assert_eq!(state.doc.images[&image.key].bytes.as_slice(), bytes); + let bounds = image.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 10.0, 20.0)); + assert_eq!((bounds.width(), bounds.height()), (100.0, 200.0), "fit in the old 300 by 200 bounds"); + assert_eq!(state.history.undo.len(), undo + 1); + assert_eq!(app.session.journal.get(journal).map(|(command, _)| command.as_str()), Some("links.replaceEmbedded")); + + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); +} + +#[test] +fn replace_image_with_a_desktop_path_remains_linked() { + use crate::tests::picks::{poll, scripted}; + use vectorcraft_doc::{NodeId, NodeKind}; + + let dir = Folder::new("replace-desktop-path"); + let (mut app, _, embedded) = app(&dir); + let path = dir.file("replacement.png", &png(10, 20)); + let picker = scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + + super::links::replace(&mut app, vec![embedded]); + picker.answer(&[&path]); + poll(&mut app, &ctx); + + let state = app.session.doc().unwrap(); + let NodeKind::Image(image) = &state.doc.node(NodeId(embedded)).unwrap().kind else { panic!("replacement must keep the image's id") }; + assert_eq!((image.width, image.height), (10, 20)); + assert_eq!(image.link.as_ref().unwrap().path, path); +} + /// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for /// each image there and links each one to its file; with no folder picked, nothing changes. #[test] diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index e08d0bf603..1d32ff4d15 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -695,7 +695,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option fn ask_open(app: &mut VectorcraftApp, filters: &[(&str, &[&str])], command: &'static str) -> Value { let request = filters.iter().fold(PickRequest::open("variables"), |r, (name, exts)| r.filter(*name, exts)); file_asks::ask(app, request, Owner::Document, move |app, picked| match file_asks::open_params(&picked) { - Some(params) => app.run(command, Value::Object(params)), + Some(mut params) => { + // The combined importer uses the file name to choose a reader. The dedicated readers already know the format. + if command != "variable.import" { + params.remove("name"); + } + app.run(command, Value::Object(params)) + } None => Ok(Value::Null), }) } @@ -739,6 +745,48 @@ fn save_library(app: &mut VectorcraftApp) -> Value { #[cfg(test)] mod tests { use super::*; + + fn pick_variable_source(command: fn(&mut VectorcraftApp) -> Value, name: &str, bytes: &[u8]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let picker = crate::tests::picks::scripted(&mut app); + assert_eq!(command(&mut app), json!({"pending": "fileDialog"})); + picker.answer_contents(&[(name, bytes)]); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + app + } + + fn browser_xml() -> String { + let mut source = vectorcraft_engine::Session::new(); + source.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + source.execute("variable.define", &json!({"name": "Caption", "kind": "text"})).unwrap(); + source.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_owned() + } + + #[test] + fn browser_variable_import_reads_csv_and_tsv_from_the_file_name() { + for (name, bytes) in [("rows.CSV", &b"Caption,Other\nHello,World\n"[..]), ("rows.tsv", &b"Caption\tOther\nHello\tWorld\n"[..])] { + let app = pick_variable_source(import_data_source, name, bytes); + let data = &app.session.active().unwrap().doc.variables; + assert_eq!(data.datasets.len(), 1, "{name}"); + assert!(data.variables.iter().any(|v| v.name == "Caption")); + } + } + + #[test] + fn browser_variable_import_reads_xml_from_the_file_name() { + let app = pick_variable_source(import_data_source, "variables.XML", browser_xml().as_bytes()); + assert!(app.session.active().unwrap().doc.variables.variables.iter().any(|v| v.name == "Caption")); + } + + #[test] + fn browser_dedicated_variable_importers_accept_file_bytes() { + let csv = pick_variable_source(import_datasets, "rows.csv", b"Caption\nHello\n"); + assert_eq!(csv.session.active().unwrap().doc.variables.datasets.len(), 1); + let xml = pick_variable_source(load_library, "variables.xml", browser_xml().as_bytes()); + assert!(xml.session.active().unwrap().doc.variables.variables.iter().any(|v| v.name == "Caption")); + } use crate::i18n::LangExt; fn app_with_data() -> VectorcraftApp { diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 5a66573eef..c1908fd90f 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -308,9 +308,23 @@ fn export_preferences(app: &mut VectorcraftApp) { fn import_preferences(app: &mut VectorcraftApp) { let request = PickRequest::open("preferences").filter("Preferences", &["json"]); file_asks::ask(app, request, Owner::Free, |app, picked| { - let Picked::Paths(paths) = picked else { return Ok(Value::Null) }; - let Some(path) = paths.first() else { return Ok(Value::Null) }; - match app.run("prefs.import", json!({ "path": path.to_string_lossy() })) { + let params = match picked { + Picked::Paths(paths) => { + let Some(path) = paths.first() else { return Ok(Value::Null) }; + json!({ "path": path.to_string_lossy() }) + } + Picked::Contents(files) => { + let Some((_, bytes)) = files.into_iter().next() else { return Ok(Value::Null) }; + // Match prefs.import's file cap before allocating its JSON text parameter. + if bytes.len() > 1 << 20 { + return Err("The preferences file is larger than 1 MB".into()); + } + let data = String::from_utf8(bytes).map_err(|_| "The preferences file is not valid UTF-8")?; + json!({ "data": data }) + } + _ => return Ok(Value::Null), + }; + match app.run("prefs.import", params) { Ok(_) => app.status("Preferences imported."), Err(e) => app.status(e), } diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 81b8e4219e..6bdf24de68 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -797,6 +797,41 @@ fn prefs_import_refreshes_an_open_preferences_dialog() { assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(7.0)); } +#[test] +fn browser_import_applies_picked_preferences_and_refreshes_the_draft() { + let mut a = app(); + open(&mut a, Some("General")); + set_field(&mut a, "keyboardIncrement", json!(9)).unwrap(); + let picker = crate::tests::picks::scripted(&mut a); + a.services.read = None; + let data = json!({"format": "vectorcraft-preferences", "version": 1, "prefs": {"keyboardIncrement": 7}}).to_string(); + import_preferences(&mut a); + picker.answer_contents(&[("preferences.json", data.as_bytes())]); + file_asks::poll(&mut a); + assert!(same(&field(&a, "keyboardIncrement"), &json!(7.0))); + assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(7.0)); + assert_eq!(a.ui.status, "Preferences imported."); + assert!(is_open(&a)); +} + +#[test] +fn browser_import_refuses_bad_contents_without_losing_draft_edits() { + for bytes in [vec![0xff], vec![b' '; (1 << 20) + 1], b"not JSON".to_vec()] { + let mut a = app(); + open(&mut a, Some("General")); + set_field(&mut a, "keyboardIncrement", json!(9)).unwrap(); + let before = a.session.prefs.to_json(); + let picker = crate::tests::picks::scripted(&mut a); + import_preferences(&mut a); + picker.answer_contents(&[("preferences.json", &bytes)]); + file_asks::poll(&mut a); + assert_eq!(a.session.prefs.to_json(), before); + assert!(same(&field(&a, "keyboardIncrement"), &json!(9))); + assert!(!a.ui.status.is_empty(), "the invalid picked file reports an error"); + assert_ne!(a.ui.status, "Preferences imported."); + } +} + /// An import that turns Enable Touch Workspace on or off switches the workspace on a touch screen, /// as OK in Preferences does. #[test] diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index e92f4bbdf9..b1fa7cb347 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -170,6 +170,51 @@ fn new_from_template_takes_bytes_from_agents() { assert_eq!(app.session.active().unwrap().path, None); } +#[test] +fn new_from_template_opens_browser_bytes_and_desktop_paths_as_untitled_copies() { + let folder = dir("new-from-template-pick"); + let name = "Source Drawing.svg"; + let bytes = br#""#; + let path = folder.join(name); + std::fs::write(&path, bytes).unwrap(); + for browser in [false, true] { + let mut app = app(); + if browser { + app.services.download = Some(Box::new(|_, _| Ok(()))); + } + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + rect(&mut app); + let source = app.session.active().unwrap(); + let source_uid = source.uid; + let source_undo = source.history.undo.len(); + let picker = scripted(&mut app); + picks::asks(&mut app, "file.newFromTemplate"); + assert_eq!(picker.requests()[0].purpose, "template"); + if browser { + picker.answer_contents(&[(name, bytes)]); + } else { + picker.answer(&[path.to_str().unwrap()]); + } + poll(&mut app); + + let opened = app.session.active().unwrap(); + assert!(opened.title().starts_with("Untitled-"), "browser={browser}: the template copy was named {:?}", opened.title()); + assert_eq!((app.session.documents().len(), app.views.len()), (2, 2)); + assert_eq!((opened.path.as_deref(), opened.history.undo.len()), (None, 0)); + assert_eq!(opened.doc.layers[0].children().unwrap().len(), 1); + let source = &app.session.documents()[0]; + assert_eq!((source.uid, source.history.undo.len()), (source_uid, source_undo)); + if browser { + picks::asks(&mut app, "file.newFromTemplate"); + picker.answer_contents(&[(name, b"not a drawing")]); + poll(&mut app); + assert_eq!(app.session.documents().len(), 2, "an invalid template opens no document"); + assert!(app.ui.status.contains("Couldn't open Source Drawing.svg"), "{}", app.ui.status); + } + } + let _ = std::fs::remove_dir_all(folder); +} + #[test] fn show_in_folder_needs_a_saved_document_and_a_file_manager() { let shown = Rc::new(RefCell::new(vec![])); @@ -515,3 +560,36 @@ fn revert_confirmation_never_discards_another_drawings_changes() { let _ = std::fs::remove_dir_all(d); assert_eq!(result, (count, true), "the second drawing must retain its unsaved edits"); } + +#[test] +fn acknowledging_import_loss_does_not_overwrite_the_source_with_another_drawing() { + let d = dir("lossy-drawing-switch"); + let path = d.join("source.vectorcraft").to_string_lossy().to_string(); + let mut app = app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("file.saveAs", json!({"path": path})).unwrap(); + let saved = std::fs::read(&path).unwrap(); + let st = app.session.doc_mut().unwrap(); + st.imported_from = Some(path.clone()); + st.import_losses = vec!["hidden type".into()]; + rect(&mut app); + + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + rect(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let params = json!({"path": path, "options": {"compress": true}}); + assert_eq!(app.run("file.saveAs", params.clone()).unwrap()["pending"], confirm::KIND); + app.run("document.activate", json!({"index": 1})).unwrap(); + answer_top(&mut app, true); + crate::background::wait_all(&mut app); + let after_switch = std::fs::read(&path).unwrap(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.saveAs", params).unwrap(); + answer_top(&mut app, true); + crate::background::wait_all(&mut app); + let after_original = std::fs::read(&path).unwrap(); + let _ = std::fs::remove_dir_all(d); + assert!(after_switch == saved, "drawing B must never overwrite A's file"); + assert!(after_original != saved, "approval in drawing A must still save A"); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 53aa6f39cb..4a65e884e1 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -70,6 +70,30 @@ fn allow_once(app: &mut VectorcraftApp) { script_run::settle_files(app, DialogResult::Ok(FilesAnswer { answer: "once", paths, left_out: false, automated: false })); } +#[test] +fn a_script_file_reply_does_not_populate_a_reopened_dialog() { + let mut app = app(); + let picker = scripted(&mut app); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "File.openDialog('Choose');"})).unwrap().unwrap(); + script_runs::poll(&mut app); + script_run::with_host(&app, |host, _| host.get_mut::().unwrap().choose = true).unwrap(); + pump(&mut app); + assert_eq!(picker.requests().len(), 1); + + script_run::forget::(&app); + script_run::open_picker(&app, app.session.script_picker().unwrap()); + let old_path = std::env::temp_dir().join("original-script-picker.txt"); + picker.answer(&[&old_path.to_string_lossy()]); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + + assert!(picked(&app).is_empty(), "the old file chooser must not populate the new open dialog"); + set(&app, PICKER_KIND, "answer", json!("deny")).unwrap(); + assert!(confirm(&mut app, PICKER_KIND)); + finish(&mut app); +} + #[test] fn the_warning_comes_before_the_run_and_cancel_runs_nothing() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 6f567df149..151708f897 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10194,6 +10194,7 @@ layer of its own below the others; files that carry the editing data (Preserve E Export for Screens) keep it as the artboard's color, not as art. `includeArtboardFill: false` on `document.export`, `document.serialize`, `document.exportForScreens` (Include Artboard Fill) or `file.print` leaves it out. `inspect_document` lists it as the artboard's `color` (`#rrggbb`), and `ui.colorPicker {artboard: index}` opens the Color Picker for it. +The artboard preview and confirmation require the opening document to be active. Artboard Options' Show Center Mark and Show Cross Hairs: `artboard.setProps {index, showCenterMark?: bool, showCrossHairs?: bool}` (or each entry of `artboards`) turns them on or off for that artboard in one undo step, and @@ -10689,6 +10690,8 @@ listed in `warnings`. ASCII and binary DXF files are read; DWG files answer an e ## Links panel +`links.replaceEmbedded {ids, dataBase64}` uses raster file bytes to replace existing canvas images. It embeds the new pixels and keeps the image ids. The new aspect ratio fits inside the old bounds, and a distorted image keeps its corners. The command records one undo step and returns `{replaced: [ids]}`. The browser's Replace Image uses this operation with the file picker result. + `links.list {show?: all|missing|modified|embedded, sort?: name|kind|status|size}` lists every image in the layers, top first, as the Links panel does (`sort: "size"`, the panel menu's Sort by Size, puts the smallest file first by the size Link Info shows; rows without one, embedded images and missing files whose size is not kept, come last, and equal @@ -16886,10 +16889,11 @@ Unit Converter is a built-in add-on that shows one length in every unit at once `addon.units.convert` and `addon.units.selectionSize`, and in the desktop app it lives in Object › Plug-ins › Unit Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither command changes the document. -`addon.units.convert {value, unit?}` reads `value` as a number field reads it: a number, or text with a unit suffix and +`addon.units.convert {value, unit?}` accepts a number, or text with a unit suffix and `+ - * /` arithmetic, where `x`, `X` and `×` multiply as `*` does (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`, -`"3cm*50%"`, `"2x3 mm"`, `"13q"`), a decimal comma read as a point (`"0,5 mm"`) and a single number with a thousands -comma (`"1,000 mm"`) refused, in at most 1024 bytes with at most 128 `+ - * /` signs (each multiplication sign counts). +`"3cm*50%"`, `"2x3 mm"`, `"13q"`). The command reads an unambiguous decimal comma as a point (`"0,5 mm"`). +It refuses numbers that look like grouped integers, whether alone (`"1,000 mm"`) or in arithmetic (`"1,500+2"`). +Text may contain at most 1024 bytes and 128 `+ - * /` signs (each multiplication sign counts). A number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`, `centimeters`, `pixels`, `feetInches`, `meters`, `yards`, `feet`, `q`, `ha`; default `points`); a suffix in the text takes precedence over `unit`. It works without an open document. The command fails when `value` is missing, does not diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index df69c18888..f361929e7c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -970,7 +970,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** a Transform section comes first (#5219): the reference point the Transform panel and Control bar share, the active artboard's X and Y (of that point) and W and H with the Constrain Width and Height Proportions link, its preset and orientation, and Move and Scale Artwork with Artboard. The Artboards section follows, with the name field, Artboard Options and Fill. The active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). -- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). +- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard preview and confirmation require its opening document to be active. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). - **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`), and a Fill chosen in Properties colors each of them (#5698); a Shift- or Ctrl/Cmd-click on an Artboards panel row with another tool in use switches to the Artboard tool and selects as it does; with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). - **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Escape in the distort tools:** Escape during a Puppet Warp pin drag or turn, a Perspective Grid tool handle or plane widget drag, a Perspective Selection move, resize or plane widget drag, or a Liquify stroke cancels it: the art goes back to how the press found it, no undo step is added, and the tool stays chosen. Puppet Warp also selects again the pins selected before the press, and Escape during a Liquify Alt-drag puts the brush size back. Regression tests: `escape_cancels_*` in `crates/tools/src/distort/puppet.rs`, `perspective.rs` and `liquify.rs`, and `escape_cancels_a_puppet_warp_perspective_or_liquify_drag` in `tests/distortkeys.rs`. @@ -2538,6 +2538,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. - On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed. - In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one. + - Replace Image in the browser embeds the picked raster in the existing image and fits it within the old bounds in one undo step. The desktop picker continues to link to the chosen file. Evidence includes `replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step` and `replace_image_with_a_desktop_path_remains_linked`. - The Links panel menu's Sort by Size ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) lists the links by file size, smallest first (`links.list {sort: "size"}`). VectorCraft's own rules: a file's size is the one Link Info shows, rows without one (embedded images, a missing file whose size the document does not keep) come last, and equal sizes go by name. - When a document opens with notes and with linked files that changed on disk (Update Links: Manually) or, on the web, can't be read, the status bar shows the line about the linked files, then counts the notes and names the first, and hovering it lists the notes. The same holds when the line about modified files follows the Linked File Not Found dialog, and File › New from Template… shows the notes of the file it opens as File › Open does (`an_open_with_modified_links_keeps_link_notice_and_import_notes_reachable`, `new_from_template_preserves_open_warnings`, `an_open_with_unreadable_links_keeps_import_notes_reachable`, `modified_links_after_the_missing_ones_keep_the_open_notes`, `combined_open_and_link_status_lists_notes_on_hover_and_for_accessibility`). - On the web, when a document opens with linked files that can't be read and linked files that changed on disk (Update Links: Manually), the status bar shows the line about the unreadable files, and the line about the changed files is the first of the notes its hover lists, ahead of the open's notes. With Ask When Modified the update question opens and the line about the unreadable files stays (`a_web_open_with_unreadable_and_modified_links_keeps_both_lines`). @@ -3077,6 +3078,9 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. +The `addon.units.convert` command rejects numbers that look like grouped integers even in expressions such as +`1,500+2`. The panel treats separators according to the input locale. + ## Cutting Tools add-on: Stencil Bridges (2026-11-12) A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges.