From 60700e00fc3fb0fb8fb09754f93eca99bfc8219d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 19:26:22 -0700 Subject: [PATCH 001/199] Native format: document.save can write path coordinates at a fixed precision Native files store every anchor and handle as a full double, such as 3.4876474632797176, so a file of traced art is larger than it needs to be. document.save, file.saveAs, file.saveCopy and file.saveAsTemplate take precision (0 to 9) for native files. The save rounds the anchors and handles of path objects, Live Corners' uncut outlines, blend spines, envelope outlines, Intertwine areas and brush art to that many decimal places, in the layers, symbols, graph designs, patterns and opacity masks, and in the art that placed documents become in files for older versions. Colors, transforms, opacity and type are written exactly. Without precision the file is written as before, and Save does not remember the option. A .ai file, saved or exported, ignores precision. The VectorCraft Options dialog shows no row for it. A save given precision beside the path for a format that does not read it (SVG, PDF, .ai and .ait) says so in its warnings, as it does for compress, version and preview. MCP save_file passes precision on to the save as it passes the other native options, and its schema, description and docs/mcp.md list it. --- crates/doc/src/lib.rs | 104 +++++++++++++++++ crates/engine/src/cmd/fileio/native.rs | 26 ++++- crates/engine/src/cmd/fileio/save.rs | 14 ++- crates/engine/src/cmd/fileio/tests.rs | 14 ++- crates/engine/src/tests_placed_document.rs | 41 +++++++ crates/engine/src/tests_saveoptions.rs | 70 ++++++++++++ crates/format/src/lib.rs | 24 +++- crates/format/tests/it/save_options.rs | 123 ++++++++++++++++++++- crates/mcp/src/tests_fileio.rs | 20 +++- crates/mcp/src/tools.rs | 8 +- crates/ui-egui/src/dialogs/save_options.rs | 19 +++- docs/mcp.md | 8 +- 12 files changed, 445 insertions(+), 26 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index a222e8e919..4d1b03efd0 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -2116,6 +2116,110 @@ impl Document { d.drop_edit_modes(); std::borrow::Cow::Owned(d) } + + /// Round every path's anchors and handles to `decimals` decimal places: path objects (with + /// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine + /// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being + /// edited included), opacity masks and the brushes kept as foreign data. Colors, transforms, + /// opacity, live shapes' own sizes, meshes and type (its frames and paths included) are left + /// as they are. + pub fn round_geometry(&mut self, decimals: u8) { + let scale = 10f64.powi(i32::from(decimals)); + let round = |v: f64| { + let r = (v * scale).round() / scale; + if !r.is_finite() { + v + } else if r == 0.0 { + // `-0.0` is written as `0.0`. + 0.0 + } else { + r + } + }; + let round_path = |path: &mut vectorcraft_geom::PathData| { + for a in path.subpaths.iter_mut().flat_map(|s| s.anchors.iter_mut()) { + for p in [&mut a.p, &mut a.h_in, &mut a.h_out] { + *p = Point::new(round(p.x), round(p.y)); + } + } + }; + let mut fix = |n: &mut Node| { + match &mut n.kind { + NodeKind::Path { path, live, .. } => { + round_path(path); + // Live Corners' uncut outline. + if let Some(LiveShape::Path { base, .. }) = live.as_deref_mut() { + round_path(base); + } + } + NodeKind::Blend { spec, .. } => { + if let Some(spine) = &mut spec.spine { + round_path(spine); + } + } + NodeKind::Envelope { kind, .. } => { + if let EnvelopeKind::TopObject { path } = kind.as_mut() { + round_path(path); + } + } + _ => {} + } + if let Some(area) = n.extras_if_any().and_then(|e| e.intertwine.as_deref_mut()) { + round_path(area); + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + placed_document::each_mut(Arc::make_mut(root), &mut fix); + } + if self.unknown.contains_key("brushes") + && let Some(brushes) = self.unknown.get_mut("brushes") + { + round_json_paths(brushes, &round); + } + } +} + +/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every +/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as +/// [`Document::round_geometry`] rounds the nodes it holds. +fn round_json_paths(v: &mut serde_json::Value, round: &impl Fn(f64) -> f64) { + use serde_json::Value; + match v { + Value::Object(o) => { + if o.get("type").and_then(Value::as_str) == Some("text") { + return; + } + if let Some(subpaths) = o.get_mut("subpaths").and_then(Value::as_array_mut) { + let anchors = subpaths.iter_mut().filter_map(|s| s.get_mut("anchors").and_then(Value::as_array_mut)).flatten(); + for a in anchors.filter_map(Value::as_object_mut) { + let points = a.iter_mut().filter(|(k, _)| matches!(k.as_str(), "p" | "in" | "out")).filter_map(|(_, v)| v.as_array_mut()); + for xy in points { + for n in xy.iter_mut().filter(|n| n.is_f64()) { + if let Some(r) = n.as_f64().and_then(|x| serde_json::Number::from_f64(round(x))) { + *n = Value::Number(r); + } + } + } + } + } + for c in o.values_mut() { + round_json_paths(c, round); + } + } + Value::Array(a) => { + for c in a { + round_json_paths(c, round); + } + } + _ => {} + } } /// Graphic styles. diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index bcca24c34d..b36e387deb 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -35,6 +35,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "false", description: "embed a PNG preview of the first artboard (at most 256 pixels on its longer side) for file browsers", }, + FormatOption { + name: "precision", + ty: "integer", + default: "null", + description: "round path anchors and handles to this many decimal places, 0 to 9 (a smaller file; colors, transforms and type are kept exactly); null writes them exactly. Only the save that gives it rounds", + }, SEPARATE_ARTBOARDS, SEPARATE_RANGE, INCLUDE_LINKED, @@ -131,6 +137,7 @@ struct NativeOptions { compress: Option, version: Option, preview: bool, + precision: Option, include_linked: bool, embed_profiles: Option, pdf_compatible: bool, @@ -151,6 +158,7 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> compress: o.compress.unwrap_or(false), version: o.version.unwrap_or(vectorcraft_format::VERSION), include_linked: o.include_linked, + precision: o.precision.map(|v| precision(cmd, &v)).transpose()?, ..SaveOptions::default() }; if o.embed_profiles.unwrap_or(true) { @@ -160,6 +168,20 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Ok((so, Extras { preview: o.preview, pdf: o.pdf_compatible })) } +/// The `precision` option `v`: a whole number of decimal places, 0 to +/// [`vectorcraft_format::MAX_PRECISION`]. Any other value, a string included, gets the range message. +fn precision(cmd: &str, v: &Value) -> Result { + let (key, min, max) = ("precision", 0u8, vectorcraft_format::MAX_PRECISION); + if let Some(x) = v.as_f64() + && x.fract() == 0.0 + && (f64::from(min)..=f64::from(max)).contains(&x) + { + return Ok(x as u8); + } + let x = v.as_f64().map_or_else(|| v.to_string(), |x| x.to_string()); + Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))) +} + /// The `.vectorcraft` file of `doc` with the options in `p`. pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { let mut out = Vec::new(); @@ -230,8 +252,8 @@ pub(super) fn ai_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Re let mut q = p.clone(); if let Some(o) = q.as_object_mut() { // AI carries the current native format without a separate preview. Its compression - // and PDF-content flags are still validated as booleans. - o.retain(|k, _| !matches!(k.as_str(), "version" | "preview")); + // and PDF-content flags are still validated as booleans. Its coordinates are written exactly. + o.retain(|k, _| !matches!(k.as_str(), "version" | "preview" | "precision")); if o.get("pdfCompatible").is_some_and(Value::is_null) { o.remove("pdfCompatible"); } diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 3eb64f3eaf..adce6a6ac7 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -257,7 +257,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { given = svg; } else { // So do PDF options (as the Save PDF dialog and document.exportPdf name them) and the - // native ones (compress, version, preview). + // native ones (compress, version, preview, precision). if let Some(o) = p.as_object() { given.extend( o.iter().filter(|(k, v)| !v.is_null() && k.as_str() != "path" && reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())), @@ -288,7 +288,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { } /// The native save options, which a save also takes beside the path. -const NATIVE_OPTIONS: [&str; 3] = ["compress", "version", "preview"]; +const NATIVE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "precision"]; /// The first option `p` gives both beside the path and in `options` with different values, as /// `(key, top-level value, options value)`. For an SVG save (`svg`), an SVG option's value on @@ -827,6 +827,8 @@ impl SaveJob { st.path = Some(path); st.format = self.plan.format.id; st.save_options = self.plan.options; + // A later save rounds only when it gives `precision` too. + st.save_options.remove("precision"); st.save_artboards = self.snapshot.artboards.iter().map(|a| a.id).collect(); st.converted = false; st.recovered = false; @@ -942,7 +944,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version or preview given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified", has_doc, |s, p| save(s, SaveMode::Save, p) ), @@ -951,7 +953,7 @@ pub(super) fn specs() -> Vec { "Save As…", ["File"], Some("Cmd+Shift+S"), - "{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}", + "{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, precision?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}", has_doc, |s, p| save(s, SaveMode::SaveAs, p) ), @@ -960,7 +962,7 @@ pub(super) fn specs() -> Vec { "Save a Copy…", ["File"], Some("Cmd+Alt+S"), - "{…as document.save} {path?, format?, options?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" copy.\", folder?, warnings}", + "{…as document.save} {path?, format?, options?, precision?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" copy.\", folder?, warnings}", has_doc, |s, p| save(s, SaveMode::Copy, p) ), @@ -969,7 +971,7 @@ pub(super) fn specs() -> Vec { "Save as Template…", ["File"], None, - "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}", + "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}", has_doc, |s, p| save(s, SaveMode::Template, p) ), diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 530b681ba7..d1e2674a5a 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -703,8 +703,8 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() { } /// An option given beside the path (an SVG option flat or in `svg`) and in `options` with different -/// values is refused before anything is written; `compress`, `version` or `preview` beside the path of a format that doesn't -/// read it is named in the warnings. +/// values is refused before anything is written; `compress`, `version`, `preview` or `precision` beside the path of a format +/// that doesn't read it is named in the warnings. #[test] fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() { let d = tmp_dir("save-options"); @@ -751,6 +751,16 @@ fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() { let r = s.execute("file.saveCopy", &json!({"path": d.join("a.ai").to_string_lossy(), "compress": false, "version": 3})).unwrap(); let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); assert!(w.iter().any(|w| w.starts_with("`version` was not used")) && !w.iter().any(|w| w.starts_with("`compress`")), "{w:?}"); + // `precision` is read by native files and templates only. + for name in ["p.svg", "p.pdf", "p.ai"] { + let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap(); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(w.iter().any(|w| w.starts_with("`precision` was not used:")), "{name}: {w:?}"); + } + for name in ["p.vectorcraft", "p.vctemplate"] { + let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{name}: {r}"); + } let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/engine/src/tests_placed_document.rs b/crates/engine/src/tests_placed_document.rs index dd9e47462f..4a0f359aec 100644 --- a/crates/engine/src/tests_placed_document.rs +++ b/crates/engine/src/tests_placed_document.rs @@ -691,6 +691,47 @@ fn a_placed_documents_resources_stay_its_own() { assert!(near(centre_colour(&old), BLUE)); } +#[test] +fn saved_for_older_apps_with_a_precision_the_placed_art_is_rounded_too() { + let dir = Folder::new("placed-precision"); + let src = dir.file("triangle.vectorcraft"); + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let points = [(3.4876474632797176, 1.0), (90.0, 2.123456789), (40.0, 80.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y)); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::path::SubPath::polyline(&points, true)); + d.insert(Some(layer), 0, Node::path(id, path, look(BLUE))).unwrap(); + write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + place(&mut s, &src); + // The coordinates of every anchor and handle in a file's layers. + fn coords(v: &Value, out: &mut Vec) { + match v { + Value::Object(o) => { + for a in o.get("anchors").and_then(Value::as_array).into_iter().flatten() { + out.extend(["p", "in", "out"].iter().filter_map(|k| a[*k].as_array()).flatten().filter_map(Value::as_f64)); + } + o.values().for_each(|c| coords(c, out)); + } + Value::Array(a) => a.iter().for_each(|c| coords(c, out)), + _ => {} + } + } + let mut saved = |p: Value| { + let file: Value = serde_json::from_slice(&decode(&s.execute("document.serialize", &p).unwrap())).unwrap(); + assert!(!file.to_string().contains("placeddocument"), "{file}"); + let mut out = vec![]; + coords(&file["document"]["layers"], &mut out); + out + }; + let at4 = |x: f64| (x * 1e4).round() / 1e4 == x; + let exact = saved(json!({"format": "vectorcraft", "version": 3})); + assert!(exact.len() >= 6 && !exact.iter().all(|x| at4(*x)), "{exact:?}"); + let rounded = saved(json!({"format": "vectorcraft", "version": 3, "precision": 4})); + assert_eq!(rounded.len(), exact.len()); + assert!(rounded.iter().all(|x| at4(*x)), "{rounded:?}"); +} + #[test] fn break_link_gives_the_editable_copy_placing_without_link_gives() { let dir = Folder::new("placed-break"); diff --git a/crates/engine/src/tests_saveoptions.rs b/crates/engine/src/tests_saveoptions.rs index ff14cf6980..f1f449b758 100644 --- a/crates/engine/src/tests_saveoptions.rs +++ b/crates/engine/src/tests_saveoptions.rs @@ -353,3 +353,73 @@ fn format_options_list_the_save_options() { let v = s.execute("file.formatOptions", &json!({})).unwrap(); assert_eq!(v["options"]["includeLinked"]["value"], true); } + +/// The anchors of the first object in the native file at `path`. +fn saved_anchors(path: &str) -> Vec { + let d = vectorcraft_format::load(&std::fs::read(path).unwrap()).unwrap(); + let NodeKind::Path { path, .. } = &d.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() +} + +#[test] +fn precision_rounds_the_paths_of_that_save_only() { + let dir = Folder::new("precision"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 1000, "height": 1000})).unwrap(); + // 1,000 anchors at coordinates with many decimal places (a fixed pseudo-random sequence). + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 11) as f64 / (1u64 << 53) as f64 * 1000.0 + }; + let anchors: Vec = (0..1000).map(|_| json!({"x": next(), "y": next()})).collect(); + s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let (exact, rounded) = (dir.file("exact.vectorcraft"), dir.file("rounded.vectorcraft")); + s.execute("document.save", &json!({"path": exact, "compress": false})).unwrap(); + s.execute("document.save", &json!({"path": rounded, "compress": false, "precision": 3})).unwrap(); + let (e, r) = (std::fs::metadata(&exact).unwrap().len(), std::fs::metadata(&rounded).unwrap().len()); + assert!(r < e, "{r} bytes rounded, {e} exact"); + let (want, got) = (saved_anchors(&exact), saved_anchors(&rounded)); + assert_eq!(got.len(), 1000); + for (w, g) in want.iter().zip(&got) { + assert!((w.x - g.x).abs() <= 0.0005 && (w.y - g.y).abs() <= 0.0005, "{w:?} saved as {g:?}"); + assert_eq!(((g.x * 1000.0).round() / 1000.0, (g.y * 1000.0).round() / 1000.0), (g.x, g.y)); + } + // The document keeps its exact anchors, and Save doesn't remember the precision. + let v = s.execute("file.formatOptions", &json!({})).unwrap(); + assert!(v["options"]["precision"]["value"].is_null(), "{}", v["options"]["precision"]); + s.execute("document.save", &json!({})).unwrap(); + assert_eq!(saved_anchors(&rounded), want); + // A precision that isn't a whole number from 0 to 9 is refused, by the command that was given it. + for (wrong, got) in [(json!(10), "10"), (json!(2.5), "2.5"), (json!(-1), "-1"), (json!("4"), "\"4\""), (json!(true), "true")] { + for cmd in ["file.saveCopy", "document.save"] { + let e = s.execute(cmd, &json!({"precision": wrong})).unwrap_err().to_string(); + assert!(e.contains(&format!("`{cmd}`")) && !e.contains("document.export"), "{cmd} {wrong}: {e}"); + assert!(e.contains(&format!("`precision` must be a whole number between 0 and 9 (got {got})")), "{cmd} {wrong}: {e}"); + } + } + // A type error in another native option names that command too. + let e = s.execute("document.save", &json!({"version": "4"})).unwrap_err().to_string(); + assert!(e.contains("`document.save`") && !e.contains("document.export"), "{e}"); +} + +#[test] +fn a_ai_file_ignores_precision_as_save_does() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 10.123456789, "y": 20.987654321}, {"x": 60.5, "y": 70.25}]})).unwrap(); + let want: Vec<_> = { + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() + }; + for cmd in ["document.export", "file.saveCopy"] { + for precision in [json!(3), json!(10)] { + let r = s.execute(cmd, &json!({"format": "ai", "precision": precision})).unwrap(); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "x.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let NodeKind::Path { path, .. } = &t.doc().unwrap().doc.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + let got: Vec<_> = path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(); + assert_eq!(got, want, "{cmd} {precision}"); + } + } +} diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index d76453beeb..c1422d1aa9 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -229,11 +229,26 @@ pub struct SaveOptions { pub profiles: BTreeMap>, /// Create PDF-Compatible File: a PDF of the document to carry. pub pdf: Option>, + /// Decimal places to round path anchors and handles to ([`Document::round_geometry`]), at + /// most [`MAX_PRECISION`] (a larger value rounds to that many); `None` writes them exactly. + pub precision: Option, } +/// The most decimal places [`SaveOptions::precision`] rounds path geometry to. +pub const MAX_PRECISION: u8 = 9; + impl Default for SaveOptions { fn default() -> Self { - Self { pretty: false, compress: false, version: VERSION, preview: None, include_linked: false, profiles: BTreeMap::new(), pdf: None } + Self { + pretty: false, + compress: false, + version: VERSION, + preview: None, + include_linked: false, + profiles: BTreeMap::new(), + pdf: None, + precision: None, + } } } @@ -299,7 +314,8 @@ struct Body { } /// `doc` as [`save_to`] writes it with `o`: without editing-mode working copies, with placed -/// documents as their art for older versions, and its images taken out. +/// documents as their art for older versions, path geometry rounded to `o.precision`, and its +/// images taken out. fn body(doc: &Document, o: &SaveOptions) -> Result { let version = o.version; let mut d = doc.without_edit_modes().into_owned(); @@ -311,6 +327,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { } else { d.drop_placed_resources(); } + // The art placed documents became for older versions is rounded too. + if let Some(decimals) = o.precision { + d.round_geometry(decimals.min(MAX_PRECISION)); + } let linked = d.linked_only_images(); // The blobs go in the file's `images` (only those the document uses). let blobs = std::mem::take(&mut d.images); diff --git a/crates/format/tests/it/save_options.rs b/crates/format/tests/it/save_options.rs index 5cafcb114b..3c0d7c20f8 100644 --- a/crates/format/tests/it/save_options.rs +++ b/crates/format/tests/it/save_options.rs @@ -5,10 +5,13 @@ use std::sync::Arc; use serde_json::Value; +use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::links::LinkInfo; -use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Symbol}; -use vectorcraft_format::{ICC_MIME, PRETTY_MAX_BYTES, PRETTY_MAX_OBJECTS, SaveOptions, load, load_file, pdf_content, save_file, save_with}; -use vectorcraft_geom::path::{PathData, SubPath}; +use vectorcraft_doc::{Appearance, BlendSpec, Document, EnvelopeKind, ImageBlob, ImageObject, LiveShape, Node, NodeKind, OpacityMask, Symbol}; +use vectorcraft_format::{ + ICC_MIME, MAX_PRECISION, PRETTY_MAX_BYTES, PRETTY_MAX_OBJECTS, SaveOptions, load, load_file, pdf_content, save_file, save_with, +}; +use vectorcraft_geom::path::{Anchor, PathData, SubPath}; use vectorcraft_geom::{Affine, Point}; use vectorcraft_testkit::fixtures::DocBuilder; @@ -206,3 +209,117 @@ fn art_outside_the_layers_counts_too() { assert!(!is_pretty(&bytes)); assert_eq!(load(&bytes).unwrap().symbols.len(), 1); } + +/// One path at `x, y`, its out handle at `x + 6.1234567, y - 0.00001` (`-0.0` at 4 decimals when +/// `y` is 0), filled with a color whose components have many digits. +fn precise_path(d: &mut Document, x: f64, y: f64) -> Node { + let p = Point::new(x, y); + let a = Anchor { p, h_in: p, h_out: Point::new(x + 6.1234567, y - 0.00001), kind: Default::default() }; + let sp = SubPath::new(vec![a, Anchor::corner(Point::new(x + 20.0, y))], false); + let fill = Paint::solid(Color::rgb(0.02745098, 0.33333334, 0.9019608)); + Node::path(d.alloc_id(), PathData::single(sp), Appearance::basic(fill, Paint::None, 0.0)) +} + +/// A document with a precise path in the layer, in an opacity mask, in a symbol (placed with a +/// precise transform) and in a brush kept as foreign data. +fn precise_doc() -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let mut n = precise_path(&mut d, 3.4876474632797176, 3.499999999999999); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(precise_path(&mut d, 7.77777777, 1.0), false))); + d.insert(Some(layer), 0, n).unwrap(); + let art = precise_path(&mut d, 1.23456789, 0.0); + d.symbols.push(Symbol { name: "S".into(), art: Arc::new(art) }); + let xf = Affine::new([1.0, 0.0, 0.0, 1.0, 0.123456789, 0.0]); + let id = d.alloc_id(); + d.insert(Some(layer), 1, Node::new(id, NodeKind::SymbolInstance { symbol: "S".into(), xf })).unwrap(); + let brush = serde_json::to_value(precise_path(&mut d, 5.55555555, 4.0)).unwrap(); + d.unknown.insert("brushes".into(), serde_json::json!([{"name": "B", "type": "art", "art": brush}])); + d +} + +fn first_anchor(n: &Node) -> Anchor { + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {n:?}") }; + path.subpaths[0].anchors[0] +} + +#[test] +fn precision_rounds_path_anchors_and_handles_only() { + let d = precise_doc(); + let bytes = save_with(&d, &SaveOptions { precision: Some(4), ..SaveOptions::default() }).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(!text.contains("-0.0"), "a handle rounded to zero is written as 0.0"); + let back = load(&bytes).unwrap(); + let path = &back.layers[0].children().unwrap()[0]; + let a = first_anchor(path); + assert_eq!((a.p, a.h_in, a.h_out), (Point::new(3.4876, 3.5), Point::new(3.4876, 3.5), Point::new(9.6111, 3.5))); + let mask = path.extras().mask.as_ref().unwrap(); + assert_eq!(first_anchor(&mask.art).p, Point::new(7.7778, 1.0)); + let a = first_anchor(&back.symbols[0].art); + assert_eq!((a.p, a.h_out), (Point::new(1.2346, 0.0), Point::new(7.358, 0.0))); + let brush = &back.unknown["brushes"][0]["art"]["kind"]["path"]["subpaths"][0]["anchors"][0]; + assert_eq!((brush["p"][0].as_f64(), brush["out"][0].as_f64()), (Some(5.5556), Some(11.679))); + // Colors and transforms keep every digit. + let original = &d.layers[0].children().unwrap()[0]; + assert_eq!(path.appearance, original.appearance); + assert_eq!(mask.art.appearance, original.extras().mask.as_ref().unwrap().art.appearance); + let NodeKind::SymbolInstance { xf, .. } = &back.layers[0].children().unwrap()[1].kind else { panic!("not an instance") }; + assert_eq!(xf.as_coeffs()[4], 0.123456789); + // The document saved is left as it was. + assert_eq!(first_anchor(&d.layers[0].children().unwrap()[0]).p.x, 3.4876474632797176); +} + +#[test] +fn precision_rounds_the_paths_objects_keep_besides_their_own() { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let path = || PathData::single(SubPath::polyline(&[Point::new(1.23456789, 0.0), Point::new(9.87654321, 5.0)], false)); + // Live Corners' uncut outline, and an Intertwine area. + let mut n = precise_path(&mut d, 1.0, 1.0); + if let NodeKind::Path { live, .. } = &mut n.kind { + *live = Some(Box::new(LiveShape::Path { base: path(), radii: vec![2.0], kinds: vec![], radii_relative: false })); + } + n.extras_mut().intertwine = Some(Box::new(path())); + d.insert(Some(layer), 0, n).unwrap(); + // A blend's replaced spine and an envelope's top-object outline. + let keys = vec![Arc::new(precise_path(&mut d, 1.0, 1.0)), Arc::new(precise_path(&mut d, 50.0, 1.0))]; + let blend = BlendSpec { spine: Some(path()), ..BlendSpec::default() }; + let id = d.alloc_id(); + d.insert(Some(layer), 1, Node::new(id, NodeKind::Blend { children: keys, spec: Box::new(blend) })).unwrap(); + let envelope = NodeKind::Envelope { + content: vec![Arc::new(precise_path(&mut d, 1.0, 1.0))], + kind: Box::new(EnvelopeKind::TopObject { path: path() }), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Default::default(), + }; + let id = d.alloc_id(); + d.insert(Some(layer), 2, Node::new(id, envelope)).unwrap(); + // The same three objects as brushes' art, and type, whose frame stays exact. + let mut brushes: Vec = d.layers[0].children().unwrap().iter().map(|n| serde_json::json!({"art": n})).collect(); + let frame = serde_json::json!({"subpaths": [{"anchors": [{"p": [1.23456789, 0.0]}], "closed": true}]}); + brushes.push(serde_json::json!({"art": {"id": 99, "kind": {"type": "text", "kind": "area", "frame": frame}}})); + d.unknown.insert("brushes".into(), Value::Array(brushes)); + let text = |precision| String::from_utf8(save_with(&d, &SaveOptions { precision, ..SaveOptions::default() }).unwrap()).unwrap(); + let exact = text(None); + assert_eq!((exact.matches("1.23456789").count(), exact.matches("9.87654321").count()), (9, 8), "{exact}"); + let rounded = text(Some(4)); + assert_eq!((rounded.matches("1.23456789").count(), rounded.matches("9.87654321").count()), (1, 0), "{rounded}"); + assert_eq!((rounded.matches("1.2346").count(), rounded.matches("9.8765").count()), (8, 8), "{rounded}"); +} + +#[test] +fn without_precision_coordinates_are_written_exactly() { + let d = precise_doc(); + let exact = save_with(&d, &SaveOptions::default()).unwrap(); + let text = String::from_utf8(exact.clone()).unwrap(); + for x in ["3.4876474632797176", "3.499999999999999", "7.77777777", "1.23456789", "5.55555555"] { + assert!(text.contains(x), "{x}"); + } + assert_eq!(first_anchor(&load(&exact).unwrap().layers[0].children().unwrap()[0]).p.x, 3.4876474632797176); + // A precision over MAX_PRECISION rounds to MAX_PRECISION decimals. + let at = |p| save_with(&d, &SaveOptions { precision: Some(p), ..SaveOptions::default() }).unwrap(); + assert_eq!(at(200), at(MAX_PRECISION)); + assert!(at(0).len() < at(MAX_PRECISION).len()); +} diff --git a/crates/mcp/src/tests_fileio.rs b/crates/mcp/src/tests_fileio.rs index 1788f558e5..6cb5c9c94b 100644 --- a/crates/mcp/src/tests_fileio.rs +++ b/crates/mcp/src/tests_fileio.rs @@ -195,6 +195,15 @@ fn save_file_takes_the_native_save_options() { let shown = saved_with(&mut h, "preview.vectorcraft", json!({"preview": true})); assert!(vectorcraft_format::preview(&shown).is_some(), "a preview"); assert!(vectorcraft_format::preview(&plain).is_none(), "off by default"); + // `precision` rounds the path coordinates of that save only. + let mut p = Headless::new(); + p.call("engine.execute", json!({"command": "file.new", "params": {"width": 100, "height": 100}})).unwrap(); + p.call("engine.execute", json!({"command": "path.create", "params": {"anchors": [{"x": 10.123456, "y": 20.654321}, {"x": 30.5, "y": 40.25}]}})) + .unwrap(); + let exact = String::from_utf8(saved_with(&mut p, "exact.vectorcraft", json!({"compress": false}))).unwrap(); + assert!(exact.contains("10.123456") && exact.contains("20.654321"), "{exact}"); + let rounded = String::from_utf8(saved_with(&mut p, "rounded.vectorcraft", json!({"compress": false, "precision": 1}))).unwrap(); + assert!(!rounded.contains("10.123456") && !rounded.contains("20.654321") && rounded.contains("20.7"), "{rounded}"); // Version 2 files can't be compressed: the engine's error comes back. let r = call_tool(&mut h, "save_file", &json!({"path": tmp("v2.vectorcraft"), "version": 2, "compress": true})); assert!(r.is_error && r.content[0]["text"].as_str().unwrap().contains("can't be compressed"), "{r:?}"); @@ -232,6 +241,9 @@ fn save_file_warns_about_options_it_does_not_use() { let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored.ai"), "compress": false, "version": 3}))); let w = warnings(&r); assert!(ignored(&w, "version") && !ignored(&w, "compress"), "{w:?}"); + // `precision` is read by native files only. + let r = text(&call_tool(&mut h, "save_file", &json!({"path": tmp("ignored-precision.svg"), "precision": 2}))); + assert!(ignored(&warnings(&r), "precision"), "{r}"); // A top-level value that disagrees with `options` is refused, and nothing is written. let path = tmp("both.vectorcraft"); @@ -241,7 +253,9 @@ fn save_file_warns_about_options_it_does_not_use() { assert!(r.is_error && e.contains("`compress: true` and `options.compress: false` disagree"), "{r:?}"); assert!(!std::path::Path::new(&path).exists(), "nothing is written"); // Nothing to say when they agree or when every option applies. - for mut args in [json!({"compress": true, "options": {"compress": true}}), json!({"compress": false, "version": 3, "preview": true})] { + for mut args in + [json!({"compress": true, "options": {"compress": true}}), json!({"compress": false, "version": 3, "preview": true, "precision": 4})] + { args["path"] = json!(tmp("quiet.vectorcraft")); let r = text(&call_tool(&mut h, "save_file", &args)); assert_eq!(r["warnings"], json!([]), "{args}: {r}"); @@ -272,12 +286,12 @@ fn save_file_is_the_same_call_in_the_app_and_headless() { let path = tmp("app.vectorcraft"); let (addr, app) = recording_app(); let mut remote = Remote::connect(&addr).unwrap(); - let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "options": {"preview": true}}); + let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "precision": 2, "options": {"preview": true}}); assert!(!call_tool(&mut remote, "save_file", &args).is_error); drop(remote); let seen = app.join().unwrap(); assert_eq!(seen[0]["method"], "app.save"); - assert_eq!(seen[0]["params"], json!({"path": path, "compress": true, "version": 3, "options": {"preview": true}, "wait": true})); + assert_eq!(seen[0]["params"], json!({"path": path, "compress": true, "version": 3, "precision": 2, "options": {"preview": true}, "wait": true})); } /// The app is asked to write the file before it replies (`wait`), even with Background Save on, so a diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index a11bbb098a..c88cdd87b7 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -37,7 +37,7 @@ fn string(desc: &str) -> Value { json!({"type": "string", "description": desc}) } /// The arguments `save_file` passes on to `document.save` beside `path`. -const SAVE_FILE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "options"]; +const SAVE_FILE_OPTIONS: [&str; 5] = ["compress", "version", "preview", "precision", "options"]; /// The arguments `doc_inspect` / `inspect_document` pass on to `document.inspect`. const INSPECT_KEYS: [&str; 6] = ["depth", "childLimit", "ids", "kind", "limit", "offset"]; @@ -363,7 +363,7 @@ pub fn tool_definitions() -> Vec { "save_file", "Save file", &format!( - "Save the active document with the engine's document.save: by default to its own file in its own format (native .vectorcraft unless it was opened from or saved as SVG, PDF or a restorable .ai). With `path`, the extension picks the format: .{}. Other formats are exports (see export). A native file is gzipped when `compress` is true (default: the useCompression preference, Preferences > File Handling > Use Compression); `version` writes it for an older VectorCraft and `preview` embeds a PNG of the first artboard. `options` carries the format's save options (see run_command document.formats); giving `compress`, `version` or `preview` both at the top level and in `options` with different values is an error. The reply's `format` says what was written and `warnings` what that format loses and each option given that the format doesn't read (such as `compress` for .svg). In the running app the call returns once the file is written, or with the error, even with Background Save on. When the save asks first (before replacing a file that opened with losses, or with a file dialog for an untitled document without `path`), the reply is `pending` or \"cancelled\" as before.", + "Save the active document with the engine's document.save: by default to its own file in its own format (native .vectorcraft unless it was opened from or saved as SVG, PDF or a restorable .ai). With `path`, the extension picks the format: .{}. Other formats are exports (see export). A native file is gzipped when `compress` is true (default: the useCompression preference, Preferences > File Handling > Use Compression); `version` writes it for an older VectorCraft, `preview` embeds a PNG of the first artboard, and `precision` rounds path anchors and handles to that many decimal places for that save only. `options` carries the format's save options (see run_command document.formats); giving `compress`, `version`, `preview` or `precision` both at the top level and in `options` with different values is an error. The reply's `format` says what was written and `warnings` what that format loses and each option given that the format doesn't read (such as `compress` for .svg). In the running app the call returns once the file is written, or with the error, even with Background Save on. When the save asks first (before replacing a file that opened with losses, or with a file dialog for an untitled document without `path`), the reply is `pending` or \"cancelled\" as before.", save_extensions().join(", .") ), obj( @@ -372,6 +372,7 @@ pub fn tool_definitions() -> Vec { "compress": {"type": "boolean", "description": "Native files: gzip the file (default: the useCompression preference)"}, "version": {"type": "integer", "minimum": 1, "maximum": vectorcraft_format::VERSION, "description": "Native files: the format version to write (default: the current one; 1 and 2 are never compressed)"}, "preview": {"type": "boolean", "description": "Native files: embed a PNG of the first artboard, at most 256 px (default false)"}, + "precision": {"type": "integer", "minimum": 0, "maximum": vectorcraft_format::MAX_PRECISION, "description": "Native files: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact (default: exact)"}, "options": {"type": "object", "description": "The format's save options, passed through (see run_command document.formats); default: as last saved"}, }), &[], @@ -1184,7 +1185,8 @@ fn named_export_params(a: &Args) -> &'static [&'static str] { /// What `save_file` with arguments `a` adds to the save's `warnings`, for a file written in format /// `written` (none when nothing was written yet): each key in `options` that the format doesn't -/// read. The save itself warns about `compress`, `version` and `preview` given at the top level. +/// read. The save itself warns about `compress`, `version`, `preview` and `precision` given at the +/// top level. fn save_file_warnings(a: &Args, written: Option<&str>) -> Vec { let Some(f) = written.and_then(format) else { return vec![] }; let nested = a.get("options").and_then(Value::as_object); diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 9118252b30..ea5ffb971f 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -74,15 +74,16 @@ fn separates(f: &Format) -> bool { f.options.iter().any(|o| o.name == "separateArtboards") } -/// The options the dialog shows: arrays and objects are for agents, and a page range replaces the -/// single artboard choice; none for a format with its own dialog. A `.ait` template has no -/// Version: Save as Template writes it PDF-compatible only. +/// The options the dialog shows: arrays and objects are for agents, as is a native file's +/// `precision`, and a page range replaces the single artboard choice; none for a format with its +/// own dialog. A `.ait` template has no Version: Save as Template writes it PDF-compatible only. fn shown(f: &Format) -> impl Iterator { let range = f.options.iter().any(|o| o.name == "range"); let separate = separates(f); let options = if own_dialog(f) { &[][..] } else { f.options }; options.iter().filter(move |o| { !(matches!(o.ty, "array" | "object") + || o.name == "precision" || (range && o.name == "artboard") || (separate && o.name == "range") || (matches!(f.id, "ai" | "ait") && o.name == "useArtboards") @@ -740,6 +741,18 @@ mod tests { assert!(!names("ait").contains(&"aiVersion"), "{:?}", names("ait")); } + /// The native options dialog has no row for `precision`, which agents give with the save + /// command; the rows it has stay. + #[test] + fn the_native_options_have_no_precision_row() { + for id in ["vectorcraft", "template"] { + let f = fileio::format(id).unwrap(); + assert!(f.options.iter().any(|o| o.name == "precision"), "{id}"); + let names: Vec<&str> = shown(f).map(|o| o.name).collect(); + assert!(!names.contains(&"precision") && names.contains(&"version") && names.contains(&"compress"), "{id}: {names:?}"); + } + } + /// A name typed in the Save as Template panel with a Save As format's extension has it /// replaced with the template's, as Save As replaces the extension of a format it doesn't write. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index b8a56499f7..48f061964a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -420,7 +420,7 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | | `open_file` | `{path}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG, JPEG, GIF, WebP, TIFF, BMP, Targa (`.tga`/`.vda`/`.icb`/`.vst`), PSD/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). `run_command document.formats` lists the formats. | -| `save_file` | `{path?, compress?, version?, preview?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), and `preview: true` embeds a PNG of the first artboard. `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version` or `preview` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version` or `preview`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version` or `preview`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. | +| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a `.ai` file reads `compress` but not `version`, `preview` or `precision`). `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warning for a top-level `compress`, `version`, `preview` or `precision`. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG, SVGZ and EPS write one file per chosen artboard. Rasters, DXF, EMF and WMF write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | @@ -596,7 +596,11 @@ can't be read becomes a placeholder in its box, named in `warnings` and `missing Native files: `run_command document.save {compress: true}` writes a gzip-compressed `.vectorcraft` (the `useCompression` preference makes that the default for saves; compressed files open like any other, told apart by their content). `version: 2` or `1` writes a file older VectorCraft versions open (format name `drawcraft`, never -compressed), and `preview: true` embeds a PNG of the first artboard, at most 256 px on its longer side. A save writes +compressed), and `preview: true` embeds a PNG of the first artboard, at most 256 px on its longer side. +`precision: 4` (0 to 9) rounds the anchors and handles of paths to that many decimal places (in the layers, symbols, +graph designs, patterns, opacity masks and brushes); colors, transforms, opacity and type are written exactly. +Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores +`precision`. A save writes a temporary file and renames it over the old one, so a failed save never damages the file; only the images the document uses are written, and document keys written by a newer version are kept. An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented From a4878b873e1b80cd453151bf860dc5408fa0b066 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 08:35:53 -0700 Subject: [PATCH 002/199] Native format: the preview and PDF of a save at a fixed precision show the rounded art A save with `precision` rounded only the native document, and drew the embedded preview and the `pdfCompatible` PDF from the exact document. An app reading the PDF showed paths up to 0.5 pt away from what VectorCraft reopens at `precision: 0`. When `precision` is set, the preview and the PDF are now drawn from a copy of the document rounded as the file holds it. For an older version, placed documents in that copy become groups of their art first, as the file stores them, so their rounded art shows too. Tests: a save at precision 0 puts the path in the embedded PDF on the rounded coordinates, and its preview matches the one drawn from the saved document; the same for a version 3 save of a placed document. --- crates/engine/src/cmd/fileio/native.rs | 24 +++++++++++++-- crates/engine/src/tests_placed_document.rs | 6 ++++ crates/engine/src/tests_saveoptions.rs | 36 ++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 65 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index b36e387deb..ac6cbe6b7a 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -199,13 +199,19 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } else { std::borrow::Cow::Borrowed(doc) }; + // With a precision, the preview and PDF show the rounded art the file holds. + let drawn = match so.precision { + Some(decimals) if extras.preview || extras.pdf => Cow::Owned(rounded(&full, so.version, decimals)), + _ => Cow::Borrowed(full.as_ref()), + }; if extras.preview { - so.preview = preview_png(&full)?; + so.preview = preview_png(&drawn)?; } if extras.pdf { // Every artboard as PDF pages (no editing data: the file is the native document). - so.pdf = Some(super::pdf::encode(cmd, &full, &json!({ "range": "all", "preserveEditing": false }))?.0); + so.pdf = Some(super::pdf::encode(cmd, &drawn, &json!({ "range": "all", "preserveEditing": false }))?.0); } + drop(drawn); let native = match full { Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::VERSION => { // Include available bytes without replacing missing, relinkable placed objects. @@ -219,6 +225,20 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } +/// `doc` with its path geometry rounded to `decimals` places, as [`vectorcraft_format::save_to`] +/// writes it for `version`: placed documents become groups of their art for older versions. +fn rounded(doc: &Document, version: u32, decimals: u8) -> Document { + let mut d = if version < vectorcraft_format::VERSION && doc.has_placed() { + let mut d = doc.with_placed_art().into_owned(); + d.placed_as_groups(); + d + } else { + doc.clone() + }; + d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION)); + d +} + /// The ICC files of the profiles `doc` is tagged with that were loaded from files (the built-in /// ones are there wherever VectorCraft runs). fn embedded_profiles(doc: &Document) -> BTreeMap> { diff --git a/crates/engine/src/tests_placed_document.rs b/crates/engine/src/tests_placed_document.rs index 4a0f359aec..de0181e1ef 100644 --- a/crates/engine/src/tests_placed_document.rs +++ b/crates/engine/src/tests_placed_document.rs @@ -730,6 +730,12 @@ fn saved_for_older_apps_with_a_precision_the_placed_art_is_rounded_too() { let rounded = saved(json!({"format": "vectorcraft", "version": 3, "precision": 4})); assert_eq!(rounded.len(), exact.len()); assert!(rounded.iter().all(|x| at4(*x)), "{rounded:?}"); + // The preview shows the rounded art the older app opens, not the placed file's exact art. + let file = decode(&s.execute("file.saveCopy", &json!({"version": 3, "precision": 0, "preview": true})).unwrap()); + let preview = vectorcraft_format::preview(&file); + assert!(preview.is_some()); + assert_eq!(preview, crate::cmd::fileio::preview_png(&vectorcraft_format::load(&file).unwrap()).unwrap()); + assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap()); } #[test] diff --git a/crates/engine/src/tests_saveoptions.rs b/crates/engine/src/tests_saveoptions.rs index f1f449b758..2f9d3cafe2 100644 --- a/crates/engine/src/tests_saveoptions.rs +++ b/crates/engine/src/tests_saveoptions.rs @@ -423,3 +423,39 @@ fn a_ai_file_ignores_precision_as_save_does() { } } } + +/// The anchors of every path in `n` and the art it holds. +fn all_anchors(n: &vectorcraft_doc::Node, out: &mut Vec) { + if let NodeKind::Path { path, .. } = &n.kind { + out.extend(path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))); + } + for c in n.children().into_iter().flatten() { + all_anchors(c, out); + } +} + +#[test] +fn the_preview_and_pdf_of_a_save_at_a_precision_show_the_rounded_art() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let anchors = json!([{"x": 10.4, "y": 20.3}, {"x": 80.6, "y": 30.7}, {"x": 45.35, "y": 85.65}]); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let file = bytes_of(&s.execute("file.saveCopy", &json!({"precision": 0, "pdfCompatible": true, "preview": true})).unwrap()["dataBase64"]); + // The embedded PDF, opened, has the path on whole points. + let pdf = vectorcraft_format::pdf_content(&file).unwrap(); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "x.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)})).unwrap(); + let mut got = vec![]; + for l in &t.doc().unwrap().doc.layers { + all_anchors(l, &mut got); + } + for (x, y) in [(10.0, 20.0), (81.0, 31.0), (45.0, 86.0)] { + assert!(got.iter().any(|p| (p.x - x).abs() < 1e-3 && (p.y - y).abs() < 1e-3), "({x}, {y}) not in {got:?}"); + } + assert!(got.iter().all(|p| (p.x - p.x.round()).abs() < 1e-3 && (p.y - p.y.round()).abs() < 1e-3), "{got:?}"); + // The preview is the one the saved document draws, not the exact art's. + let preview = vectorcraft_format::preview(&file); + assert!(preview.is_some()); + assert_eq!(preview, crate::cmd::fileio::preview_png(&vectorcraft_format::load(&file).unwrap()).unwrap()); + assert_ne!(preview, crate::cmd::fileio::preview_png(&s.doc().unwrap().doc).unwrap()); +} diff --git a/docs/mcp.md b/docs/mcp.md index 48f061964a..3ef0706914 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -599,7 +599,7 @@ their content). `version: 2` or `1` writes a file older VectorCraft versions ope compressed), and `preview: true` embeds a PNG of the first artboard, at most 256 px on its longer side. `precision: 4` (0 to 9) rounds the anchors and handles of paths to that many decimal places (in the layers, symbols, graph designs, patterns, opacity masks and brushes); colors, transforms, opacity and type are written exactly. -Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores +The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores `precision`. A save writes a temporary file and renames it over the old one, so a failed save never damages the file; only the images the document uses are written, and document keys written by a newer version are kept. From f41e40bbc65b8eca53d6281e6d25ef5fdde7a5de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 29 Oct 2026 10:27:33 -0700 Subject: [PATCH 003/199] Save: a native save's precision is not kept for new documents --- crates/engine/src/cmd/fileio/save.rs | 2 +- crates/engine/src/tests/saveoptions.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 6b1d32dd68..d4f7b17040 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -871,7 +871,7 @@ impl SaveJob { let saved = self.plan.retargets() && self.plan.path.is_some(); if saved && self.plan.format.id == "vectorcraft" { let mut last = self.plan.options.clone(); - last.retain(|k, _| !ARTBOARD_PARAMS.contains(&k.as_str()) && !matches!(k.as_str(), "separateArtboards" | "compress")); + last.retain(|k, _| !ARTBOARD_PARAMS.contains(&k.as_str()) && !matches!(k.as_str(), "separateArtboards" | "compress" | "precision")); s.prefs.native_save_options = last; } // The other open documents that place this one show the new version. diff --git a/crates/engine/src/tests/saveoptions.rs b/crates/engine/src/tests/saveoptions.rs index b3c9c5e8c8..d52cbba610 100644 --- a/crates/engine/src/tests/saveoptions.rs +++ b/crates/engine/src/tests/saveoptions.rs @@ -403,6 +403,19 @@ fn precision_rounds_the_paths_of_that_save_only() { assert!(e.contains("`document.save`") && !e.contains("document.export"), "{e}"); } +#[test] +fn precision_is_not_remembered_for_new_documents() { + let dir = Folder::new("precision-preferences"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("document.save", &json!({"path": dir.file("rounded.vectorcraft"), "precision": 3})).unwrap(); + assert!(!s.prefs.native_save_options.contains_key("precision")); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let options = s.execute("file.formatOptions", &json!({"format": "vectorcraft"})).unwrap(); + assert!(options["options"]["precision"]["value"].is_null(), "{}", options["options"]["precision"]); +} + #[test] fn a_ai_file_ignores_precision_as_save_does() { let mut s = Session::new(); From 891766a5ed1df2ccb2da3ac4b188068407f2d035 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 18:34:18 -0700 Subject: [PATCH 004/199] Native format: precision rounds Intertwine areas of every tier A save with precision rounded the tier-1 Intertwine area but left the areas of tier 2 and up exact. The format test now gives the object a tier-2 area too, and sets the symbol's new dynamic field. --- crates/doc/src/document_ext.rs | 6 ++++-- crates/format/tests/it/save_options.rs | 9 +++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index e866d15e89..c81d761f96 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -164,8 +164,10 @@ impl Document { } _ => {} } - if let Some(area) = n.extras_if_any().and_then(|e| e.intertwine.as_deref_mut()) { - round_path(area); + if let Some(e) = n.extras_if_any() { + for area in e.intertwine.as_deref_mut().into_iter().chain(e.intertwine_tiers.iter_mut()) { + round_path(area); + } } }; let roots = self diff --git a/crates/format/tests/it/save_options.rs b/crates/format/tests/it/save_options.rs index 327a7f63cb..5cbf45e9c8 100644 --- a/crates/format/tests/it/save_options.rs +++ b/crates/format/tests/it/save_options.rs @@ -229,7 +229,7 @@ fn precise_doc() -> Document { n.extras_mut().mask = Some(Box::new(OpacityMask::new(precise_path(&mut d, 7.77777777, 1.0), false))); d.insert(Some(layer), 0, n).unwrap(); let art = precise_path(&mut d, 1.23456789, 0.0); - d.symbols.push(Symbol { name: "S".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); let xf = Affine::new([1.0, 0.0, 0.0, 1.0, 0.123456789, 0.0]); let id = d.alloc_id(); d.insert(Some(layer), 1, Node::new(id, NodeKind::SymbolInstance { symbol: "S".into(), xf })).unwrap(); @@ -274,12 +274,13 @@ fn precision_rounds_the_paths_objects_keep_besides_their_own() { let mut d = Document::new(100.0, 100.0); let layer = d.layers[0].id; let path = || PathData::single(SubPath::polyline(&[Point::new(1.23456789, 0.0), Point::new(9.87654321, 5.0)], false)); - // Live Corners' uncut outline, and an Intertwine area. + // Live Corners' uncut outline, and Intertwine areas of tiers 1 and 2. let mut n = precise_path(&mut d, 1.0, 1.0); if let NodeKind::Path { live, .. } = &mut n.kind { *live = Some(Box::new(LiveShape::Path { base: path(), radii: vec![2.0], kinds: vec![], radii_relative: false })); } n.extras_mut().intertwine = Some(Box::new(path())); + n.extras_mut().intertwine_tiers = vec![path()]; d.insert(Some(layer), 0, n).unwrap(); // A blend's replaced spine and an envelope's top-object outline. let keys = vec![Arc::new(precise_path(&mut d, 1.0, 1.0)), Arc::new(precise_path(&mut d, 50.0, 1.0))]; @@ -303,10 +304,10 @@ fn precision_rounds_the_paths_objects_keep_besides_their_own() { d.unknown.insert("brushes".into(), Value::Array(brushes)); let text = |precision| String::from_utf8(save_with(&d, &SaveOptions { precision, ..SaveOptions::default() }).unwrap()).unwrap(); let exact = text(None); - assert_eq!((exact.matches("1.23456789").count(), exact.matches("9.87654321").count()), (9, 8), "{exact}"); + assert_eq!((exact.matches("1.23456789").count(), exact.matches("9.87654321").count()), (11, 10), "{exact}"); let rounded = text(Some(4)); assert_eq!((rounded.matches("1.23456789").count(), rounded.matches("9.87654321").count()), (1, 0), "{rounded}"); - assert_eq!((rounded.matches("1.2346").count(), rounded.matches("9.8765").count()), (8, 8), "{rounded}"); + assert_eq!((rounded.matches("1.2346").count(), rounded.matches("9.8765").count()), (10, 10), "{rounded}"); } #[test] From 01798d86ab2a04daa549767684b336a413317481 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 05:34:19 -0800 Subject: [PATCH 005/199] Native format: tests for exact saves, rounding halves, closed and tiny paths Without `precision` 500 coordinates of every size reopen bit for bit and a second save writes the same bytes. Halves round away from zero, a closed path keeps its closing anchor on its first one, a shape smaller than one step collapses onto one point, coordinates at the edge of the canvas round to the asked places, and saving a rounded file again at the same precision writes the same bytes. docs/mcp.md states these rules. --- crates/format/tests/it/save_options.rs | 90 +++++++++++++++++++++++++- docs/mcp.md | 5 +- 2 files changed, 93 insertions(+), 2 deletions(-) diff --git a/crates/format/tests/it/save_options.rs b/crates/format/tests/it/save_options.rs index 5cbf45e9c8..3cd163ed15 100644 --- a/crates/format/tests/it/save_options.rs +++ b/crates/format/tests/it/save_options.rs @@ -7,7 +7,9 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::links::LinkInfo; -use vectorcraft_doc::{Appearance, BlendSpec, Document, EnvelopeKind, ImageBlob, ImageObject, LiveShape, Node, NodeKind, OpacityMask, Symbol}; +use vectorcraft_doc::{ + Appearance, BlendSpec, Document, EnvelopeKind, ImageBlob, ImageObject, LiveShape, MAX_COORD, Node, NodeKind, OpacityMask, Symbol, +}; use vectorcraft_format::{ ICC_MIME, MAX_PRECISION, PRETTY_MAX_BYTES, PRETTY_MAX_OBJECTS, SaveOptions, load, load_file, pdf_content, save_file, save_with, }; @@ -324,3 +326,89 @@ fn without_precision_coordinates_are_written_exactly() { assert_eq!(at(200), at(MAX_PRECISION)); assert!(at(0).len() < at(MAX_PRECISION).len()); } + +/// A document holding one path through `points`. +fn doc_with_path(points: &[Point], closed: bool) -> Document { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let path = PathData::single(SubPath::polyline(points, closed)); + d.insert(Some(layer), 0, Node::path(id, path, Appearance::basic(Paint::None, Paint::None, 0.0))).unwrap(); + d +} + +/// The first subpath of the first object of `d` saved at `precision` and opened again. +fn saved_subpath(d: &Document, precision: Option) -> SubPath { + let back = load(&save_with(d, &SaveOptions { precision, ..SaveOptions::default() }).unwrap()).unwrap(); + let NodeKind::Path { path, .. } = &back.layers[0].children().unwrap()[0].kind else { panic!("not a path") }; + path.subpaths[0].clone() +} + +#[test] +fn without_precision_every_coordinate_reopens_bit_for_bit() { + // 500 anchors at coordinates of every size and sign (a fixed pseudo-random sequence). + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + let unit = (seed >> 11) as f64 / (1u64 << 53) as f64 - 0.5; + unit * 10f64.powi((seed % 13) as i32 - 6) + }; + let mut points: Vec = (0..500).map(|_| Point::new(next(), next())).collect(); + points.extend([Point::new(MAX_COORD, -1e-300), Point::new(f64::MIN_POSITIVE, -3_999_999.123_456_789)]); + let d = doc_with_path(&points, false); + let bytes = save_with(&d, &SaveOptions::default()).unwrap(); + let got: Vec = saved_subpath(&d, None).anchors.iter().map(|a| a.p).collect(); + let bits = |ps: &[Point]| ps.iter().map(|p| (p.x.to_bits(), p.y.to_bits())).collect::>(); + assert_eq!(bits(&got), bits(&points)); + // Saving the reopened file writes the same bytes. + assert_eq!(save_with(&load(&bytes).unwrap(), &SaveOptions::default()).unwrap(), bytes); +} + +#[test] +fn precision_rounds_halves_away_from_zero() { + // These halves are exact in binary, so the scaled value is exactly .5. + let d = doc_with_path(&[Point::new(0.125, -0.125), Point::new(0.375, -0.375), Point::new(1.5, -2.5)], false); + let at = |p| saved_subpath(&d, Some(p)).anchors.iter().map(|a| a.p).collect::>(); + assert_eq!(at(2), [Point::new(0.13, -0.13), Point::new(0.38, -0.38), Point::new(1.5, -2.5)]); + assert_eq!(at(0), [Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(2.0, -3.0)]); + // `1.005` is stored as slightly less than the decimal, so it goes down. + let d = doc_with_path(&[Point::new(1.005, -1.005)], false); + assert_eq!(saved_subpath(&d, Some(2)).anchors[0].p, Point::new(1.0, -1.0)); +} + +#[test] +fn a_rounded_closed_path_stays_closed_on_its_first_anchor() { + let first = Point::new(10.123456, 20.987654); + let d = doc_with_path(&[first, Point::new(50.55555, 20.4444), Point::new(30.01, 60.996), first], true); + let sp = saved_subpath(&d, Some(2)); + assert!(sp.closed); + assert_eq!(sp.anchors.len(), 4); + assert_eq!(sp.anchors[0].p, Point::new(10.12, 20.99)); + assert_eq!(sp.anchors[3].p, sp.anchors[0].p); +} + +#[test] +fn a_shape_smaller_than_the_precision_keeps_its_anchors_on_one_point() { + let d = doc_with_path(&[Point::new(5.0001, 5.0001), Point::new(5.0004, 5.0001), Point::new(5.0002, 5.0004)], true); + let sp = saved_subpath(&d, Some(3)); + assert!(sp.closed); + assert_eq!(sp.anchors.iter().map(|a| a.p).collect::>(), [Point::new(5.0, 5.0); 3]); +} + +#[test] +fn precision_rounds_coordinates_at_the_edge_of_the_canvas() { + let points = [Point::new(3_999_999.123_456_789, -3_999_999.987_654_321), Point::new(MAX_COORD, -MAX_COORD)]; + let d = doc_with_path(&points, false); + let at = |p| saved_subpath(&d, Some(p)).anchors.iter().map(|a| a.p).collect::>(); + assert_eq!(at(3), [Point::new(3_999_999.123, -3_999_999.988), points[1]]); + for (got, want) in at(MAX_PRECISION).iter().zip(&points) { + assert!((got.x - want.x).abs() <= 1e-9 && (got.y - want.y).abs() <= 1e-9, "{got:?} vs {want:?}"); + } +} + +#[test] +fn saving_a_rounded_file_at_the_same_precision_again_writes_the_same_bytes() { + let o = SaveOptions { precision: Some(2), ..SaveOptions::default() }; + let once = save_with(&precise_doc(), &o).unwrap(); + assert_eq!(save_with(&load(&once).unwrap(), &o).unwrap(), once); +} diff --git a/docs/mcp.md b/docs/mcp.md index 5754f17a7a..7108d0b5c2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -639,7 +639,10 @@ their content). `version: 2` or `1` writes a file older VectorCraft versions ope compressed), and `preview: true` embeds a PNG of the first artboard, at most 256 px on its longer side. `precision: 4` (0 to 9) rounds the anchors and handles of paths to that many decimal places (in the layers, symbols, graph designs, patterns, opacity masks and brushes); colors, transforms, opacity and type are written exactly. -The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores +Each coordinate goes to the nearest step of its stored binary value, and a value exactly halfway rounds away from +zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on +its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the +file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores `precision`. A save writes a temporary file and renames it over the old one, so a failed save never damages the file; only the images the document uses are written, and document keys written by a newer version are kept. From 205e5b3e8be497db92286f51f3c7ac53287ed1f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 01:06:40 -0800 Subject: [PATCH 006/199] Global Edit: a Shift-click on a highlighted match leaves it out of the edit While Global Edit is on, a Shift-click (not a Shift-drag) with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out: it is no longer highlighted and later edits leave it as it is. The object the edit started from stays in, and Global Edit ends when fewer than two matches are left. Leaving a match out is not an undo step. - New command `select.globalEditExclude {id}` returns `{active, count, ids}`; the Selection tool calls it on the release of a Shift-click. - `ToolContext::global_edit` gives the tools the Global Edit's objects. - Label and messages in the i18n catalogs; docs/mcp.md, docs/ui-parity.md and docs/target-app-parity.md updated. Source: https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html --- crates/engine/src/cmd/globaledit.rs | 52 +++++++++++- crates/engine/src/tests/globaledit.rs | 114 ++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/context.rs | 3 + crates/tools/src/lib.rs | 1 + crates/tools/src/select.rs | 68 +++++++++++---- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + docs/mcp.md | 8 ++ docs/target-app-parity.md | 3 +- docs/ui-parity.md | 2 +- 35 files changed, 303 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 6ff31dabea..56ae301408 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -59,8 +59,15 @@ //! opacity, blending, fills and effects). When the model group gains or loses objects, or one of //! them becomes another kind of object, each member takes the model's objects at that level //! whole, keeping its own ids in order. At most [`MAX_MEMBERS`] objects are taken, so that a huge -//! document can't stall the start or every edit. Rotated copies and excluding a member with a -//! Shift-click are not covered. +//! document can't stall the start or every edit. +//! +//! In the how-to above, a Shift-click on one of the found objects takes it out of the edit. Here a +//! Shift-click (not a Shift-drag) with the Selection tool on a highlighted member, or on an object +//! inside it, leaves that member out (`select.globalEditExclude`): it is no longer highlighted, +//! and later edits leave it as it is. +//! The object the edit started from can't be left out (a Shift-click on it selects it or +//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving +//! one out is not an undo step. Rotated copies are not covered. use serde::Serialize; use serde_json::{Value, json}; @@ -68,10 +75,11 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, Nod use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape}; use super::wand::{fill_of, stroke_of}; -use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc}; +use super::{CommandSpec, Result, Session, bad, bool_or, checked_id, cmd, has_doc}; const C: &str = "select.globalEdit"; const OPTIONS: &str = "select.globalEditOptions"; +const EXCLUDE: &str = "select.globalEditExclude"; /// The most objects a Global Edit takes, the selected one included. pub const MAX_MEMBERS: usize = 10_000; const UNSUPPORTED: &str = "Global Edit works on paths, compound paths, symbol instances and groups of them"; @@ -96,6 +104,15 @@ pub fn specs() -> Vec { has_doc, set_options ), + cmd!( + "select.globalEditExclude", + "Leave Out of Global Edit", + [], + None, + "{id} while Global Edit is on: leave the object `id` of the Global Edit (not the one it started from) out of it, as a Shift-click on it with the Selection tool does: it is no longer highlighted and later edits leave it as it is; with fewer than two objects left, Global Edit ends; not an undo step → {active, count, ids} (the objects left in it; none once it has ended)", + is_on, + exclude + ), ] } @@ -385,6 +402,35 @@ fn toggle(s: &mut Session, p: &Value) -> Result { Ok(json!({ "active": true, "count": ids.len(), "ids": ids })) } +fn is_on(s: &Session) -> std::result::Result<(), String> { + match s.active() { + None => Err("no document open".into()), + Some(st) if st.global_edit.is_none() => Err("Global Edit is off".into()), + Some(_) => Ok(()), + } +} + +/// Leave one object out of the Global Edit (a Shift-click on it): not the object it started from. +fn exclude(s: &mut Session, p: &Value) -> Result { + let id = checked_id(s, p.get("id").ok_or_else(|| bad(EXCLUDE, "missing id"))?, EXCLUDE)?; + let st = s.doc_mut()?; + let Some(ge) = &mut st.global_edit else { return Err(bad(EXCLUDE, "Global Edit is off")) }; + match ge.members.iter().position(|(m, _)| *m == id) { + Some(i) if i > 0 => { + ge.members.remove(i); + } + _ => return Err(bad(EXCLUDE, "only an object of the Global Edit other than the one it started from can be left out")), + } + let ids: Vec = if ge.members.len() < 2 { + st.global_edit = None; + vec![] + } else { + ge.members.iter().map(|(id, _)| id.0).collect() + }; + st.revision += 1; + Ok(json!({ "active": !ids.is_empty(), "count": ids.len(), "ids": ids })) +} + fn set_options(s: &mut Session, p: &Value) -> Result { let o = s.global_edit_options.with(p, &s.doc()?.doc, OPTIONS)?; s.global_edit_options = o.clone(); diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index aeb426ac45..b73efd0df5 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -391,6 +391,120 @@ fn undo_and_redo_drop_the_members_the_document_lacks() { assert_eq!(members(&s), None); } +#[test] +fn an_object_left_out_keeps_its_own_shape_while_the_others_follow() { + let mut s = session(); + let [a, b, c, ..] = squares(&mut s); + assert_eq!(start(&mut s, a, json!({})), [a, b, c]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap(); + assert_eq!(r, json!({"active": true, "count": 2, "ids": [a.0, c.0]})); + assert_eq!(members(&s), Some(vec![a, c])); + assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 1, "the copy is no longer highlighted"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "not an undo step"); + assert_eq!(s.doc().unwrap().selection.objects, [a], "the selection stays"); + let b_was = node(&s, b); + s.execute("object.setBounds", &json!({"height": 50, "reference": 0})).unwrap(); + assert!(close(bounds(&s, c), Rect::new(500.0, 0.0, 520.0, 10.0)), "{:?}", bounds(&s, c)); + assert_eq!(node(&s, b), b_was, "the copy left out keeps its shape"); +} + +/// A Shift-drag with the Selection tool from `from` to `to`. +fn shift_drag(s: &mut Session, from: (f64, f64), to: (f64, f64)) { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let steps = if from == to { + vec![(PointerKind::Down, from), (PointerKind::Up, to)] + } else { + vec![(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] + }; + for (kind, (x, y)) in steps { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() }), v).unwrap(); + } +} + +/// A Shift-click with the Selection tool at (`x`, `y`). +fn shift_click(s: &mut Session, x: f64, y: f64) { + shift_drag(s, (x, y), (x, y)); +} + +#[test] +fn a_shift_click_on_a_highlighted_object_leaves_it_out() { + let mut s = session(); + let [a, b, c, ..] = squares(&mut s); + start(&mut s, a, json!({})); + // A Shift-drag that starts on the copy moves the selection and leaves the copy in. + shift_drag(&mut s, (350.0, 50.0), (390.0, 50.0)); + assert_eq!(members(&s), Some(vec![a, b, c]), "a drag leaves nothing out"); + assert!(bounds(&s, a).x0 > 0.0, "the selection moved: {:?}", bounds(&s, a)); + s.execute("edit.undo", &json!({})).unwrap(); + shift_click(&mut s, 350.0, 50.0); + assert_eq!(members(&s), Some(vec![a, c]), "the copy is left out"); + assert_eq!(s.doc().unwrap().selection.objects, [a], "and not selected"); + // A Shift-click on the object the edit started from deselects it, as before. + shift_click(&mut s, 50.0, 50.0); + assert_eq!(members(&s), Some(vec![a, c])); + assert!(s.doc().unwrap().selection.objects.is_empty()); + shift_click(&mut s, 510.0, 10.0); + assert_eq!(members(&s), None, "one object left: Global Edit ends"); + assert!(s.doc().unwrap().selection.objects.is_empty()); + // With Global Edit off, a Shift-click selects, as before. + shift_click(&mut s, 350.0, 50.0); + assert_eq!(s.doc().unwrap().selection.objects, [b]); +} + +#[test] +fn a_shift_click_inside_a_matched_group_leaves_the_whole_group_out() { + let mut s = session(); + let (g, _) = card(&mut s, 0.0, 1.0); + let (copy, _) = card(&mut s, 300.0, 1.0); + let (small, _) = card(&mut s, 500.0, 0.5); + assert_eq!(start(&mut s, g, json!({})), [g, copy, small]); + // On the circle in the copy. + shift_click(&mut s, 370.0, 20.0); + assert_eq!(members(&s), Some(vec![g, small])); + assert_eq!(s.doc().unwrap().selection.objects, [g]); + // An object inside a member that is selected: a Shift-click deselects it, as before. + let inner = kids(&s, small)[0]; + sel(&mut s, &[inner]); + shift_click(&mut s, 505.0, 5.0); + assert_eq!(members(&s), Some(vec![g, small])); +} + +#[test] +fn leaving_out_all_but_one_ends_global_edit_and_the_first_object_stays() { + let mut s = session(); + let [a, b, c, wide, _] = squares(&mut s); + let e = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap_err().to_string(); + assert!(e.contains("Global Edit is off"), "{e}"); + start(&mut s, a, json!({})); + for id in [a, wide] { + let e = s.execute("select.globalEditExclude", &json!({"id": id.0})).unwrap_err().to_string(); + assert!(e.contains("other than the one it started from"), "{id}: {e}"); + } + assert_eq!(members(&s), Some(vec![a, b, c]), "nothing left out"); + s.execute("select.globalEditExclude", &json!({"id": c.0})).unwrap(); + let r = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap(); + assert_eq!(r, json!({"active": false, "count": 0, "ids": []})); + assert_eq!(members(&s), None, "one object left: Global Edit ends"); + assert!(crate::cmd::globaledit::highlights(&s).is_empty()); +} + +#[test] +fn a_group_left_out_keeps_its_objects_while_the_others_follow() { + let mut s = session(); + let (g, [_, dot, _]) = card(&mut s, 0.0, 1.0); + let (copy, [_, cdot, _]) = card(&mut s, 300.0, 1.0); + let (small, [_, sdot, _]) = card(&mut s, 500.0, 0.5); + assert_eq!(start(&mut s, g, json!({})), [g, copy, small]); + s.execute("select.globalEditExclude", &json!({"id": copy.0})).unwrap(); + let was = fill(&s, cdot); + sel(&mut s, &[dot]); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + assert_eq!((fill(&s, sdot), fill(&s, cdot)), ("#12ab34".to_string(), was)); +} + /// Two 100 pt squares and a 20 pt one made after `begin`, all three in a Global Edit; `put_back` /// takes the document back to before the small one. The small square leaves the Global Edit, and /// a square made under its freed id is not edited with the others. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index c54bda1297..dbb02a2af1 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -328,6 +328,7 @@ impl Session { screen: view.screen, plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position), precise_cursors: self.precise_cursors(), + global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()), }; let tool = &mut self.tool; match crate::guard::catch_panic(|| f(tool.as_mut(), &cx)) { diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index d6860bb7bc..85b7272223 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -256,6 +256,9 @@ pub struct ToolContext<'a> { /// General › Use Precise Cursors, or Caps Lock while it is on: the drawing tools' pointers are /// crosshairs ([`crate::Cursor::precise`]), and the Blob Brush and the Eraser show no tip outline. pub precise_cursors: bool, + /// The objects of the Global Edit in progress (Select › Start Global Edit), the one it started + /// from first, each with its transform; empty while Global Edit is off. + pub global_edit: &'a [(NodeId, vectorcraft_geom::Affine)], } impl ToolContext<'_> { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 67d2f59095..481fa2a697 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -508,6 +508,7 @@ pub(crate) mod testutil { screen: None, plane_widget: Some(Default::default()), precise_cursors: false, + global_edit: &[], } } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 737a29f676..2819c33697 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -32,6 +32,8 @@ //! With Smart Guides and Invoke Distance Guides on, Alt/Option held over another object shows how //! far the selection is from it, and over an empty part of an artboard how far it is from the //! artboard's edges ([`crate::guides::distance_guides`]). +//! While Global Edit is on, a Shift-click on a highlighted object of it, or on an object inside +//! one, leaves that object out of the edit (`select.globalEditExclude`). use std::cell::RefCell; use std::collections::HashMap; @@ -72,6 +74,9 @@ enum State { /// guides: released without a drag, it becomes the key object that Align aligns to if /// `can_be_key` allows it (the key again: no key). key: Option, + /// Shift-pressed on this highlighted object of the Global Edit: released without a drag, + /// it leaves the Global Edit (`select.globalEditExclude`). + exclude: Option, }, Scaling { handle: Handle, @@ -719,7 +724,7 @@ impl Tool for SelectionTool { && cx.select_behind && let Some(behind) = object_behind(cx, p) { - self.state = State::Moving { start: p, press: p, hold: p, began: false, deselect: None, key: None }; + self.state = State::Moving { start: p, press: p, hold: p, began: false, deselect: None, key: None, exclude: None }; return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } let (hit, scope) = match selected_source_hit(cx, p) { @@ -730,15 +735,9 @@ impl Tool for SelectionTool { Some(h) => { let top = h.top_object(scope); let mut out = vec![]; - let (mut deselect, mut key) = (None, None); + let (mut deselect, mut key, mut exclude) = (None, None, None); if m.shift { - // A Shift-click takes a selected object out of the selection when it - // is released; a Shift-drag moves the selection, constrained. - if cx.selection.contains(top) { - deselect = Some(top); - } else { - out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); - } + (deselect, exclude) = shift_press(cx, &h, top, &mut out); } else if !cx.selection.contains(top) { out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] }))); } else if (cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty()) && !m.cmd && !m.alt { @@ -747,7 +746,7 @@ impl Tool for SelectionTool { // Grabbed by no anchor or centre, a press on a path's stroke or beside its // edge holds the path there, and that point of it snaps (#3701). let hold = if grabbed.is_some() { grab } else { hold_point(cx, &h, p) }; - self.state = State::Moving { start: grab, press: p, hold, began: false, deselect, key }; + self.state = State::Moving { start: grab, press: p, hold, began: false, deselect, key, exclude }; out } None => { @@ -833,7 +832,9 @@ impl Tool for SelectionTool { self.state = State::Idle; b.finish() } - (PointerKind::Up, State::Moving { began, deselect, key, .. }) => self.release_move(cx, ev.backquote, began, deselect, key), + (PointerKind::Up, State::Moving { began, deselect, key, exclude, .. }) => { + self.release_move(cx, ev.backquote, began, deselect, key, exclude) + } (PointerKind::Up, State::Scaling { .. } | State::Rotating { .. }) => { let mut out = if ev.backquote || self.last_backquote { self.last_box_pos.map_or_else(Vec::new, |pos| self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, pos, ..*ev })) @@ -976,6 +977,32 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option { stack.get(next).or(stack.first()).copied() } +/// A Shift-press on `top` (hit by `h`): a Shift-click takes a selected object out of the selection +/// when it is released, and a Shift-drag moves the selection, constrained. On an object of the +/// Global Edit that is highlighted, the release leaves that object out of the edit instead. +/// Returns the object to deselect and the object to leave out on release; adds to `out` the +/// action that selects `top` at once. +fn shift_press(cx: &ToolContext, h: &Hit, top: NodeId, out: &mut Vec) -> (Option, Option) { + if let Some(member) = global_edit_member(cx, h) { + (None, Some(member)) + } else if cx.selection.contains(top) { + (Some(top), None) + } else { + out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); + (None, None) + } +} + +/// The object of the Global Edit in progress that the click `h` lands on or inside, when it is +/// highlighted: neither the object the edit started from nor one that is selected or holds a +/// selected object (`select.globalEditExclude` leaves it out of the edit). +fn global_edit_member(cx: &ToolContext, h: &Hit) -> Option { + let others = cx.global_edit.get(1..)?; + let member = h.ancestry.iter().chain([&h.leaf]).find(|id| others.iter().any(|(m, _)| m == *id)).copied()?; + let selected = cx.selection.objects.iter().any(|s| cx.doc.ancestry(*s).is_some_and(|a| a.contains(&member))); + (!selected).then_some(member) +} + /// Can a click make `id` the key object? `select.key` takes only a selected top-level object. In /// isolation mode a click can pick a sublayer (inside an isolated layer), a compound-path member /// (inside an isolated compound path) or an object inside another selected object (inside an @@ -1052,11 +1079,24 @@ pub(crate) fn handle_cursor(h: Handle, angle: f64) -> Cursor { mod tests; impl SelectionTool { - fn release_move(&mut self, cx: &ToolContext, backquote: bool, began: bool, deselect: Option, key: Option) -> Vec { + fn release_move( + &mut self, + cx: &ToolContext, + backquote: bool, + began: bool, + deselect: Option, + key: Option, + exclude: Option, + ) -> Vec { self.state = State::Idle; self.measure = None; self.guides.clear(); self.moving = None; + // A Shift-click (no drag) on a highlighted object of the Global Edit leaves it out. + if let (false, Some(id)) = (began, exclude) { + self.last_move = None; + return vec![Action::Exec("select.globalEditExclude".into(), json!({ "id": id.0 }))]; + } let changed_mode = self.last_move.as_ref().is_some_and(|params| params.get("objects").is_some()) != backquote; let last = self.last_move.take().map(|mut params| { if backquote { @@ -1250,7 +1290,7 @@ impl SelectionTool { /// grabs the selection by that art (at `grab`), as a press on its visible part does. fn press_nothing(&mut self, cx: &ToolContext, p: Point, grab: Point, m: Mods) { self.state = if !m.shift && selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects).is_some() { - State::Moving { start: grab, press: p, hold: grab, began: false, deselect: None, key: None } + State::Moving { start: grab, press: p, hold: grab, began: false, deselect: None, key: None, exclude: None } } else { State::Marquee { start: p, cur: p, toggle: m.shift, enclosed: false } }; @@ -1279,7 +1319,7 @@ impl SelectionTool { } // Shift has already constrained `d`: any change is a snap. self.snapped = (d - unsnapped).hypot() > 1e-9; - self.state = State::Moving { start, press, hold, began: true, deselect: None, key: None }; + self.state = State::Moving { start, press, hold, began: true, deselect: None, key: None, exclude: None }; self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y))); let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }); if backquote { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f3f6cbfbb6..abbfb99af0 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5568,6 +5568,7 @@ axis Y Axis Y ос Create New Set Създаване на нов набор Stop Global Edit Край на глобалното редактиране Global Edit Options Опции за глобално редактиране + Leave Out of Global Edit Изключване от глобалното редактиране @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобалното редактиране работи с пътища, съставни пътища, екземпляри на символи и групи от тях Match Съвпадение On Artboards В работните области diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7efa9c0e7..353c8aced0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5591,6 +5591,7 @@ axis Y Axis Y osa Create New Set Napravi novi skup Stop Global Edit Zaustavi globalno uređivanje Global Edit Options Opcije globalnog uređivanja + Leave Out of Global Edit Isključi iz globalnog uređivanja Match Podudaranje On Artboards Na radnim pločama All Artboards Sve radne ploče @@ -5599,6 +5600,8 @@ axis Y Axis Y osa @msg select one object odaberite jedan objekat @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globalno uređivanje radi na putanjama, složenim putanjama, instancama simbola i njihovim grupama @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nisu pronađeni slični objekti (rotirane ili zrcaljene kopije se ne podudaraju); promijenite opcije globalnog uređivanja i pokušajte ponovo +@msg Global Edit is off Globalno uređivanje je isključeno +@msg only an object of the Global Edit other than the one it started from can be left out iz globalnog uređivanja može se isključiti samo objekt koji nije onaj od kojeg je počelo @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ili raspon poput 1, 3-5, a ne {v} Add to Symbols Dodaj u simbole Basic Shapes Osnovni oblici diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd6172d6a6..0732f1dcb9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1701,6 +1701,7 @@ digits Malayalam Malaiàlam Global Global Global Brush Dimensions Dimensions globals del pinzell Global Edit Options Opcions globals d’edició + Leave Out of Global Edit Exclou de l’edició global Global Process Color Color de procés global Global Process Color, CMYK Color de procés global, CMYK Glow Amount Quantitat de resplendor @@ -5197,6 +5198,8 @@ digits Malayalam Malaiàlam @msg no selected slice in the image: select slices, or save all of them no hi ha cap tall seleccionat a la imatge: seleccioneu talls o deseu-los tots @msg no selection bounds no hi ha límits de selecció @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again no s’ha trobat cap objecte similar (les còpies girades o reflexades no coincideixen); canvieu les opcions d’edició global i torneu-ho a provar +@msg Global Edit is off L’edició global no està activa +@msg only an object of the Global Edit other than the one it started from can be left out només es pot excloure un objecte de l’edició global que no sigui aquell amb què va començar @msg no slice selected no hi ha cap tall seleccionat @msg no such action no existeix aquesta acció @msg no such anchor no existeix aquest punt d’ancoratge diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 34c7f4e035..ee43ff7a4f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5664,6 +5664,7 @@ axis Y Axis osa Y Create New Set Vytvořit novou sadu Stop Global Edit Ukončit globální úpravy Global Edit Options Možnosti globálních úprav + Leave Out of Global Edit Vyřadit z globálních úprav Match Shoda On Artboards Na pracovních plochách All Artboards Všechny pracovní plochy @@ -5672,6 +5673,8 @@ axis Y Axis osa Y @msg select one object vyberte jeden objekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globální úpravy pracují s cestami, složenými cestami, instancemi symbolů a jejich skupinami @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nebyly nalezeny žádné podobné objekty (otočené a zrcadlené kopie se nevyhledávají); změňte možnosti globálních úprav a zkuste to znovu +@msg Global Edit is off Globální úpravy nejsou zapnuté +@msg only an object of the Global Edit other than the one it started from can be left out z globálních úprav lze vyřadit jen jiný objekt než ten, od kterého začaly @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all nebo rozsah, například 1, 3-5, ne {v} Add to Symbols Přidat do symbolů Basic Shapes Základní tvary diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5a23913424..ada600836a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5584,6 +5584,7 @@ axis Y Axis Y-akse Create New Set Opret nyt sæt Stop Global Edit Stop global redigering Global Edit Options Indstillinger for global redigering + Leave Out of Global Edit Udelad fra global redigering @msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering virker på stier, sammensatte stier, symbolforekomster og grupper af dem Match Match On Artboards På tegneflader diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 101bbefac6..5eb56eb855 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5246,6 +5246,7 @@ axis Y Axis Y-Achse Create New Set Neuen Satz erstellen Stop Global Edit Globale Bearbeitung beenden Global Edit Options Optionen für globale Bearbeitung + Leave Out of Global Edit Von globaler Bearbeitung ausschließen Match Übereinstimmung On Artboards Auf Zeichenflächen All Artboards Alle Zeichenflächen @@ -5254,6 +5255,8 @@ axis Y Axis Y-Achse @msg select one object wählen Sie ein Objekt aus @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale Bearbeitung funktioniert mit Pfaden, zusammengesetzten Pfaden, Symbolinstanzen und Gruppen daraus @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again keine ähnlichen Objekte gefunden (gedrehte oder gespiegelte Kopien werden nicht erkannt); ändern Sie die Optionen für globale Bearbeitung und versuchen Sie es erneut +@msg Global Edit is off Globale Bearbeitung ist nicht aktiv +@msg only an object of the Global Edit other than the one it started from can be left out nur ein Objekt der globalen Bearbeitung außer dem, mit dem sie begonnen hat, kann ausgeschlossen werden @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all oder ein Bereich wie 1, 3-5, nicht {v} Add to Symbols Zu Symbolen hinzufügen Basic Shapes Grundformen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e704faade5..2cdad74880 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5615,6 +5615,7 @@ axis Y Axis Άξονας Y Create New Set Δημιουργία νέου συνόλου Stop Global Edit Τερματισμός καθολικής επεξεργασίας Global Edit Options Επιλογές καθολικής επεξεργασίας + Leave Out of Global Edit Εξαίρεση από την καθολική επεξεργασία Match Αντιστοίχιση On Artboards Σε πίνακες σχεδίασης All Artboards Όλοι οι πίνακες σχεδίασης @@ -5623,6 +5624,8 @@ axis Y Axis Άξονας Y @msg select one object επιλέξτε ένα αντικείμενο @msg Global Edit works on paths, compound paths, symbol instances and groups of them Η καθολική επεξεργασία λειτουργεί σε διαδρομές, σύνθετες διαδρομές, παρουσίες συμβόλων και ομάδες τους @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again δεν βρέθηκαν παρόμοια αντικείμενα (τα περιστραμμένα ή κατοπτρισμένα αντίγραφα δεν εντοπίζονται)· αλλάξτε τις επιλογές καθολικής επεξεργασίας και δοκιμάστε ξανά +@msg Global Edit is off Η καθολική επεξεργασία δεν είναι ενεργή +@msg only an object of the Global Edit other than the one it started from can be left out μπορεί να εξαιρεθεί μόνο ένα αντικείμενο της καθολικής επεξεργασίας εκτός από εκείνο με το οποίο ξεκίνησε @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ή ένα εύρος όπως 1, 3-5, όχι {v} Add to Symbols Προσθήκη στα σύμβολα Basic Shapes Βασικά σχήματα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4ebddbe9a9..c142256922 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5605,6 +5605,7 @@ axis Y Axis Eje Y Create New Set Crear nuevo conjunto Stop Global Edit Detener edición global Global Edit Options Opciones de edición global + Leave Out of Global Edit Excluir de la edición global Match Coincidir On Artboards En mesas de trabajo All Artboards Todas las mesas de trabajo @@ -5613,6 +5614,8 @@ axis Y Axis Eje Y @msg select one object seleccione un objeto @msg Global Edit works on paths, compound paths, symbol instances and groups of them La edición global funciona con trazados, trazados compuestos, instancias de símbolos y grupos de ellos @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again no se encontraron objetos similares (las copias giradas o reflejadas no coinciden); cambie las opciones de edición global e inténtelo de nuevo +@msg Global Edit is off La edición global no está activa +@msg only an object of the Global Edit other than the one it started from can be left out solo se puede excluir un objeto de la edición global distinto de aquel con el que empezó @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervalo como 1, 3-5, no {v} Add to Symbols Agregar a símbolos Basic Shapes Formas básicas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7042b21f22..c5dfa7dcda 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5694,6 +5694,7 @@ axis Y Axis Y-akseli Create New Set Luo uusi sarja Stop Global Edit Lopeta yleismuokkaus Global Edit Options Yleismuokkauksen asetukset + Leave Out of Global Edit Jätä pois yleismuokkauksesta Match Vastaavuus On Artboards Piirtoalustoilla All Artboards Kaikki piirtoalustat @@ -5702,6 +5703,8 @@ axis Y Axis Y-akseli @msg select one object valitse yksi objekti @msg Global Edit works on paths, compound paths, symbol instances and groups of them Yleismuokkaus toimii poluille, yhdistelmäpoluille, symbolien esiintymille ja niiden ryhmille @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again samankaltaisia objekteja ei löytynyt (kierrettyjä tai peilattuja kopioita ei tunnisteta); muuta yleismuokkauksen asetuksia ja yritä uudelleen +@msg Global Edit is off Yleismuokkaus ei ole käynnissä +@msg only an object of the Global Edit other than the one it started from can be left out yleismuokkauksesta voi jättää pois vain muun objektin kuin sen, josta se alkoi @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all tai alue, kuten 1, 3-5, ei {v} Add to Symbols Lisää symboleihin Basic Shapes Perusmuodot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 48eb621eb9..131a91becf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5661,6 +5661,7 @@ axis Y Axis Axe Y Create New Set Créer un jeu Stop Global Edit Arrêter la modification globale Global Edit Options Options de modification globale + Leave Out of Global Edit Exclure de la modification globale Match Correspondance On Artboards Sur les plans de travail All Artboards Tous les plans de travail @@ -5669,6 +5670,8 @@ axis Y Axis Axe Y @msg select one object sélectionnez un seul objet @msg Global Edit works on paths, compound paths, symbol instances and groups of them La modification globale s’applique aux tracés, aux tracés transparents, aux occurrences de symboles et aux groupes de ces objets @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again aucun objet similaire trouvé (les copies pivotées ou symétriques ne sont pas reconnues) ; modifiez les options de modification globale et réessayez +@msg Global Edit is off La modification globale n’est pas active +@msg only an object of the Global Edit other than the one it started from can be left out seul un objet de la modification globale autre que celui à partir duquel elle a commencé peut être exclu @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards` : all ou une plage telle que 1, 3-5, et non {v} Add to Symbols Ajouter aux symboles Basic Shapes Formes de base diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 81f9482631..d3b3791fe3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5649,6 +5649,7 @@ axis Y Axis Y tengely Create New Set Új készlet létrehozása Stop Global Edit Globális szerkesztés befejezése Global Edit Options Globális szerkesztés beállításai + Leave Out of Global Edit Kizárás a globális szerkesztésből Match Egyezés On Artboards Rajztáblákon All Artboards Minden rajztábla @@ -5657,6 +5658,8 @@ axis Y Axis Y tengely @msg select one object jelöljön ki egy objektumot @msg Global Edit works on paths, compound paths, symbol instances and groups of them A globális szerkesztés útvonalakon, összetett útvonalakon, szimbólumpéldányokon és ezek csoportjain működik @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nem található hasonló objektum (az elforgatott vagy tükrözött másolatok nem számítanak egyezésnek); módosítsa a globális szerkesztés beállításait, és próbálja újra +@msg Global Edit is off A globális szerkesztés nincs bekapcsolva +@msg only an object of the Global Edit other than the one it started from can be left out a globális szerkesztésből csak a kiindulási objektumtól eltérő objektum zárható ki @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all vagy egy tartomány, például 1, 3-5, nem {v} Add to Symbols Hozzáadás a szimbólumokhoz Basic Shapes Alapalakzatok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 89633ae991..371dd143c6 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5584,6 +5584,7 @@ axis Y Axis Sumbu Y Create New Set Buat set baru Stop Global Edit Hentikan edit global Global Edit Options Opsi edit global + Leave Out of Global Edit Keluarkan dari edit global @msg Global Edit works on paths, compound paths, symbol instances and groups of them Edit global berfungsi pada jalur, jalur gabungan, instans simbol, dan grupnya Match Cocokkan On Artboards Di artboard diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6acfaf3c9a..d742e3745a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5280,6 +5280,7 @@ axis Y Axis Asse Y Create New Set Crea nuovo set Stop Global Edit Interrompi modifica globale Global Edit Options Opzioni modifica globale + Leave Out of Global Edit Escludi dalla modifica globale Match Corrispondenza On Artboards Sulle tavole da disegno All Artboards Tutte le tavole da disegno @@ -5288,6 +5289,8 @@ axis Y Axis Asse Y @msg select one object selezionate un oggetto @msg Global Edit works on paths, compound paths, symbol instances and groups of them La modifica globale funziona su tracciati, tracciati composti, istanze di simboli e gruppi di essi @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nessun oggetto simile trovato (le copie ruotate o riflesse non vengono riconosciute); cambiate le opzioni di modifica globale e riprovate +@msg Global Edit is off La modifica globale non è attiva +@msg only an object of the Global Edit other than the one it started from can be left out si può escludere solo un oggetto della modifica globale diverso da quello da cui è partita @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all o un intervallo come 1, 3-5, non {v} Add to Symbols Aggiungi ai simboli Basic Shapes Forme di base diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bf3cd6bd1..cea0a9b9a6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5347,6 +5347,7 @@ axis Y Axis Y 軸 Create New Set 新規セットを作成 Stop Global Edit グローバル編集を終了 Global Edit Options グローバル編集オプション + Leave Out of Global Edit グローバル編集から除外 Match 一致 On Artboards アートボード上 All Artboards すべてのアートボード @@ -5355,6 +5356,8 @@ axis Y Axis Y 軸 @msg select one object オブジェクトを 1 つ選択してください @msg Global Edit works on paths, compound paths, symbol instances and groups of them グローバル編集はパス、複合パス、シンボルインスタンスとそれらのグループに使用できます @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 類似するオブジェクトが見つかりません(回転または反転したコピーは一致しません)。グローバル編集オプションを変更してもう一度試してください +@msg Global Edit is off グローバル編集はオフです +@msg only an object of the Global Edit other than the one it started from can be left out 除外できるのは、グローバル編集を開始したオブジェクト以外のオブジェクトだけです @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all または 1, 3-5 のような範囲を指定してください ({v} ではなく) Add to Symbols シンボルに追加 Basic Shapes 基本シェイプ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cf411b072c..84b3f66208 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5579,6 +5579,7 @@ axis Y Axis Y ღერძი Create New Set ახალი ნაკრების შექმნა Stop Global Edit გლობალური რედაქტირების დასრულება Global Edit Options გლობალური რედაქტირების პარამეტრები + Leave Out of Global Edit გლობალური რედაქტირებიდან გამორიცხვა Match დამთხვევა On Artboards სამუშაო დაფებზე All Artboards ყველა სამუშაო დაფა @@ -5587,6 +5588,8 @@ axis Y Axis Y ღერძი @msg select one object მონიშნეთ ერთი ობიექტი @msg Global Edit works on paths, compound paths, symbol instances and groups of them გლობალური რედაქტირება მუშაობს ტრაექტორიებზე, შედგენილ ტრაექტორიებზე, სიმბოლოს ეგზემპლარებსა და მათ ჯგუფებზე @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again მსგავსი ობიექტები ვერ მოიძებნა (შემობრუნებული ან არეკლილი ასლები არ ემთხვევა); შეცვალეთ გლობალური რედაქტირების პარამეტრები და სცადეთ ხელახლა +@msg Global Edit is off გლობალური რედაქტირება გამორთულია +@msg only an object of the Global Edit other than the one it started from can be left out გლობალური რედაქტირებიდან შეიძლება გამოირიცხოს მხოლოდ ობიექტი, რომლითაც ის არ დაწყებულა @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ან დიაპაზონი, მაგალითად 1, 3-5, და არა {v} Add to Symbols სიმბოლოებში დამატება Basic Shapes ძირითადი ფიგურები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81f6c600c6..28a614178a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5243,6 +5243,7 @@ axis Y Axis Y축 Create New Set 새 세트 만들기 Stop Global Edit 전체 편집 중지 Global Edit Options 전체 편집 옵션 + Leave Out of Global Edit 전체 편집에서 제외 Match 일치 On Artboards 아트보드에서 All Artboards 모든 아트보드 @@ -5251,6 +5252,8 @@ axis Y Axis Y축 @msg select one object 개체 하나를 선택하십시오 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 전체 편집은 패스, 컴파운드 패스, 심볼 인스턴스 및 이들의 그룹에서 작동합니다 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 유사한 개체를 찾을 수 없습니다(회전하거나 반사한 복사본은 일치하지 않습니다). 전체 편집 옵션을 변경한 후 다시 시도하십시오 +@msg Global Edit is off 전체 편집이 꺼져 있습니다 +@msg only an object of the Global Edit other than the one it started from can be left out 전체 편집을 시작한 개체가 아닌 전체 편집의 개체만 제외할 수 있습니다 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all 또는 1, 3-5 같은 범위여야 합니다({v}이(가) 아님) Add to Symbols 심볼에 추가 Basic Shapes 기본 모양 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3448536832..05bdc42843 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5628,6 +5628,7 @@ axis Y Axis Y-as Create New Set Nieuwe set maken Stop Global Edit Globale bewerking stoppen Global Edit Options Opties voor globale bewerking + Leave Out of Global Edit Uitsluiten van globale bewerking @msg Global Edit works on paths, compound paths, symbol instances and groups of them Globale bewerking werkt op paden, samengestelde paden, symboolinstanties en groepen daarvan Match Overeenkomst On Artboards Op tekengebieden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14825f83cf..d788919c63 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5517,6 +5517,7 @@ axis Y Axis Oś Y Create New Set Utwórz nowy zestaw Stop Global Edit Zakończ edycję globalną Global Edit Options Opcje edycji globalnej + Leave Out of Global Edit Wyklucz z edycji globalnej Match Dopasowanie On Artboards Na obszarach kompozycji All Artboards Wszystkie obszary kompozycji @@ -5525,6 +5526,8 @@ axis Y Axis Oś Y @msg select one object zaznacz jeden obiekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Edycja globalna działa na ścieżkach, ścieżkach złożonych, wystąpieniach symboli i ich grupach @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nie znaleziono podobnych obiektów (obrócone i odbite kopie nie są dopasowywane); zmień opcje edycji globalnej i spróbuj ponownie +@msg Global Edit is off Edycja globalna jest wyłączona +@msg only an object of the Global Edit other than the one it started from can be left out z edycji globalnej można wykluczyć tylko obiekt inny niż ten, od którego się zaczęła @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all lub zakres, np. 1, 3-5, a nie {v} Add to Symbols Dodaj do symboli Basic Shapes Kształty podstawowe diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 96a31c3e57..a7755a4ec5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5580,6 +5580,7 @@ axis Y Axis Eixo Y Create New Set Criar Novo Conjunto Stop Global Edit Parar Edição Global Global Edit Options Opções de Edição Global + Leave Out of Global Edit Deixar Fora da Edição Global Match Corresponder On Artboards Nas Mesas de Trabalho All Artboards Todas as Mesas de Trabalho @@ -5588,6 +5589,8 @@ axis Y Axis Eixo Y @msg select one object selecione um objeto @msg Global Edit works on paths, compound paths, symbol instances and groups of them A edição global funciona com demarcadores, demarcadores compostos, instâncias de símbolos e grupos deles @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again nenhum objeto semelhante encontrado (cópias giradas ou refletidas não são correspondidas); altere as opções de edição global e tente novamente +@msg Global Edit is off A edição global está desativada +@msg only an object of the Global Edit other than the one it started from can be left out só é possível deixar fora da edição global um objeto diferente daquele com que ela começou @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ou um intervalo como 1, 3-5, não {v} Add to Symbols Adicionar aos Símbolos Basic Shapes Formas Básicas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fdb51b80df..7907e355cf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5275,6 +5275,7 @@ axis Y Axis Ось Y Create New Set Создать новый набор Stop Global Edit Завершить глобальное редактирование Global Edit Options Параметры глобального редактирования + Leave Out of Global Edit Исключить из глобального редактирования Match Совпадение On Artboards На монтажных областях All Artboards Все монтажные области @@ -5283,6 +5284,8 @@ axis Y Axis Ось Y @msg select one object выберите один объект @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальное редактирование работает с контурами, составными контурами, экземплярами символов и их группами @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again похожие объекты не найдены (повёрнутые или отражённые копии не учитываются); измените параметры глобального редактирования и повторите попытку +@msg Global Edit is off Глобальное редактирование выключено +@msg only an object of the Global Edit other than the one it started from can be left out исключить из глобального редактирования можно только объект, отличный от того, с которого оно началось @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all или диапазон, например 1, 3-5, а не {v} Add to Symbols Добавить в символы Basic Shapes Базовые фигуры diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e2dddf022b..8e60690d29 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5687,6 +5687,7 @@ axis Y Axis Y-axel Create New Set Skapa ny uppsättning Stop Global Edit Avsluta global redigering Global Edit Options Alternativ för global redigering + Leave Out of Global Edit Uteslut från global redigering Match Matcha On Artboards På ritytor All Artboards Alla ritytor @@ -5695,6 +5696,8 @@ axis Y Axis Y-axel @msg select one object markera ett objekt @msg Global Edit works on paths, compound paths, symbol instances and groups of them Global redigering fungerar på banor, sammansatta banor, symbolinstanser och grupper av dem @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again inga liknande objekt hittades (roterade eller speglade kopior matchas inte); ändra alternativen för global redigering och försök igen +@msg Global Edit is off Global redigering är inte aktiv +@msg only an object of the Global Edit other than the one it started from can be left out bara ett annat objekt än det som den globala redigeringen började med kan uteslutas @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all eller ett intervall som 1, 3-5, inte {v} Add to Symbols Lägg till i symboler Basic Shapes Grundformer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9ecf2ccf93..f9ee3f5b40 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5621,6 +5621,7 @@ axis Y Axis Y ekseni Create New Set Yeni Set Oluştur Stop Global Edit Genel Düzenlemeyi Durdur Global Edit Options Genel Düzenleme Seçenekleri + Leave Out of Global Edit Genel Düzenlemenin Dışında Bırak Match Eşleştir On Artboards Çalışma Yüzeylerinde All Artboards Tüm Çalışma Yüzeyleri @@ -5629,6 +5630,8 @@ axis Y Axis Y ekseni @msg select one object bir nesne seçin @msg Global Edit works on paths, compound paths, symbol instances and groups of them Genel düzenleme yollar, bileşik yollar, sembol örnekleri ve bunların grupları üzerinde çalışır @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again benzer nesne bulunamadı (döndürülmüş veya yansıtılmış kopyalar eşleşmez); Genel Düzenleme Seçeneklerini değiştirip yeniden deneyin +@msg Global Edit is off Genel düzenleme kapalı +@msg only an object of the Global Edit other than the one it started from can be left out yalnızca genel düzenlemenin başladığı nesne dışındaki bir nesne düzenlemenin dışında bırakılabilir @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all ya da 1, 3-5 gibi bir aralık olmalı, {v} değil Add to Symbols Sembollere Ekle Basic Shapes Temel Şekiller diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d348440a2c..5c48fa3066 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5260,6 +5260,7 @@ axis Y Axis Вісь Y Create New Set Створити новий набір Stop Global Edit Завершити глобальне редагування Global Edit Options Параметри глобального редагування + Leave Out of Global Edit Виключити з глобального редагування Match Збіг On Artboards На монтажних областях All Artboards Усі монтажні області @@ -5268,6 +5269,8 @@ axis Y Axis Вісь Y @msg select one object виберіть один об’єкт @msg Global Edit works on paths, compound paths, symbol instances and groups of them Глобальне редагування працює з контурами, складеними контурами, екземплярами символів та їхніми групами @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again схожих об’єктів не знайдено (повернуті чи віддзеркалені копії не враховуються); змініть параметри глобального редагування та спробуйте ще раз +@msg Global Edit is off Глобальне редагування вимкнено +@msg only an object of the Global Edit other than the one it started from can be left out виключити з глобального редагування можна лише об’єкт, відмінний від того, з якого воно почалося @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all або діапазон, наприклад 1, 3-5, а не {v} Add to Symbols Додати до символів Basic Shapes Базові фігури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 09652ede2b..edb1b428bb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5263,6 +5263,7 @@ axis Y Axis Trục Y Create New Set Tạo bộ mới Stop Global Edit Dừng chỉnh sửa toàn cục Global Edit Options Tùy chọn chỉnh sửa toàn cục + Leave Out of Global Edit Loại khỏi chỉnh sửa toàn cục Match Khớp On Artboards Trên các bảng vẽ All Artboards Tất cả bảng vẽ @@ -5271,6 +5272,8 @@ axis Y Axis Trục Y @msg select one object hãy chọn một đối tượng @msg Global Edit works on paths, compound paths, symbol instances and groups of them Chỉnh sửa toàn cục hoạt động trên đường dẫn, đường dẫn phức hợp, phiên bản biểu tượng và nhóm của chúng @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again không tìm thấy đối tượng tương tự (các bản sao đã xoay hoặc lật không được tính); hãy thay đổi tùy chọn chỉnh sửa toàn cục rồi thử lại +@msg Global Edit is off Chỉnh sửa toàn cục đang tắt +@msg only an object of the Global Edit other than the one it started from can be left out chỉ có thể loại khỏi chỉnh sửa toàn cục một đối tượng khác với đối tượng mà nó bắt đầu @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all hoặc một phạm vi như 1, 3-5, không phải {v} Add to Symbols Thêm vào ký hiệu Basic Shapes Hình cơ bản diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 841bd4528a..62b97891fa 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5504,6 +5504,7 @@ axis Y Axis Y 轴 Create New Set 创建新组 Stop Global Edit 停止全局编辑 Global Edit Options 全局编辑选项 + Leave Out of Global Edit 从全局编辑中排除 Match 匹配 On Artboards 在画板上 All Artboards 所有画板 @@ -5512,6 +5513,8 @@ axis Y Axis Y 轴 @msg select one object 请选择一个对象 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 全局编辑适用于路径、复合路径、符号实例及其编组 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 未找到相似对象(旋转或镜像的副本不会匹配);请更改全局编辑选项后重试 +@msg Global Edit is off 全局编辑未开启 +@msg only an object of the Global Edit other than the one it started from can be left out 只能从全局编辑中排除起始对象以外的对象 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:应为 all 或 1, 3-5 这样的范围,而不是 {v} Add to Symbols 添加到符号 Basic Shapes 基本形状 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a515d59a74..efcc94a588 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5300,6 +5300,7 @@ axis Y Axis Y 軸 Create New Set 建立新組 Stop Global Edit 停止整體編輯 Global Edit Options 整體編輯選項 + Leave Out of Global Edit 從整體編輯中排除 Match 符合 On Artboards 在工作區域上 All Artboards 所有工作區域 @@ -5308,6 +5309,8 @@ axis Y Axis Y 軸 @msg select one object 請選取一個物件 @msg Global Edit works on paths, compound paths, symbol instances and groups of them 整體編輯適用於路徑、複合路徑、符號實體及其群組 @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again 找不到相似的物件(旋轉或鏡像的副本不會相符);請變更整體編輯選項後再試一次 +@msg Global Edit is off 整體編輯未開啟 +@msg only an object of the Global Edit other than the one it started from can be left out 只能從整體編輯中排除起始物件以外的物件 @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`:應為 all 或 1, 3-5 這類範圍,而不是 {v} Add to Symbols 新增至符號 Basic Shapes 基本形狀 diff --git a/docs/mcp.md b/docs/mcp.md index 50f73e7b70..f13ff4c8f2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1484,6 +1484,14 @@ Redo, a cancelled drag or scrub), the matches it no longer has leave the Global are left. An edit that would take any match past the canvas fails with the coordinates-out-of-range error and changes nothing. Nothing of it is saved. +`select.globalEditExclude {id}` leaves the match `id` out of the Global Edit, as a Shift-click on a highlighted match +(or on an object inside it) with the Selection tool does: it is no longer highlighted, and later edits leave it as it +is. It returns `{active, count, ids}`, the objects left in the Global Edit; with fewer than two left, the Global Edit +ends (`{active: false, count: 0, ids: []}`). The object the Global Edit started from can't be left out, and neither +can an object that is not a match. It is not an undo step. A Shift-drag that starts on a match moves the selection +and leaves the match in. Source: [Update assets quickly with Global +Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html). + ## Saved selections Select → Save Selection… keeps the selected objects under a name, in the document: `select.save {name?}` (default diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a340f6476a..4b8b615d5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -121,7 +121,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939); the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies and excluding a match with Shift-click, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, and PDF gradients mixing a spot color with RGB or Lab stops | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | @@ -482,6 +482,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Pattern-only backquote drags:** With Selection move, bounding-box scale or rotate, or the Rotate, Reflect, Scale or Shear tool, backquote held at mouse release applies the drag matrix to selected pattern paint while object geometry stays in place. The key may be pressed after mouse press; if released before the mouse button, the drag commits as an ordinary transform. Objects without pattern paint stay still; stroke-only patterns and patterned objects in mixed selections take the same matrix. Regression tests: `backquote_move_uses_release_state_and_one_commit` and `backquote_box_scale_and_rotate_use_pattern_matrix_at_release` in `select/tests.rs`, `backquote_drag_previews_and_commits_pattern_only_for_each_transform_tool` in `xform/transform.rs`, `selection_backquote_drag_changes_pattern_fill_and_stroke_without_moving_mixed_art` and `selection_backquote_drag_changes_stroke_only_pattern` in `tests/pattern.rs`, `egui_backtick_drag_uses_key_state_at_release` in `canvas/tests.rs`, and `synthetic_pointer_backquote_keeps_solid_object_in_place` in `control/tests.rs`. Scores and hours unchanged. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. - **Escape in more tool drags:** Escape during an Anchor Point drag, a Mesh tool drag, a Direct Selection drag of a mesh point, a corner widget or the brackets of type on a path, or a Shape Builder drag cancels it: the art goes back to how the press found it, no undo step is added, the release does nothing, and the tool stays chosen. Escape during a Measure tool drag brings back the measurement before it. Regression tests: `escape_cancels_*` in `draw2/anchor/tests.rs`, `meshedit.rs`, `direct/tests.rs`, `builder/tests.rs` and `xform/measure.rs`, and `escape_cancels_an_anchor_point_mesh_shape_builder_or_measure_drag` in `tests/toolescape.rs`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 89ea9b36a8..6f24114692 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -300,7 +300,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)) | partial | #3712; the New Action dialog (name, set menu, shortcut, colour) and dragging actions between sets remain | | Actions panel: Delete Selection (bottom bar) deletes the selected set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Removes the selected action, command, or action set from the panel") | partial | `ui.actionSet.delete`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: deleting a set asks first (a selected action is still deleted at once), Shift-click on a set's name selects a range of sets, ≡ › Delete does the same as the button, and Default Actions and the last set can be deleted. Undo does not restore a deleted set, and recorded commands cannot be selected or deleted | | Properties panel per context (every selection type's Quick Actions) | partial | one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817) and Merge Live Paint (a Live Paint group with more) in Quick Actions, the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there | -| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs | partial | #3521, `select.globalEdit` / `select.globalEditOptions`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); the Control panel's copy of the options, Shift-click to leave a match out, rotated copies and highlighting matches before the start remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | +| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control panel's copy of the options, rotated copies and highlighting matches before the start remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | From 1cd5bc4016f764c86ab18a4f374b37f06510b9b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 01:28:57 -0800 Subject: [PATCH 007/199] Global Edit: a Shift-click on a match inside a selected group deselects the group A match that sits inside a selected object is no longer highlighted, and a Shift-click on it with the Selection tool deselects that object as before instead of leaving the match out of the Global Edit. --- crates/engine/src/cmd/globaledit.rs | 8 ++++++-- crates/engine/src/tests/globaledit.rs | 14 ++++++++++++++ crates/tools/src/select.rs | 10 ++++++---- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 56ae301408..dc54cf7922 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -716,8 +716,9 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se edited } -/// The outlines of the members of the active document's Global Edit that are not selected, in -/// their layer's colour: the canvas highlights them while Global Edit is on. +/// The outlines of the members of the active document's Global Edit that are not selected, hold +/// no selected object and sit inside no selected object, in their layer's colour: the canvas +/// highlights them while Global Edit is on. pub fn highlights(s: &Session) -> Outlines { let Some(st) = s.active() else { return vec![] }; let Some(ge) = &st.global_edit else { return vec![] }; @@ -732,6 +733,9 @@ pub fn highlights(s: &Session) -> Outlines { .iter() .filter_map(|(id, _)| { let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?; + if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) { + return None; + } let path = match n.stroke_path() { Some(p) => p, None => n.geometric_bounds_with(&symbols)?.to_path(0.1), diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index b73efd0df5..786a351ac3 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -472,6 +472,20 @@ fn a_shift_click_inside_a_matched_group_leaves_the_whole_group_out() { assert_eq!(members(&s), Some(vec![g, small])); } +#[test] +fn a_shift_click_on_a_member_inside_a_selected_group_deselects_the_group() { + let mut s = session(); + let [a, b, c, wide, _] = squares(&mut s); + let pair = group_of(&mut s, &[b, wide]); + let all = start(&mut s, a, json!({})); + assert_eq!(all, [a, c, b], "the copy in the group comes after the small square"); + sel(&mut s, &[pair]); + assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "the copy inside the selected group is not highlighted"); + shift_click(&mut s, 350.0, 50.0); + assert_eq!(members(&s), Some(all), "nothing is left out"); + assert!(s.doc().unwrap().selection.objects.is_empty(), "the group is deselected"); +} + #[test] fn leaving_out_all_but_one_ends_global_edit_and_the_first_object_stays() { let mut s = session(); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 2819c33697..36aca60924 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -994,13 +994,15 @@ fn shift_press(cx: &ToolContext, h: &Hit, top: NodeId, out: &mut Vec) -> } /// The object of the Global Edit in progress that the click `h` lands on or inside, when it is -/// highlighted: neither the object the edit started from nor one that is selected or holds a -/// selected object (`select.globalEditExclude` leaves it out of the edit). +/// highlighted: neither the object the edit started from nor one that is selected, holds a +/// selected object or sits inside a selected object (`select.globalEditExclude` leaves it out of +/// the edit). fn global_edit_member(cx: &ToolContext, h: &Hit) -> Option { let others = cx.global_edit.get(1..)?; let member = h.ancestry.iter().chain([&h.leaf]).find(|id| others.iter().any(|(m, _)| m == *id)).copied()?; - let selected = cx.selection.objects.iter().any(|s| cx.doc.ancestry(*s).is_some_and(|a| a.contains(&member))); - (!selected).then_some(member) + let holds = cx.selection.objects.iter().any(|s| cx.doc.ancestry(*s).is_some_and(|a| a.contains(&member))); + let inside = cx.doc.ancestry(member).is_some_and(|a| a.iter().any(|id| cx.selection.contains(*id))); + (!holds && !inside).then_some(member) } /// Can a click make `id` the key object? `select.key` takes only a selected top-level object. In From c88d88548c96921280d0d9b3c45c46a5dc81f159 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 01:41:48 -0800 Subject: [PATCH 008/199] Global Edit: a Shift-drag from a highlighted match selects it and moves it A Shift-press on a highlighted object of the Global Edit waits for the release to leave it out of the edit. A drag from it now selects it when the drag starts and moves it with the selection, as a Shift-drag from an unselected object did. The snap targets are gathered after the object joins the selection. --- crates/engine/src/tests/globaledit.rs | 6 ++++- crates/tools/src/select.rs | 35 ++++++++++++++++++--------- crates/tools/src/select/tests.rs | 28 +++++++++++++++++++++ 3 files changed, 56 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 786a351ac3..60bf81a060 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -434,11 +434,15 @@ fn a_shift_click_on_a_highlighted_object_leaves_it_out() { let mut s = session(); let [a, b, c, ..] = squares(&mut s); start(&mut s, a, json!({})); - // A Shift-drag that starts on the copy moves the selection and leaves the copy in. + // A Shift-drag that starts on the copy selects it and moves it with the selection, and leaves + // the copy in. shift_drag(&mut s, (350.0, 50.0), (390.0, 50.0)); assert_eq!(members(&s), Some(vec![a, b, c]), "a drag leaves nothing out"); + assert_eq!(s.doc().unwrap().selection.objects, [a, b]); assert!(bounds(&s, a).x0 > 0.0, "the selection moved: {:?}", bounds(&s, a)); + assert!(bounds(&s, b).x0 > 300.0, "the copy moved with it: {:?}", bounds(&s, b)); s.execute("edit.undo", &json!({})).unwrap(); + sel(&mut s, &[a]); shift_click(&mut s, 350.0, 50.0); assert_eq!(members(&s), Some(vec![a, c]), "the copy is left out"); assert_eq!(s.doc().unwrap().selection.objects, [a], "and not selected"); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 36aca60924..f2f4229dea 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -74,9 +74,11 @@ enum State { /// guides: released without a drag, it becomes the key object that Align aligns to if /// `can_be_key` allows it (the key again: no key). key: Option, - /// Shift-pressed on this highlighted object of the Global Edit: released without a drag, - /// it leaves the Global Edit (`select.globalEditExclude`). - exclude: Option, + /// Shift-pressed on this highlighted object of the Global Edit, and the object the press + /// hit: released without a drag, the first leaves the Global Edit + /// (`select.globalEditExclude`); a drag selects the second and moves it with the + /// selection. + exclude: Option<(NodeId, NodeId)>, }, Scaling { handle: Handle, @@ -755,8 +757,8 @@ impl Tool for SelectionTool { } } } - (PointerKind::Drag, State::Moving { start, press, hold, began, .. }) => { - self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, began)) + (PointerKind::Drag, State::Moving { start, press, hold, began, exclude, .. }) => { + self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, began), exclude) } (PointerKind::Drag, State::Scaling { handle, bx, areas }) => { self.last_backquote = ev.backquote; @@ -979,12 +981,12 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option { /// A Shift-press on `top` (hit by `h`): a Shift-click takes a selected object out of the selection /// when it is released, and a Shift-drag moves the selection, constrained. On an object of the -/// Global Edit that is highlighted, the release leaves that object out of the edit instead. -/// Returns the object to deselect and the object to leave out on release; adds to `out` the -/// action that selects `top` at once. -fn shift_press(cx: &ToolContext, h: &Hit, top: NodeId, out: &mut Vec) -> (Option, Option) { +/// Global Edit that is highlighted, the release leaves that object out of the edit instead, and a +/// drag selects `top` when it starts. Returns the object to deselect and the object to leave out +/// on release (with `top`); adds to `out` the action that selects `top` at once. +fn shift_press(cx: &ToolContext, h: &Hit, top: NodeId, out: &mut Vec) -> (Option, Option<(NodeId, NodeId)>) { if let Some(member) = global_edit_member(cx, h) { - (None, Some(member)) + (None, Some((member, top))) } else if cx.selection.contains(top) { (Some(top), None) } else { @@ -1088,14 +1090,14 @@ impl SelectionTool { began: bool, deselect: Option, key: Option, - exclude: Option, + exclude: Option<(NodeId, NodeId)>, ) -> Vec { self.state = State::Idle; self.measure = None; self.guides.clear(); self.moving = None; // A Shift-click (no drag) on a highlighted object of the Global Edit leaves it out. - if let (false, Some(id)) = (began, exclude) { + if let (false, Some((id, _))) = (began, exclude) { self.last_move = None; return vec![Action::Exec("select.globalEditExclude".into(), json!({ "id": id.0 }))]; } @@ -1305,13 +1307,22 @@ impl SelectionTool { m: Mods, backquote: bool, (start, press, hold, began): (Point, Point, Point, bool), + exclude: Option<(NodeId, NodeId)>, ) -> Vec { let mut out = vec![]; if !began { if p.distance(press) < Self::drag_threshold(cx) { return out; } + // A Shift-drag from a highlighted object of the Global Edit selects it and moves it + // with the selection. `cx` still holds the selection without it, so the snap targets + // are gathered at the next drag event. + if let Some((_, top)) = exclude { + out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); + } out.push(Action::Begin(if m.alt { "Copy".into() } else { "Move".into() })); + self.moving = exclude.is_none().then(|| MoveSnap::new(cx)); + } else if self.moving.is_none() { self.moving = Some(MoveSnap::new(cx)); } let mut d = move_delta(start, p, m.shift, cx.constrain_angle); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 4b41a8592a..4555eee7aa 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1004,6 +1004,34 @@ fn shift_click_toggles_an_object_on_release() { assert!(t.pointer(&cx2, &shift(PointerKind::Up, 150.0, 150.0)).is_empty()); } +/// A Shift-drag that starts on a highlighted object of the Global Edit selects that object and +/// moves it; only a Shift-click leaves it out of the edit. +#[test] +fn shift_drag_on_a_global_edit_match_selects_and_moves_it() { + let (d, a, b) = two_rects(Rect::new(300.0, 100.0, 400.0, 200.0)); + let p = paint(); + let s = Selection::default(); + let members = [(a, Affine::IDENTITY), (b, Affine::IDENTITY)]; + let cx = ToolContext { global_edit: &members, ..cx(&d, &s, &p) }; + let shift = |kind, x, y| ev(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() }); + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &shift(PointerKind::Down, 350.0, 150.0)).is_empty()); + let mut actions = t.pointer(&cx, &shift(PointerKind::Drag, 390.0, 150.0)); + assert_eq!(actions[..2], [Action::Exec("select.toggle".into(), json!({"id": b.0})), Action::Begin("Move".into())]); + actions.extend(t.pointer(&cx, &shift(PointerKind::Drag, 395.0, 150.0))); + actions.extend(t.pointer(&cx, &shift(PointerKind::Up, 395.0, 150.0))); + assert!( + actions.iter().any(|a| matches!(a, Action::Preview(c, v) if c == "object.transform" && v["matrix"][4].as_f64().is_some_and(|x| x > 39.0))), + "moved right: {actions:?}" + ); + assert_eq!(actions.last(), Some(&Action::Commit)); + assert!(!actions.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.globalEditExclude")), "{actions:?}"); + // A Shift-click on it leaves it out instead. + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &shift(PointerKind::Down, 350.0, 150.0)).is_empty()); + assert_eq!(t.pointer(&cx, &shift(PointerKind::Up, 350.0, 150.0)), vec![Action::Exec("select.globalEditExclude".into(), json!({"id": b.0}))]); +} + /// #541: a click on one object of a selection of several makes it the key object; a click on /// the key again lets it go. A drag moves them all, a lone object has no key unless ruler /// guides are selected with it. From 023b5eedec23ef84d6981bcf80cb42a8a19c5d18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 01:51:38 -0800 Subject: [PATCH 009/199] Docs: a Shift-drag from a Global Edit match selects and moves it --- docs/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index f13ff4c8f2..edde007aa5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1488,8 +1488,8 @@ nothing. Nothing of it is saved. (or on an object inside it) with the Selection tool does: it is no longer highlighted, and later edits leave it as it is. It returns `{active, count, ids}`, the objects left in the Global Edit; with fewer than two left, the Global Edit ends (`{active: false, count: 0, ids: []}`). The object the Global Edit started from can't be left out, and neither -can an object that is not a match. It is not an undo step. A Shift-drag that starts on a match moves the selection -and leaves the match in. Source: [Update assets quickly with Global +can an object that is not a match. It is not an undo step. A Shift-drag that starts on a match selects it and moves +it with the selection, and leaves it in the Global Edit. Source: [Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html). ## Saved selections From a5c015359608fa26fc40d75397c2f061d4396f3a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 02:15:14 -0800 Subject: [PATCH 010/199] Global Edit: a Shift-drag from a highlighted match snaps from its first move The snap targets of a Shift-drag that starts on a highlighted Global Edit match are gathered when the drag begins, for the selection with the match added, before the first preview moves it. The first preview is now snapped to the grid or to points, and later previews snap from the original position. --- crates/tools/src/select.rs | 18 ++++++++++-------- crates/tools/src/select/tests.rs | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index f2f4229dea..cac9e6adfd 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1315,15 +1315,17 @@ impl SelectionTool { return out; } // A Shift-drag from a highlighted object of the Global Edit selects it and moves it - // with the selection. `cx` still holds the selection without it, so the snap targets - // are gathered at the next drag event. - if let Some((_, top)) = exclude { - out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); - } + // with the selection: its snap targets are gathered for the selection with it. + self.moving = Some(match exclude { + Some((_, top)) => { + out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 }))); + let mut selection = cx.selection.clone(); + selection.add(top); + MoveSnap::new(&ToolContext { selection: &selection, ..*cx }) + } + None => MoveSnap::new(cx), + }); out.push(Action::Begin(if m.alt { "Copy".into() } else { "Move".into() })); - self.moving = exclude.is_none().then(|| MoveSnap::new(cx)); - } else if self.moving.is_none() { - self.moving = Some(MoveSnap::new(cx)); } let mut d = move_delta(start, p, m.shift, cx.constrain_angle); let unsnapped = d; diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 4555eee7aa..8f6299f06d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1032,6 +1032,25 @@ fn shift_drag_on_a_global_edit_match_selects_and_moves_it() { assert_eq!(t.pointer(&cx, &shift(PointerKind::Up, 350.0, 150.0)), vec![Action::Exec("select.globalEditExclude".into(), json!({"id": b.0}))]); } +/// The first preview of a Shift-drag from a Global Edit match snaps, the match's bounds taken in +/// with the selection's: with Snap to Grid, a move of 13 right brings the right edge (413) onto +/// the gridline 414. +#[test] +fn shift_drag_on_a_global_edit_match_snaps_from_its_first_event() { + let (d, a, b) = two_rects(Rect::new(300.0, 100.0, 400.0, 200.0)); + let p = paint(); + let s = Selection::default(); + let members = [(a, Affine::IDENTITY), (b, Affine::IDENTITY)]; + let cx = ToolContext { global_edit: &members, snap_to_grid: true, ..cx(&d, &s, &p) }; + let shift = |kind, x, y| ev(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() }); + let mut t = SelectionTool::default(); + assert!(t.pointer(&cx, &shift(PointerKind::Down, 350.0, 150.0)).is_empty()); + let actions = t.pointer(&cx, &shift(PointerKind::Drag, 363.0, 150.0)); + let Some(Action::Preview(_, v)) = actions.get(2) else { panic!("{actions:?}") }; + let m = Vec2::new(v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()); + assert!(moved_by(m, (14.0, 0.0)), "{m:?}"); +} + /// #541: a click on one object of a selection of several makes it the key object; a click on /// the key again lets it go. A drag moves them all, a lone object has no key unless ruler /// guides are selected with it. From 60e1600caa258d8307747e9ad5360f6c21d85803 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 02:49:36 -0800 Subject: [PATCH 011/199] SVG: circles and ellipses import as four-anchor ellipses usvg turns each and into arcs and then into a number of cubics that depends on f32 rounding: an ellipse that export wrote as could come back with eight anchors instead of the four it was written from. The renderer flattens the two outlines differently, so a round trip of a flat filled ellipse redrew 158 edge pixels by up to 43 levels, and prop_svg::plain_art_survives_visually failed on main. Import now records the ids of and elements in the prepass and rebuilds each as the ellipse VectorCraft draws: four smooth anchors on the axes, starting at the right as SVG defines, with handles KAPPA of the radii long, then transformed as before. Tests: prop_svg::filled_ellipse_on_the_artboard_edge_survives_visually (the failing case) and basic_shapes::circles_and_ellipses_import_as_the_ellipse_drawn fail without the change. --- crates/svg/src/import.rs | 3 ++ crates/svg/src/import/convert.rs | 45 ++++++++++++++++++++++++++++- crates/svg/src/import/importer.rs | 9 ++++-- crates/svg/src/import/prepass.rs | 12 ++++++++ crates/svg/tests/it/basic_shapes.rs | 45 +++++++++++++++++++++++++++++ crates/svg/tests/it/prop_svg.rs | 28 ++++++++++++++++++ docs/target-app-parity.md | 1 + 7 files changed, 139 insertions(+), 4 deletions(-) diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 18f4f088d6..0201c591e5 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -161,6 +161,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul foreign: found.foreign, sublayers: found.sublayers, sublayer_groups: HashSet::new(), + ellipses: found.ellipses, screen: k, converted_nodes: 1, max_nodes, @@ -318,6 +319,8 @@ struct Importer { sublayers: HashSet, /// The groups made of them, made sublayers where they sit in a layer ([`promote_sublayers`]). sublayer_groups: HashSet, + /// Ids of the `` and `` elements ([`prepass`]). + ellipses: HashSet, /// Points per screen pixel (the root's user unit before its `viewBox`): what a non-scaling /// stroke's width is measured in. screen: f64, diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 40c2cf5779..a154a233fb 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -1,4 +1,6 @@ -use super::{Affine, Arc, BezPath, BlendMode, Color, FillRule, GradientStop, HashMap, Node, Point, XNode, roxmltree}; +use super::{Affine, Arc, BezPath, BlendMode, Color, FillRule, GradientStop, HashMap, Node, PathData, Point, XNode, roxmltree}; +use vectorcraft_geom::path::{Anchor, AnchorKind, SubPath}; +use vectorcraft_geom::shapes::KAPPA; /// `n` with every object id (its descendants' and its mask art's too) zeroed, to compare art. pub(super) fn without_ids(n: &Node) -> Node { @@ -135,6 +137,47 @@ pub(super) fn bezpath(p: &usvg::tiny_skia_path::Path, m: Affine) -> BezPath { bp } +/// The path usvg makes of a `` or `` (`p`: one closed outline of arcs from the +/// right end of the horizontal axis round through the bottom) as the ellipse VectorCraft draws: four +/// smooth anchors on the axes in the same order, each quarter a cubic with handles [`KAPPA`] of the +/// radii long, the ellipse export writes as ``. `None` when `p` is not such an outline. +pub(super) fn drawn_ellipse(p: &usvg::tiny_skia_path::Path) -> Option { + use usvg::tiny_skia_path::PathSegment as S; + let mut ends = vec![]; + let mut closed = false; + for s in p.segments() { + match s { + S::MoveTo(q) if ends.is_empty() => ends.push(Point::new(q.x as f64, q.y as f64)), + S::LineTo(q) | S::QuadTo(_, q) | S::CubicTo(_, _, q) if !ends.is_empty() && !closed => ends.push(Point::new(q.x as f64, q.y as f64)), + S::Close if !closed => closed = true, + _ => return None, + } + } + let (x0, x1) = ends.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.x), hi.max(q.x))); + let (y0, y1) = ends.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.y), hi.max(q.y))); + let (c, rx, ry) = (Point::new((x0 + x1) / 2.0, (y0 + y1) / 2.0), (x1 - x0) / 2.0, (y1 - y0) / 2.0); + // usvg works in f32: the tolerance follows the size of the numbers. + let tol = 1e-5 * (c.x.abs() + c.y.abs() + rx + ry).max(1.0); + let axes = [Point::new(x1, c.y), Point::new(c.x, y1), Point::new(x0, c.y), Point::new(c.x, y0)]; + let on_ellipse = |q: &Point| (((q.x - c.x) / rx).powi(2) + ((q.y - c.y) / ry).powi(2) - 1.0).abs() <= 1e-3; + if !closed + || rx <= tol + || ry <= tol + || ends.first().is_none_or(|s| s.distance(axes[0]) > tol) + || !axes.iter().all(|a| ends.iter().any(|q| q.distance(*a) <= tol)) + || !ends.iter().all(on_ellipse) + { + return None; + } + let anchors = (0..4) + .map(|i| { + let (p, next, prev) = (axes[i], axes[(i + 1) % 4], axes[(i + 3) % 4]); + Anchor { p, h_in: p + (prev - c) * KAPPA, h_out: p + (next - c) * KAPPA, kind: AnchorKind::Smooth } + }) + .collect(); + Some(PathData::single(SubPath::new(anchors, true))) +} + /// The shapes of clip path `cp` on an element whose user space `ts` maps to the document. pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine) -> Vec<(BezPath, FillRule)> { fn collect(g: &usvg::Group, m: Affine, out: &mut Vec<(BezPath, FillRule)>) { diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 0e0b8127ef..eeb0a4804c 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -1,4 +1,4 @@ -use super::convert::{aff, bezpath, blend, clip_shapes, gradient_stops, is_plain, made_up, rule, uncut, unique_name, without_ids}; +use super::convert::{aff, bezpath, blend, clip_shapes, drawn_ellipse, gradient_stops, is_plain, made_up, rule, uncut, unique_name, without_ids}; use super::layers::filter_names; use super::prepass::link; use super::{ @@ -601,7 +601,8 @@ impl Importer { if !p.is_visible() { return None; } - let path = PathData::from_bezpath(&bezpath(p.data(), acc)); + let ellipse = if self.ellipses.contains(p.id()) { drawn_ellipse(p.data()) } else { None }; + let path = ellipse.map_or_else(|| PathData::from_bezpath(&bezpath(p.data(), acc)), |e| e.transformed(acc)); if path.is_empty() { return None; } @@ -683,9 +684,10 @@ impl Importer { std::mem::take(&mut self.non_scaling), std::mem::take(&mut self.data), std::mem::take(&mut self.events), + std::mem::take(&mut self.ellipses), ); let art = self.group_node(tree.root(), acc); - (self.links, self.hidden, self.uses, self.labels, self.non_scaling, self.data, self.events) = outer; + (self.links, self.hidden, self.uses, self.labels, self.non_scaling, self.data, self.events, self.ellipses) = outer; art } } @@ -720,6 +722,7 @@ mod tests { foreign: HashMap::new(), sublayers: HashSet::new(), sublayer_groups: HashSet::new(), + ellipses: HashSet::new(), screen: 1.0, converted_nodes: 0, max_nodes: 1000, diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index 8018138dc6..2afa651a5d 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -28,6 +28,9 @@ pub(super) struct Found { pub(super) scripts: Vec, /// Ids of the `` elements marked as layers ([`marked_layer`]). pub(super) sublayers: HashSet, + /// Ids of the `` and `` elements, which come back as the ellipse VectorCraft + /// draws ([`drawn_ellipse`](super::convert::drawn_ellipse)). + pub(super) ellipses: HashSet, pub(super) warnings: Vec, } @@ -115,6 +118,8 @@ impl Edits { /// * objects with event attributes get an id when they have none, recorded with them /// ([`user_events`]), and the `