From 60700e00fc3fb0fb8fb09754f93eca99bfc8219d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 19:26:22 -0700 Subject: [PATCH 001/674] 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/674] 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 f33617142c5d30f0fb17c36d1018950e631f7af9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 16:36:05 -0700 Subject: [PATCH 003/674] Save As .ai: carry editing data that other apps open as layers and paths A PDF-compatible .ai now also carries, on its first page's PieceInfo, an editing copy of the art in the form VectorCraft's own .ai reader reads: AIPrivateData streams of 64 KiB holding the program compressed with Zstandard after %AI24_ZStandard_Data, an AIMetaData stream of its header comments, and the ContainerVersion, CreatorVersion, NumBlock, RoundtripStreamType and RoundtripVersion entries. The program holds the header comments, the color swatches and color groups, every artboard, layers and sublayers (name, order, visibility, lock, color, printing, dimming), groups, paths, fills and strokes (width, caps, joins, miter limit, dashes, overprint, fill rule), process, spot and global colors, guides, hidden and locked objects and object names. Type, gradients, patterns, images, symbols, live objects, brushes, clipping groups and compound paths are written as plain filled and stroked paths, each with a warning; transparency and effects other than geometry effects are left out. The .ai option editingData (on by default, Include Editing Data for Other Apps in Save As) turns it off. The legacy version 7 writer is unchanged; the path, guide and line style operators both writers write move to eps/src/ai_ops.rs. LoadOptions::native off opens a file from its editing copy or pages instead of the VectorCraft document it carries. --- Cargo.lock | 1 + crates/engine/src/cmd/fileio/load.rs | 4 +- crates/engine/src/cmd/fileio/native.rs | 6 + crates/engine/src/cmd/fileio/pdf.rs | 17 +- crates/engine/src/cmd/fileio/pdfimport.rs | 6 +- crates/engine/src/cmd/fileio/save.rs | 38 +- crates/engine/src/cmd/fileio/tests_pdfedit.rs | 48 ++ crates/eps/Cargo.toml | 2 + crates/eps/src/ai_editing.rs | 238 ++++++ crates/eps/src/ai_editing/tests.rs | 645 ++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 710 ++++++++++++++++++ crates/eps/src/ai_ops.rs | 97 +++ crates/eps/src/legacy_ai.rs | 8 +- crates/eps/src/legacy_ai/encoding.rs | 11 +- crates/eps/src/legacy_ai/writer.rs | 73 +- crates/eps/src/lib.rs | 6 + crates/pdf/src/lib.rs | 7 +- crates/pdf/src/piece_info.rs | 126 ++++ crates/pdf/src/post.rs | 10 +- crates/ui-egui/src/dialogs/save_options.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 44 files changed, 1984 insertions(+), 94 deletions(-) create mode 100644 crates/eps/src/ai_editing.rs create mode 100644 crates/eps/src/ai_editing/tests.rs create mode 100644 crates/eps/src/ai_editing/writer.rs create mode 100644 crates/eps/src/ai_ops.rs create mode 100644 crates/pdf/src/piece_info.rs diff --git a/Cargo.lock b/Cargo.lock index ef60276c11..2778315c8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6240,6 +6240,7 @@ dependencies = [ "vectorcraft-effects", "vectorcraft-geom", "vectorcraft-metafile", + "vectorcraft-pathops", "vectorcraft-pdf", "vectorcraft-render", "vectorcraft-testkit", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 56f5aa0d73..7a56aa7d0e 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -263,9 +263,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } "pdf" | "ai" | "ait" => { // Saved with Preserve Editing: the document it carries, unless some pages are picked. - let editing = opts - .pages - .is_none() + let editing = (opts.pages.is_none() && opts.native) .then(|| vectorcraft_pdf::editing_with(bytes, opts.password.as_deref())) .flatten() .map(|e| (e.intact, move || Some(e.data))); diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index bcca24c34d..fb1ff6c8cb 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -99,6 +99,12 @@ pub const AI_OPTIONS: &[FormatOption] = &[ default: "true", description: "compress the PDF's content and the native document it carries (the PDF option compression.compressText)", }, + FormatOption { + name: "editingData", + ty: "boolean", + default: "true", + description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, paths, fills and strokes, colors, swatches and artboards, with type, gradients, patterns, images, symbols, clipping and live objects as plain filled and stroked paths, without transparency (written only with every artboard, as Preserve Editing is)", + }, FormatOption { name: "aiVersion", ty: "string", diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index df512f629c..641aa08453 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -263,7 +263,7 @@ pub const EDITING_NEEDS_EVERY_ARTBOARD: &str = pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec, Vec)> { // Keep the editable object tree independent of preview fallbacks used by the drawn pages. let (full, mut warnings) = crate::cmd::place::document::full_documents(doc); - let (bytes, drawn_warnings) = encode_carrying(cmd, &full, p, || Ok(vectorcraft_format::save(doc, false)))?; + let (bytes, drawn_warnings) = encode_carrying(cmd, &full, p, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; warnings.extend(drawn_warnings); warnings.extend(overflow_warning(cmd, &full, p)?); Ok((bytes, warnings)) @@ -281,8 +281,15 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result Result>) -> Result<(Vec, Vec)> { +/// native document with its save options, whose pages may be left blank), and `private()`, the +/// editing copy of the art for other apps with what it couldn't hold, on the first page. +pub(super) fn encode_carrying( + cmd: &str, + doc: &Document, + p: &Value, + native: impl FnOnce() -> Result>, + private: impl FnOnce() -> Result)>>, +) -> Result<(Vec, Vec)> { let mut opts = options(cmd, doc, p)?; if opts.settings.thumbnails { opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?; @@ -291,6 +298,10 @@ pub(super) fn encode_carrying(cmd: &str, doc: &Document, p: &Value, native: impl if opts.settings.preserve_editing { if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) { opts.native = Some(native()?); + if let Some((data, lost)) = private()? { + opts.private_data = Some(data); + warnings.extend(lost); + } } else { opts.settings.preserve_editing = false; warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string()); diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index e747be71fa..0273efd923 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -39,6 +39,9 @@ pub struct LoadOptions { /// A `.ai` opens from its editing copy even where that draws differently from its PDF part /// (which can be older than it), with a warning, instead of from the PDF part. pub trust_editing_data: bool, + /// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries; + /// off, it opens as another app would open it, from the editing copy of its art or its pages. + pub native: bool, } impl Default for LoadOptions { @@ -54,6 +57,7 @@ impl Default for LoadOptions { dxf: Default::default(), editing_data: true, trust_editing_data: false, + native: true, } } } @@ -91,7 +95,7 @@ impl LoadOptions { Some(v) => (v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true, false or \"always\""))?, false), }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; - Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data }) + Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, native: true }) } /// Does the document read only part of the file, or read it differently (a page range, another diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 486777a247..e211fd7195 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -584,6 +584,14 @@ fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError { } } +/// The `.ai` option `editingData`: whether the file also carries the editing copy of the art that +/// other apps read (default on). +#[derive(Default, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct AiEditingData { + editing_data: Option, +} + /// The shared Save and Export encoder for PDF-compatible `.ai` files (and `.ait` templates, the /// same file). pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result { @@ -613,13 +621,35 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res return Err(bad(cmd, "pdfCompatible: false needs every artboard to keep the editable artwork")); } } - let pages = doc.without_edit_modes(); + let edited = doc.without_edit_modes(); // Resolve placed files only for the drawn pages. Missing files become preview images there; // the native attachment keeps the original placed objects and their relinkable metadata. - let (pages, placed_warnings) = - if pdf_compatible { crate::cmd::place::document::full_documents(&pages) } else { (std::borrow::Cow::Owned(blank_pages(&pages)), Vec::new()) }; + let (pages, placed_warnings) = if pdf_compatible { + crate::cmd::place::document::full_documents(&edited) + } else { + (std::borrow::Cow::Owned(blank_pages(&edited)), Vec::new()) + }; let native = || super::native::ai_native(cmd, doc, &native_options); - let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native)?; + let other_apps: AiEditingData = super::encode::options(f, ¶ms)?; + let private = || { + if !other_apps.editing_data.unwrap_or(true) { + return Ok(None); + } + // The art with placed files resolved as the pages draw them, also when the pages are blank. + let resolved; + let art: &Document = if pdf_compatible { + &pages + } else { + resolved = crate::cmd::place::document::full_documents(&edited).0; + &resolved + }; + let o = vectorcraft_eps::AiEditingOptions { + title: doc.title.clone(), + created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time), + }; + vectorcraft_eps::ai_private_data(art, &o).map(Some).map_err(|e| bad(cmd, e)) + }; + let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?; warnings.extend(placed_warnings); if !pdf_compatible { warnings.push(NOT_PDF_COMPATIBLE.to_string()); diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 35d3945402..358c9840c1 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -403,3 +403,51 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { assert_eq!(comparable(&s.doc().unwrap().doc), before); assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } + +/// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded. +fn outline(doc: &vectorcraft_doc::Document) -> Vec { + fn walk(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let b = n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + let kind = match &n.kind { + vectorcraft_doc::NodeKind::Layer { .. } => "layer", + vectorcraft_doc::NodeKind::Group { .. } => "group", + vectorcraft_doc::NodeKind::Path { .. } => "path", + _ => "other", + }; + out.push(format!("{depth} {kind} {:?} {} {b:?}", n.name, n.visible)); + walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } + } + let mut out = vec![]; + walk(&doc.layers, 0, &mut out); + out +} + +/// A `.ai` also carries the editing copy of its art that other apps read: opened without the +/// VectorCraft document it carries, it gives back the same layers, groups and paths, its page +/// matching them. `editingData: false` leaves the copy out. +#[test] +fn ai_files_carry_an_editing_copy_for_other_apps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 60, "y": 10, "width": 50, "height": 30})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("layer.new", &json!({"name": "Top"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 120, "y": 50, "width": 60, "height": 40})).unwrap(); + let before = outline(&s.doc().unwrap().doc); + let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap()); + let private = vectorcraft_pdf::illustrator_data(&bytes, None).expect("the editing copy for other apps"); + assert!(private.starts_with(b"%AI24_ZStandard_Data")); + let opts = LoadOptions { native: false, ..Default::default() }; + let l = load::load_with("art.ai", &bytes, &opts).unwrap(); + assert!(l.editing_data && !l.restored); + assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings); + assert_eq!(outline(&l.doc), before); + let r = s.execute("document.export", &json!({"format": "ai", "editingData": false})).unwrap(); + assert_eq!(vectorcraft_pdf::illustrator_data(&b64(&r), None), None); + assert!(s.execute("document.export", &json!({"format": "ai", "editingData": "no"})).is_err()); +} diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 6743c2a2a4..0004a65d31 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -13,6 +13,8 @@ vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } +# The editing data for other apps writes clipped art cut to its clipping path. +vectorcraft-pathops = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } # Windows metafile previews, opened when a file's PostScript can't be read. diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs new file mode 100644 index 0000000000..0ad1b932a3 --- /dev/null +++ b/crates/eps/src/ai_editing.rs @@ -0,0 +1,238 @@ +//! The editing copy of the art that a PDF-compatible `.ai` file carries in its first page's +//! `PieceInfo` ([`vectorcraft_pdf::PrivateData`]): the document's layers, sublayers, groups, paths, +//! colors, swatches and artboards in the form [`crate::import`]'s `.ai` reader reads, so that apps +//! that open `.ai` files from that copy get them as editable objects. +//! +//! The form is the one the published specification documents (Adobe Illustrator File Format +//! Specification, version 7.0, see [`crate::legacy_ai`]) for paths (§5.3), colors (§5.4), +//! groups and compound paths (§5.3.5), guides (§6) and layers (§9), with the newer forms the reader +//! reads from files users sent: +//! +//! - Header comments: `%%BoundingBox`, `%%HiResBoundingBox`, `%AI5_FileFormat 14.0`, the first +//! artboard as `%AI3_Cropmarks` and `%AI5_ArtSize`, `%AI5_RulerUnits`, `%AI9_ColorModel` (1 RGB, 2 +//! CMYK), `%AI5_NumLayers`, and the version comment `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). +//! - Setup: the color swatches (`%AI5_BeginPalette`, `0 0 Pb`, each swatch's color operator and +//! `(name) Pc`, a color group as `0 (name) count Pg` before its swatches, `PB`), then the +//! artboards as the `ArtboardArray` of the `/Document` dictionary, on `%_` lines. +//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0 +//! dimPercent 0 Lb` (14 operands; a color that isn't one of the preset layer colors has the +//! index -1), `(name) Ln`, its art and sublayers, `LB`, `%AI5_EndLayer--`. +//! - Colors: `g` gray, `k` CMYK, `c m y k r g b Xa` RGB (Lab is written as RGB); a spot color +//! `c m y k (name) tint x` (CMYK) or `c m y k r g b|L a b (name) tint 1|2 Xx` (RGB or Lab); a +//! global process color `… (name) tint model Xk`; Registration `1 1 1 1 ([Registration]) tint +//! Xs`. Upper case paints the stroke. +//! - State before each object: locked `A`, hidden `Xw` (`1` or `0`). An object's name follows it as +//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are `(N) *`, the +//! path, `(N) *` (`(n) *` when closed). +//! +//! Strings are written in UTF-8. Art space has y up, its origin at the first artboard's bottom-left +//! corner. What the form above can't hold is written as plain filled and stroked paths, each such +//! loss a warning: type as its outlines, gradients as their average color, pattern fills as their +//! tiles cut to the shape, clipping groups and clipping layers as their art cut to the clipping +//! path (the clipping path's fill cut too, its stroke not), images as their outlines filled with +//! their average color, symbols and live objects as their art, strokes a plain line can't draw as +//! their filled outlines, several fills or strokes as a group of a path for each, gradient and +//! pattern swatches, transparency and live effects other than geometry effects left out. +//! +//! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with +//! the version numbers of the newest files users sent ([`private_data`]). + +use std::fmt::Write; +use std::sync::Arc; + +use vectorcraft_doc::{Document, Node, Unit}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_pdf::PrivateData; + +use crate::ps; + +mod writer; + +use writer::Writer; + +/// The version comment's value: the creator version of the newest files users sent. +pub const CREATOR_VERSION: &str = "30.7.0"; +/// The `PieceInfo` numbers that go with Zstandard-compressed data: container 12, creator 30, +/// round trip 24, stream type 2. +const CONTAINER_VERSION: u32 = 12; +const CREATOR: u32 = 30; +const ROUNDTRIP_VERSION: u32 = 24; +const ROUNDTRIP_STREAM_TYPE: u32 = 2; +/// What starts the data streams of Zstandard-compressed data. +const ZSTD_MARKER: &[u8] = b"%AI24_ZStandard_Data"; + +/// The first line of a PostScript file (the DSC version comment). +const PS_HEADER: &str = "%!PS-Adobe-3.0"; // brand-ok: the PostScript header comment + +/// What to write in the header. +#[derive(Clone, Debug, Default)] +pub struct AiEditingOptions { + /// `%%Title`. + pub title: String, + /// `%%CreationDate`, Unix seconds. + pub created: Option, +} + +/// The editing data and what it couldn't hold. +#[derive(Clone, Debug, Default)] +pub struct AiEditingOutput { + /// The program: header comments, setup, layers, trailer. + pub program: Vec, + /// Its header comments, up to `%%EndComments`. + pub header: Vec, + pub warnings: Vec, +} + +/// Write `doc` as the editing data of a `.ai` file: every artboard and layer. +pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result { + let board = doc.artboards.first().ok_or("the document has no artboard")?.rect; + if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) { + return Err("the document has no artboard".into()); + } + // Live geometry effects as their result, as the PDF part draws them. + let baked = baked(doc); + let doc = baked.as_ref().unwrap_or(doc); + // The document is y down; art space y up from the first artboard's bottom-left corner. + let to_art = Affine::new([1.0, 0.0, 0.0, -1.0, -board.x0, board.y1]); + let mut w = Writer::new(doc, to_art); + for layer in &doc.layers { + w.layer(layer); + } + let layers = doc.layers.len(); + let (width, height) = (board.width(), board.height()); + let art = doc + .layers + .iter() + .filter(|l| l.visible) + .filter_map(|l| l.visual_bounds()) + .map(|b| to_art.transform_rect_bbox(b)) + .filter(|b| b.is_finite()) + .reduce(|a, b| a.union(b)) + .unwrap_or(Rect::new(0.0, 0.0, width, height)); + let header = header(doc, o, &w, art, (width, height), layers); + let mut s = header.clone(); + s.push_str("%%BeginProlog\n%%EndProlog\n%%BeginSetup\n"); + w.palette(&mut s); + artboards(&mut s, doc, to_art); + s.push_str("%%EndSetup\n"); + s.push_str(&w.body); + s.push_str("%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n"); + Ok(AiEditingOutput { program: s.into_bytes(), header: header.into_bytes(), warnings: w.warnings }) +} + +/// `doc` with its geometry effects baked ([`vectorcraft_effects::bake_document`]), in its symbols' +/// art too (which instances are written as); `None` when nothing changes. +fn baked(doc: &Document) -> Option { + let baked = vectorcraft_effects::bake_document(doc); + let d = baked.as_ref().unwrap_or(doc); + if !d.symbols.iter().any(|s| vectorcraft_effects::needs_bake(&s.art)) { + return baked; + } + // The symbols' art baked as the layers of a copy of the document. + let mut art = d.clone(); + art.layers = d.symbols.iter().map(|s| Arc::new(Node::group(s.art.id, vec![s.art.clone()]))).collect(); + // The copy keeps what baking adds to the document (the images color adjustments make). + let Some(mut out) = vectorcraft_effects::bake_document(&art) else { return baked }; + let arts: Vec>> = out.layers.iter().map(|l| l.children().and_then(|c| c.first()).cloned()).collect(); + out.layers = d.layers.clone(); + for (s, a) in out.symbols.iter_mut().zip(arts) { + if let Some(a) = a { + s.art = a; + } + } + Some(out) +} + +/// The editing data of `doc` as a `.ai` file's first page carries it: the program compressed with +/// Zstandard after `%AI24_ZStandard_Data`, its header as the `AIMetaData`, and the version numbers +/// that go with that form; and what it couldn't hold. +pub fn private_data(doc: &Document, o: &AiEditingOptions) -> Result<(PrivateData, Vec), String> { + let out = export_ai_editing(doc, o)?; + let mut data = ZSTD_MARKER.to_vec(); + data.extend(ruzstd::encoding::compress_to_vec(out.program.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)); + let p = PrivateData { + data, + metadata: out.header, + container_version: CONTAINER_VERSION, + creator_version: CREATOR, + roundtrip_version: ROUNDTRIP_VERSION, + roundtrip_stream_type: ROUNDTRIP_STREAM_TYPE, + }; + Ok((p, out.warnings)) +} + +/// The header comments, through `%%EndComments`. `art`: the visible art's bounds, `size` the first +/// artboard's, in art space. +fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, (width, height): (f64, f64), layers: usize) -> String { + let mut s = String::new(); + s.push_str(PS_HEADER); + s.push('\n'); + let _ = writeln!(s, "%%Creator: VectorCraft {}", env!("CARGO_PKG_VERSION")); + let _ = writeln!(s, "%%AI8_CreatorVersion: {CREATOR_VERSION}"); + let _ = writeln!(s, "%%Title: {}", ps::bytes(o.title.as_bytes())); + if let Some(t) = o.created { + let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); + let _ = writeln!(s, "%%CreationDate: ({mo}/{d}/{y:04}) ({h:02}:{mi:02})"); + } + let _ = writeln!(s, "%%BoundingBox: {} {} {} {}", art.x0.floor() as i64, art.y0.floor() as i64, art.x1.ceil() as i64, art.y1.ceil() as i64); + s.push_str("%%HiResBoundingBox: "); + ps::push_nums(&mut s, &[art.x0, art.y0, art.x1, art.y1]); + s.pop(); + s.push('\n'); + s.push_str("%%DocumentProcessColors: Cyan Magenta Yellow Black\n"); + s.push_str("%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n"); + let spots = w.spot_swatches(); + for (i, (name, _)) in spots.iter().enumerate() { + let _ = writeln!(s, "{} {}", if i == 0 { "%%DocumentCustomColors:" } else { "%%+" }, ps::bytes(name.as_bytes())); + } + for (i, (name, cmyk)) in spots.iter().enumerate() { + s.push_str(if i == 0 { "%%CMYKCustomColor: " } else { "%%+ " }); + ps::push_nums(&mut s, &cmyk.map(f64::from)); + let _ = writeln!(s, "{}", ps::bytes(name.as_bytes())); + } + let (w2, h2) = (ps::num(width), ps::num(height)); + let _ = writeln!(s, "%AI3_Cropmarks: 0 0 {w2} {h2}"); + let (cx, cy) = (ps::num(width / 2.0), ps::num(height / 2.0)); + let _ = writeln!(s, "%AI3_TemplateBox: {cx} {cy} {cx} {cy}"); + let _ = writeln!(s, "%AI3_TileBox: 0 0 {w2} {h2}"); + s.push_str("%AI3_DocumentPreview: None\n"); + let _ = writeln!(s, "%AI5_ArtSize: {w2} {h2}"); + let _ = writeln!(s, "%AI5_RulerUnits: {}", ruler_units(doc.units)); + s.push_str("%AI24_LargeCanvasScale: 1\n"); + let model = if doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { 2 } else { 1 }; + let _ = writeln!(s, "%AI9_ColorModel: {model}"); + let _ = writeln!(s, "%AI5_NumLayers: {layers}"); + s.push_str("%%EndComments\n"); + s +} + +/// `%AI5_RulerUnits` of `u` (as the reader reads it; units it has no number for are points). +fn ruler_units(u: Unit) -> u8 { + match u { + Unit::Inches => 0, + Unit::Millimeters => 1, + Unit::Picas => 3, + Unit::Centimeters => 4, + Unit::Pixels => 6, + Unit::Points | Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet => 2, + } +} + +/// The artboards as the `ArtboardArray` of the `/Document` dictionary: each one's top-left and +/// bottom-right corners in art space (`PositionPoint1`, `PositionPoint2`) and its name. +fn artboards(s: &mut String, doc: &Document, to_art: Affine) { + s.push_str("%AI9_BeginDocumentData\n%_/Document :\n%_/Dictionary :\n%_/Array :\n"); + for ab in &doc.artboards { + let r = to_art.transform_rect_bbox(ab.rect); + s.push_str("%_/Dictionary :\n%_"); + ps::push_nums(s, &[r.x0, r.y1]); + s.push_str("/RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_"); + ps::push_nums(s, &[r.x1, r.y0]); + s.push_str("/RealPointRelToROrigin\n%_ (PositionPoint2) ,\n"); + let _ = writeln!(s, "%_{} /UnicodeString (Name) ,\n%_; ,", ps::bytes(ab.name.as_bytes())); + } + s.push_str("%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"); +} + +#[cfg(test)] +mod tests; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs new file mode 100644 index 0000000000..0490ae3918 --- /dev/null +++ b/crates/eps/src/ai_editing/tests.rs @@ -0,0 +1,645 @@ +//! The editing data written, then read back by VectorCraft's own reader ([`crate::ai_alone`]). + +use std::sync::Arc; + +use vectorcraft_color::swatch::{Swatch, SwatchGroup}; +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeKind, + StrokeLayer, Symbol, +}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; + +use super::*; + +fn opts() -> AiEditingOptions { + AiEditingOptions { title: "Sample".into(), created: Some(0) } +} + +/// The program written from `doc`, as text. +fn program(doc: &Document) -> String { + String::from_utf8(export_ai_editing(doc, &opts()).unwrap().program).unwrap() +} + +/// `doc` written, then read back from the private data alone. +fn read_back(doc: &Document) -> Document { + let (p, _) = private_data(doc, &opts()).unwrap(); + crate::ai_alone(&p.data).unwrap().0 +} + +fn solid(c: Color) -> Paint { + Paint::solid(c) +} + +/// A swatch's color at `tint`, linked to it. +fn linked(name: &str, full: Color, tint: f32) -> Paint { + Paint::Solid { color: full.tinted(tint), swatch: Some(name.into()), tint } +} + +const BRAND: Color = Color::Cmyk { c: 0.1, m: 0.7, y: 0.2, k: 0.05 }; +const GOLD: Color = Color::Cmyk { c: 0.0, m: 0.25, y: 0.9, k: 0.1 }; +const SKY: Color = Color::Rgb { r: 0.25, g: 0.5, b: 1.0 }; +const MINT: Color = Color::Lab { l: 80.0, a: -40.0, b: 10.0 }; + +/// A 200 × 100 document with a second artboard: swatches (process, global process, CMYK, RGB and +/// Lab spot colors, a color group); a layer `Back` (preset color 2) holding a named group `Pair` +/// of a named rectangle `Red` (stroked 2 pt, round caps, bevel joins, miter limit 4, dashed, over +/// a gray fill that overprints) and a hidden, locked one, an even-odd ellipse in a global color at +/// half tint, an open path stroked in a spot color, a guide, and a hidden locked sublayer `Sub` +/// (a custom color, not printing, dimmed) holding a path filled with an RGB and stroked with a Lab +/// spot color; a second layer `Front`, locked, with a CMYK square named like the rectangle. +fn sample() -> Document { + let mut doc = Document::new(200.0, 100.0); + let mut second = doc.artboards[0].clone(); + second.id = 2; + second.name = "Back side".into(); + second.rect = Rect::new(250.0, 0.0, 450.0, 100.0); + doc.artboards.push(second); + let swatch = |name: &str, c: Color, global: bool, spot: bool| Swatch { name: name.into(), paint: solid(c), global, spot }; + doc.swatches = vec![ + Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false }, + swatch("Teal", Color::rgb(0.0, 0.5, 0.5), false, false), + swatch("Brand", BRAND, true, false), + swatch("Gold", GOLD, true, true), + swatch("Sky", SKY, true, true), + swatch("Mint", MINT, true, true), + ] + .into(); + doc.swatch_groups = vec![SwatchGroup { name: "Grays".into(), swatches: vec![swatch("Mid", Color::gray(0.5), false, false)] }].into(); + doc.layers.clear(); + let back = doc.add_layer(Some("Back")); + let front = doc.add_layer(Some("Front")); + + let mut stroke = StrokeLayer::new(solid(Color::rgb(0.0, 0.0, 1.0)), 2.0); + stroke.cap = LineCap::Round; + stroke.join = LineJoin::Bevel; + stroke.miter_limit = 4.0; + stroke.dash = Some(Dash { pattern: vec![3.0, 2.0], offset: 1.0, align_corners: false }); + let fill = FillLayer { overprint: true, ..FillLayer::new(solid(Color::gray(0.25))) }; + let mut red = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), + Appearance { items: vec![AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)], ..Appearance::default() }, + ); + red.name = Some("Red".into()); + let mut hidden = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(50.0, 10.0, 80.0, 40.0)), + Appearance::basic(solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), Paint::None, 0.0), + ); + hidden.visible = false; + hidden.locked = true; + let mut pair = Node::group(doc.alloc_id(), vec![Arc::new(red), Arc::new(hidden)]); + pair.name = Some("Pair".into()); + doc.insert(Some(back), usize::MAX, pair).unwrap(); + + let ellipse = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::ellipse(Rect::new(100.0, 10.0, 160.0, 50.0)), + rule: FillRule::EvenOdd, + live: None, + clipping: false, + guide: false, + }, + ); + let ellipse = Node { appearance: Appearance::basic(linked("Brand", BRAND, 0.5), Paint::None, 0.0).into(), ..ellipse }; + doc.insert(Some(back), usize::MAX, ellipse).unwrap(); + let mut open = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((10.0, 60.0).into()), + kurbo::PathEl::LineTo((60.0, 90.0).into()), + ])); + open.subpaths.iter_mut().for_each(|sp| sp.closed = false); + let line = Node::path(doc.alloc_id(), open, Appearance::basic(Paint::None, linked("Gold", GOLD, 1.0), 3.0)); + doc.insert(Some(back), usize::MAX, line).unwrap(); + let guide = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::rectangle(Rect::new(0.0, 50.0, 200.0, 50.0)), + rule: FillRule::NonZero, + live: None, + clipping: false, + guide: true, + }, + ); + doc.insert(Some(back), usize::MAX, guide).unwrap(); + + let mut sub = Node::layer(doc.alloc_id(), "Sub", LayerColor::Custom([10, 200, 30])); + if let NodeKind::Layer { printable, dim_images, .. } = &mut sub.kind { + *printable = false; + *dim_images = Some(70); + } + sub.visible = false; + sub.locked = true; + let sub = doc.insert(Some(back), usize::MAX, sub).unwrap(); + let skyfill = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(120.0, 60.0, 190.0, 95.0)), + Appearance::basic(linked("Sky", SKY, 0.8), linked("Mint", MINT, 1.0), 1.0), + ); + doc.insert(Some(sub), usize::MAX, skyfill).unwrap(); + + let mut square = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(300.0, 20.0, 340.0, 60.0)), + Appearance::basic(solid(Color::cmyk(0.5, 0.0, 1.0, 0.0)), Paint::None, 0.0), + ); + square.name = Some("Red".into()); + doc.insert(Some(front), usize::MAX, square).unwrap(); + if let Some(l) = doc.layers.get_mut(1) { + let l = Arc::make_mut(l); + l.locked = true; + if let NodeKind::Layer { color, .. } = &mut l.kind { + *color = LayerColor::Preset(2); + } + } + doc +} + +/// `v` to three decimals. +fn r3(v: f64) -> String { + format!("{:.3}", (v * 1000.0).round() / 1000.0 + 0.0) +} + +fn color(c: &Color) -> String { + let f = |v: f32| r3(f64::from(v)); + match *c { + Color::Gray { k } => format!("gray {}", f(k)), + Color::Cmyk { c, m, y, k } => format!("cmyk {} {} {} {}", f(c), f(m), f(y), f(k)), + Color::Rgb { r, g, b } => format!("rgb {} {} {}", f(r), f(g), f(b)), + Color::Lab { l, a, b } => format!("lab {} {} {}", f(l), f(a), f(b)), + } +} + +fn paint(p: &Paint) -> String { + match p { + Paint::Solid { color: c, swatch, tint } => format!("{} {swatch:?} {}", color(c), r3(f64::from(*tint))), + Paint::None => "none".into(), + other => format!("{other:?}"), + } +} + +/// What the reader's view of the slice's constructs is made of, one line per object. +fn view(nodes: &[Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let head = format!("{depth} {:?} shown={} locked={}", n.name, n.visible, n.locked); + match &n.kind { + NodeKind::Layer { color, printable, preview, dim_images, clip, children, .. } => { + out.push(format!("{head} layer {color:?} printable={printable} preview={preview} dim={dim_images:?} clip={clip}")); + view(children, depth + 1, out); + } + NodeKind::Group { children, clip } => { + out.push(format!("{head} group clip={clip}")); + view(children, depth + 1, out); + } + NodeKind::Path { path, rule, guide, .. } => { + let mut s = format!("{head} path {rule:?} guide={guide}"); + for sp in &path.subpaths { + s += &format!(" [closed={}", sp.closed); + // Points are written to four decimals. + let r2 = |v: f64| format!("{:.2}", v + 0.0); + for a in &sp.anchors { + s += &format!(" {},{} {},{} {},{}", r2(a.h_in.x), r2(a.h_in.y), r2(a.p.x), r2(a.p.y), r2(a.h_out.x), r2(a.h_out.y)); + } + s += "]"; + } + if !guide { + // Items that paint nothing aren't written. + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + s += &match it { + AppearanceItem::Fill(f) => format!(" fill({} op={})", paint(&f.paint), f.overprint), + AppearanceItem::Stroke(st) => format!( + " stroke({} w={} {:?} {:?} m={} {:?} op={})", + paint(&st.paint), + r3(st.width), + st.cap, + st.join, + r3(st.miter_limit), + st.dash.as_ref().map(|d| (d.pattern.clone(), d.offset)), + st.overprint + ), + }; + } + } + out.push(s); + } + other => out.push(format!("{head} {other:?}")), + } + } +} + +fn lines(doc: &Document) -> Vec { + let mut out = vec![]; + view(&doc.layers, 0, &mut out); + out +} + +fn swatches(doc: &Document) -> Vec { + let one = |s: &Swatch| format!("{} global={} spot={} {}", s.name, s.global, s.spot, paint(&s.paint)); + let mut out: Vec = doc.swatches.iter().filter(|s| !matches!(s.paint, Paint::None)).map(one).collect(); + for g in doc.swatch_groups.iter() { + out.push(format!("group {}", g.name)); + out.extend(g.swatches.iter().map(one)); + } + out +} + +#[test] +fn the_reader_reads_back_every_construct_of_the_slice() { + let doc = sample(); + let back = read_back(&doc); + assert_eq!(lines(&back), lines(&doc)); + assert_eq!(swatches(&back), swatches(&doc)); + let boards: Vec<(String, Rect)> = back.artboards.iter().map(|a| (a.name.clone(), a.rect)).collect(); + assert_eq!( + boards, + vec![("Artboard 1".to_string(), Rect::new(0.0, 0.0, 200.0, 100.0)), ("Back side".to_string(), Rect::new(250.0, 0.0, 450.0, 100.0))] + ); + assert_eq!(back.color_mode, doc.color_mode); + assert_eq!(back.units, doc.units); +} + +#[test] +fn writing_again_gives_the_same_bytes() { + let doc = sample(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); + // What the reader reads back is written as the same program. + assert_eq!(program(&read_back(&doc)), String::from_utf8(first.program).unwrap()); + assert!(first.warnings.is_empty(), "{:?}", first.warnings); +} + +#[test] +fn the_data_is_zstandard_compressed_with_the_header_as_metadata() { + let doc = sample(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let (p, _) = private_data(&doc, &opts()).unwrap(); + assert!(p.data.starts_with(ZSTD_MARKER)); + let mut body = p.data.get(ZSTD_MARKER.len()..).unwrap(); + let mut decoded = vec![]; + std::io::Read::read_to_end(&mut ruzstd::decoding::StreamingDecoder::new(&mut body).unwrap(), &mut decoded).unwrap(); + assert_eq!(decoded, out.program); + assert!(out.program.starts_with(&out.header)); + assert_eq!(p.metadata, out.header); + let header = String::from_utf8(out.header).unwrap(); + assert!(header.ends_with("%%EndComments\n")); + for line in [ + "%%AI8_CreatorVersion: 30.7.0\n", + "%AI5_FileFormat 14.0\n", + "%AI3_Cropmarks: 0 0 200 100\n", + "%AI5_ArtSize: 200 100\n", + "%AI9_ColorModel: 1\n", + "%AI5_NumLayers: 2\n", + "%%DocumentCustomColors: (Gold)\n%%+ (Sky)\n%%+ (Mint)\n", + ] { + assert!(header.contains(line), "{line}"); + } + assert_eq!((p.container_version, p.creator_version, p.roundtrip_version, p.roundtrip_stream_type), (12, 30, 24, 2)); +} + +#[test] +fn a_pdf_carries_the_data_on_its_first_page() { + let doc = sample(); + let (p, _) = private_data(&doc, &opts()).unwrap(); + let pdf = + vectorcraft_pdf::export(&doc, &vectorcraft_pdf::PdfOptions { private_data: Some(p.clone()), ..vectorcraft_pdf::PdfOptions::uncompressed() }) + .unwrap(); + assert_eq!(vectorcraft_pdf::illustrator_data(&pdf, None).as_deref(), Some(&p.data[..])); + let (read, _) = crate::ai_alone(&vectorcraft_pdf::illustrator_data(&pdf, None).unwrap()).unwrap(); + assert_eq!(lines(&read), lines(&doc)); +} + +#[test] +fn names_are_xml_ids_numbered_when_taken() { + let text = program(&sample()); + assert!(text.contains("%_/XMLUID : (Red) ; (AI10_ArtUID) ,")); + assert!(text.contains("%_/XMLUID : (Red_00000000000000000001_) ; (AI10_ArtUID) ,")); + assert!(text.contains("%_/XMLUID : (Pair) ; (AI10_ArtUID) ,")); +} + +#[test] +fn many_objects_of_one_name_are_numbered_in_turn() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..20_000 { + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default()); + n.name = Some("Dot".into()); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let text = program(&doc); + let ids: std::collections::HashSet<&str> = text.lines().filter(|l| l.starts_with("%_/XMLUID")).collect(); + assert_eq!(ids.len(), 20_000); + assert!(text.contains("(Dot_00000000000000019999_)")); +} + +#[test] +fn layers_have_fourteen_operands() { + let text = program(&sample()); + assert!(text.contains("%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Back) Ln\n"), "{text}"); + assert!(text.contains("%AI5_BeginLayer\n0 1 0 0 1 0 1 -1 10 200 30 0 70 0 Lb\n(Sub) Ln\n"), "{text}"); +} + +/// A 200 × 100 document of what slice 1 writes as plain paths: a gradient fill, a clipping group, +/// a compound path, an image, type, a symbol instance and a half-transparent square. +fn unsupported() -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let fill = |p: Paint| Appearance::basic(p, Paint::None, 0.0); + let g = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], + ); + let shaded = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), fill(Paint::Gradient(Box::new(GradientPaint::new(g))))); + doc.insert(Some(layer), usize::MAX, shaded).unwrap(); + let clip = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::rectangle(Rect::new(40.0, 10.0, 50.0, 30.0)), + rule: FillRule::NonZero, + live: None, + clipping: true, + guide: false, + }, + ); + let clipped = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(35.0, 15.0, 60.0, 25.0)), + Appearance::basic(solid(Color::gray(0.5)), solid(Color::BLACK), 1.0), + ); + let mut window = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(clipped)], clip: true }); + window.name = Some("Window".into()); + doc.insert(Some(layer), usize::MAX, window).unwrap(); + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(70.0, 10.0, 90.0, 30.0)), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(75.0, 15.0, 85.0, 25.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = fill(solid(Color::cmyk(0.0, 1.0, 1.0, 0.0))).into(); + doc.insert(Some(layer), usize::MAX, ring).unwrap(); + let mut png = vec![]; + let img = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { + key, + width: 2, + height: 1, + xf: Affine::new([10.0, 0.0, 0.0, 10.0, 100.0, 10.0]), + link: None, + placement: Default::default(), + pixels: None, + }; + let im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Type", + vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }, + ); + let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + let art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill(solid(Color::rgb(0.0, 1.0, 0.0)))); + doc.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((150.0, 10.0)) }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let mut faded = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(170.0, 10.0, 190.0, 30.0)), fill(solid(Color::BLACK))); + faded.opacity = 0.5; + doc.insert(Some(layer), usize::MAX, faded).unwrap(); + doc +} + +/// Every path in `nodes` and their descendants. +fn paths(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match n.children() { + Some(c) => paths(c, out), + None => out.push((**n).clone()), + } + } +} + +#[test] +fn art_the_slice_does_not_cover_is_written_as_plain_paths() { + let doc = unsupported(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + for w in [writer::GRADIENTS, writer::CLIPPING, writer::IMAGES, writer::TYPE, writer::LIVE, writer::TRANSPARENCY] { + assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); + } + let back = read_back(&doc); + let layer = back.layers[0].children().unwrap(); + let kinds: Vec<&str> = layer + .iter() + .map(|n| match n.kind { + NodeKind::Path { .. } => "path", + NodeKind::Group { .. } => "group", + NodeKind::Compound { .. } => "compound", + _ => "other", + }) + .collect(); + assert_eq!(kinds, ["path", "group", "compound", "path", "group", "group", "path"]); + let mut all = vec![]; + paths(layer, &mut all); + assert!(all.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }))); + // The gradient as its average color. + assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5)))); + // The clipping group: the gray fill and the black stroke's outline, cut to the 10 × 20 clip. + let window = &layer[1]; + assert_eq!(window.name.as_deref(), Some("Window")); + let b = window.visual_bounds().unwrap(); + assert!((b.x0 - 40.0).abs() < 0.01 && (b.x1 - 50.0).abs() < 0.01, "{b:?}"); + // The image's outline filled with its pixels' average. + assert_eq!(paint(layer[3].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.0, 0.5)))); + assert_eq!(layer[3].visual_bounds().map(|b| (r3(b.x0), r3(b.y0), r3(b.x1), r3(b.y1))), Some((r3(100.0), r3(10.0), r3(120.0), r3(20.0)))); + // The half-transparent square, opaque. + assert_eq!(layer[6].opacity, 1.0); +} + +#[test] +fn brushed_strokes_are_written_as_their_brush_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut line = Node::path( + doc.alloc_id(), + shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()), + Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 4.0), + ); + line.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + doc.insert(Some(layer), usize::MAX, line).unwrap(); + let pieces = vectorcraft_brush::stroke_pieces( + &doc, + &vectorcraft_brush::find(&doc, "3 pt. Round").unwrap(), + &shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()).to_bezpath(), + doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap(), + ); + let back = read_back(&doc); + let NodeKind::Group { children, .. } = &back.layers[0].children().unwrap()[0].kind else { panic!("a group of the brush's art") }; + assert_eq!(children.len(), pieces.len()); + let bounds = |n: &Node| n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 10.0).round())); + assert_eq!(children.iter().map(|c| bounds(c)).collect::>(), pieces.iter().map(bounds).collect::>()); +} + +#[test] +fn type_is_written_as_create_outlines_makes_it() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let style = vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), underline: true, ..vectorcraft_doc::CharStyle::default() }; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Under", style); + let mut t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + t.name = Some("Title".into()); + doc.insert(Some(layer), usize::MAX, t.clone()).unwrap(); + let outlined = vectorcraft_effects::outline_text(&t).unwrap(); + let back = read_back(&doc); + let group = &back.layers[0].children().unwrap()[0]; + assert_eq!(group.name.as_deref(), Some("Title")); + let rounded = |n: &Node| n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 100.0).round())); + // The underline reaches below the glyphs: the bounds match only with it. + assert_eq!(rounded(group), rounded(&outlined)); +} + +#[test] +fn a_stained_symbol_instance_is_written_in_its_stained_colors() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let art = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::basic(solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0), + ); + doc.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + let mut instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((50.0, 10.0)) }); + instance.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + let stained = vectorcraft_brush::instance_art(&doc.symbols[0].art, &instance); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let NodeKind::Group { children, .. } = &back.layers[0].children().unwrap()[0].kind else { panic!("the instance's group") }; + assert_eq!(paint(children[0].appearance.items[0].paint()), paint(stained.appearance.items[0].paint())); + assert_ne!(paint(stained.appearance.items[0].paint()), paint(&solid(Color::rgb(0.0, 1.0, 0.0))), "the instance stains its art"); +} + +#[test] +fn a_layer_with_crop_marks_keeps_its_art_and_gets_the_marks() { + for clipping in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let at = Rect::new(50.0, 30.0, 90.0, 60.0); + if clipping { + let clip = Node::new( + doc.alloc_id(), + NodeKind::Path { path: shapes::rectangle(at), rule: FillRule::NonZero, live: None, clipping: true, guide: false }, + ); + doc.insert(Some(layer), usize::MAX, clip).unwrap(); + } + let square = Node::path(doc.alloc_id(), shapes::rectangle(at), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + if let Some(l) = doc.layers.get_mut(0) { + let fx = vectorcraft_doc::Effect { id: vectorcraft_effects::CROP_MARKS.into(), params: serde_json::json!({}), visible: true }; + let l = Arc::make_mut(l); + let mut ap = (*l.appearance).clone(); + ap.effects.push(fx); + l.appearance = ap.into(); + if let NodeKind::Layer { clip, .. } = &mut l.kind { + *clip = clipping; + } + } + let name = doc.layers[0].name.clone(); + let back = read_back(&doc); + assert_eq!(back.layers.len(), 1); + assert_eq!(back.layers[0].name, name); + let members = back.layers[0].children().unwrap(); + assert_eq!(members.len(), 2, "clipping {clipping}: the square and the marks"); + assert!(matches!(members[0].kind, NodeKind::Path { .. })); + assert!(matches!(members[1].kind, NodeKind::Group { .. })); + // The marks lie around the square, outside a clipping path. + let marks = members[1].visual_bounds().unwrap(); + assert!(marks.x0 < at.x0 - 1.0 && marks.x1 > at.x1 + 1.0, "clipping {clipping}: {marks:?}"); + } +} + +#[test] +fn geometry_effects_in_a_symbol_are_written_as_their_result() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut ap = Appearance::basic(solid(Color::BLACK), Paint::None, 0.0); + ap.effects.push(vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 5}), visible: true }); + let art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), ap); + doc.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((50.0, 20.0)) }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let b = back.layers[0].children().unwrap()[0].visual_bounds().unwrap(); + // The 10 pt square offset by 5 pt, at (50, 20). + assert!((b.x0 - 45.0).abs() < 0.1 && (b.x1 - 65.0).abs() < 0.1 && (b.y0 - 15.0).abs() < 0.1 && (b.y1 - 35.0).abs() < 0.1, "{b:?}"); +} + +#[test] +fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut png = vec![]; + image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { key, width: 2, height: 2, xf: Affine::scale(5.0), link: None, placement: Default::default(), pixels: None }; + let mut im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + let shift = serde_json::json!({"amount": 100, "preserveLightness": false}); + let mut ap = (*im.appearance).clone(); + ap.effects.push(vectorcraft_doc::Effect { id: "adjust.shiftToColor".into(), params: shift, visible: true }); + im.appearance = ap.into(); + doc.symbols.push(Symbol { name: "Picture".into(), art: Arc::new(im) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Picture".into(), xf: Affine::translate((50.0, 20.0)) }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let fill = paint(all[0].appearance.items[0].paint()); + assert_ne!(fill, paint(&solid(Color::gray(0.5))), "the adjusted image is found"); + assert_ne!(fill, paint(&solid(Color::rgb(0.0, 0.0, 0.0))), "the image is adjusted"); +} + +#[test] +fn effects_on_a_fill_are_reported_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut fill = FillLayer::new(solid(Color::BLACK)); + fill.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({}), visible: true }); + let ap = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Appearance::default() }; + let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), ap); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); +} + +#[test] +fn images_too_large_to_average_are_mid_gray() { + let mut png = vec![]; + image::GrayImage::new(5000, 4000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + assert_eq!(image_average_of(&png), paint(&solid(Color::gray(0.5)))); + let mut small = vec![]; + image::GrayImage::new(50, 40).write_to(&mut std::io::Cursor::new(&mut small), image::ImageFormat::Png).unwrap(); + assert_eq!(image_average_of(&small), paint(&solid(Color::rgb(0.0, 0.0, 0.0)))); +} + +/// The fill an image of `png` is written with, as the reader reads it. +fn image_average_of(png: &[u8]) -> String { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let blob = ImageBlob::new("image/png", png.to_vec()); + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { key, width: 10, height: 10, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + paint(read_back(&doc).layers[0].children().unwrap()[0].appearance.items[0].paint()) +} + +#[test] +fn a_document_without_an_artboard_is_an_error() { + let mut doc = Document::new(200.0, 100.0); + doc.artboards.clear(); + assert!(export_ai_editing(&doc, &opts()).is_err()); + doc.artboards.push(Artboard { rect: Rect::new(0.0, 0.0, 0.0, 10.0), ..Document::new(1.0, 1.0).artboards[0].clone() }); + assert!(export_ai_editing(&doc, &opts()).is_err()); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs new file mode 100644 index 0000000000..ff0d6ed771 --- /dev/null +++ b/crates/eps/src/ai_editing/writer.rs @@ -0,0 +1,710 @@ +//! The program's art and swatches (see [`super`] for the form). + +use std::collections::{HashMap, HashSet}; +use std::fmt::Write; +use std::sync::Arc; + +use vectorcraft_color::cms::Cms; +use vectorcraft_color::swatch::{REGISTRATION, Swatch}; +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, FillLayer, LAYER_COLORS, LayerColor, Node, NodeKind, StrokeLayer}; +use vectorcraft_effects::stroke; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, SubPath}; +use vectorcraft_pathops::BoolOp; + +use crate::ai_ops::{self, average, unit}; +use crate::ps; + +/// How deep symbols, live objects and pattern tiles may nest in one another (deeper art is left +/// out). Groups and layers need no limit of their own: a document is never deeper than +/// [`vectorcraft_doc::MAX_DEPTH`]. +const MAX_NEST: u32 = 8; +/// The side of the image whose pixels are averaged (larger ones are scaled down to it first). +const AVERAGE_SIDE: u32 = 64; +/// Most pixels an image may have to be decoded and averaged (more: mid gray). +const MAX_AVERAGED_PIXELS: u64 = 1 << 24; + +pub(super) const TYPE: &str = "type is written as its outlines in the editing data for other apps"; +pub(super) const GRADIENTS: &str = "gradients are written as their average color in the editing data for other apps"; +const PATTERNS: &str = "pattern fills are written as their tiles cut to the shape in the editing data for other apps"; +pub(super) const CLIPPING: &str = + "clipping groups and clipping layers are written as their art cut to the clipping path in the editing data for other apps"; +pub(super) const IMAGES: &str = "images are written as their outlines filled with their average color in the editing data for other apps"; +pub(super) const LIVE: &str = + "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; +const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; +pub(super) const TRANSPARENCY: &str = "transparency (opacity, blending modes, opacity masks) is left out of the editing data for other apps"; +pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps"; +const SWATCHES: &str = "gradient and pattern swatches are left out of the editing data for other apps"; +const TEMPLATES: &str = "template layers are written as dimmed layers that don't print in the editing data for other apps"; + +pub(super) struct Writer<'a> { + doc: &'a Document, + /// The document → art space. + to_art: Affine, + cms: Arc, + pub(super) body: String, + pub(super) warnings: Vec, + /// The lock and hidden state (`A`, `Xw`) the last operators set; `None` at a layer's start. + state: Option<(bool, bool)>, + /// The region the art being written is cut to (a clipping path's, in document space). + clip: Option, + /// Symbols, live objects and pattern tiles being written inside one another. + nest: u32, + /// The XML ids objects are named with so far. + ids: HashSet, + /// The number the next object named after each XML id tries first. + next: HashMap, + /// The document's brushes, read the first time a brushed stroke is written. + brushes: Option>, +} + +impl<'a> Writer<'a> { + pub(super) fn new(doc: &'a Document, to_art: Affine) -> Self { + Self { + doc, + to_art, + cms: vectorcraft_color::cms::active(), + body: String::new(), + warnings: vec![], + state: None, + clip: None, + nest: 0, + ids: HashSet::new(), + next: HashMap::new(), + brushes: None, + } + } + + fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + fn line(&mut self, s: &str) { + self.body.push_str(s); + self.body.push('\n'); + } + + // ---------- layers and objects ---------- + + /// A top-level layer. A layer that baking its effects made a group of the layer and the art an + /// effect adds (Crop Marks) is written as that layer holding the added art too, and any other + /// object at the top level in a layer of its own. + pub(super) fn layer(&mut self, n: &Node) { + if n.is_layer() { + return self.write_layer(n, &[]); + } + let members = n.children().map(Vec::as_slice).unwrap_or_default(); + self.transparency(n); + match members.iter().find(|c| c.is_layer()) { + Some(l) => { + // The group took the layer's name. The added art is outside the layer's clipping. + let layer = Node { name: l.name.clone().or_else(|| n.name.clone()), ..(**l).clone() }; + let added: Vec> = members.iter().filter(|c| !c.is_layer()).cloned().collect(); + self.write_layer(&layer, &added); + } + None => { + let mut layer = Node::layer(n.id, n.name.as_deref().unwrap_or("Layer"), LayerColor::Preset(0)); + (layer.visible, layer.locked) = (n.visible, n.locked); + self.write_layer(&layer, &[Arc::new(n.clone())]); + } + } + } + + /// A layer or sublayer: `%AI5_BeginLayer`, its options `Lb`, its name `Ln`, its art, then + /// `after` (outside its clipping path when it clips), `LB`, `%AI5_EndLayer--`. + fn write_layer(&mut self, n: &Node, after: &[Arc]) { + let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return }; + let [r, g, b] = match color { + LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1), + LayerColor::Custom(rgb) => *rgb, + }; + let index = match color { + LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i), + _ => -1, + }; + if *template { + self.warn(TEMPLATES); + } + self.transparency(n); + let flag = |b: bool| u8::from(b); + let dim = dim_images.unwrap_or(50); + let _ = writeln!( + self.body, + "%AI5_BeginLayer\n{} {} {} {} {} 0 1 {index} {r} {g} {b} 0 {dim} 0 Lb\n{} Ln", + flag(n.visible), + flag(*preview), + flag(!n.locked), + flag(*printable && !*template), + flag(dim_images.is_some() || *template), + ps::bytes(n.name.as_deref().unwrap_or("Layer").as_bytes()), + ); + self.state = None; + if *clip { + self.warn(CLIPPING); + self.clip_contents(children); + } else { + for c in children { + self.node(c); + } + } + for c in after { + self.node(c); + } + self.line("LB\n%AI5_EndLayer--"); + // The reader's state carries over into the art that follows. + self.state = None; + } + + /// Set the lock and hidden state of the object that follows. + fn state(&mut self, locked: bool, hidden: bool) { + let (was_locked, was_hidden) = match self.state { + Some((l, h)) => (Some(l), Some(h)), + None => (None, None), + }; + if was_locked != Some(locked) { + self.line(if locked { "1 A" } else { "0 A" }); + } + if was_hidden != Some(hidden) { + self.line(if hidden { "1 Xw" } else { "0 Xw" }); + } + self.state = Some((locked, hidden)); + } + + /// Warn when `n` has transparency or effects the data leaves out. + fn transparency(&mut self, n: &Node) { + if n.opacity < 1.0 || n.blend != BlendMode::Normal || n.extras().mask.as_ref().is_some_and(|m| !m.disabled) { + self.warn(TRANSPARENCY); + } + let items = n.appearance.items.iter().filter(|i| i.visible()).flat_map(|i| i.effects()); + if n.appearance.effects.iter().chain(items).any(|e| e.visible) { + self.warn(EFFECTS); + } + } + + /// One object, its state before it and its name after it. + fn node(&mut self, n: &Node) { + if let NodeKind::Layer { .. } = n.kind { + return self.write_layer(n, &[]); + } + self.transparency(n); + self.state(n.locked, !n.visible); + let start = self.body.len(); + match &n.kind { + NodeKind::Layer { .. } => {} + NodeKind::Group { children, clip } => { + self.line("u"); + if *clip { + self.warn(CLIPPING); + self.clip_contents(children); + } else { + for c in children { + self.node(c); + } + } + self.line("U"); + } + NodeKind::Path { path, rule, guide, .. } => { + if *guide { + ai_ops::guide(&mut self.body, self.to_art, path, true); + } else { + self.shape(n, path, *rule); + } + } + NodeKind::Compound { children, rule } => { + let mut subpaths = vec![]; + for p in children.iter().filter_map(|c| c.path_data()) { + subpaths.extend(p.subpaths.iter().cloned()); + } + self.shape(n, &PathData::new(subpaths), *rule); + } + NodeKind::Text(_) => self.text(n), + NodeKind::Image(im) => { + let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); + let color = image_average(self.doc.image_blob(im).map(|b| b.bytes.as_slice())); + self.warn(IMAGES); + self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(color))); + } + NodeKind::SymbolInstance { symbol, xf } => { + self.warn(LIVE); + self.line("u"); + if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) + && self.nest < MAX_NEST + { + // Stained by the instance's fill, as the canvas draws it. + let mut art = vectorcraft_brush::instance_art(&sym.art, n); + art.transform(*xf, false); + art.visible = true; + art.locked = false; + art.name = None; + self.nest += 1; + self.node(&art); + self.nest -= 1; + } + self.line("U"); + } + NodeKind::Blend { .. } + | NodeKind::Envelope { .. } + | NodeKind::Mesh(_) + | NodeKind::Repeat(_) + | NodeKind::PlacedDocument(_) + | NodeKind::Intertwine { .. } => { + self.warn(LIVE); + self.line("u"); + if self.nest < MAX_NEST { + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + self.nest += 1; + for c in g.children().map(Vec::as_slice).unwrap_or_default() { + self.node(c); + } + self.nest -= 1; + } + self.line("U"); + } + } + if self.body.len() > start { + self.name(n); + } + } + + /// `n`'s name, after it: an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id, + /// numbered (`_` and 20 digits, `_`) when another object has that id. + fn name(&mut self, n: &Node) { + let Some(name) = n.name.as_deref().filter(|s| !s.is_empty()) else { return }; + let base = vectorcraft_doc::xml_id::from_object_name(name); + let mut id = base.clone(); + let next = self.next.entry(base.clone()).or_insert(0); + while self.ids.contains(&id) { + *next += 1; + id = format!("{base}_{next:020}_"); + } + self.ids.insert(id.clone()); + let _ = writeln!(self.body, "%_/ArtDictionary :\n%_/XMLUID : {} ; (AI10_ArtUID) ,\n%_;\n%_", ps::bytes(id.as_bytes())); + } + + /// A container's members, the first one's outline cutting the others: its fills painted + /// behind them (cut to the region outside too), its strokes over them, not cut by it. + fn clip_contents(&mut self, children: &[Arc]) { + let Some((first, rest)) = children.split_first() else { return }; + // Nothing to clip by hides the clipped art. + let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return }; + let paint = first.clip_paint(); + let outer = self.clip.clone(); + let region = self.cut(&PathData::from_bezpath(&outline), rule); + self.clip = Some(region); + if let Some(fill) = &paint.fill { + self.node(fill); + } + for c in rest { + self.node(c); + } + self.clip = outer; + if let Some(stroke) = &paint.stroke { + self.node(stroke); + } + } + + /// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path. + fn cut(&self, path: &PathData, rule: FillRule) -> PathData { + match &self.clip { + Some(clip) => vectorcraft_pathops::boolean(path, rule, clip, FillRule::NonZero, BoolOp::Intersect), + None => vectorcraft_pathops::boolean(path, rule, path, rule, BoolOp::Intersect), + } + } + + // ---------- paths ---------- + + /// A path's fills and strokes: one object with one fill and a plain stroke over it where it + /// can be, else a group of an object for each (in paint order). + fn shape(&mut self, n: &Node, path: &PathData, rule: FillRule) { + if path.is_empty() { + return; + } + let items: Vec<&AppearanceItem> = n + .appearance + .items + .iter() + .filter(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && s.width.is_finite(), + }) + .collect(); + if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { + self.warn(TRANSPARENCY); + } + let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); + match items.as_slice() { + [] => self.path_object(path, rule, None, None), + [AppearanceItem::Fill(f)] if solid(&f.paint) => self.path_object(path, rule, Some(f), None), + [AppearanceItem::Stroke(s)] if direct_stroke(s) => self.path_object(path, rule, None, Some(s)), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if solid(&f.paint) && direct_stroke(s) => { + self.path_object(path, rule, Some(f), Some(s)) + } + [one] => self.item(path, rule, one), + items => { + self.line("u"); + for i in items { + self.item(path, rule, i); + } + self.line("U"); + } + } + } + + /// One fill or stroke of a path as an object of its own. + fn item(&mut self, path: &PathData, rule: FillRule, item: &AppearanceItem) { + match item { + AppearanceItem::Fill(f) => self.fill_object(path, rule, f), + AppearanceItem::Stroke(s) if direct_stroke(s) => self.path_object(path, rule, None, Some(s)), + AppearanceItem::Stroke(s) => { + self.warn(STROKES); + if self.brush_art(path, s) { + return; + } + let outline = stroke::outline_region(path, rule, s); + let fill = FillLayer { overprint: s.overprint, ..FillLayer::new(s.paint.clone()) }; + self.fill_object(&outline, FillRule::NonZero, &fill); + } + } + } + + /// A brushed stroke `st` of `path` as a group of its brush's art. False when it has no brush + /// the document knows (or brushes nest too deep). + fn brush_art(&mut self, path: &PathData, st: &StrokeLayer) -> bool { + if self.nest >= MAX_NEST { + return false; + } + let doc = self.doc; + let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc)); + let Some(b) = st.brush.as_deref().and_then(|name| brushes.iter().find(|b| b.name == name)) else { return false }; + let art = vectorcraft_brush::stroke_pieces(doc, b, &path.to_bezpath(), st); + let state = self.state; + self.nest += 1; + self.line("u"); + for piece in &art { + self.node(piece); + } + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + self.line("U"); + self.nest -= 1; + true + } + + /// A fill as an object of its own: a gradient as its average color, a pattern as its tiles + /// cut to the path. + fn fill_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer) { + match &f.paint { + Paint::Solid { .. } => self.path_object(path, rule, Some(f), None), + Paint::Gradient(g) => { + self.warn(GRADIENTS); + let flat = FillLayer { paint: Paint::solid(average(&g.gradient)), ..f.clone() }; + self.path_object(path, rule, Some(&flat), None); + } + Paint::Pattern { pattern, xf } => { + self.warn(PATTERNS); + let doc = self.doc; + let Some(def) = doc.pattern(pattern).filter(|_| self.nest < MAX_NEST) else { + let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() }; + return self.path_object(path, rule, Some(&flat), None); + }; + let tiles = def.instances_in(*xf, path.to_bezpath().bounding_box()); + let outer = self.clip.clone(); + let region = self.cut(path, rule); + self.clip = Some(region); + self.nest += 1; + let state = self.state; + self.line("u"); + for t in &tiles { + self.node(t); + } + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + self.line("U"); + self.nest -= 1; + self.clip = outer; + } + Paint::None => {} + } + } + + /// A path object painted with `fill` (a color) and `stroke` (a plain line of a color) over + /// it; several subpaths make a compound path. Where the art is cut to a clipping path, the + /// fill is the path's region cut to it and the stroke its outline cut to it, filled. + fn path_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>) { + if self.clip.is_none() { + return self.plain_object(path, rule, fill, stroke); + } + let both = fill.is_some() && stroke.is_some(); + if both { + self.line("u"); + } + if fill.is_some() || stroke.is_none() { + let region = self.cut(path, rule); + self.plain_object(®ion, FillRule::NonZero, fill, None); + } + if let Some(s) = stroke { + let outline = stroke::outline_region(path, rule, s); + let region = self.cut(&outline, FillRule::NonZero); + let fill = FillLayer { overprint: s.overprint, ..FillLayer::new(s.paint.clone()) }; + self.plain_object(®ion, FillRule::NonZero, Some(&fill), None); + } + if both { + self.line("U"); + } + } + + /// [`Self::path_object`] without cutting: the paint (`O`/`R` overprint, line style), `XR`, + /// each subpath's points and painting operator (`*u` … `*U` around several). + fn plain_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>) { + let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + if subpaths.is_empty() { + return; + } + if let Some(f) = fill { + self.color(&f.paint, false); + self.line(if f.overprint { "1 O" } else { "0 O" }); + } + if let Some(s) = stroke { + self.color(&s.paint, true); + self.line(if s.overprint { "1 R" } else { "0 R" }); + ai_ops::line_style(&mut self.body, s); + } + self.line(if rule == FillRule::EvenOdd { "1 XR" } else { "0 XR" }); + let op = match (fill.is_some(), stroke.is_some()) { + (true, true) => 'b', + (true, false) => 'f', + (false, true) => 's', + (false, false) => 'n', + }; + let several = subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in subpaths { + ai_ops::subpath(&mut self.body, self.to_art, sp); + let op = if sp.closed { op } else { op.to_ascii_uppercase() }; + self.body.push(op); + self.body.push('\n'); + } + if several { + self.line("*U"); + } + } + + // ---------- type ---------- + + /// Type `n` as a group of what Type › Create Outlines makes of it + /// ([`vectorcraft_effects::outline_text`]): each run's glyphs with their underline and + /// strikethrough, its color glyphs, and the object's own fills and strokes. + fn text(&mut self, n: &Node) { + self.warn(TYPE); + self.line("u"); + if let Some(outlined) = vectorcraft_effects::outline_text(n) { + let state = self.state; + for c in outlined.children().map(Vec::as_slice).unwrap_or_default() { + self.node(c); + } + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + } + self.line("U"); + } + + // ---------- color ---------- + + /// Set the fill (or with `stroke`, the stroke) color to solid paint `p`: a spot or global + /// swatch by its name, Registration, else the color itself. + fn color(&mut self, p: &Paint, stroke: bool) { + let Paint::Solid { color, swatch, tint } = p else { + return self.plain_color(Color::gray(1.0), stroke); + }; + if swatch.as_deref() == Some(REGISTRATION) { + let mut s = String::from("1 1 1 1 "); + s.push_str(&ps::bytes(REGISTRATION.as_bytes())); + s.push(' '); + ps::push_num(&mut s, f64::from(1.0 - unit(*tint))); + s.push_str(if stroke { " XS" } else { " Xs" }); + return self.line(&s); + } + let doc = self.doc; + if let Some(name) = swatch + && let Some(sw) = doc.swatch(name).filter(|s| s.global || s.spot) + && let Paint::Solid { color: full, swatch: None, .. } = sw.paint + { + let mut s = String::new(); + self.named(&mut s, name, full, *tint, sw.spot, stroke); + return self.body.push_str(&s); + } + self.plain_color(*color, stroke); + } + + /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB, and + /// Lab as RGB), with its CMYK equivalent. + fn plain_color(&mut self, color: Color, stroke: bool) { + let s = &mut self.body; + let op = |fill: &'static str, line: &'static str| if stroke { line } else { fill }; + match color { + // Gray is ink coverage; the format's gray is lightness. + Color::Gray { k } => { + ps::push_num(s, f64::from(1.0 - unit(k))); + let _ = writeln!(s, " {}", op("g", "G")); + } + Color::Cmyk { c, m, y, k } => { + ps::push_nums(s, &[c, m, y, k].map(|v| f64::from(unit(v)))); + let _ = writeln!(s, "{}", op("k", "K")); + } + Color::Rgb { .. } | Color::Lab { .. } => { + let cmyk = self.cms.to_cmyk(&color, self.cms.settings().intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v)))); + let _ = writeln!(s, "{}", op("Xa", "XA")); + } + } + } + + /// A spot (`spot`) or global process color `name` of full color `full` at `tint`, written to + /// `s`: its CMYK equivalent, its RGB or Lab values, the name, how much lighter than the full + /// color, and for any but a CMYK spot color (`x`) the model (0 CMYK, 1 RGB, 2 Lab) before + /// `Xx` (spot) or `Xk` (global process). + fn named(&self, s: &mut String, name: &str, full: Color, tint: f32, spot: bool, stroke: bool) { + let cmyk = self.cms.to_cmyk(&self.doc.linked_color(full, spot), self.cms.settings().intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + let model = match full { + Color::Rgb { r, g, b } => { + ps::push_nums(s, &[r, g, b].map(|v| f64::from(unit(v)))); + Some(1) + } + Color::Lab { l, a, b } => { + ps::push_nums(s, &[f64::from(l), f64::from(a), f64::from(b)]); + Some(2) + } + _ if spot => None, + _ => Some(0), + }; + s.push_str(&ps::bytes(name.as_bytes())); + s.push(' '); + ps::push_num(s, f64::from(1.0 - unit(tint))); + let op = match (model, spot) { + (None, _) => "x", + (Some(_), true) => "Xx", + (Some(_), false) => "Xk", + }; + if let Some(m) = model { + let _ = write!(s, " {m}"); + } + let op = if stroke { op.to_ascii_uppercase() } else { op.to_string() }; + let _ = writeln!(s, " {op}"); + } + + // ---------- swatches ---------- + + /// The swatches: `%AI5_BeginPalette`, `0 0 Pb`, each color swatch's color and `(name) Pc` + /// (the ungrouped ones first, then each color group's after `0 (name) count Pg`), `PB`, + /// `%AI5_EndPalette`. + pub(super) fn palette(&mut self, s: &mut String) { + s.push_str("%AI5_BeginPalette\n0 0 Pb\n"); + let doc = self.doc; + for sw in doc.swatches.iter() { + self.swatch(s, sw); + } + for g in doc.swatch_groups.iter() { + let colors: Vec<&Swatch> = g.swatches.iter().filter(|sw| writable(sw)).collect(); + let _ = writeln!(s, "0 {} {} Pg", ps::bytes(g.name.as_bytes()), colors.len()); + for sw in &g.swatches { + self.swatch(s, sw); + } + } + s.push_str("PB\n%AI5_EndPalette\n"); + } + + /// One swatch of the palette: a color swatch's color and `(name) Pc`; gradient and pattern + /// swatches are left out. + fn swatch(&mut self, s: &mut String, sw: &Swatch) { + if sw.name == REGISTRATION || matches!(sw.paint, Paint::None) { + return; + } + if !writable(sw) { + return self.warn(SWATCHES); + } + let Paint::Solid { color, swatch, .. } = &sw.paint else { return }; + if swatch.is_none() && (sw.global || sw.spot) { + self.named(s, &sw.name, *color, 1.0, sw.spot, false); + } else { + let body = std::mem::take(&mut self.body); + self.plain_color(*color, false); + s.push_str(&std::mem::replace(&mut self.body, body)); + } + let _ = writeln!(s, "{} Pc", ps::bytes(sw.name.as_bytes())); + } + + /// The spot color swatches, with their full colors' CMYK equivalents, for the header. + pub(super) fn spot_swatches(&self) -> Vec<(String, [f32; 4])> { + let intent = self.cms.settings().intent; + self.doc + .swatches_iter() + .filter(|sw| sw.spot) + .filter_map(|sw| match sw.paint { + Paint::Solid { color, swatch: None, .. } => { + Some((sw.name.clone(), self.cms.to_cmyk(&self.doc.linked_color(color, true), intent).map(unit))) + } + _ => None, + }) + .collect() + } +} + +/// Is `sw` a color swatch the palette writes? +fn writable(sw: &Swatch) -> bool { + matches!(sw.paint, Paint::Solid { .. }) && sw.name != REGISTRATION +} + +/// Does a plain line of one color draw `s` (the line style operators can write it)? +fn direct_stroke(s: &StrokeLayer) -> bool { + matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s) +} + +/// The image `bytes` decoded, when its header gives at most [`MAX_AVERAGED_PIXELS`] pixels; the +/// decoder may allocate at most 8 bytes a pixel. +fn decode_bounded(bytes: &[u8]) -> Option { + let reader = || -> image::ImageResult>> { + let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_AVERAGED_PIXELS * 8); + r.limits(limits); + Ok(r) + }; + let (w, h) = reader().and_then(|r| r.into_dimensions()).ok()?; + if u64::from(w) * u64::from(h) > MAX_AVERAGED_PIXELS { + return None; + } + reader().and_then(|r| r.decode()).ok() +} + +/// The average color of the image `bytes` (scaled down first), transparent pixels over white; +/// mid gray when it can't be decoded or has more than [`MAX_AVERAGED_PIXELS`] pixels. +fn image_average(bytes: Option<&[u8]>) -> Color { + let Some(img) = bytes.and_then(decode_bounded) else { return Color::gray(0.5) }; + let img = if img.width() > AVERAGE_SIDE || img.height() > AVERAGE_SIDE { img.thumbnail(AVERAGE_SIDE, AVERAGE_SIDE) } else { img }; + let rgba = img.to_rgba8(); + let mut sum = [0u64; 3]; + let mut n = 0u64; + for px in rgba.pixels() { + let [r, g, b, a] = px.0; + let over = |c: u8| (u64::from(c) * u64::from(a) + 255 * (255 - u64::from(a))) / 255; + sum[0] += over(r); + sum[1] += over(g); + sum[2] += over(b); + n += 1; + } + if n == 0 { + return Color::gray(0.5); + } + let c = |v: u64| (v as f32 / n as f32 / 255.0).clamp(0.0, 1.0); + Color::rgb(c(sum[0]), c(sum[1]), c(sum[2])) +} diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs new file mode 100644 index 0000000000..cfa3928eca --- /dev/null +++ b/crates/eps/src/ai_ops.rs @@ -0,0 +1,97 @@ +//! Operators the legacy `.ai` writer ([`crate::legacy_ai`]) and the editing data writer +//! ([`crate::ai_editing`]) both write: path points, guides and line style (Adobe Illustrator File +//! Format Specification, version 7.0, §5.3, §5.4 and §6), and the colors they write in place of +//! the paint they can't hold. + +use std::fmt::Write; + +use vectorcraft_color::{Color, Gradient}; +use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer}; +use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, SubPath}; + +use crate::ps; + +/// One subpath's points, taken into art space by `xf`: `m`, then a line or curve to each point +/// (lower case: the point is smooth, upper case: a corner, §5.3.2), and for a closed one the +/// segment back to the start, which says whether the start is smooth or a corner (as the +/// specification's examples close paths: the start point again, then the painting operator). +pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) { + let Some(first) = sp.anchors.first() else { return }; + let pt = |s: &mut String, p: Point| { + let p = xf * p; + ps::push_nums(s, &[p.x, p.y]); + }; + pt(s, first.p); + s.push_str("m\n"); + let segment = |s: &mut String, a: &Anchor, b: &Anchor| { + let straight = a.h_out == a.p && b.h_in == b.p; + let smooth = b.kind == AnchorKind::Smooth; + if straight { + pt(s, b.p); + s.push_str(if smooth { "l\n" } else { "L\n" }); + } else { + pt(s, a.h_out); + pt(s, b.h_in); + pt(s, b.p); + s.push_str(if smooth { "c\n" } else { "C\n" }); + } + }; + for pair in sp.anchors.windows(2) { + if let [a, b] = pair { + segment(s, a, b); + } + } + if sp.closed + && sp.anchors.len() > 1 + && let Some(last) = sp.anchors.last() + { + segment(s, last, first); + } +} + +/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`; with `closing`, a closed +/// subpath ends `(n) *` (the painting operator that closes it first). +pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, closing: bool) { + for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { + s.push_str("(N) *\n"); + subpath(s, xf, sp); + s.push_str(if closing && sp.closed { "(n) *\n" } else { "(N) *\n" }); + } +} + +pub(crate) fn unit(v: f32) -> f32 { + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } +} + +/// The average colour of a gradient's stops (in RGB). +pub(crate) fn average(g: &Gradient) -> Color { + let n = g.stops.len().max(1) as f32; + let sum = g.stops.iter().map(|s| s.color.to_rgb()).fold([0.0f32; 3], |a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]]); + Color::rgb(unit(sum[0] / n), unit(sum[1] / n), unit(sum[2] / n)) +} + +/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. +pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) { + let cap = match st.cap { + LineCap::Butt => 0, + LineCap::Round => 1, + LineCap::Square => 2, + }; + let join = match st.join { + LineJoin::Miter => 0, + LineJoin::Round => 1, + LineJoin::Bevel => 2, + }; + ps::push_num(s, st.width); + let _ = write!(s, " w {cap} J {join} j "); + ps::push_num(s, if st.miter_limit.is_finite() { st.miter_limit.max(1.0) } else { 10.0 }); + s.push_str(" M ["); + let dash = st.dash.as_ref().filter(|d| d.is_dashed()); + if let Some(d) = dash { + ps::push_nums(s, &d.pattern); + s.pop(); + } + s.push_str("] "); + ps::push_num(s, dash.map_or(0.0, |d| d.offset)); + s.push_str(" d\n"); +} diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index fc7d6e9d9c..9fd1b86322 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -64,13 +64,13 @@ use std::sync::Arc; use vectorcraft_color::cms::Cms; use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, Paint}; use vectorcraft_doc::{ - AppearanceItem, AreaOptions, CharPosition, CharStyle, Document, FillLayer, ImageBlob, Justify, LAYER_COLORS, LayerColor, LineCap, LineJoin, Node, - NodeKind, ParaDirection, ParaStyle, PathEffect, StrokeLayer, TextKind, TextObject, + AppearanceItem, AreaOptions, CharPosition, CharStyle, Document, FillLayer, ImageBlob, Justify, LAYER_COLORS, LayerColor, Node, NodeKind, + ParaDirection, ParaStyle, PathEffect, StrokeLayer, TextKind, TextObject, }; use vectorcraft_effects::stroke; -use vectorcraft_geom::{Affine, AnchorKind, BezPath, FillRule, PathData, Point, Rect, Shape, SubPath, Vec2}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, SubPath, Vec2}; -use crate::{latin, ps}; +use crate::{ai_ops, latin, ps}; mod encoding; mod prolog; diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index b67296e72a..21903cac04 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -60,9 +60,7 @@ pub(super) enum Ink { }, } -pub(super) fn unit(v: f32) -> f32 { - if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } -} +pub(super) use crate::ai_ops::{average, unit}; /// Can `a` be drawn through (a finite, non-flat map)? pub(super) fn invertible(a: Affine) -> bool { @@ -172,10 +170,3 @@ pub(super) fn direct_fill(p: &Paint) -> bool { pub(super) fn direct_stroke(s: &StrokeLayer) -> bool { matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s) } - -/// The average colour of a gradient's stops (in RGB). -pub(super) fn average(g: &Gradient) -> Color { - let n = g.stops.len().max(1) as f32; - let sum = g.stops.iter().map(|s| s.color.to_rgb()).fold([0.0f32; 3], |a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]]); - Color::rgb(unit(sum[0] / n), unit(sum[1] / n), unit(sum[2] / n)) -} diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 31caf715f0..152df7d1e4 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -357,13 +357,9 @@ impl<'a> Writer<'a> { self.line(if sp.closed { "h\nW\nn" } else { "H\nW\nN" }); } - /// A guide (§6): `(N) *`, its path, `(N) *`. + /// A guide ([`ai_ops::guide`]). fn guide(&mut self, path: &PathData) { - for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { - self.line("(N) *"); - self.subpath(sp); - self.line("(N) *"); - } + ai_ops::guide(&mut self.body, self.to_art, path, false); } /// A path's fills and strokes: one object with one fill and a plain stroke over it where it @@ -522,71 +518,14 @@ impl<'a> Writer<'a> { self.line(if rule == FillRule::EvenOdd { "1 XR" } else { "0 XR" }); } - /// One subpath's points, in art space: `m`, then a line or curve to each point (lower case: the - /// point is smooth, upper case: a corner, §5.3.2), and for a closed one the segment back to the - /// start, which says whether the start is smooth or a corner (as the specification's examples - /// close paths: the start point again, then the painting operator). + /// One subpath's points, in art space ([`ai_ops::subpath`]). fn subpath(&mut self, sp: &SubPath) { - let Some(first) = sp.anchors.first() else { return }; - let xf = self.to_art; - let s = &mut self.body; - let pt = |s: &mut String, p: Point| { - let p = xf * p; - ps::push_nums(s, &[p.x, p.y]); - }; - pt(s, first.p); - s.push_str("m\n"); - let segment = |s: &mut String, a: &vectorcraft_geom::Anchor, b: &vectorcraft_geom::Anchor| { - let straight = a.h_out == a.p && b.h_in == b.p; - let smooth = b.kind == AnchorKind::Smooth; - if straight { - pt(s, b.p); - s.push_str(if smooth { "l\n" } else { "L\n" }); - } else { - pt(s, a.h_out); - pt(s, b.h_in); - pt(s, b.p); - s.push_str(if smooth { "c\n" } else { "C\n" }); - } - }; - for pair in sp.anchors.windows(2) { - if let [a, b] = pair { - segment(s, a, b); - } - } - if sp.closed - && sp.anchors.len() > 1 - && let Some(last) = sp.anchors.last() - { - segment(s, last, first); - } + ai_ops::subpath(&mut self.body, self.to_art, sp); } - /// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. + /// The stroke's width, cap, join, miter limit and dashes ([`ai_ops::line_style`]). fn line_style(&mut self, st: &StrokeLayer) { - let cap = match st.cap { - LineCap::Butt => 0, - LineCap::Round => 1, - LineCap::Square => 2, - }; - let join = match st.join { - LineJoin::Miter => 0, - LineJoin::Round => 1, - LineJoin::Bevel => 2, - }; - let s = &mut self.body; - ps::push_num(s, st.width); - let _ = write!(s, " w {cap} J {join} j "); - ps::push_num(s, if st.miter_limit.is_finite() { st.miter_limit.max(1.0) } else { 10.0 }); - s.push_str(" M ["); - let dash = st.dash.as_ref().filter(|d| d.is_dashed()); - if let Some(d) = dash { - ps::push_nums(s, &d.pattern); - s.pop(); - } - s.push_str("] "); - ps::push_num(s, dash.map_or(0.0, |d| d.offset)); - s.push_str(" d\n"); + ai_ops::line_style(&mut self.body, st); } // ---------- colour ---------- diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 59926fe188..3747376e80 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -28,7 +28,12 @@ //! - `import`: the PostScript interpreter. //! - `print`: print jobs as PostScript files ([`print()`]), their pages drawn by `scene`. //! - `legacy_ai`: legacy `.ai` files of version 7 ([`export_legacy_ai`]), with their layers and groups. +//! - `ai_editing`: the editing copy of the art a PDF-compatible `.ai` file carries +//! ([`export_ai_editing`], [`ai_private_data`]). +//! - `ai_ops`: the path and line style operators those two write. +mod ai_editing; +mod ai_ops; mod import; mod latin; mod legacy_ai; @@ -37,6 +42,7 @@ mod ps; mod scene; mod tiff; +pub use ai_editing::{AiEditingOptions, AiEditingOutput, CREATOR_VERSION, export_ai_editing, private_data as ai_private_data}; pub use import::{Imported, POSTSCRIPT_ERRORS, ai_alone, family_style, import, import_trusting, import_with, is_loss, layered_ai, page}; pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai}; pub use print::{PrintJob, PrintPage, print}; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 95a0260c6d..7ca44a4fd4 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -17,7 +17,8 @@ //! printer's marks around it (the media box), drawn in Registration. [`PdfSettings`] is the Save PDF //! dialog's model (standard, compatibility, General, Compression, Marks and Bleeds, Output, //! Advanced, Security); options the writer doesn't apply yet come back as warnings. With Preserve -//! Editing the native document rides along as an embedded file ([`editing()`]). Each page can +//! Editing the native document rides along as an embedded file ([`editing()`]), and the first +//! page can carry a `.ai` file's editing copy of the art ([`PrivateData`]). Each page can //! carry a thumbnail ([`Thumbnail`], drawn by the caller), and Fast Web View writes a linearised //! file (still linearised when encrypted). A PDF 1.3 file ([`PdfSettings::pdf13`]) must be flat: //! the app flattens the document first, and the writer refuses transparency that is left. @@ -63,6 +64,7 @@ mod output; mod pages; mod patch; mod pdfx; +mod piece_info; mod post; mod presets; mod print; @@ -79,6 +81,7 @@ pub use import::{ import, import_with_report, is_glyph_outlines, is_outlines_note, }; pub use pages::{PageInfo, PdfInfo, has_illustrator_data, illustrator_data, info, is_postscript}; +pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; pub use presets::*; pub use print::*; @@ -102,6 +105,8 @@ pub struct PdfOptions { pub modified: Option, /// The native document (`.vectorcraft` bytes) Preserve Editing embeds. pub native: Option>, + /// The editing copy of the art for the first page's `PieceInfo`, as a `.ai` file carries it. + pub private_data: Option, /// The pages drawn small, in page order: what Embed Page Thumbnails embeds (the writer /// doesn't draw; [`page_areas`] says what each page shows). pub thumbnails: Vec, diff --git a/crates/pdf/src/piece_info.rs b/crates/pdf/src/piece_info.rs new file mode 100644 index 0000000000..c6e457ef39 --- /dev/null +++ b/crates/pdf/src/piece_info.rs @@ -0,0 +1,126 @@ +//! An editor's private data on the first page: a page-piece dictionary (ISO 32000-1 §14.5, +//! `PieceInfo`) holding the editing copy of the art that `.ai` files carry, laid out as in the +//! `.ai` files users sent, the form [`crate::illustrator_data`] reads. +//! +//! - The page dictionary gets `/PieceInfo << /Illustrator n 0 R >>` and its own `/LastModified` +//! (which §14.5 requires with `PieceInfo`). +//! - Object `n` is the data dictionary: `<< /LastModified (D:…) /Private m 0 R >>`. +//! - Object `m` holds `AIMetaData` (a stream of the data's header comments), `AIPrivateData1` … +//! `AIPrivateDataN` (the data in streams of [`PRIVATE_CHUNK`] bytes, the last one shorter), +//! `ContainerVersion`, `CreatorVersion`, `NumBlock` (N), `RoundtripStreamType` and +//! `RoundtripVersion`. Every stream has a `/Length` and no filter: the data comes compressed. + +use std::fmt::Write as _; + +use crate::PdfError; +use crate::linearize::{self, Parsed}; +use crate::patch::Patch; + +/// Bytes in each private data stream but the last. +pub const PRIVATE_CHUNK: usize = 1 << 16; + +/// The `PieceInfo` key the data dictionary is under. +const OWNER: &str = "Illustrator"; // brand-ok: the key the files use + +/// The private data a page-piece dictionary carries (see the module documentation). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PrivateData { + /// The data, as its streams hold it joined. + pub data: Vec, + /// What the `AIMetaData` stream holds. + pub metadata: Vec, + pub container_version: u32, + pub creator_version: u32, + pub roundtrip_version: u32, + pub roundtrip_stream_type: u32, +} + +/// `pdf` with `p` in its first page's `PieceInfo`, dated `modified` (Unix seconds, UTC). +pub(crate) fn add(pdf: Vec, p: &PrivateData, modified: i64) -> Result, PdfError> { + let failed = |why: &str| PdfError::Write(format!("can't add the editing data for other apps: {why}")); + let Parsed { xref, pages, .. } = linearize::parse(&pdf).map_err(failed)?; + let first = *pages.first().ok_or_else(|| failed("a page can't be read"))?; + let (dict, _) = xref.dict(&pdf, first).ok_or_else(|| failed("a page can't be read"))?; + let mut patch = Patch::new(&xref); + let metadata = patch.add_object(stream(&p.metadata)); + let blocks: Vec = p.data.chunks(PRIVATE_CHUNK).map(|c| patch.add_object(stream(c))).collect(); + let mut private = format!("<< /AIMetaData {metadata} 0 R"); + for (i, n) in blocks.iter().enumerate() { + let _ = write!(private, " /AIPrivateData{} {n} 0 R", i + 1); + } + let _ = write!( + private, + " /ContainerVersion {} /CreatorVersion {} /NumBlock {} /RoundtripStreamType {} /RoundtripVersion {} >>", + p.container_version, + p.creator_version, + blocks.len(), + p.roundtrip_stream_type, + p.roundtrip_version + ); + let private = patch.add_object(private.into_bytes()); + let date = pdf_date(modified); + let owner = patch.add_object(format!("<< /LastModified {date} /Private {private} 0 R >>").into_bytes()); + patch.replace(dict, dict, format!("/PieceInfo << /{OWNER} {owner} 0 R >> /LastModified {date} ").into_bytes()); + patch.apply(&pdf, &xref) +} + +/// A stream object of `bytes`, not filtered. +fn stream(bytes: &[u8]) -> Vec { + let mut s = format!("<< /Length {} >>\nstream\n", bytes.len()).into_bytes(); + s.extend_from_slice(bytes); + s.extend_from_slice(b"\nendstream"); + s +} + +/// `at` (Unix seconds) as a PDF date string in UTC (ISO 32000-1 §7.9.4). +fn pdf_date(at: i64) -> String { + let [y, mo, d, h, mi, s] = vectorcraft_doc::metadata::civil(at); + format!("(D:{y:04}{mo:02}{d:02}{h:02}{mi:02}{s:02}Z)") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{PdfOptions, export}; + use vectorcraft_doc::Document; + + fn data(len: usize) -> PrivateData { + PrivateData { + data: (0..len).map(|i| (i % 251) as u8).collect(), + metadata: b"%!PS-Adobe-3.0\n%%EndComments\n".to_vec(), + container_version: 12, + creator_version: 30, + roundtrip_version: 24, + roundtrip_stream_type: 2, + } + } + + #[test] + fn the_first_page_carries_the_data_in_streams_of_64_kib() { + let doc = Document::new(200.0, 100.0); + let p = data(PRIVATE_CHUNK * 2 + 10); + let opts = PdfOptions { private_data: Some(p.clone()), ..PdfOptions::uncompressed() }; + let pdf = export(&doc, &opts).unwrap(); + assert_eq!(crate::illustrator_data(&pdf, None).as_deref(), Some(&p.data[..])); + let text = String::from_utf8_lossy(&pdf); + for key in ["/AIPrivateData1 ", "/AIPrivateData2 ", "/AIPrivateData3 ", "/NumBlock 3 ", "/ContainerVersion 12 ", "/CreatorVersion 30 "] { + assert!(text.contains(key), "{key}"); + } + assert!(!text.contains("/AIPrivateData4")); + assert_eq!(text.matches("/LastModified (D:").count(), 2, "the page's and the data dictionary's"); + assert!(text.contains(&format!("<< /Length {PRIVATE_CHUNK} >>")) && text.contains("<< /Length 10 >>")); + } + + #[test] + fn without_the_data_the_page_has_no_piece_info() { + let pdf = export(&Document::new(200.0, 100.0), &PdfOptions::uncompressed()).unwrap(); + assert!(!String::from_utf8_lossy(&pdf).contains("/PieceInfo")); + assert_eq!(crate::illustrator_data(&pdf, None), None); + } + + #[test] + fn dates_are_in_utc() { + assert_eq!(pdf_date(0), "(D:19700101000000Z)"); + assert_eq!(pdf_date(1_793_000_000), "(D:20261026073320Z)"); + } +} diff --git a/crates/pdf/src/post.rs b/crates/pdf/src/post.rs index eda3b9a5a6..e735d079fe 100644 --- a/crates/pdf/src/post.rs +++ b/crates/pdf/src/post.rs @@ -1,5 +1,6 @@ //! What the export does to the file once it is written, in this order: the pages' thumbnails -//! (General › Embed page thumbnails), the seal of the editing data, fast web view (a linearised +//! (General › Embed page thumbnails), a `.ai` file's editing copy of the art +//! ([`crate::PrivateData`]), the seal of the editing data, fast web view (a linearised //! file, [`crate::linearize`]) and encryption ([`crate::encrypt`]), which a linearised file goes //! through between its two steps so that it stays linearised. Also here: what makes a file say it //! is PDF 1.3 ([`declare_pdf13`]), for PDF 1.3 and PDF/X-1a and PDF/X-3 files, the file's @@ -214,6 +215,13 @@ pub(crate) fn finish(pdf: Vec, opts: &PdfOptions, editing: bool, warnings: & } (false, _) => pdf, }; + let pdf = match &opts.private_data { + Some(p) => { + let at = opts.modified.or(opts.created).or_else(vectorcraft_doc::metadata::output_time).unwrap_or(0); + crate::piece_info::add(pdf, p, at)? + } + None => pdf, + }; let pdf = if editing { crate::editing::seal(pdf)? } else { pdf }; if !set.fast_web_view { return crate::encrypt::protect(pdf, set); diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index b320897dee..d4d4ca577e 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -100,6 +100,7 @@ fn label(o: &FormatOption) -> String { "embedProfiles" => tl!("Embed ICC Profiles").into(), "pdfCompatible" => tl!("Create PDF-Compatible File").into(), "compress" => tl!("Use Compression").into(), + "editingData" => tl!("Include Editing Data for Other Apps").into(), _ => form::humanize(o.name), } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 1f5588aea4..0f504eafdf 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3402,6 +3402,7 @@ font-technology Variable Променливи Use Artboards Използване на работните области Use Black Point Compensation Използване на компенсация на черната точка Use Compression Използване на компресия + Include Editing Data for Other Apps Включване на данни за редактиране за други приложения Use document bleed settings Използване на настройките за изтичане на документа Use Even-Odd Fill Rule Използване на правило за запълване четно-нечетно Use Japanese Crop Marks Използване на японски марки за изрязване diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ef160b85a0..0292db6cd5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3561,6 +3561,7 @@ theme Appearance Motiv Type Object Selection by Path Only Výběr textového objektu pouze podle cesty UI Scaling Měřítko rozhraní Use Compression Použít kompresi + Include Editing Data for Other Apps Zahrnout data pro úpravy v jiných aplikacích Use Japanese Crop Marks Použít japonské ořezové značky Use Low Resolution Proxy for Linked EPS Pro propojené EPS použít zástupce v nízkém rozlišení Use Precise Cursors Používat přesné kurzory diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4e4ca02755..7180aa9168 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3310,6 +3310,7 @@ theme Appearance Udseende Type Object Selection by Path Only Markering af tekstobjekter udelukkende via kurve UI Scaling UI-skalering Use Compression Anvend komprimering + Include Editing Data for Other Apps Medtag redigeringsdata til andre apps Use Japanese Crop Marks Anvend japanske beskæringsmærker Use Low Resolution Proxy for Linked EPS Anvend proxy med lav opløsning til koblede EPS-filer Use Precise Cursors Anvend præcise markører diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7f1c43e6cd..2a2e2cb678 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3423,6 +3423,7 @@ effect Points Punkte Use Artboards Zeichenflächen verwenden Use Black Point Compensation Tiefenkompensierung verwenden Use Compression Komprimierung verwenden + Include Editing Data for Other Apps Bearbeitungsdaten für andere Apps einschließen Use document bleed settings Anschnitteinstellungen des Dokuments verwenden Use Even-Odd Fill Rule Gerade-Ungerade-Füllregel verwenden Use Japanese Crop Marks Japanische Schnittmarken verwenden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 26de8c133a..0087e072c5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3753,6 +3753,7 @@ theme Appearance Εμφάνιση Use Artboards Χρήση πινάκων σχεδίασης Use Black Point Compensation Χρήση αντιστάθμισης μαύρου σημείου Use Compression Χρήση συμπίεσης + Include Editing Data for Other Apps Συμπερίληψη δεδομένων επεξεργασίας για άλλες εφαρμογές Use document bleed settings Χρήση ρυθμίσεων ξακρίσματος εγγράφου Use Even-Odd Fill Rule Χρήση κανόνα γεμίσματος άρτιου-περιττού Use Japanese Crop Marks Χρήση ιαπωνικών σημαδιών περικοπής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f3ecd85fe8..36aabd4347 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3470,6 +3470,7 @@ font-technology Variable Variables Use Artboards Usar mesas de trabajo Use Black Point Compensation Usar compensación de punto negro Use Compression Usar compresión + Include Editing Data for Other Apps Incluir datos de edición para otras aplicaciones Use document bleed settings Usar los ajustes de sangrado del documento Use Even-Odd Fill Rule Usar regla de relleno par-impar Use Japanese Crop Marks Usar marcas de corte japonesas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 917393059e..140610b20c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3487,6 +3487,7 @@ theme Appearance Ulkoasu Type Object Selection by Path Only Tekstiobjektin valinta vain polusta UI Scaling Käyttöliittymän skaalaus Use Compression Käytä pakkausta + Include Editing Data for Other Apps Sisällytä muokkaustiedot muille sovelluksille Use Japanese Crop Marks Käytä japanilaisia rajausmerkkejä Use Low Resolution Proxy for Linked EPS Käytä matalan tarkkuuden välityskuvaa linkitetyille EPS-tiedostoille Use Precise Cursors Käytä tarkkoja kohdistimia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e6b8a9459c..3c76003280 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3467,6 +3467,7 @@ font-technology Variable Variables Use Artboards Utiliser les plans de travail Use Black Point Compensation Utiliser la compensation du point noir Use Compression Utiliser la compression + Include Editing Data for Other Apps Inclure les données de modification pour d’autres applications Use document bleed settings Utiliser les paramètres de fond perdu du document Use Even-Odd Fill Rule Utiliser la règle de remplissage pair-impair Use Japanese Crop Marks Utiliser les traits de coupe japonais diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 84b1cc37b5..ca0e1c7cb1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4180,6 +4180,7 @@ mark-style Japanese Japán Use Artboards Rajztáblák használata Use Black Point Compensation Feketepont-kompenzáció használata Use Compression Tömörítés használata + Include Editing Data for Other Apps Szerkesztési adatok hozzáadása más alkalmazásokhoz Use Default Alapértelmezett használata Use document bleed settings A dokumentum kifutóbeállításainak használata Use Even-Odd Fill Rule Páros-páratlan kitöltési szabály diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4d813f3baa..5e84209fd1 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3310,6 +3310,7 @@ theme Appearance Tampilan Type Object Selection by Path Only Pemilihan objek teks hanya berdasarkan jalur UI Scaling Penskalaan UI Use Compression Gunakan kompresi + Include Editing Data for Other Apps Sertakan data penyuntingan untuk aplikasi lain Use Japanese Crop Marks Gunakan tanda potong Jepang Use Low Resolution Proxy for Linked EPS Gunakan proksi resolusi rendah untuk EPS tertaut Use Precise Cursors Gunakan kursor presisi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8a065733e2..cad5953268 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3505,6 +3505,7 @@ mark-style Japanese Giapponese Use Artboards Usa tavole da disegno Use Black Point Compensation Usa compensazione punto nero Use Compression Usa compressione + Include Editing Data for Other Apps Includi dati di modifica per altre app Use document bleed settings Usa impostazioni abbondanza del documento Use Even-Odd Fill Rule Usa regola di riempimento pari-dispari Use Japanese Crop Marks Usa segni di ritaglio giapponesi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6e6ed4a706..f29474c6d3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3153,6 +3153,7 @@ mark-style Japanese 日本式 Use Artboards アートボードを使用 Use Black Point Compensation ブラックポイントの補正を使用 Use Compression 圧縮を使用 + Include Editing Data for Other Apps 他のアプリ用の編集データを含める Use Even-Odd Fill Rule 奇偶規則を使用 Use Japanese Crop Marks 日本式トンボを使用 Use Low Resolution Proxy for Linked EPS リンク EPS に低解像度プロキシを使用 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d85bbf2f1d..70fb410122 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3118,6 +3118,7 @@ theme Appearance იერსახე Type Object Selection by Path Only ტექსტური ობიექტის მონიშვნა მხოლოდ ტრაექტორიით UI Scaling ინტერფეისის მასშტაბირება Use Compression შეკუმშვის გამოყენება + Include Editing Data for Other Apps სხვა აპებისთვის რედაქტირების მონაცემების ჩართვა Use Japanese Crop Marks იაპონური ჭრის ნიშნების გამოყენება Use Low Resolution Proxy for Linked EPS დაბალი გარჩევადობის პროქსის გამოყენება დაკავშირებული EPS-ისთვის Use Precise Cursors ზუსტი კურსორების გამოყენება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a6bccad0bf..58449d4de7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3147,6 +3147,7 @@ mark-style Japanese 일본식 Use Artboards 아트보드 사용 Use Black Point Compensation 블랙 포인트 보정 사용 Use Compression 압축 사용 + Include Editing Data for Other Apps 다른 앱용 편집 데이터 포함 Use Even-Odd Fill Rule 짝홀 칠 규칙 사용 Use Japanese Crop Marks 일본식 자르기 표시 사용 Use Low Resolution Proxy for Linked EPS 연결된 EPS에 저해상도 프록시 사용 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d53f44c377..40051c6e1a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3324,6 +3324,7 @@ theme Appearance Vormgeving Type Object Selection by Path Only Tekstobjecten alleen via hun pad selecteren UI Scaling UI-schaling Use Compression Compressie gebruiken + Include Editing Data for Other Apps Bewerkingsgegevens voor andere apps opnemen Use Japanese Crop Marks Japanse aftekenlijnen gebruiken Use Low Resolution Proxy for Linked EPS Proxy met lage resolutie gebruiken voor gekoppelde EPS Use Precise Cursors Nauwkeurige cursors gebruiken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e1ccecb25e..78f20c0a3d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3423,6 +3423,7 @@ theme Appearance Wygląd Type Object Selection by Path Only Zaznaczanie obiektów tekstowych tylko po ścieżce UI Scaling Skalowanie interfejsu Use Compression Używaj kompresji + Include Editing Data for Other Apps Dołącz dane edycji dla innych aplikacji Use Japanese Crop Marks Używaj japońskich znaczników przycięcia Use Low Resolution Proxy for Linked EPS Używaj podglądu niskiej rozdzielczości dla połączonych EPS Use Precise Cursors Używaj precyzyjnych kursorów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d4fc9c9a78..6f0b780950 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2835,6 +2835,7 @@ Use Artboards Usar Mesas de Trabalho Use Black Point Compensation Usar Compensação de Ponto Preto Use Compression Usar Compressão + Include Editing Data for Other Apps Incluir Dados de Edição para Outros Aplicativos Use Even-Odd Fill Rule Usar Regra de Preenchimento Par-Ímpar Use Japanese Crop Marks Usar Marcas de Corte Japonesas Use Low Resolution Proxy for Linked EPS Usar Proxy de Baixa Resolução para EPS Vinculado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 972f4a2b2f..5dc2ab0ad7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3501,6 +3501,7 @@ mark-style Japanese Японский Use Artboards Использовать монтажные области Use Black Point Compensation Использовать компенсацию чёрной точки Use Compression Использовать сжатие + Include Editing Data for Other Apps Включать данные редактирования для других приложений Use document bleed settings Использовать параметры вылета документа Use Even-Odd Fill Rule Использовать правило заливки «чёт-нечет» Use Japanese Crop Marks Использовать японские метки обрезки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b755101a8e..88cfae71ac 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3402,6 +3402,7 @@ font-technology Variable Variabla Use Artboards Använd ritytor Use Black Point Compensation Använd svartpunktskompensering Use Compression Använd komprimering + Include Editing Data for Other Apps Inkludera redigeringsdata för andra appar Use document bleed settings Använd dokumentets inställningar för utfall Use Even-Odd Fill Rule Använd fyllningsregeln jämn-udda Use Japanese Crop Marks Använd japanska beskärningsmärken diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cc84fbb5d2..d541483eab 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3295,6 +3295,7 @@ font-technology Variable Değişken Use Artboards Çalışma Yüzeylerini Kullan Use Black Point Compensation Siyah Nokta Telafisi Kullan Use Compression Sıkıştırmayı Kullan + Include Editing Data for Other Apps Diğer Uygulamalar İçin Düzenleme Verilerini Ekle Use document bleed settings Belge taşma payı ayarlarını kullan Use Even-Odd Fill Rule Çift-Tek Doldurma Kuralını Kullan Use Japanese Crop Marks Japonca Kırpma İşaretlerini Kullan diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 32f3ba05ce..f7d9bc25bd 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3498,6 +3498,7 @@ effect Points Точки Use Artboards Використовувати монтажні області Use Black Point Compensation Використовувати компенсацію чорної точки Use Compression Використовувати стиск + Include Editing Data for Other Apps Включати дані редагування для інших програм Use document bleed settings Використовувати параметри вильоту документа Use Even-Odd Fill Rule Використовувати правило заливки «парне–непарне» Use Japanese Crop Marks Використовувати японські мітки обрізання diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 01be6b1e72..48af3294e9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3870,6 +3870,7 @@ mark-style Japanese Kiểu Nhật Use Artboards Dùng bảng vẽ Use Black Point Compensation Dùng bù điểm đen Use Compression Dùng nén + Include Editing Data for Other Apps Bao gồm dữ liệu chỉnh sửa cho ứng dụng khác Use document bleed settings Dùng cài đặt bleed của tài liệu Use Even-Odd Fill Rule Dùng quy tắc tô chẵn-lẻ Use Japanese Crop Marks Dùng dấu cắt kiểu Nhật diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 599fe0e806..7491686c7b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3342,6 +3342,7 @@ font-script Japanese 汉字 Use Artboards 使用画板 Use Black Point Compensation 使用黑场补偿 Use Compression 使用压缩 + Include Editing Data for Other Apps 包含供其他应用使用的编辑数据 Use document bleed settings 使用文档的出血设置 Use Even-Odd Fill Rule 使用奇偶填色规则 Use Japanese Crop Marks 使用日式裁切标记 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8f19370adf..6197799daa 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4286,6 +4286,7 @@ font-script Japanese 漢字 Use Artboards 使用工作區域 Use Black Point Compensation 使用黑點補償 Use Compression 使用壓縮 + Include Editing Data for Other Apps 包含供其他應用程式使用的編輯資料 Use document bleed settings 使用文件的出血設定 Use Even-Odd Fill Rule 使用奇偶填色規則 Use Japanese Crop Marks 使用日式裁切標記 From b8279befba85bb281597a4eba5fd37c7a0cbe80e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 17:45:42 -0700 Subject: [PATCH 004/674] Save As .ai: write the editing data's header, palette and layers in the full layout The editing data now has the layout of the .ai files it was learned from: - Lines end in CR LF. Line breaks inside strings stay escaped. - The header adds %%For (the document's author), %%Canvassize 16383, %AI7_ImageSettings, %AI5_ArtFlags, %AI5_TargetResolution, %AI5_OpenViewLayers (a digit for each layer, 7 shown and 6 hidden) and %AI7_GridSettings (the document's grid spacing and subdivisions), in the order those files have them. - The setup starts with 0 Bn (no gradient definitions). - The palette starts with the Registration swatch: Xs in a CMYK document, Xz with black's CMYK equivalent in an RGB one. Reading the file back does not add a swatch for it. - Each layer and sublayer carries its name as an XML id in an /ArtDictionary after Ln. An object named like a layer gets a numbered id. - The LastModified dates of the PieceInfo dictionaries end in +00'00'. --- crates/eps/src/ai_editing.rs | 65 +++++++++++++++++++----- crates/eps/src/ai_editing/tests.rs | 79 +++++++++++++++++++++++++---- crates/eps/src/ai_editing/writer.rs | 34 +++++++++++-- crates/pdf/src/piece_info.rs | 9 ++-- 4 files changed, 153 insertions(+), 34 deletions(-) diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 0ad1b932a3..272e92755d 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -8,15 +8,20 @@ //! groups and compound paths (§5.3.5), guides (§6) and layers (§9), with the newer forms the reader //! reads from files users sent: //! -//! - Header comments: `%%BoundingBox`, `%%HiResBoundingBox`, `%AI5_FileFormat 14.0`, the first -//! artboard as `%AI3_Cropmarks` and `%AI5_ArtSize`, `%AI5_RulerUnits`, `%AI9_ColorModel` (1 RGB, 2 -//! CMYK), `%AI5_NumLayers`, and the version comment `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). -//! - Setup: the color swatches (`%AI5_BeginPalette`, `0 0 Pb`, each swatch's color operator and -//! `(name) Pc`, a color group as `0 (name) count Pg` before its swatches, `PB`), then the -//! artboards as the `ArtboardArray` of the `/Document` dictionary, on `%_` lines. +//! - Header comments: `%%For` (the document's author), `%%Canvassize`, `%%BoundingBox`, +//! `%%HiResBoundingBox`, `%AI5_FileFormat 14.0`, `%AI7_ImageSettings`, the first artboard as +//! `%AI3_Cropmarks` and `%AI5_ArtSize`, `%AI5_RulerUnits`, `%AI9_ColorModel` (1 RGB, 2 CMYK), +//! `%AI5_ArtFlags`, `%AI5_TargetResolution`, `%AI5_NumLayers`, `%AI5_OpenViewLayers` (a digit for +//! each layer, 7 shown and 6 hidden), `%AI7_GridSettings` (§2.1.1), and the version comment +//! `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). +//! - Setup: `0 Bn` (no gradient definitions, §3), the color swatches (`%AI5_BeginPalette`, +//! `0 0 Pb`, the Registration swatch, each swatch's color operator and `(name) Pc`, a color group as `0 (name) count Pg` +//! before its swatches, `PB`), then the artboards as the `ArtboardArray` of the `/Document` +//! dictionary, on `%_` lines. //! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0 //! dimPercent 0 Lb` (14 operands; a color that isn't one of the preset layer colors has the -//! index -1), `(name) Ln`, its art and sublayers, `LB`, `%AI5_EndLayer--`. +//! index -1), `(name) Ln`, the layer's name as an XML id in an `/ArtDictionary`, its art and +//! sublayers, `LB`, `%AI5_EndLayer--`. //! - Colors: `g` gray, `k` CMYK, `c m y k r g b Xa` RGB (Lab is written as RGB); a spot color //! `c m y k (name) tint x` (CMYK) or `c m y k r g b|L a b (name) tint 1|2 Xx` (RGB or Lab); a //! global process color `… (name) tint model Xk`; Registration `1 1 1 1 ([Registration]) tint @@ -25,7 +30,7 @@ //! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are `(N) *`, the //! path, `(N) *` (`(n) *` when closed). //! -//! Strings are written in UTF-8. Art space has y up, its origin at the first artboard's bottom-left +//! Lines end in CR LF. Strings are written in UTF-8. Art space has y up, its origin at the first artboard's bottom-left //! corner. What the form above can't hold is written as plain filled and stroked paths, each such //! loss a warning: type as its outlines, gradients as their average color, pattern fills as their //! tiles cut to the shape, clipping groups and clipping layers as their art cut to the clipping @@ -60,6 +65,16 @@ const ROUNDTRIP_VERSION: u32 = 24; const ROUNDTRIP_STREAM_TYPE: u32 = 2; /// What starts the data streams of Zstandard-compressed data. const ZSTD_MARKER: &[u8] = b"%AI24_ZStandard_Data"; +/// `%%Canvassize`: the side of the canvas in points, as the files users sent have it. +const CANVAS_SIZE: u32 = 16383; +/// `%AI5_ArtFlags` (§2.1.1, Table 4), as the files users sent have them: page setup, print tiles, +/// placed images, preview patterns, split long paths, tile full pages, printer's default +/// screens, auto default screens, compatible gradient printing. +const ART_FLAGS: &str = "0 0 0 1 0 0 1 0 0"; +/// `%AI5_TargetResolution` (§2.1.1). +const TARGET_RESOLUTION: u32 = 800; +/// The gridlines' gray: VectorCraft's default grid color (200 of 255). +const GRID_GRAY: f64 = 200.0 / 255.0; /// The first line of a PostScript file (the DSC version comment). const PS_HEADER: &str = "%!PS-Adobe-3.0"; // brand-ok: the PostScript header comment @@ -98,7 +113,6 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result Result Vec { + s.replace('\n', "\r\n").into_bytes() } /// `doc` with its geometry effects baked ([`vectorcraft_effects::bake_document`]), in its symbols' @@ -163,17 +184,20 @@ pub fn private_data(doc: &Document, o: &AiEditingOptions) -> Result<(PrivateData /// The header comments, through `%%EndComments`. `art`: the visible art's bounds, `size` the first /// artboard's, in art space. -fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, (width, height): (f64, f64), layers: usize) -> String { +fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, (width, height): (f64, f64)) -> String { let mut s = String::new(); s.push_str(PS_HEADER); s.push('\n'); let _ = writeln!(s, "%%Creator: VectorCraft {}", env!("CARGO_PKG_VERSION")); let _ = writeln!(s, "%%AI8_CreatorVersion: {CREATOR_VERSION}"); + // The user and the organization (§2.1.1). + let _ = writeln!(s, "%%For: {} ()", ps::bytes(doc.metadata.author.as_bytes())); let _ = writeln!(s, "%%Title: {}", ps::bytes(o.title.as_bytes())); if let Some(t) = o.created { let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); let _ = writeln!(s, "%%CreationDate: ({mo}/{d}/{y:04}) ({h:02}:{mi:02})"); } + let _ = writeln!(s, "%%Canvassize: {CANVAS_SIZE}"); let _ = writeln!(s, "%%BoundingBox: {} {} {} {}", art.x0.floor() as i64, art.y0.floor() as i64, art.x1.ceil() as i64, art.y1.ceil() as i64); s.push_str("%%HiResBoundingBox: "); ps::push_nums(&mut s, &[art.x0, art.y0, art.x1, art.y1]); @@ -181,6 +205,8 @@ fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, (width, h s.push('\n'); s.push_str("%%DocumentProcessColors: Cyan Magenta Yellow Black\n"); s.push_str("%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n"); + // Linked images aren't embedded (the data holds no images). + s.push_str("%AI7_ImageSettings: 0\n"); let spots = w.spot_swatches(); for (i, (name, _)) in spots.iter().enumerate() { let _ = writeln!(s, "{} {}", if i == 0 { "%%DocumentCustomColors:" } else { "%%+" }, ps::bytes(name.as_bytes())); @@ -201,7 +227,18 @@ fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, (width, h s.push_str("%AI24_LargeCanvasScale: 1\n"); let model = if doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { 2 } else { 1 }; let _ = writeln!(s, "%AI9_ColorModel: {model}"); - let _ = writeln!(s, "%AI5_NumLayers: {layers}"); + let _ = writeln!(s, "%AI5_ArtFlags: {ART_FLAGS}"); + let _ = writeln!(s, "%AI5_TargetResolution: {TARGET_RESOLUTION}"); + let _ = writeln!(s, "%AI5_NumLayers: {}", doc.layers.len()); + // A digit for each layer: 7 shown, 6 hidden. + let views: String = doc.layers.iter().map(|l| if l.visible { '7' } else { '6' }).collect(); + if !views.is_empty() { + let _ = writeln!(s, "%AI5_OpenViewLayers: {views}"); + } + // Gridlines and subdivisions (§2.1.1, Table 6): in back, lines, in VectorCraft's grid gray. + let (space, subdiv) = (ps::num(doc.grid.spacing), doc.grid.subdivisions); + let gray = ps::num(GRID_GRAY); + let _ = writeln!(s, "%AI7_GridSettings: {space} {subdiv} {space} {subdiv} 1 0 {gray} {gray} {gray} {gray} {gray} {gray}"); s.push_str("%%EndComments\n"); s } diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 0490ae3918..e0d0b2d684 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -16,9 +16,9 @@ fn opts() -> AiEditingOptions { AiEditingOptions { title: "Sample".into(), created: Some(0) } } -/// The program written from `doc`, as text. +/// The program written from `doc`, as text with its CR LF line ends read as LF. fn program(doc: &Document) -> String { - String::from_utf8(export_ai_editing(doc, &opts()).unwrap().program).unwrap() + String::from_utf8(export_ai_editing(doc, &opts()).unwrap().program).unwrap().replace("\r\n", "\n") } /// `doc` written, then read back from the private data alone. @@ -266,7 +266,8 @@ fn writing_again_gives_the_same_bytes() { assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); // What the reader reads back is written as the same program. - assert_eq!(program(&read_back(&doc)), String::from_utf8(first.program).unwrap()); + let read = export_ai_editing(&read_back(&doc), &opts()).unwrap(); + assert_eq!(read.program, first.program); assert!(first.warnings.is_empty(), "{:?}", first.warnings); } @@ -283,17 +284,18 @@ fn the_data_is_zstandard_compressed_with_the_header_as_metadata() { assert!(out.program.starts_with(&out.header)); assert_eq!(p.metadata, out.header); let header = String::from_utf8(out.header).unwrap(); - assert!(header.ends_with("%%EndComments\n")); + assert!(header.ends_with("%%EndComments\r\n")); + let header = header.replace("\r\n", "\n"); for line in [ - "%%AI8_CreatorVersion: 30.7.0\n", - "%AI5_FileFormat 14.0\n", + "%%AI8_CreatorVersion: 30.7.0\n%%For: () ()\n%%Title: (Sample)\n", + "%%Canvassize: 16383\n", + "%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n%AI7_ImageSettings: 0\n%%DocumentCustomColors: (Gold)\n%%+ (Sky)\n%%+ (Mint)\n", "%AI3_Cropmarks: 0 0 200 100\n", "%AI5_ArtSize: 200 100\n", - "%AI9_ColorModel: 1\n", - "%AI5_NumLayers: 2\n", - "%%DocumentCustomColors: (Gold)\n%%+ (Sky)\n%%+ (Mint)\n", + "%AI9_ColorModel: 1\n%AI5_ArtFlags: 0 0 0 1 0 0 1 0 0\n%AI5_TargetResolution: 800\n%AI5_NumLayers: 2\n", + "%AI5_OpenViewLayers: 77\n%AI7_GridSettings: 72 8 72 8 1 0 0.7843 0.7843 0.7843 0.7843 0.7843 0.7843\n%%EndComments\n", ] { - assert!(header.contains(line), "{line}"); + assert!(header.contains(line), "{line}\n{header}"); } assert_eq!((p.container_version, p.creator_version, p.roundtrip_version, p.roundtrip_stream_type), (12, 30, 24, 2)); } @@ -328,7 +330,7 @@ fn many_objects_of_one_name_are_numbered_in_turn() { doc.insert(Some(layer), usize::MAX, n).unwrap(); } let text = program(&doc); - let ids: std::collections::HashSet<&str> = text.lines().filter(|l| l.starts_with("%_/XMLUID")).collect(); + let ids: std::collections::HashSet<&str> = text.lines().filter(|l| l.starts_with("%_/XMLUID : (Dot")).collect(); assert_eq!(ids.len(), 20_000); assert!(text.contains("(Dot_00000000000000019999_)")); } @@ -340,6 +342,61 @@ fn layers_have_fourteen_operands() { assert!(text.contains("%AI5_BeginLayer\n0 1 0 0 1 0 1 -1 10 200 30 0 70 0 Lb\n(Sub) Ln\n"), "{text}"); } +#[test] +fn layers_are_named_as_xml_ids_after_their_names() { + let mut doc = sample(); + let layer = doc.layers[0].id; + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default()); + n.name = Some("Back".into()); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let text = program(&doc); + assert!(text.contains("(Back) Ln\n%_/ArtDictionary :\n%_/XMLUID : (Back) ; (AI10_ArtUID) ,\n%_;\n%_\n"), "{text}"); + assert!(text.contains("(Sub) Ln\n%_/ArtDictionary :\n%_/XMLUID : (Sub) ; (AI10_ArtUID) ,\n"), "{text}"); + // An object named as a layer is numbered. + assert!(text.contains("%_/XMLUID : (Back_00000000000000000001_) ; (AI10_ArtUID) ,"), "{text}"); + // The reader keeps the names where they were. + let read = read_back(&doc); + assert_eq!(read.layers[0].name.as_deref(), Some("Back")); + let names: Vec> = read.layers[0].children().unwrap().iter().map(|c| c.name.as_deref()).collect(); + assert_eq!(names.last(), Some(&Some("Back"))); +} + +#[test] +fn lines_end_in_cr_lf() { + let mut doc = sample(); + doc.metadata.author = "A\nB".into(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let text = String::from_utf8(out.program).unwrap(); + assert_eq!(text.matches('\n').count(), text.matches("\r\n").count()); + assert_eq!(text.matches('\r').count(), text.matches("\r\n").count()); + // A line break in a string stays in the string, escaped. + assert!(text.contains("%%For: (A\\nB) ()\r\n"), "{text}"); +} + +#[test] +fn the_palette_starts_with_registration() { + let mut doc = sample(); + let rgb = program(&doc); + assert!(rgb.contains("0 0 Pb\n"), "{rgb}"); + let cell = rgb.split("0 0 Pb\n").nth(1).unwrap().lines().take(2).collect::>(); + assert!(cell[0].ends_with(" 0 0 0 ([Registration]) 0 1 Xz") && cell[0].split(' ').count() == 11, "{cell:?}"); + assert_eq!(cell[1], "([Registration]) Pc"); + doc.color_mode = vectorcraft_doc::ColorMode::Cmyk; + assert!(program(&doc).contains("0 0 Pb\n1 1 1 1 ([Registration]) 0 Xs\n([Registration]) Pc\n")); + // It's the built-in swatch: reading back adds no swatch. + assert_eq!(swatches(&read_back(&doc)), swatches(&doc)); +} + +#[test] +fn hidden_layers_open_hidden() { + let mut doc = sample(); + let mut hidden = Node::layer(doc.alloc_id(), "Off", LayerColor::Preset(1)); + hidden.visible = false; + doc.layers.push(Arc::new(hidden)); + let text = program(&doc); + assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}"); +} + /// A 200 × 100 document of what slice 1 writes as plain paths: a gradient fill, a clipping group, /// a compound path, an image, type, a symbol instance and a half-transparent square. fn unsupported() -> Document { diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index ff0d6ed771..39a19b4c12 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -113,7 +113,7 @@ impl<'a> Writer<'a> { } } - /// A layer or sublayer: `%AI5_BeginLayer`, its options `Lb`, its name `Ln`, its art, then + /// A layer or sublayer: `%AI5_BeginLayer`, its options `Lb`, its name `Ln` and as an XML id, its art, then /// `after` (outside its clipping path when it clips), `LB`, `%AI5_EndLayer--`. fn write_layer(&mut self, n: &Node, after: &[Arc]) { let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return }; @@ -131,6 +131,7 @@ impl<'a> Writer<'a> { self.transparency(n); let flag = |b: bool| u8::from(b); let dim = dim_images.unwrap_or(50); + let name = n.name.as_deref().unwrap_or("Layer"); let _ = writeln!( self.body, "%AI5_BeginLayer\n{} {} {} {} {} 0 1 {index} {r} {g} {b} 0 {dim} 0 Lb\n{} Ln", @@ -139,8 +140,9 @@ impl<'a> Writer<'a> { flag(!n.locked), flag(*printable && !*template), flag(dim_images.is_some() || *template), - ps::bytes(n.name.as_deref().unwrap_or("Layer").as_bytes()), + ps::bytes(name.as_bytes()), ); + self.xml_id(if name.is_empty() { "Layer" } else { name }); self.state = None; if *clip { self.warn(CLIPPING); @@ -269,10 +271,15 @@ impl<'a> Writer<'a> { } } - /// `n`'s name, after it: an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id, - /// numbered (`_` and 20 digits, `_`) when another object has that id. + /// `n`'s name, after it (see [`Self::xml_id`]). fn name(&mut self, n: &Node) { let Some(name) = n.name.as_deref().filter(|s| !s.is_empty()) else { return }; + self.xml_id(name); + } + + /// An `/ArtDictionary` whose `AI10_ArtUID` is `name` as an XML id, numbered (`_` and 20 + /// digits, `_`) when a layer or another object has that id. + fn xml_id(&mut self, name: &str) { let base = vectorcraft_doc::xml_id::from_object_name(name); let mut id = base.clone(); let next = self.next.entry(base.clone()).or_insert(0); @@ -604,11 +611,12 @@ impl<'a> Writer<'a> { // ---------- swatches ---------- - /// The swatches: `%AI5_BeginPalette`, `0 0 Pb`, each color swatch's color and `(name) Pc` + /// The swatches: `%AI5_BeginPalette`, `0 0 Pb`, the Registration swatch, each color swatch's color and `(name) Pc` /// (the ungrouped ones first, then each color group's after `0 (name) count Pg`), `PB`, /// `%AI5_EndPalette`. pub(super) fn palette(&mut self, s: &mut String) { s.push_str("%AI5_BeginPalette\n0 0 Pb\n"); + self.registration_cell(s); let doc = self.doc; for sw in doc.swatches.iter() { self.swatch(s, sw); @@ -623,6 +631,22 @@ impl<'a> Writer<'a> { s.push_str("PB\n%AI5_EndPalette\n"); } + /// The Registration swatch, which every palette in the files users sent starts with: in a + /// CMYK document `1 1 1 1 ([Registration]) 0 Xs`, in an RGB one black's CMYK equivalent, + /// `0 0 0 ([Registration]) 0 1 Xz`; then `([Registration]) Pc`. + fn registration_cell(&self, s: &mut String) { + let name = ps::bytes(REGISTRATION.as_bytes()); + if self.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { + let _ = writeln!(s, "1 1 1 1 {name} 0 Xs"); + } else { + let black = Color::rgb(0.0, 0.0, 0.0); + let cmyk = self.cms.to_cmyk(&black, self.cms.settings().intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + let _ = writeln!(s, "0 0 0 {name} 0 1 Xz"); + } + let _ = writeln!(s, "{name} Pc"); + } + /// One swatch of the palette: a color swatch's color and `(name) Pc`; gradient and pattern /// swatches are left out. fn swatch(&mut self, s: &mut String, sw: &Swatch) { diff --git a/crates/pdf/src/piece_info.rs b/crates/pdf/src/piece_info.rs index c6e457ef39..157f36c5c5 100644 --- a/crates/pdf/src/piece_info.rs +++ b/crates/pdf/src/piece_info.rs @@ -72,10 +72,11 @@ fn stream(bytes: &[u8]) -> Vec { s } -/// `at` (Unix seconds) as a PDF date string in UTC (ISO 32000-1 §7.9.4). +/// `at` (Unix seconds) as a PDF date string in UTC (ISO 32000-1 §7.9.4), with the offset written +/// as hours and minutes, as in the files users sent. fn pdf_date(at: i64) -> String { let [y, mo, d, h, mi, s] = vectorcraft_doc::metadata::civil(at); - format!("(D:{y:04}{mo:02}{d:02}{h:02}{mi:02}{s:02}Z)") + format!("(D:{y:04}{mo:02}{d:02}{h:02}{mi:02}{s:02}+00'00')") } #[cfg(test)] @@ -120,7 +121,7 @@ mod tests { #[test] fn dates_are_in_utc() { - assert_eq!(pdf_date(0), "(D:19700101000000Z)"); - assert_eq!(pdf_date(1_793_000_000), "(D:20261026073320Z)"); + assert_eq!(pdf_date(0), "(D:19700101000000+00'00')"); + assert_eq!(pdf_date(1_793_000_000), "(D:20261026073320+00'00')"); } } From a5be18b693aeb466d871476803a3b44ff6a9cb62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 17:57:36 -0700 Subject: [PATCH 005/674] Save As .ai: name dots and corner-fitted dashes in the editing data's stroke warning Dotted strokes (zero-length dashes with round or projecting caps) and dashes fitted to corners are written as filled outlines in the editing data for other apps. The warning that lists the strokes written that way now names them. --- crates/eps/src/ai_editing/tests.rs | 20 ++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index e0d0b2d684..402e34f4d4 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -387,6 +387,26 @@ fn the_palette_starts_with_registration() { assert_eq!(swatches(&read_back(&doc)), swatches(&doc)); } +#[test] +fn dotted_strokes_are_written_as_their_dots_with_a_warning() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut stroke = StrokeLayer::new(solid(Color::rgb(0.0, 0.0, 0.0)), 4.0); + stroke.cap = LineCap::Round; + stroke.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false }); + let line = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((10.0, 50.0).into()), + kurbo::PathEl::LineTo((60.0, 50.0).into()), + ])); + let n = Node::path(doc.alloc_id(), line, Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Appearance::default() }); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("dots")), "{:?}", out.warnings); + let text = program(&doc); + assert!(!text.contains("[0 10] 0 d"), "{text}"); + assert!(text.matches("\nf\n").count() >= 5, "a filled dot for each dash: {text}"); +} + #[test] fn hidden_layers_open_hidden() { let mut doc = sample(); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 39a19b4c12..24c0d57b85 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -32,7 +32,7 @@ pub(super) const CLIPPING: &str = pub(super) const IMAGES: &str = "images are written as their outlines filled with their average color in the editing data for other apps"; pub(super) const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; -const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; +const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const TRANSPARENCY: &str = "transparency (opacity, blending modes, opacity masks) is left out of the editing data for other apps"; pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps"; const SWATCHES: &str = "gradient and pattern swatches are left out of the editing data for other apps"; From 9cd5e3df8f775784f9344dbcefd20e8caa1a47e9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 21:35:06 -0700 Subject: [PATCH 006/674] Save As .ai: place the editing data's art on its artboard and carry it on every page The editing data wrote art space with its origin at the first artboard's bottom-left corner, its artboard records lacked keys a reader requires, and its %%Creator line made the reader measure %AI3_TemplateBox on an 8640-point canvas. Other apps opened the art 3,871.5 points away from its artboard. Art space is now ruler space, as in the .ai files users sent: y up from the first artboard's top-left corner. The artboards together are centered on the 16383-point canvas. Each artboard's record gives its top-left corner there (RulerOrigin), its pixel aspect ratio (PAR), DisplayMark and whether it is selected, and %AI3_TemplateBox holds the canvas's center. %%Creator names the format's app and holds no version number. %AI3_Cropmarks and %AI3_TileBox give the first artboard, %AI5_ArtSize is 14400 14400, and the /Document dictionary gives the canvas size. A file with several artboards carried the data on its first page only, and other apps opened it as a PDF, page by page. Every page now refers to the one data dictionary, as the files users sent do. The format details come from users' own .ai files, static analysis of Illustrator's program and the user's manual testing in Illustrator. --- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/eps/src/ai_editing.rs | 99 +++++++++++++++++++++-------- crates/eps/src/ai_editing/tests.rs | 46 +++++++++++++- crates/pdf/src/lib.rs | 2 +- crates/pdf/src/piece_info.rs | 45 +++++++++++-- 5 files changed, 156 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 641aa08453..14b692e73d 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -282,7 +282,7 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result Result Result Option { Some(out) } -/// The editing data of `doc` as a `.ai` file's first page carries it: the program compressed with +/// The editing data of `doc` as a `.ai` file's pages carry it: the program compressed with /// Zstandard after `%AI24_ZStandard_Data`, its header as the `AIMetaData`, and the version numbers /// that go with that form; and what it couldn't hold. pub fn private_data(doc: &Document, o: &AiEditingOptions) -> Result<(PrivateData, Vec), String> { @@ -182,13 +197,28 @@ pub fn private_data(doc: &Document, o: &AiEditingOptions) -> Result<(PrivateData Ok((p, out.warnings)) } -/// The header comments, through `%%EndComments`. `art`: the visible art's bounds, `size` the first -/// artboard's, in art space. -fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, (width, height): (f64, f64)) -> String { +/// Where art space's origin lies on the canvas (y down, [`CANVAS_SIZE`] points square): the +/// artboards together centered on the canvas's center, on whole points, as the files users sent +/// place them. +fn ruler_origin(doc: &Document, to_art: Affine) -> (f64, f64) { + let all = doc.artboards.iter().map(|ab| to_art.transform_rect_bbox(ab.rect)).filter(|r| r.is_finite()).reduce(|a, b| a.union(b)); + let c = all.map_or((0.0, 0.0), |r| (r.center().x, r.center().y)); + let mid = canvas_center(); + ((mid - c.0).floor(), (mid + c.1).floor()) +} + +/// The canvas's center, on its own axes and in both directions. +fn canvas_center() -> f64 { + f64::from(CANVAS_SIZE) / 2.0 +} + +/// The header comments, through `%%EndComments`. `art`: the visible art's bounds, `first` the first +/// artboard, in art space; `origin` art space's origin on the canvas ([`ruler_origin`]). +fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, first: Rect, origin: (f64, f64)) -> String { let mut s = String::new(); s.push_str(PS_HEADER); s.push('\n'); - let _ = writeln!(s, "%%Creator: VectorCraft {}", env!("CARGO_PKG_VERSION")); + let _ = writeln!(s, "%%Creator: {CREATOR_TEXT}"); let _ = writeln!(s, "%%AI8_CreatorVersion: {CREATOR_VERSION}"); // The user and the organization (§2.1.1). let _ = writeln!(s, "%%For: {} ()", ps::bytes(doc.metadata.author.as_bytes())); @@ -216,13 +246,17 @@ fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, (width, h ps::push_nums(&mut s, &cmyk.map(f64::from)); let _ = writeln!(s, "{}", ps::bytes(name.as_bytes())); } - let (w2, h2) = (ps::num(width), ps::num(height)); - let _ = writeln!(s, "%AI3_Cropmarks: 0 0 {w2} {h2}"); - let (cx, cy) = (ps::num(width / 2.0), ps::num(height / 2.0)); + // The first artboard, left, bottom, right, top. + let mut board = String::new(); + ps::push_nums(&mut board, &[first.x0, first.y0, first.x1, first.y1]); + board.pop(); + let _ = writeln!(s, "%AI3_Cropmarks: {board}"); + // The canvas's center in art space. + let (cx, cy) = (ps::num(canvas_center() - origin.0), ps::num(origin.1 - canvas_center())); let _ = writeln!(s, "%AI3_TemplateBox: {cx} {cy} {cx} {cy}"); - let _ = writeln!(s, "%AI3_TileBox: 0 0 {w2} {h2}"); + let _ = writeln!(s, "%AI3_TileBox: {board}"); s.push_str("%AI3_DocumentPreview: None\n"); - let _ = writeln!(s, "%AI5_ArtSize: {w2} {h2}"); + let _ = writeln!(s, "%AI5_ArtSize: {ART_SIZE} {ART_SIZE}"); let _ = writeln!(s, "%AI5_RulerUnits: {}", ruler_units(doc.units)); s.push_str("%AI24_LargeCanvasScale: 1\n"); let model = if doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { 2 } else { 1 }; @@ -256,19 +290,30 @@ fn ruler_units(u: Unit) -> u8 { } /// The artboards as the `ArtboardArray` of the `/Document` dictionary: each one's top-left and -/// bottom-right corners in art space (`PositionPoint1`, `PositionPoint2`) and its name. -fn artboards(s: &mut String, doc: &Document, to_art: Affine) { +/// bottom-right corners in art space (`PositionPoint1`, `PositionPoint2`), its top-left corner on +/// the canvas (`RulerOrigin`, `origin` being art space's origin there), its pixel aspect ratio +/// (`PAR`), `DisplayMark` 0 (as in the files users sent), whether it is the selected one (the +/// first) and its name; then the canvas's size. Apps that read the editing data drop a record that +/// lacks any of the first five. +fn artboards(s: &mut String, doc: &Document, to_art: Affine, origin: (f64, f64)) { s.push_str("%AI9_BeginDocumentData\n%_/Document :\n%_/Dictionary :\n%_/Array :\n"); - for ab in &doc.artboards { + for (i, ab) in doc.artboards.iter().enumerate() { let r = to_art.transform_rect_bbox(ab.rect); s.push_str("%_/Dictionary :\n%_"); ps::push_nums(s, &[r.x0, r.y1]); s.push_str("/RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_"); ps::push_nums(s, &[r.x1, r.y0]); - s.push_str("/RealPointRelToROrigin\n%_ (PositionPoint2) ,\n"); + s.push_str("/RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_"); + ps::push_nums(s, &[origin.0 + r.x0, origin.1 - r.y1]); + s.push_str("/RealPoint\n%_ (RulerOrigin) ,\n%_"); + let par = ab.video_ruler_pixel_aspect_ratio; + ps::push_num(s, if par.is_finite() && par > 0.0 { par } else { 1.0 }); + let _ = writeln!(s, " /Real (PAR) ,\n%_0 /Int (DisplayMark) ,\n%_{} /Bool (IsArtboardSelected) ,", u8::from(i == 0)); let _ = writeln!(s, "%_{} /UnicodeString (Name) ,\n%_; ,", ps::bytes(ab.name.as_bytes())); } - s.push_str("%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"); + s.push_str("%_; (ArtboardArray) ,\n"); + let _ = writeln!(s, "%_{CANVAS_SIZE} /Int (AIDocumentCanvasSize) ,"); + s.push_str("%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"); } #[cfg(test)] diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 402e34f4d4..e7f9c9d398 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -290,8 +290,8 @@ fn the_data_is_zstandard_compressed_with_the_header_as_metadata() { "%%AI8_CreatorVersion: 30.7.0\n%%For: () ()\n%%Title: (Sample)\n", "%%Canvassize: 16383\n", "%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n%AI7_ImageSettings: 0\n%%DocumentCustomColors: (Gold)\n%%+ (Sky)\n%%+ (Mint)\n", - "%AI3_Cropmarks: 0 0 200 100\n", - "%AI5_ArtSize: 200 100\n", + "%AI3_Cropmarks: 0 -100 200 0\n%AI3_TemplateBox: 225.5 -50.5 225.5 -50.5\n%AI3_TileBox: 0 -100 200 0\n", + "%AI5_ArtSize: 14400 14400\n", "%AI9_ColorModel: 1\n%AI5_ArtFlags: 0 0 0 1 0 0 1 0 0\n%AI5_TargetResolution: 800\n%AI5_NumLayers: 2\n", "%AI5_OpenViewLayers: 77\n%AI7_GridSettings: 72 8 72 8 1 0 0.7843 0.7843 0.7843 0.7843 0.7843 0.7843\n%%EndComments\n", ] { @@ -300,6 +300,48 @@ fn the_data_is_zstandard_compressed_with_the_header_as_metadata() { assert_eq!((p.container_version, p.creator_version, p.roundtrip_version, p.roundtrip_stream_type), (12, 30, 24, 2)); } +/// Art space is ruler space: y up from the first artboard's top-left corner. The artboards +/// together sit centered on the canvas: each one's top-left corner on the canvas (y down) is its +/// `RulerOrigin`, and the template box holds the canvas's center in art space. +#[test] +fn art_lies_on_its_artboard_in_ruler_space() { + let mut doc = Document::new(200.0, 100.0); + let mut second = doc.artboards[0].clone(); + (second.id, second.name, second.rect) = (2, "Back".into(), Rect::new(250.0, 0.0, 450.0, 100.0)); + doc.artboards.push(second); + let rect = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(10.0, 20.0, 30.0, 40.0)), + Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0), + ); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, rect).unwrap(); + let text = program(&doc); + for line in [ + "%%BoundingBox: 10 -40 30 -20\n", + "%AI3_Cropmarks: 0 -100 200 0\n", + "%AI3_TemplateBox: 225.5 -50.5 225.5 -50.5\n", + "\n10 -20 m\n", + "%_0 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_200 -100 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_7966 8141 /RealPoint\n%_ (RulerOrigin) ,\n%_1 /Real (PAR) ,\n%_0 /Int (DisplayMark) ,\n%_1 /Bool (IsArtboardSelected) ,\n", + "%_250 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_450 -100 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_8216 8141 /RealPoint\n%_ (RulerOrigin) ,\n%_1 /Real (PAR) ,\n%_0 /Int (DisplayMark) ,\n%_0 /Bool (IsArtboardSelected) ,\n", + "%_16383 /Int (AIDocumentCanvasSize) ,\n", + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + // The creator names the format's app, before the canvas size and the template box, and holds + // no version number another app could read as the format's version. + let creator = text.lines().find_map(|l| l.strip_prefix("%%Creator: ")).unwrap(); + assert!(creator.contains("Illustrator"), "{creator}"); + assert!(!creator.contains("88") && !creator.chars().any(|c| c.is_ascii_digit()), "{creator}"); + assert!(text.find("%%Creator: ").unwrap() < text.find("%%Canvassize: 16383").unwrap()); + assert!(text.find("%%Canvassize: 16383").unwrap() < text.find("%AI3_TemplateBox").unwrap()); + // The reader puts the art back where it was, on its artboard. + let read = read_back(&doc); + assert_eq!(read.artboards.iter().map(|a| a.rect).collect::>(), doc.artboards.iter().map(|a| a.rect).collect::>()); + let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(bounds, Rect::new(10.0, 20.0, 30.0, 40.0)); +} + #[test] fn a_pdf_carries_the_data_on_its_first_page() { let doc = sample(); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 7ca44a4fd4..c12459fbe3 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -105,7 +105,7 @@ pub struct PdfOptions { pub modified: Option, /// The native document (`.vectorcraft` bytes) Preserve Editing embeds. pub native: Option>, - /// The editing copy of the art for the first page's `PieceInfo`, as a `.ai` file carries it. + /// The editing copy of the art for every page's `PieceInfo`, as a `.ai` file carries it. pub private_data: Option, /// The pages drawn small, in page order: what Embed Page Thumbnails embeds (the writer /// doesn't draw; [`page_areas`] says what each page shows). diff --git a/crates/pdf/src/piece_info.rs b/crates/pdf/src/piece_info.rs index 157f36c5c5..60cd80228a 100644 --- a/crates/pdf/src/piece_info.rs +++ b/crates/pdf/src/piece_info.rs @@ -1,9 +1,11 @@ -//! An editor's private data on the first page: a page-piece dictionary (ISO 32000-1 §14.5, +//! An editor's private data on every page: a page-piece dictionary (ISO 32000-1 §14.5, //! `PieceInfo`) holding the editing copy of the art that `.ai` files carry, laid out as in the //! `.ai` files users sent, the form [`crate::illustrator_data`] reads. //! -//! - The page dictionary gets `/PieceInfo << /Illustrator n 0 R >>` and its own `/LastModified` -//! (which §14.5 requires with `PieceInfo`). +//! - Every page dictionary gets `/PieceInfo << /Illustrator n 0 R >>`, the same object `n` on +//! each page, and its own `/LastModified` (which §14.5 requires with `PieceInfo`). A file with +//! several pages whose pages do not all refer to the one data dictionary opens in other apps as +//! a PDF, without the editing data. //! - Object `n` is the data dictionary: `<< /LastModified (D:…) /Private m 0 R >>`. //! - Object `m` holds `AIMetaData` (a stream of the data's header comments), `AIPrivateData1` … //! `AIPrivateDataN` (the data in streams of [`PRIVATE_CHUNK`] bytes, the last one shorter), @@ -35,12 +37,15 @@ pub struct PrivateData { pub roundtrip_stream_type: u32, } -/// `pdf` with `p` in its first page's `PieceInfo`, dated `modified` (Unix seconds, UTC). +/// `pdf` with `p` in every page's `PieceInfo`, dated `modified` (Unix seconds, UTC). pub(crate) fn add(pdf: Vec, p: &PrivateData, modified: i64) -> Result, PdfError> { let failed = |why: &str| PdfError::Write(format!("can't add the editing data for other apps: {why}")); let Parsed { xref, pages, .. } = linearize::parse(&pdf).map_err(failed)?; - let first = *pages.first().ok_or_else(|| failed("a page can't be read"))?; - let (dict, _) = xref.dict(&pdf, first).ok_or_else(|| failed("a page can't be read"))?; + if pages.is_empty() { + return Err(failed("a page can't be read")); + } + let dicts = pages.iter().map(|&n| xref.dict(&pdf, n).map(|(at, _)| at)).collect::>>(); + let dicts = dicts.ok_or_else(|| failed("a page can't be read"))?; let mut patch = Patch::new(&xref); let metadata = patch.add_object(stream(&p.metadata)); let blocks: Vec = p.data.chunks(PRIVATE_CHUNK).map(|c| patch.add_object(stream(c))).collect(); @@ -60,7 +65,9 @@ pub(crate) fn add(pdf: Vec, p: &PrivateData, modified: i64) -> Result>").into_bytes()); - patch.replace(dict, dict, format!("/PieceInfo << /{OWNER} {owner} 0 R >> /LastModified {date} ").into_bytes()); + for dict in dicts { + patch.replace(dict, dict, format!("/PieceInfo << /{OWNER} {owner} 0 R >> /LastModified {date} ").into_bytes()); + } patch.apply(&pdf, &xref) } @@ -112,6 +119,30 @@ mod tests { assert!(text.contains(&format!("<< /Length {PRIVATE_CHUNK} >>")) && text.contains("<< /Length 10 >>")); } + #[test] + fn every_page_refers_to_the_one_data_dictionary() { + let mut doc = Document::new(200.0, 100.0); + let mut second = doc.artboards[0].clone(); + (second.id, second.name, second.rect) = (2, "Back".into(), vectorcraft_geom::Rect::new(240.0, 0.0, 440.0, 100.0)); + doc.artboards.push(second); + let opts = PdfOptions { private_data: Some(data(10)), ..PdfOptions::uncompressed() }; + let pdf = export(&doc, &opts).unwrap(); + let Parsed { xref, pages, .. } = linearize::parse(&pdf).unwrap(); + assert_eq!(pages.len(), 2); + let owners: Vec = pages + .iter() + .map(|&n| { + let (at, end) = xref.dict(&pdf, n).unwrap(); + let page = String::from_utf8_lossy(&pdf[at..end]).into_owned(); + assert!(page.contains("/LastModified (D:"), "{page}"); + let i = page.find("/PieceInfo << /Illustrator ").expect("every page carries the data"); + page[i..].split(">>").next().unwrap().to_string() + }) + .collect(); + assert_eq!(owners[0], owners[1]); + assert_eq!(String::from_utf8_lossy(&pdf).matches("/AIPrivateData1 ").count(), 1, "the data is written once"); + } + #[test] fn without_the_data_the_page_has_no_piece_info() { let pdf = export(&Document::new(200.0, 100.0), &PdfOptions::uncompressed()).unwrap(); From 80c43c8133b524f351778b68fffdd4deee1b7610 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 21:52:04 -0700 Subject: [PATCH 007/674] Save As .ai: keep the group fills and strokes of pattern tiles in the editing data A pattern fill is written as its tiles cut to the shape. A group in the tile art with fills or strokes of its own was written as its members alone, without that paint, because only the layers and the symbols' art were baked before writing. The patterns' tile art is now baked the same way as the symbols' art, so its group paint and geometry effects are written as plain paths. --- crates/eps/src/ai_editing.rs | 27 ++++++++++++++++++--------- crates/eps/src/ai_editing/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 552a99fe0f..d87a003962 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -156,26 +156,35 @@ fn crlf(s: &str) -> Vec { s.replace('\n', "\r\n").into_bytes() } -/// `doc` with its geometry effects baked ([`vectorcraft_effects::bake_document`]), in its symbols' -/// art too (which instances are written as); `None` when nothing changes. +/// `doc` with its geometry effects and group paint baked ([`vectorcraft_effects::bake_document`]), +/// in its symbols' art and its patterns' tile art too (which instances and pattern fills are +/// written as); `None` when nothing changes. fn baked(doc: &Document) -> Option { let baked = vectorcraft_effects::bake_document(doc); let d = baked.as_ref().unwrap_or(doc); - if !d.symbols.iter().any(|s| vectorcraft_effects::needs_bake(&s.art)) { + let needs = vectorcraft_effects::needs_bake; + if !d.symbols.iter().any(|s| needs(&s.art)) && !d.patterns.iter().any(|p| p.art.iter().any(|a| needs(a))) { return baked; } - // The symbols' art baked as the layers of a copy of the document. + // The symbols' art, then each pattern's art, baked as the layers of a copy of the document. let mut art = d.clone(); - art.layers = d.symbols.iter().map(|s| Arc::new(Node::group(s.art.id, vec![s.art.clone()]))).collect(); + let symbols = d.symbols.iter().map(|s| Arc::new(Node::group(s.art.id, vec![s.art.clone()]))); + let patterns = d.patterns.iter().map(|p| Arc::new(Node::group(vectorcraft_doc::NodeId(0), p.art.clone()))); + art.layers = symbols.chain(patterns).collect(); // The copy keeps what baking adds to the document (the images color adjustments make). let Some(mut out) = vectorcraft_effects::bake_document(&art) else { return baked }; - let arts: Vec>> = out.layers.iter().map(|l| l.children().and_then(|c| c.first()).cloned()).collect(); - out.layers = d.layers.clone(); - for (s, a) in out.symbols.iter_mut().zip(arts) { - if let Some(a) = a { + let layers = std::mem::replace(&mut out.layers, d.layers.clone()); + let mut members = layers.iter().map(|l| l.children().cloned().unwrap_or_default()); + for s in out.symbols.iter_mut() { + if let Some(a) = members.next().and_then(|m| m.first().cloned()) { s.art = a; } } + for p in out.patterns.iter_mut() { + if let Some(m) = members.next() { + p.art = m; + } + } Some(out) } diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index e7f9c9d398..696014fb92 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -718,6 +718,27 @@ fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { assert_ne!(fill, paint(&solid(Color::rgb(0.0, 0.0, 0.0))), "the image is adjusted"); } +#[test] +fn a_group_fill_in_a_pattern_tile_is_written() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let dot = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + let mut group = Node::group(doc.alloc_id(), vec![Arc::new(dot)]); + group.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + doc.patterns.push(vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(group)])); + let filled = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), + Appearance::basic(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "the tiles keep their group's fill"); +} + #[test] fn effects_on_a_fill_are_reported_left_out() { let mut doc = Document::new(200.0, 100.0); From 00fe03187993dbf6110346cc9e49fa581d244566 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 21:58:55 -0700 Subject: [PATCH 008/674] Save As .ai: write inline graphics in type as their art in the editing data Type is written as its outlines, and the outlines leave out inline graphics, so the editing data lost them while the PDF page drew them. Each inline graphic is now written as its symbol's art where the layout places it, over the characters and under the object's own fills and strokes above the Characters row, in the order the PDF page draws them. --- crates/eps/src/ai_editing.rs | 2 +- crates/eps/src/ai_editing/tests.rs | 34 +++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 52 ++++++++++++++++++++++++----- 3 files changed, 79 insertions(+), 9 deletions(-) diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index d87a003962..9f3c24fe3f 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -36,7 +36,7 @@ //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the //! artboards together are centered; each artboard's `RulerOrigin` is its top-left corner there, and //! `%AI3_TemplateBox` holds the canvas's center in art space. What the form above can't hold is written as plain filled and stroked paths, each such -//! loss a warning: type as its outlines, gradients as their average color, pattern fills as their +//! loss a warning: type as its outlines and its inline graphics' art, gradients as their average color, pattern fills as their //! tiles cut to the shape, clipping groups and clipping layers as their art cut to the clipping //! path (the clipping path's fill cut too, its stroke not), images as their outlines filled with //! their average color, symbols and live objects as their art, strokes a plain line can't draw as diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 696014fb92..a3acb5d2fc 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -617,6 +617,40 @@ fn type_is_written_as_create_outlines_makes_it() { assert_eq!(rounded(group), rounded(&outlined)); } +#[test] +fn inline_graphics_in_type_are_written_as_their_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mark = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0), + ); + doc.symbols.push(Symbol { name: "Mark".into(), art: Arc::new(mark) }); + let style = vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "A", style.clone()); + t.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("Mark"), style)); + let mut text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + // A stroke of the object's own above the Characters row: drawn over the inline graphic. + let red = solid(Color::rgb(1.0, 0.0, 0.0)); + text.appearance = + Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(red.clone(), 3.0))], contents_index: Some(0), ..Appearance::default() } + .into(); + doc.insert(Some(layer), usize::MAX, text).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let has = |p: &Node, c: &Paint| p.appearance.items.iter().any(|i| paint(i.paint()) == paint(c)); + let blue = solid(Color::rgb(0.0, 0.0, 1.0)); + let art: Vec<&Node> = all.iter().filter(|p| has(p, &blue)).collect(); + assert_eq!(art.len(), 1, "the inline graphic is written"); + // To the right of the letter, 18 pt high as the run's size makes it. + let b = art[0].visual_bounds().unwrap(); + assert!(b.x0 > 10.0 && (b.height() - 18.0).abs() < 0.01, "{b:?}"); + let at = |c: &Paint| all.iter().position(|p| has(p, c)).unwrap(); + assert!(at(&blue) < at(&red), "the stroke above the characters is over the inline graphic"); +} + #[test] fn a_stained_symbol_instance_is_written_in_its_stained_colors() { let mut doc = Document::new(200.0, 100.0); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 24c0d57b85..58947715ce 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -507,19 +507,55 @@ impl<'a> Writer<'a> { /// Type `n` as a group of what Type › Create Outlines makes of it /// ([`vectorcraft_effects::outline_text`]): each run's glyphs with their underline and - /// strikethrough, its color glyphs, and the object's own fills and strokes. + /// strikethrough, its color glyphs, and the object's own fills and strokes; then its inline + /// graphics as their symbols' art where the layout places them, as the PDF page draws them. fn text(&mut self, n: &Node) { self.warn(TYPE); self.line("u"); - if let Some(outlined) = vectorcraft_effects::outline_text(n) { - let state = self.state; - for c in outlined.children().map(Vec::as_slice).unwrap_or_default() { - self.node(c); - } - if let Some((locked, hidden)) = state { - self.state(locked, hidden); + let doc = self.doc; + let resolved = match &n.kind { + NodeKind::Text(t) => Some(doc.inline_resolved(t).into_owned()), + _ => None, + }; + let node = match &resolved { + Some(t) => Node { kind: NodeKind::Text(Box::new(t.clone())), ..n.clone() }, + None => n.clone(), + }; + let state = self.state; + let outlined = vectorcraft_effects::outline_text(&node); + let pieces = outlined.as_ref().and_then(|o| o.children()).map(Vec::as_slice).unwrap_or_default(); + // The object's fills and strokes above the Characters row, when they paint, are the last + // piece: the inline graphics go under it, as the PDF page draws them. + let above = !node.appearance.split_contents().1.is_empty() && { + let bare = Node { appearance: Default::default(), ..node.clone() }; + let glyphs = vectorcraft_effects::outline_text(&bare).and_then(|o| o.children().map(Vec::len)).unwrap_or_default(); + pieces.len() > glyphs + }; + let (under, over) = pieces.split_at(pieces.len() - usize::from(above)); + for c in under { + self.node(c); + } + if let Some(t) = resolved.as_ref().filter(|_| self.nest < MAX_NEST) { + let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + for ig in &layout.inlines { + let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; + let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue }; + self.warn(LIVE); + let mut art_node = (*sym.art).clone(); + // Strokes scale with the art, as on the canvas. + art_node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true); + (art_node.visible, art_node.locked, art_node.name) = (true, false, None); + self.nest += 1; + self.node(&art_node); + self.nest -= 1; } } + for c in over { + self.node(c); + } + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } self.line("U"); } From 25a193e5a9e60f47c988853d31d752a31ea1ec17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 22:03:38 -0700 Subject: [PATCH 009/674] Save As .ai: bound the symbol art the editing data writes Instances of symbols that hold instances of other symbols multiply, and the editing data wrote every level for each instance above it, limited only by nesting depth: eight levels of 100 instances each could hang a save or run out of memory. The writer now counts the objects of symbol art it writes, symbol instances and inline graphics alike, and leaves out instances past 16,000,000 objects in all, as the PDF part does, with a warning. --- crates/eps/src/ai_editing.rs | 5 +++-- crates/eps/src/ai_editing/tests.rs | 25 +++++++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 21 +++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 9f3c24fe3f..e89584b8e0 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -39,8 +39,9 @@ //! loss a warning: type as its outlines and its inline graphics' art, gradients as their average color, pattern fills as their //! tiles cut to the shape, clipping groups and clipping layers as their art cut to the clipping //! path (the clipping path's fill cut too, its stroke not), images as their outlines filled with -//! their average color, symbols and live objects as their art, strokes a plain line can't draw as -//! their filled outlines, several fills or strokes as a group of a path for each, gradient and +//! their average color, symbols and live objects as their art (symbol art past +//! [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects in all left out), strokes a plain line can't draw +//! as their filled outlines, several fills or strokes as a group of a path for each, gradient and //! pattern swatches, transparency and live effects other than geometry effects left out. //! //! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index a3acb5d2fc..bede50515e 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -651,6 +651,31 @@ fn inline_graphics_in_type_are_written_as_their_art() { assert!(at(&blue) < at(&red), "the stroke above the characters is over the inline graphic"); } +/// Nested symbols whose instances multiply stop at [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects of +/// symbol art in all, with a warning. +#[test] +fn nested_symbol_instances_stop_at_the_symbol_art_limit() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // Empty paths: counted, but written as nothing, so the test stays small; and one filled square. + let empty = Arc::new(Node::path(doc.alloc_id(), PathData::new(vec![]), Appearance::default())); + let mut members = vec![empty; 4999]; + let square = shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)); + members.push(Arc::new(Node::path(doc.alloc_id(), square, Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0)))); + let leaves = Node::group(doc.alloc_id(), members); + doc.symbols.push(Symbol { name: "Leaf".into(), art: Arc::new(leaves) }); + let leaf = Arc::new(Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Leaf".into(), xf: Affine::IDENTITY })); + let trees = Node::group(doc.alloc_id(), vec![leaf; 5000]); + doc.symbols.push(Symbol { name: "Tree".into(), art: Arc::new(trees) }); + let tree = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Tree".into(), xf: Affine::IDENTITY }); + doc.insert(Some(layer), usize::MAX, tree).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_LIMIT), "{:?}", out.warnings); + // 5,001 objects for the tree and each leaf: 3,198 leaves fit in 16,000,000. + let text = String::from_utf8(out.program).unwrap(); + assert_eq!(text.matches("\r\nf\r\n").count(), 3198, "the squares of the leaves written"); +} + #[test] fn a_stained_symbol_instance_is_written_in_its_stained_colors() { let mut doc = Document::new(200.0, 100.0); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 58947715ce..1cf0390ca4 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -36,6 +36,7 @@ const STROKES: &str = "strokes a plain line can't draw (inside or outside the pa pub(super) const TRANSPARENCY: &str = "transparency (opacity, blending modes, opacity masks) is left out of the editing data for other apps"; pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps"; const SWATCHES: &str = "gradient and pattern swatches are left out of the editing data for other apps"; +pub(super) const SYMBOL_LIMIT: &str = "symbol instances past 16,000,000 objects of symbol art in all are left out of the editing data for other apps"; const TEMPLATES: &str = "template layers are written as dimmed layers that don't print in the editing data for other apps"; pub(super) struct Writer<'a> { @@ -57,6 +58,8 @@ pub(super) struct Writer<'a> { next: HashMap, /// The document's brushes, read the first time a brushed stroke is written. brushes: Option>, + /// The objects of the symbol art written so far, within [`vectorcraft_doc::MAX_SYMBOL_NODES`]. + symbol_nodes: u64, } impl<'a> Writer<'a> { @@ -73,9 +76,23 @@ impl<'a> Writer<'a> { ids: HashSet::new(), next: HashMap::new(), brushes: None, + symbol_nodes: 0, } } + /// Whether the art of a symbol, `art`, may be written: the objects of the symbol art written + /// so far stay within [`vectorcraft_doc::MAX_SYMBOL_NODES`], as in the PDF part (instances of + /// symbols that hold instances multiply). Past it the art is left out, with a warning. + fn take_symbol(&mut self, art: &Node) -> bool { + let total = self.symbol_nodes.saturating_add(art.count() as u64); + if total > vectorcraft_doc::MAX_SYMBOL_NODES { + self.warn(SYMBOL_LIMIT); + return false; + } + self.symbol_nodes = total; + true + } + fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) { self.warnings.push(w.to_string()); @@ -234,6 +251,7 @@ impl<'a> Writer<'a> { self.line("u"); if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST + && self.take_symbol(&sym.art) { // Stained by the instance's fill, as the canvas draws it. let mut art = vectorcraft_brush::instance_art(&sym.art, n); @@ -540,6 +558,9 @@ impl<'a> Writer<'a> { for ig in &layout.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue }; + if !self.take_symbol(&sym.art) { + continue; + } self.warn(LIVE); let mut art_node = (*sym.art).clone(); // Strokes scale with the art, as on the canvas. From f41e40bbc65b8eca53d6281e6d25ef5fdde7a5de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 29 Oct 2026 10:27:33 -0700 Subject: [PATCH 010/674] 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 1812ccda0804f4edb52469b1ec48c70dedcf716f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 08:53:28 -0700 Subject: [PATCH 011/674] .ai open: keep the last zero byte of a Zstandard frame in the editing data The reader cut every trailing zero byte off the Zstandard data before decoding it, to drop the padding after the last frame. A frame can end in a zero byte itself, and cutting it left the frame short, so the file failed to open with "its Zstandard compression is damaged". The reader now decodes frame after frame and stops when only zeros are left. --- crates/eps/src/import/ai.rs | 8 ++++---- crates/eps/src/import/ai/tests.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index e71fc7db41..73e248ac58 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -141,11 +141,11 @@ impl Codec { flate2::read::ZlibDecoder::new(data).take(max + 1).read_to_end(&mut out).map_err(|_| damaged("its zlib compression"))?; } Codec::Zstd => { - // The data may be several frames one after the other, padded with zeros. - let end = data.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1); - let mut src = data.get(..end).unwrap_or_default(); + // The data may be several frames one after the other, padded with zeros. A frame + // can itself end in a zero byte, so the padding is what is left after the last frame. + let mut src = data; let mut frames = 0usize; - while !src.is_empty() { + while src.iter().any(|b| *b != 0) { frames += 1; if frames > MAX_FRAMES { return Err(damaged("its Zstandard compression")); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 721365c25a..c9acad3ec5 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1219,6 +1219,19 @@ fn many_zstandard_frames_are_read_in_one_pass_and_capped() { assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed()); } +/// A Zstandard frame that ends in a zero byte keeps it: only the zeros after the last frame are +/// padding. +#[test] +fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() { + // Magic number, a single-segment header with a 1-byte content size of 3, and one raw block + // (last, 3 bytes) holding `ab` and a zero byte. + let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0]; + for padding in [0, 64] { + let raw = [&b"%AI24_ZStandard_Data"[..], &frame, &frame, &vec![0; padding]].concat(); + assert_eq!(decode_private(&raw).unwrap(), b"ab\0ab\0"); + } +} + #[test] fn closing_brackets_without_their_opening_dont_rescan_the_stack() { let n = 200_000; From b4e28e504a0b5a6ed9b07bb53498da8e266180ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 08:53:28 -0700 Subject: [PATCH 012/674] .ai save: write the artboards in the recorded part of the document data The editing data put ArtboardArray and AIDocumentCanvasSize in the part of the /Document dictionary marked /NotRecorded. Apps that read the editing data do not read artboards from there: a file opened with one default artboard the size of the first, the other artboards and the names were lost, and the art landed one artboard's height above it. The two entries now close a /Recorded part, followed by an empty /NotRecorded one, as in the files users sent. --- crates/eps/src/ai_editing.rs | 10 +++-- crates/eps/src/ai_editing/tests.rs | 70 ++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index e89584b8e0..0ca9958b57 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -19,7 +19,8 @@ //! - Setup: `0 Bn` (no gradient definitions, §3), the color swatches (`%AI5_BeginPalette`, //! `0 0 Pb`, the Registration swatch, each swatch's color operator and `(name) Pc`, a color group as `0 (name) count Pg` //! before its swatches, `PB`), then the artboards as the `ArtboardArray` of the `/Document` -//! dictionary and the canvas size as its `AIDocumentCanvasSize`, on `%_` lines. +//! dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on `%_` +//! lines. //! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0 //! dimPercent 0 Lb` (14 operands; a color that isn't one of the preset layer colors has the //! index -1), `(name) Ln`, the layer's name as an XML id in an `/ArtDictionary`, its art and @@ -304,7 +305,10 @@ fn ruler_units(u: Unit) -> u8 { /// the canvas (`RulerOrigin`, `origin` being art space's origin there), its pixel aspect ratio /// (`PAR`), `DisplayMark` 0 (as in the files users sent), whether it is the selected one (the /// first) and its name; then the canvas's size. Apps that read the editing data drop a record that -/// lacks any of the first five. +/// lacks any of the first five. Both sit in the dictionary the `/Document` marks `/Recorded`, +/// followed by an empty `/NotRecorded` one, as in the files users sent: apps that read the editing +/// data do not read artboards from the `/NotRecorded` dictionary, and then place the art one +/// artboard's height above a default artboard. fn artboards(s: &mut String, doc: &Document, to_art: Affine, origin: (f64, f64)) { s.push_str("%AI9_BeginDocumentData\n%_/Document :\n%_/Dictionary :\n%_/Array :\n"); for (i, ab) in doc.artboards.iter().enumerate() { @@ -323,7 +327,7 @@ fn artboards(s: &mut String, doc: &Document, to_art: Affine, origin: (f64, f64)) } s.push_str("%_; (ArtboardArray) ,\n"); let _ = writeln!(s, "%_{CANVAS_SIZE} /Int (AIDocumentCanvasSize) ,"); - s.push_str("%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"); + s.push_str("%_; /Recorded ,\n%_/Dictionary : /NotRecorded ,\n%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"); } #[cfg(test)] diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index bede50515e..0fe80683bc 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -342,6 +342,76 @@ fn art_lies_on_its_artboard_in_ruler_space() { assert_eq!(bounds, Rect::new(10.0, 20.0, 30.0, 40.0)); } +/// A gray rectangle at `r` (document space) in `doc`'s first layer. +fn add_rect(doc: &mut Document, r: Rect) { + let rect = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0)); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, rect).unwrap(); +} + +/// The end of the document data: the artboards and the canvas size in the `/Recorded` part of the +/// `/Document` dictionary, then an empty `/NotRecorded` part. +const RECORDED: &str = "%_; (ArtboardArray) ,\n%_16383 /Int (AIDocumentCanvasSize) ,\n%_; /Recorded ,\n%_/Dictionary : /NotRecorded ,\n%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"; + +/// One letter-size artboard: the art 36 points in from its top-left corner, the artboard's record +/// and the boxes, with the artboards in the `/Recorded` part of the `/Document` dictionary. +#[test] +fn one_artboard_is_recorded_with_its_art_in_place() { + let mut doc = Document::new(612.0, 792.0); + doc.artboards[0].name = "Page".into(); + add_rect(&mut doc, Rect::new(36.0, 36.0, 576.0, 756.0)); + let text = program(&doc); + for line in [ + "%%BoundingBox: 36 -756 576 -36\n", + "%AI3_Cropmarks: 0 -792 612 0\n", + "%AI3_TemplateBox: 306.5 -396.5 306.5 -396.5\n", + "\n36 -36 m\n", + "%_0 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_612 -792 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_7885 7795 /RealPoint\n%_ (RulerOrigin) ,\n", + "%_(Page) /UnicodeString (Name) ,\n%_; ,\n", + RECORDED, + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + let read = read_back(&doc); + assert_eq!(read.artboards.iter().map(|a| (a.name.as_str(), a.rect)).collect::>(), [("Page", Rect::new(0.0, 0.0, 612.0, 792.0))]); + let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(bounds, Rect::new(36.0, 36.0, 576.0, 756.0)); +} + +/// Two named artboards of different sizes, tops aligned: each record holds its corners in art +/// space and its top-left corner on the canvas, where the two together are centered. +#[test] +fn artboards_of_different_sizes_keep_their_names_and_places() { + let mut doc = Document::new(400.0, 300.0); + doc.artboards[0].name = "Front".into(); + let mut back = doc.artboards[0].clone(); + (back.id, back.name, back.rect) = (2, "Back".into(), Rect::new(440.0, 0.0, 740.0, 500.0)); + doc.artboards.push(back); + add_rect(&mut doc, Rect::new(50.0, 50.0, 150.0, 100.0)); + add_rect(&mut doc, Rect::new(490.0, 50.0, 590.0, 100.0)); + let text = program(&doc); + for line in [ + "%AI3_Cropmarks: 0 -300 400 0\n", + "%AI3_TemplateBox: 370.5 -250.5 370.5 -250.5\n", + "\n50 -50 m\n", + "\n490 -50 m\n", + "%_0 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_400 -300 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_7821 7941 /RealPoint\n%_ (RulerOrigin) ,\n", + "%_1 /Bool (IsArtboardSelected) ,\n%_(Front) /UnicodeString (Name) ,\n", + "%_440 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_740 -500 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_8261 7941 /RealPoint\n%_ (RulerOrigin) ,\n", + "%_0 /Bool (IsArtboardSelected) ,\n%_(Back) /UnicodeString (Name) ,\n", + RECORDED, + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + let read = read_back(&doc); + assert_eq!( + read.artboards.iter().map(|a| (a.name.as_str(), a.rect)).collect::>(), + [("Front", Rect::new(0.0, 0.0, 400.0, 300.0)), ("Back", Rect::new(440.0, 0.0, 740.0, 500.0))] + ); + let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(bounds, Rect::new(50.0, 50.0, 590.0, 100.0)); +} + #[test] fn a_pdf_carries_the_data_on_its_first_page() { let doc = sample(); From 971eaddf21bfa1e56e7cec53e142f8a076fedd1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 10:51:25 -0700 Subject: [PATCH 013/674] Docs: a saved .ai carries an editing copy of the art docs/file-format-parity.md said the PDF-compatible .ai writer never writes editing data. It now lists what the editing copy holds, what is written as plain paths, and the editingData option. --- docs/file-format-parity.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ce464cc58c..915ebc126b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -18,7 +18,7 @@ from the public specifications, and users' own `.ai` files are used locally only | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| | Formats opened or placed | ~30 | 26 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, JPEG 2000, PICT, Pixar, Word `.doc`, PS | -| Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (no Illustrator editing data) or as legacy version 7 (layers and groups, one artboard per file) | +| Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, artboards) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 17 | missing: DWG, 3D (OBJ/USDA/glTF); extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -49,8 +49,13 @@ private editing data. VectorCraft: A PDF-compatible `.ai` opens on its PDF part's trim boxes (its artboards), the bleed boxes round them becoming the document's bleed, so art in the bleed shows outside the artboard, within the bleed guide (#1266). A PDF saved with its editing data (`AIPDFPrivateData`) opens the same way. -- **Writes** a PDF-compatible `.ai` (Save As › `ai`): Illustrator opens it as plain art. It never writes - Illustrator's private editing data, which is undocumented. +- **Writes** a PDF-compatible `.ai` (Save As › `ai`). With the option `editingData` (on by default, Include + Editing Data for Other Apps) every page's `PieceInfo` also carries an editing copy of the art in + `AIPrivateData` streams, in the form VectorCraft's `.ai` reader reads: layers and sublayers, groups, paths with + their fills and strokes (a compound path as one path of all its subpaths), process, spot and global colors, swatches and color groups, guides, + hidden and locked objects, object names and every artboard with its name. Type, gradients, patterns, images, + symbols, clipping groups and live objects are written as plain filled and stroked paths, each with a warning; + transparency and effects other than geometry effects are left out. - **Writes** a legacy `.ai` of version 7 (Save As › `ai` › Version: Legacy (version 7), `aiVersion: "7"`): the PostScript form, from the published *Adobe Illustrator File Format Specification* version 7.0 ([PRONOM fmt/423](https://www.nationalarchives.gov.uk/PRONOM/fmt/423)), which apps reading `.ai` open with its From b6f0b4de2bca7b4b57590938ceff807ad3935e05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 11:33:50 -0700 Subject: [PATCH 014/674] .ai save: the editing copy warns about missing placed files A .ai saved with pdfCompatible false resolved placed files for the editing copy but dropped the warnings for the ones it couldn't find, so a missing placed file was written as its preview without a warning. The save now keeps those warnings. --- crates/engine/src/cmd/fileio/save.rs | 14 ++++++++----- crates/engine/src/tests/placed_document.rs | 24 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 2a22442c99..22ff2365f5 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -637,17 +637,21 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res } // The art with placed files resolved as the pages draw them, also when the pages are blank. let resolved; - let art: &Document = if pdf_compatible { - &pages + let (art, mut resolved_warnings): (&Document, Vec) = if pdf_compatible { + (&pages, Vec::new()) } else { - resolved = crate::cmd::place::document::full_documents(&edited).0; - &resolved + let (d, w) = crate::cmd::place::document::full_documents(&edited); + resolved = d; + (&resolved, w) }; let o = vectorcraft_eps::AiEditingOptions { title: doc.title.clone(), created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time), }; - vectorcraft_eps::ai_private_data(art, &o).map(Some).map_err(|e| bad(cmd, e)) + let (data, lost) = vectorcraft_eps::ai_private_data(art, &o).map_err(|e| bad(cmd, e))?; + // Placed files that weren't found are written as their previews here too. + resolved_warnings.extend(lost); + Ok(Some((data, resolved_warnings))) }; let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?; warnings.extend(placed_warnings); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index eb3164db8f..45ac249705 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -288,6 +288,30 @@ fn ai_export_public_aliases_preserve_missing_placed_links() { } } +/// The `.ai` editing copy for other apps draws a missing placed file as its preview, with the +/// pages or without them, and says so. +#[test] +fn ai_editing_copy_warns_about_missing_placed_files() { + let dir = Folder::new("placed-ai-editing-copy-missing"); + let src = dir.file("logo.vectorcraft"); + star_source(&src, "placed-ai-editing-copy-missing-unique"); + let mut s = session(); + place(&mut s, &src); + let parent = dir.file("parent.vectorcraft"); + save(&mut s, &parent); + std::fs::remove_file(&src).unwrap(); + open(&mut s, &parent); + let doc = &s.doc().unwrap().doc; + let (_, missing) = cmd::place::document::full_documents(doc); + assert!(!missing.is_empty()); + for compatible in [true, false] { + let enc = cmd::fileio::encode_all(doc, "ai", &json!({"pdfCompatible": compatible})).unwrap(); + for w in &missing { + assert!(enc.warnings.contains(w), "pdfCompatible {compatible}: {w:?} not in {:?}", enc.warnings); + } + } +} + /// Include Linked Files must retain relinkable objects when only their previews are available. #[test] fn native_included_links_keep_missing_placed_documents_editable() { From 891766a5ed1df2ccb2da3ac4b188068407f2d035 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 18:34:18 -0700 Subject: [PATCH 015/674] 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 a015666bd554a9614a5bd87eb4a09f6165e3d16b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 20:19:57 -0700 Subject: [PATCH 016/674] PDF import: a PDF opened without its VectorCraft document saves under a new name LoadOptions::is_partial now counts native off. A PDF saved with Preserve Editing and opened from its pages instead of the document it carries kept its save path, so Save wrote over the file and dropped that document. Save now asks for a name, as for a page range or another box. --- crates/engine/src/cmd/fileio/pdfimport.rs | 6 +++--- crates/engine/src/cmd/fileio/tests_pdffidelity.rs | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 28aeecd5dd..e646c43f89 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -99,10 +99,10 @@ impl LoadOptions { } /// Does the document read only part of the file, or read it differently (a page range, another - /// box, a password, without its hidden layers)? Writing it back would lose the rest, so Save - /// doesn't (it asks for a name). + /// box, a password, without its hidden layers, without the VectorCraft document it carries)? + /// Writing it back would lose the rest, so Save doesn't (it asks for a name). pub fn is_partial(&self) -> bool { - self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers + self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible diff --git a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs index 862f3f0bed..86cb84cfcb 100644 --- a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs @@ -141,6 +141,8 @@ fn load_options_read_text_and_layers() { assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back"); let d = LoadOptions::default(); assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false)); + let n = LoadOptions { native: false, ..Default::default() }; + assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back"); } #[test] From 5dc36cac8d5b6fbdda59d5d0eb76647ab3893b2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 20:19:57 -0700 Subject: [PATCH 017/674] .ai save: the editing data comments say what VectorCraft writes The comments on the %%Creator line and on the artboards' Recorded and NotRecorded parts of the document dictionary now describe what the writer writes. --- crates/eps/src/ai_editing.rs | 18 +++++++----------- crates/eps/src/ai_editing/tests.rs | 2 +- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 0ca9958b57..c818ecbf1e 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -84,12 +84,10 @@ const TARGET_RESOLUTION: u32 = 800; /// The gridlines' gray: VectorCraft's default grid color (200 of 255). const GRID_GRAY: f64 = 200.0 / 255.0; -/// `%%Creator`. Apps that read the editing data take the file's version from this line while they -/// read the header, and only a creator that names the format's app gets the version that measures -/// `%AI3_TemplateBox` on a canvas of [`CANVAS_SIZE`] points; any other creator places the art -/// 3,871.5 points off its artboard. The text holds no version number (a number in it would be -/// read as the format's version). -const CREATOR_TEXT: &str = "VectorCraft, editing data for Illustrator"; // brand-ok: the creator the format's version is read from +/// `%%Creator`: the creator line VectorCraft writes in the header of the editing data. It names +/// VectorCraft and the format's app, and holds no version number; the version is written on its +/// own in `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). +const CREATOR_TEXT: &str = "VectorCraft, editing data for Illustrator"; // brand-ok: the creator line VectorCraft writes /// The first line of a PostScript file (the DSC version comment). const PS_HEADER: &str = "%!PS-Adobe-3.0"; // brand-ok: the PostScript header comment @@ -304,11 +302,9 @@ fn ruler_units(u: Unit) -> u8 { /// bottom-right corners in art space (`PositionPoint1`, `PositionPoint2`), its top-left corner on /// the canvas (`RulerOrigin`, `origin` being art space's origin there), its pixel aspect ratio /// (`PAR`), `DisplayMark` 0 (as in the files users sent), whether it is the selected one (the -/// first) and its name; then the canvas's size. Apps that read the editing data drop a record that -/// lacks any of the first five. Both sit in the dictionary the `/Document` marks `/Recorded`, -/// followed by an empty `/NotRecorded` one, as in the files users sent: apps that read the editing -/// data do not read artboards from the `/NotRecorded` dictionary, and then place the art one -/// artboard's height above a default artboard. +/// first) and its name; then the canvas's size. Every record holds all of these entries. The +/// artboards and the canvas size are written in the `/Recorded` part of the `/Document` +/// dictionary, followed by an empty `/NotRecorded` part. fn artboards(s: &mut String, doc: &Document, to_art: Affine, origin: (f64, f64)) { s.push_str("%AI9_BeginDocumentData\n%_/Document :\n%_/Dictionary :\n%_/Array :\n"); for (i, ab) in doc.artboards.iter().enumerate() { diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 0fe80683bc..437a4f5fa5 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -329,7 +329,7 @@ fn art_lies_on_its_artboard_in_ruler_space() { assert!(text.contains(line), "{line}\n{text}"); } // The creator names the format's app, before the canvas size and the template box, and holds - // no version number another app could read as the format's version. + // no version number (the version is written in `%%AI8_CreatorVersion`). let creator = text.lines().find_map(|l| l.strip_prefix("%%Creator: ")).unwrap(); assert!(creator.contains("Illustrator"), "{creator}"); assert!(!creator.contains("88") && !creator.chars().any(|c| c.is_ascii_digit()), "{creator}"); From bb80e741bff3f4d3ae7702077fed9f76d49e4d32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 20:39:46 -0700 Subject: [PATCH 018/674] .ai save: the editing data tests build static symbols Symbol has a dynamic field on main; the tests set it to false. --- crates/eps/src/ai_editing/tests.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 437a4f5fa5..915cda084d 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -590,7 +590,7 @@ fn unsupported() -> Document { let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); doc.insert(Some(layer), usize::MAX, t).unwrap(); let art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill(solid(Color::rgb(0.0, 1.0, 0.0)))); - doc.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((150.0, 10.0)) }); doc.insert(Some(layer), usize::MAX, instance).unwrap(); let mut faded = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(170.0, 10.0, 190.0, 30.0)), fill(solid(Color::BLACK))); @@ -696,7 +696,7 @@ fn inline_graphics_in_type_are_written_as_their_art() { shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0), ); - doc.symbols.push(Symbol { name: "Mark".into(), art: Arc::new(mark) }); + doc.symbols.push(Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) }); let style = vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }; let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "A", style.clone()); t.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("Mark"), style)); @@ -733,10 +733,10 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() { let square = shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)); members.push(Arc::new(Node::path(doc.alloc_id(), square, Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0)))); let leaves = Node::group(doc.alloc_id(), members); - doc.symbols.push(Symbol { name: "Leaf".into(), art: Arc::new(leaves) }); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaves) }); let leaf = Arc::new(Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Leaf".into(), xf: Affine::IDENTITY })); let trees = Node::group(doc.alloc_id(), vec![leaf; 5000]); - doc.symbols.push(Symbol { name: "Tree".into(), art: Arc::new(trees) }); + doc.symbols.push(Symbol { dynamic: false, name: "Tree".into(), art: Arc::new(trees) }); let tree = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Tree".into(), xf: Affine::IDENTITY }); doc.insert(Some(layer), usize::MAX, tree).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); @@ -755,7 +755,7 @@ fn a_stained_symbol_instance_is_written_in_its_stained_colors() { shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0), ); - doc.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let mut instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((50.0, 10.0)) }); instance.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); let stained = vectorcraft_brush::instance_art(&doc.symbols[0].art, &instance); @@ -812,7 +812,7 @@ fn geometry_effects_in_a_symbol_are_written_as_their_result() { let mut ap = Appearance::basic(solid(Color::BLACK), Paint::None, 0.0); ap.effects.push(vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 5}), visible: true }); let art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), ap); - doc.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) }); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((50.0, 20.0)) }); doc.insert(Some(layer), usize::MAX, instance).unwrap(); let back = read_back(&doc); @@ -836,7 +836,7 @@ fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { let mut ap = (*im.appearance).clone(); ap.effects.push(vectorcraft_doc::Effect { id: "adjust.shiftToColor".into(), params: shift, visible: true }); im.appearance = ap.into(); - doc.symbols.push(Symbol { name: "Picture".into(), art: Arc::new(im) }); + doc.symbols.push(Symbol { dynamic: false, name: "Picture".into(), art: Arc::new(im) }); let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Picture".into(), xf: Affine::translate((50.0, 20.0)) }); doc.insert(Some(layer), usize::MAX, instance).unwrap(); let back = read_back(&doc); From 2ca27de40bb3d689e445060219db55c4c57c7617 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 20:57:37 -0700 Subject: [PATCH 019/674] .ai save: the no-PDF-content warning names the editing data A .ai saved with pdfCompatible false warned that other apps show empty pages, also when the file carries the editing copy of its art. With the editing copy the warning now says that apps that read its editing data open it; with editingData false it is unchanged. --- crates/engine/src/cmd/fileio/save.rs | 7 ++++++- crates/engine/src/tests/saveoptions.rs | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 1a9d77ebb0..35cef3e56f 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -574,6 +574,9 @@ fn blank_pages(doc: &Document) -> Document { /// Why a `.ai` file saved without PDF content looks empty elsewhere. const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages"; +/// The same, for a file that carries the editing copy of its art. +const NOT_PDF_COMPATIBLE_EDITING: &str = + "saved without PDF content: VectorCraft and apps that read its editing data open it, other apps show empty pages"; /// `e`, an error of the export encoders, under the save command `cmd` instead of /// `document.export`. @@ -631,6 +634,7 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res }; let native = || super::native::ai_native(cmd, doc, &native_options); let other_apps: AiEditingData = super::encode::options(f, ¶ms)?; + let carries_editing = std::cell::Cell::new(false); let private = || { if !other_apps.editing_data.unwrap_or(true) { return Ok(None); @@ -651,12 +655,13 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res let (data, lost) = vectorcraft_eps::ai_private_data(art, &o).map_err(|e| bad(cmd, e))?; // Placed files that weren't found are written as their previews here too. resolved_warnings.extend(lost); + carries_editing.set(true); Ok(Some((data, resolved_warnings))) }; let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?; warnings.extend(placed_warnings); if !pdf_compatible { - warnings.push(NOT_PDF_COMPATIBLE.to_string()); + warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string()); } Ok(Encoded { warnings, ..Encoded::one(bytes) }) } diff --git a/crates/engine/src/tests/saveoptions.rs b/crates/engine/src/tests/saveoptions.rs index ff17ef34eb..feca824014 100644 --- a/crates/engine/src/tests/saveoptions.rs +++ b/crates/engine/src/tests/saveoptions.rs @@ -196,7 +196,11 @@ fn ai_without_pdf_content_and_compression() { }; let (full, _) = ai(&mut s, json!({})); let (blank, warnings) = ai(&mut s, json!({"pdfCompatible": false})); - assert!(warnings.as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("without PDF content")), "{warnings}"); + let says = |w: &Value, text: &str| w.as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains(text)); + assert!(says(&warnings, "without PDF content") && says(&warnings, "apps that read its editing data open it"), "{warnings}"); + // Without the editing copy, other apps show empty pages. + let (_, plain) = ai(&mut s, json!({"pdfCompatible": false, "editingData": false})); + assert!(says(&plain, "VectorCraft opens it as before") && !says(&plain, "editing data"), "{plain}"); // The pages are empty (an import of a page finds no art), the document comes back whole. let page = |s: &mut Session, b: &[u8]| { s.execute("document.open", &json!({"name": "x.ai", "dataBase64": vectorcraft_format::base64_encode(b), "pages": "1"})).unwrap(); From b949038a2b15efc0ef6d0e335af098fd30da595e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:09:39 -0700 Subject: [PATCH 020/674] .ai save: the editing copy draws the artboards' background colors The PDF pages of a .ai draw each artboard's background color (Include Artboard Fill, on by default), but the editing copy of the art left it out, so the two differed and the file reopened from its PDF part. The editing copy now takes the same option. --- crates/engine/src/cmd/fileio/save.rs | 4 +++- crates/engine/src/cmd/fileio/tests_artboard_fill.rs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 35cef3e56f..85fea0cbd2 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -648,11 +648,13 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res resolved = d; (&resolved, w) }; + // With the artboards' background colors, as the pages draw them. + let art = super::export::with_artboard_fills(art, ¶ms, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?; let o = vectorcraft_eps::AiEditingOptions { title: doc.title.clone(), created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time), }; - let (data, lost) = vectorcraft_eps::ai_private_data(art, &o).map_err(|e| bad(cmd, e))?; + let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?; // Placed files that weren't found are written as their previews here too. resolved_warnings.extend(lost); carries_editing.set(true); diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs index 28e170e063..9a7684686a 100644 --- a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -97,6 +97,18 @@ fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards() assert_eq!(back.layers.len(), doc.layers.len(), "no art made of it"); } +#[test] +fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() { + let mut s = session(); + let opts = LoadOptions { native: false, ..Default::default() }; + for (more, fill) in [(json!({}), true), (json!({"includeArtboardFill": false}), false)] { + let l = load::load_with("a.ai", &file(&mut s, with(json!({"format": "ai"}), &more)), &opts).unwrap(); + assert!(l.editing_data && !l.restored, "{more}: {:?}", l.warnings); + let names: Vec = l.doc.layers.iter().filter_map(|l| l.name.clone()).collect(); + assert_eq!(names.iter().any(|n| n == "Artboard Fill"), fill, "{more}: {names:?}"); + } +} + #[test] fn eps_and_postscript_print_draw_the_color() { let mut s = session(); From 46cb088eae5e4535cadcc01626d300ae0ff407ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:42:42 -0700 Subject: [PATCH 021/674] Recolor Artwork: color sliders edit the selected row's new color in a chosen mode The Assign tab gets a Color Mode menu (HSB, RGB, CMYK, Lab, and Tint when the row's new color is a spot color of the Limit to Library library) and its sliders under the rows. They edit the first selected row's new color and are disabled with no row selected. Once they have edited a color in a mode, the preview and OK send recolor.apply with model "new", so the art takes the color in that mode. recolor.apply rows take an optional tint (percent, default 100): art linked to the row's global or spot library swatch takes that share of its tint. recolor.randomize keeps a row's tint. --- crates/engine/src/cmd/recolor.rs | 34 +++- crates/engine/src/tests/recolor.rs | 27 +++ crates/ui-egui/src/dialogs/recolor.rs | 227 ++++++++++++++++++++++++-- crates/ui-egui/src/tests/recolor.rs | 138 ++++++++++++++++ docs/control-protocol.md | 7 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 7 files changed, 418 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 82d1f1cfd5..5ff152a855 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", has_doc, apply ), @@ -260,6 +260,9 @@ struct Row { from: Vec, to: Option, exclude: bool, + /// The tint (0..1) of a global or spot swatch the new color is (with `limitTo`): art linked to + /// the swatch takes this share of the tint the method gives it. + tint: f32, } impl Row { @@ -280,7 +283,9 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { }; let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}"))); match p.get("map") { - Some(Value::Object(m)) => m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false })).collect(), + Some(Value::Object(m)) => { + m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0 })).collect() + } Some(Value::Array(rows)) => rows .iter() .map(|r| { @@ -289,7 +294,8 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { Some(v) => vec![cur(v)?], None => return Err(bad(cmd, "each row needs `from`")), }; - Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)? }) + let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32; + Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint }) }) .collect(), _ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")), @@ -303,6 +309,8 @@ struct Link { name: String, global: bool, color: Color, + /// The row's tint of the swatch (0..1). + tint: f32, } /// A global swatch of the color group `recolor.apply` rewrites: its name, the color it is @@ -338,9 +346,12 @@ impl ColorMap { let Some(to) = r.new_color() else { continue }; let i = out.rows.len(); let colors: Vec = r.from.iter().map(Match::color).collect(); - out.rows.push(RowMap::new(method, &colors, to).with_own_model(own_model)); + let link = links.get(n).cloned().flatten(); + // Colors that can't link to the swatch take the row's tint of it too. + let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint)); + out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(own_model)); out.tos.push(to); - out.links.push(links.get(n).cloned().flatten()); + out.links.push(link); for m in &r.from { match m { Match::Key(k) => out.keys.entry(*k).or_insert(i), @@ -365,7 +376,8 @@ impl ColorMap { } /// Recolour a colour that can link to a swatch: a row whose new colour is a global or spot - /// swatch links its colours to it (at their tints; shades and other hues stay unlinked), a + /// swatch links its colours to it (at their tints times the row's tint; shades and other hues + /// stay unlinked), a /// process swatch gives its colour in its own model; a color linked to a global swatch of the /// rewritten group that takes the row's new color keeps its link (at its tint in the row) when /// the row gives it the new color in that color's model; @@ -388,7 +400,7 @@ impl ColorMap { } let new = match (l, row.tint(*c)) { (Some(l), Some(t)) if l.global => { - let t = t.clamp(0.0, 1.0); + let t = (t * l.tint).clamp(0.0, 1.0); let shown = l.color.tinted(t); let changed = link.as_deref() != Some(l.name.as_str()) || *tint != t || *c != shown; (*c, *link, *tint) = (shown, Some(l.name.clone()), t); @@ -487,7 +499,8 @@ fn apply(s: &mut Session, p: &Value) -> Result { let mut added = vec![]; let links: Vec> = row_swatches .iter() - .map(|w| { + .zip(&rows) + .map(|(w, row)| { let w = w.as_ref()?; let name = match d.swatch(&w.name) { Some(x) if x.paint == w.paint => w.name.clone(), @@ -499,7 +512,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { } }; let color = d.global_color(&name).filter(|_| w.global).or(w.paint.color())?; - Some(Link { name, global: w.global, color }) + Some(Link { name, global: w.global, color, tint: row.tint }) }) .collect(); // The group's global swatches that its rewrite gives a color: art linked to one of them @@ -558,6 +571,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result { if r.exclude { row["exclude"] = json!(true); } + if r.tint < 1.0 { + row["tint"] = json!(f64::from((r.tint * 10_000.0).round()) / 100.0); + } row }) .collect(); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 32bff5b140..ecf71f91a2 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -537,6 +537,33 @@ fn recolor_to_a_library_spot_colour_links_it_and_adds_the_swatch() { assert_eq!(r["swatches"], json!(["Leaf"])); } +/// A row's `tint` gives the art linked to the row's spot color that share of its tint; +/// randomize keeps it on the row, and a tint that is not a number is refused. +#[test] +fn a_rows_tint_tints_the_spot_color_the_art_links_to() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 101", "color": {"c": 0.0, "m": 1.0, "y": 0.0, "k": 0.0}, "spot": true})); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink 101"], "name": "Inks"}))["data"].as_str().unwrap().to_string(); + let lib = run(&mut s, "swatch.library.load", json!({"data": data, "name": "inks.vcswatches"}))["library"].as_str().unwrap().to_string(); + run(&mut s, "swatch.delete", json!({"names": ["Ink 101"]})); + let red = rect(&mut s, json!("#e02010")); + select_all(&mut s); + let map = json!([{"from": ["rgb 224 32 16"], "to": "cmyk 0 100 0 0", "tint": 40}]); + run(&mut s, "recolor.apply", json!({"map": map, "limitTo": lib})); + match s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, tint } => { + assert_eq!(swatch.as_deref(), Some("Ink 101"), "linked to the spot color"); + assert!((tint - 0.4).abs() < 1e-4, "at the row's tint: {tint}"); + assert!(close(color, Color::cmyk(0.0, 1.0, 0.0, 0.0).tinted(0.4)), "{color:?}"); + } + p => panic!("{p:?}"), + } + let r = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": false})); + assert_eq!(r["map"][0]["tint"], json!(40.0), "{r}"); + let e = s.execute("recolor.apply", &json!({"map": [{"from": ["rgb 224 32 16"], "to": "#ff0000", "tint": "40"}]})).unwrap_err(); + assert!(e.to_string().contains("`tint` must be a number"), "{e}"); +} + #[test] fn model_param_chooses_the_model_of_the_new_colour() { // RGB art in a CMYK document: by default a CMYK replacement comes out RGB (#2170). diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index bdd5094095..30d22a4ba2 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -5,7 +5,10 @@ //! Grays (they open as OK on art last left them), the rows (click to select, Shift or Cmd/Ctrl-click //! to add; a row's arrow excludes or includes it; the hex field edits its new colour, and a //! double-click on it opens the Color Picker, -//! whose OK sets it in the model it was picked in), Merge and Separate, Randomize order or +//! whose OK sets it in the model it was picked in), the color mode menu and its sliders (HSB, RGB, +//! CMYK or Lab, and Tint when the new color is a spot color of the library), which edit the +//! first selected row's new color (once they have, OK gives the art each new color in its own +//! model), Merge and Separate, Randomize order or //! saturation and brightness, Reset, the Method and Limit to Library (its folder button imports a //! library file and limits to it; a library's colours apply as its swatches: a spot colour stays a //! spot colour, and joins the document's swatches). Edit tab: a hue and @@ -16,11 +19,13 @@ //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new //! colours as a colour group named `groupName`. //! -//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?}]), `colors` (null: Auto, or a -//! count), `method`, `preserveWhite`, `preserveBlack`, `preserveGrays`, `limitTo` (library id, -//! "document" for the document's swatches, "" for none), `group`, `groupName`, `tab` (`assign` or -//! `edit`), `rule` (harmony id), `linked`, `preview`. Changing `colors`, a preserve flag or -//! `limitTo` reduces the rows again. +//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot +//! color}]), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`, +//! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none), +//! `group`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, +//! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for +//! a gray and Tint for a spot color). Changing `colors`, a preserve flag or `limitTo` reduces the +//! rows again. use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -32,6 +37,7 @@ use vectorcraft_engine::cmd::swatchlib; use super::{DialogSpec, form}; use crate::panels::c32; +use crate::panels::color::{Mode, components, from_components, track_color}; use crate::panels::swatches::{DOCUMENT_SWATCHES, colour_libraries, limit_key}; use crate::state::Dialog; use crate::theme::{self, Tokens}; @@ -56,11 +62,21 @@ const CURRENT_W: f32 = 250.0; /// Diameter of the Edit tab's colour wheel. const WHEEL: f32 = 220.0; /// Height of the rows table, and of either tab (so switching tabs doesn't resize the dialog). -const TABLE_H: f32 = 220.0; +const TABLE_H: f32 = 182.0; const TAB_H: f32 = 400.0; const PRESETS: [&str; 5] = ["Custom", "1 Color Job", "2 Color Job", "3 Color Job", "Color Library"]; /// The id of row `i`'s new colour chip, with `i`. const NEW_CHIP: &str = "recolor-new"; +/// The color modes of the sliders under the rows; a row whose new color is a spot color of the +/// library also has Tint. +const SLIDER_MODES: [Mode; 4] = [Mode::Hsb, Mode::Rgb, Mode::Cmyk, Mode::Lab]; +/// Widths of a color slider and of its number field. +const SLIDER_W: f32 = 170.0; +const SLIDER_FIELD_W: f32 = 48.0; +/// Set once the sliders have edited a new color in a mode: OK then sends `model: "new"`. +const SLID: &str = "__slid"; +/// The slider values last shown: `{row, key, mode, v}` (HSB keeps its hue at no saturation). +const COMPS: &str = "__comps"; /// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?}`) on the selected art and, /// with `group`, on that colour group: art is reduced to as many rows as the group has colours, @@ -187,6 +203,14 @@ fn to_color(row: &Value) -> Option { color_value(&row["to"]) } +/// Give `row` the new color `c`, without a tint of the spot color it had. +fn set_to(row: &mut Value, c: &Color) { + row["to"] = key(c); + if let Some(r) = row.as_object_mut() { + r.remove("tint"); + } +} + fn excluded(row: &Value) -> bool { row["exclude"].as_bool().unwrap_or(false) } @@ -208,6 +232,10 @@ fn apply_params(d: &Dialog) -> Value { json!({"group": g, "groupColors": colors, "rename": rename}) }); let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); + // The art takes a color edited with the sliders in the mode they showed. + if d.bool(SLID) { + p["model"] = json!("new"); + } if let (Some(Value::Object(g)), Some(p)) = (group, p.as_object_mut()) { p.extend(g.into_iter().filter(|(_, v)| !v.is_null())); } @@ -265,7 +293,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: Color) -> Dialog { let mut rs = rows(&d); if let Some(r) = rs.get_mut(i) { - r["to"] = key(&c); + set_to(r, &c); snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); } @@ -393,7 +421,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut let (nr, _) = ui.allocate_exact_size(vec2(46.0, 20.0), Sense::hover()); let nresp = ui.interact(nr, egui::Id::unique((NEW_CHIP, i)), Sense::click()); let to = to_color(row).unwrap_or_default(); - chip(ui, nr, to, off); + chip(ui, nr, to.tinted(row_tint(row)), off); if nresp.clicked() { clicked = Some(i); } @@ -406,7 +434,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut if let Some(h) = widgets::hex_field_named(ui, ("recolor-hex", i), Some(&hex_name), &hex) && let Some(c) = crate::panels::color::parse_hex(&h) { - row["to"] = key(&keep_model(to, c)); + set_to(row, &keep_model(to, c)); changed = true; } }); @@ -461,7 +489,11 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut if widgets::icon_button(ui, "rotate-ccw", tl!("Reset the rows to the artwork's colors"), false, 24.0).clicked() { d.fields.remove("__reduced"); } + let target = SliderTarget::of(app, d, rows); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target)); }); + ui.add_space(6.0); + changed |= sliders(app, ui, d, rows); ui.add_space(8.0); egui::Grid::new("recolor-options").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { ui.label(egui::RichText::new(tl!("Method:")).color(t.text_dim)); @@ -530,6 +562,181 @@ fn arrow(ui: &Ui, r: Rect, on: bool, hovered: bool) { } } +/// The tint (0..1) `row` gives its spot color (1 without one). +fn row_tint(row: &Value) -> f32 { + row["tint"].as_f64().map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32) +} + +/// The `sliderMode` id of `m` (`hsb`, `rgb`, `cmyk`, `lab`). +fn mode_id(m: Mode) -> String { + serde_json::to_value(m).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() +} + +/// The name of the spot color of the library (Limit to Library) that new color `c` is. +fn spot_of(app: &VectorcraftApp, d: &Dialog, c: &Color) -> Option { + let lib = d.str("limitTo"); + if lib.is_empty() { + return None; + } + let k = ColorKey::of(c); + swatchlib::library_swatches(&app.session, &lib)? + .into_iter() + .find(|w| w.spot && w.paint.color().is_some_and(|x| ColorKey::of(&x) == k)) + .map(|w| w.name) +} + +/// The mode the sliders show new color `c` in, `None` for Tint: the mode picked in the menu, else +/// `c`'s own model (HSB for a gray), or Tint for a spot color (`spot`). +fn slider_mode(d: &Dialog, c: &Color, spot: bool) -> Option { + let picked = d.str("sliderMode"); + match SLIDER_MODES.into_iter().find(|m| mode_id(*m) == picked) { + Some(m) => Some(m), + None if spot => None, + None => Some(match Mode::of(c) { + Mode::Grayscale => Mode::Hsb, + m => m, + }), + } +} + +/// The values the sliders show for row `i`'s new color `c` in `mode`: those they set last while +/// the color is the one they set, else `c`'s. +fn slider_values(d: &Dialog, rows: &[Value], i: usize, c: &Color, mode: Mode) -> Vec { + let held = d.fields.get(COMPS).filter(|s| s["row"] == json!(i) && s["key"] == rows[i]["to"] && s["mode"] == json!(mode_id(mode))); + let v: Option> = held.and_then(|s| s["v"].as_array()).map(|a| a.iter().filter_map(Value::as_f64).map(|x| x as f32).collect()); + v.filter(|v| v.len() == mode.labels().len()).unwrap_or_else(|| components(mode, c)) +} + +/// What the color sliders edit: the first selected row, its new color, and the name of the +/// library's spot color that color is. +struct SliderTarget { + row: Option, + color: Option, + spot: Option, +} + +impl SliderTarget { + fn of(app: &VectorcraftApp, d: &Dialog, rows: &[Value]) -> Self { + let row = selection(d).into_iter().filter(|i| *i < rows.len()).min(); + let color = row.and_then(|i| to_color(&rows[i])); + let spot = color.and_then(|c| spot_of(app, d, &c)); + Self { row, color, spot } + } + + /// The mode the sliders show (`None`: Tint). + fn mode(&self, d: &Dialog) -> Option { + slider_mode(d, &self.color.unwrap_or_default(), self.spot.is_some()) + } +} + +/// The color mode menu of the sliders (HSB, RGB, CMYK, Lab, and Tint for a spot color), drawn +/// right to left: the menu, then its label. +fn mode_menu(ui: &mut Ui, d: &mut Dialog, target: &SliderTarget) { + let t = Tokens::get(ui.ctx()); + let mut labels: Vec<&str> = SLIDER_MODES.iter().map(|m| m.label()).collect(); + if target.spot.is_some() { + labels.push("Tint"); + } + let current = target.mode(d).map_or("Tint", Mode::label); + // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. + let chosen = ui + .add_enabled_ui(target.color.is_some(), |ui| { + widgets::dropdown_named(ui, "recolor-slider-mode", Some(tl!("Color Mode:")), current, &labels, 90.0) + }) + .inner; + if let Some(i) = chosen { + d.fields.insert("sliderMode".into(), json!(SLIDER_MODES.get(i).map_or_else(|| "tint".to_string(), |m| mode_id(*m)))); + } + ui.label(egui::RichText::new(tl!("Color Mode:")).color(t.text_dim)); +} + +/// One color slider in the grid: its label, its rail with `track` and its number field, showing +/// `shown` with `suffix`. Returns the whole number in `shown`'s range that a drag, a key or the +/// field sets. +fn slider_cell( + ui: &mut Ui, + id: impl std::hash::Hash + Copy, + label: &str, + shown: widgets::SliderValue, + suffix: &str, + track: &dyn Fn(f32) -> egui::Color32, +) -> Option { + let t = Tokens::get(ui.ctx()); + let (lo, hi) = (*shown.range.start(), *shown.range.end()); + let value = shown.value; + ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(label).size(12.5).color(t.text))); + let unit = ((value - lo) / (hi - lo)) as f32; + let (dragged, _, keyed) = widgets::color_slider_stepped(ui, ("recolor-slider", id), label, Some(shown), unit, SLIDER_W, track); + let typed = widgets::plain_field_named(ui, ("recolor-slider-field", id), Some(label), value, suffix, 0, SLIDER_FIELD_W); + dragged.map(|x| (lo + f64::from(x) * (hi - lo)).round()).or(keyed).or(typed).map(|v| v.clamp(lo, hi)).filter(|v| (v - value).abs() > 1e-6) +} + +/// The color sliders under the rows, two to a line: they edit the first selected row's new color +/// (the others keep theirs) in the mode of [`mode_menu`], or its tint of a spot color of the +/// library. Without a selected row they are disabled. Returns true when they changed a row. +fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { + let target = SliderTarget::of(app, d, rows); + let mode = target.mode(d); + let mut changed = false; + let top = ui.cursor().top(); + let lines = mode.map_or(1, |m| m.labels().len().div_ceil(2)); + ui.add_enabled_ui(target.color.is_some(), |ui| { + egui::Grid::new("recolor-sliders").num_columns(6).spacing([6.0, 4.0]).show(ui, |ui| { + let (Some(i), Some(c)) = (target.row, target.color) else { + // Nothing to edit: the mode's sliders, disabled. + let mode = mode.unwrap_or(Mode::Hsb); + let input = Tokens::get(ui.ctx()).input; + let grey = move |_: f32| input; + for (n, lbl) in mode.labels().iter().enumerate() { + let shown = widgets::SliderValue::field(0.0, f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); + slider_cell(ui, n, lbl, shown, mode.suffix(n), &grey); + if n % 2 == 1 { + ui.end_row(); + } + } + return; + }; + let Some(mode) = mode else { + // Tint of the spot color, and its name. + let tint = f64::from(row_tint(&rows[i])) * 100.0; + let shown = widgets::SliderValue::field(tint, 0.0..=100.0, "%", 0); + if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&c.tinted(x))) { + rows[i]["tint"] = json!(v); + changed = true; + } + ui.label(egui::RichText::new(target.spot.as_deref().unwrap_or_default()).color(Tokens::get(ui.ctx()).text)); + return; + }; + let comps = slider_values(d, rows, i, &c, mode); + let mut set: Option> = None; + for (n, lbl) in mode.labels().iter().enumerate() { + let v = comps.get(n).copied().unwrap_or(0.0); + let shown = widgets::SliderValue::field(f64::from(v), f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); + if let Some(nv) = slider_cell(ui, n, lbl, shown, mode.suffix(n), &|x| c32(&track_color(mode, &comps, n, x))) { + let mut c2 = comps.clone(); + c2[n] = nv as f32; + set = Some(c2); + } + if n % 2 == 1 { + ui.end_row(); + } + } + if let Some(c2) = set { + // The mode stays as the edit changes the color's model (a gray edited in HSB is RGB). + d.fields.insert("sliderMode".into(), json!(mode_id(mode))); + set_to(&mut rows[i], &from_components(mode, &c2)); + d.fields.insert(COMPS.into(), json!({"row": i, "key": rows[i]["to"], "mode": mode_id(mode), "v": c2})); + d.fields.insert(SLID.into(), json!(true)); + changed = true; + } + }); + }); + // Room for two lines of sliders whatever the mode, so the dialog keeps its height. + let per = (ui.cursor().top() - top) / lines as f32; + ui.add_space(per * (2 - lines.min(2)) as f32); + changed +} + /// Merge the selected rows into the first of them (its new colour stays). fn merge(rows: &mut Vec, sel: &[usize]) { let mut sel: Vec = sel.iter().copied().filter(|i| *i < rows.len()).collect(); diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 1abefd25c1..af6991d53a 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -226,6 +226,144 @@ fn edit_harness(colors: &[&str]) -> egui_kittest::Harness<'static, VectorcraftAp h } +/// Recolor Artwork open on the Assign tab of `app` (its art selected), drawn by a kittest harness. +fn assign_harness(mut app: VectorcraftApp, open: Value) -> egui_kittest::Harness<'static, VectorcraftApp> { + app.run("ui.recolorDialog", open).unwrap(); + set(&mut app, "method", json!("exact")); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + h +} + +/// Clicks the color slider named `name` at `at` (0 to 1) along its rail. +fn click_slider(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str, at: f32) { + let r = h.get_by_role_and_label(egui::accesskit::Role::Slider, name).rect(); + let pos = egui::pos2(r.left() + 4.0 + at * (r.width() - 8.0), r.center().y); + h.input_mut().events.extend(press(pos, 1)); + h.run_steps(3); +} + +/// The fill of the first object of the document. +fn first_fill(app: &VectorcraftApp) -> vectorcraft_color::Paint { + let d = &app.session.doc().unwrap().doc; + let id = d.layers[0].children().unwrap()[0].id; + d.node(id).unwrap().appearance.fill_paint() +} + +/// The color mode menu's sliders edit the first selected row's new color in the mode picked (the +/// other row keeps its color), the art previews it, and OK gives the art the color in that mode: +/// a CMYK color on RGB art makes it CMYK. Cancel leaves the art as it was, with no undo step. +#[test] +fn the_color_sliders_edit_the_selected_rows_new_color_in_their_mode() { + for confirm in [true, false] { + let mut app = app(); + art(&mut app, &["#0000ff", "#ff0000"]); + let before = first_fill(&app); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut h = assign_harness(app, json!({})); + let rows = field(h.state(), "rows"); + let blue = 0; + assert_eq!(rows[blue]["from"], json!(["rgb 0 0 255"]), "the first object's blue is the first row"); + // Both rows selected, the second one first: the sliders edit the first row. + set(h.state_mut(), "__sel", json!([1, blue])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "R").is_some(), "RGB art shows the RGB sliders"); + set(h.state_mut(), "sliderMode", json!("cmyk")); + h.run_steps(2); + click_slider(&mut h, "C", 0.5); + let edited = field(h.state(), "rows"); + let to = edited[blue]["to"].as_str().unwrap().to_string(); + assert!(to.starts_with("cmyk 50 "), "the first selected row takes C 50%: {to}"); + assert_eq!(edited[1], rows[1], "the other selected row keeps its new color"); + let Some(Color::Cmyk { c, .. }) = first_fill(h.state()).color() else { + panic!("the art previews the CMYK color: {:?}", first_fill(h.state())) + }; + assert!((c - 0.5).abs() < 1e-3, "{c}"); + h.get_by_label(if confirm { "OK" } else { "Cancel" }).click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + let app = h.state(); + if confirm { + assert_eq!(first_fill(app).color(), vectorcraft_engine::cmd::color_value(&json!(to)), "OK keeps the color, in CMYK"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + } else { + assert_eq!(first_fill(app), before, "Cancel leaves the art unchanged"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + } + } +} + +/// A gray row shows HSB, and the sliders stay in HSB once an edit makes the color RGB. +#[test] +fn a_gray_row_keeps_the_hsb_sliders_while_it_is_edited() { + let mut app = app(); + art(&mut app, &["gray 40"]); + let mut h = assign_harness(app, json!({})); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "H").is_some(), "a gray row shows HSB"); + click_slider(&mut h, "S", 0.5); + let to = field(h.state(), "rows")[0]["to"].clone(); + assert!(to.as_str().is_some_and(|k| k.starts_with("rgb ")), "{to}"); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "H").is_some(), "still HSB after the edit"); + assert_eq!(field(h.state(), "sliderMode"), json!("hsb")); +} + +/// With Limit to Library, a row whose new color is a spot color of the library shows Tint, whose T +/// slider sets the row's tint of it; OK links the art to the spot color at that tint. +#[test] +fn the_tint_slider_sets_a_spot_rows_tint() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 1, "y": 0, "k": 0}, "spot": true})).unwrap(); + let data = app.run("swatch.library.save", json!({"names": ["Ink"], "name": "Inks"})).unwrap()["data"].as_str().unwrap().to_string(); + let lib = app.run("swatch.library.load", json!({"data": data, "name": "inks.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string(); + app.run("swatch.delete", json!({"names": ["Ink"]})).unwrap(); + art(&mut app, &["cmyk 0 100 0 0"]); + let mut h = assign_harness(app, json!({"library": lib})); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_some(), "a spot row shows Tint"); + click_slider(&mut h, "T", 0.4); + assert_eq!(field(h.state(), "rows")[0]["tint"], json!(40.0)); + h.get_by_label("OK").click(); + h.run_steps(2); + match first_fill(h.state()) { + vectorcraft_color::Paint::Solid { swatch, tint, .. } => { + assert_eq!(swatch.as_deref(), Some("Ink"), "linked to the spot color"); + assert!((tint - 0.4).abs() < 1e-4, "at the row's tint: {tint}"); + } + p => panic!("{p:?}"), + } +} + +/// The dialog keeps its height when the tab or the sliders' color mode changes. +#[test] +fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let mut h = assign_harness(app, json!({})); + set(h.state_mut(), "__sel", json!([0])); + let height = |h: &mut egui_kittest::Harness<'_, VectorcraftApp>, k: &str, v: Value| { + set(h.state_mut(), k, v); + h.run_steps(6); + h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", "recolor")))).unwrap().height() + }; + let assign = height(&mut h, "sliderMode", json!("cmyk")); + for (k, v) in [("sliderMode", json!("hsb")), ("sliderMode", json!("lab")), ("tab", json!("edit")), ("tab", json!("assign"))] { + assert_eq!(height(&mut h, k, v.clone()), assign, "{k} {v}"); + } +} + /// The Assign tab's per-row hex fields are named by their row, not all "Color": a screen reader can /// tell the second from the first. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1e718c9da5..41cfd8378c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -253,9 +253,12 @@ and spot colours exist; the dialog then stays open. Recolor Artwork: `ui.recolorDialog {colors?, library?, group?}` opens the `recolor` dialog on the selected art (`colors`: a count for an n-colour job, or colours to assign as the new colours; `library`: Limit to Library, a library -or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). Fields: `rows` (`[{from: [keys], to: key, exclude?}]` +or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?}]` as `recolor.reduce` returns them), `colors` (null for Auto), `method`, `preserveWhite`, `preserveBlack`, -`preserveGrays`, `limitTo`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`. Setting +`preserveGrays`, `limitTo`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, +`sliderMode` (the mode of the color sliders under the rows: `hsb`, `rgb`, `cmyk`, `lab`, or `tint` for a row whose new +color is a spot color of the library; unset, they show the new color's own model). The sliders edit the first selected +row's new color; once they have, the preview and confirm send `recolor.apply` with `model: "new"`. Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, diff --git a/docs/mcp.md b/docs/mcp.md index b1ca3a3477..5363e96fb4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1919,16 +1919,17 @@ tints of a global swatch share its row; White and Black are preserved by default `[{from: [keys], to: key}]` to edit and pass to `recolor.apply {map, method?, model?, limitTo?, group?, groupColors?, rename?}`. For scripts and MCP, `model` selects the replacement color model: `keep` (default) retains each original color's model, `new` takes the replacement's model, and `document` converts replacements -and edited color groups to the document's model. Invalid values fail before editing. This parameter -is not a control in the Recolor Artwork dialog. A returned `note` reports a model conversion in -`keep` mode. +and edited color groups to the document's model. Invalid values fail before editing. The Recolor +Artwork dialog sends `new` once its color sliders have edited a row's new color in a color mode. A +returned `note` reports a model conversion in `keep` mode. `method` says how a row's colours take its new colour: `exact`, `preserveTints` (tints of the row's darkest colour stay tints), `scaleTints` (every colour becomes a tint as light, relative to the darkest), `tintsShades` (lighter and darker than the row's average become tints and shades) or `hueShift` (the most saturated colour takes the new colour, the others turn by the same hue). `limitTo` snaps new colours to a swatch library's nearest colour; `recolor.randomize {map, order?, saturationBrightness?, seed?}` shuffles or varies new colours; a row with -`exclude: true` keeps its colours. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo +`exclude: true` keeps its colours. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art +linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the group together. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8bfe80641a..2f82b07d24 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -123,7 +123,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 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`) | | 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 only (#2520); the dialog retains its existing controls (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 | +| 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 | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | From c50fe0220d0a59573faa8b517a446ce49135d269 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 23:52:06 -0700 Subject: [PATCH 022/674] Recolor Artwork: Reset discards slider edits and reads the art's own colors Reset now also clears the slider edit, so the preview and OK keep each color's model again instead of sending model "new". Changing the Colors count, a Preserve flag or Limit to Library, or pressing Reset, with the preview on reduced the previewed colors, so the rows no longer matched the art; the preview is now rolled back before the colors are reduced. The Tint mode follows the swatch recolor.apply links: the first library swatch of the library color nearest the row's new color, shown as Tint only when that swatch is a spot color. --- crates/ui-egui/src/dialogs/recolor.rs | 16 ++++--- crates/ui-egui/src/tests/recolor.rs | 67 +++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 30d22a4ba2..7041f96cae 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -163,6 +163,10 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { if !d.bool("__art") || d.fields.get(DONE) == Some(&sig) { return; } + // The art's own colors are reduced, not those of the preview, which runs again afterwards. + if d.fields.remove(super::form::PREVIEWED).is_some() { + let _ = app.session.cancel_interaction(); + } let mut p = sig.clone(); p["method"] = json!(d.str("method")); match app.session.execute("recolor.reduce", &p) { @@ -488,6 +492,8 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } if widgets::icon_button(ui, "rotate-ccw", tl!("Reset the rows to the artwork's colors"), false, 24.0).clicked() { d.fields.remove("__reduced"); + d.fields.remove(SLID); + d.fields.remove(COMPS); } let target = SliderTarget::of(app, d, rows); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target)); @@ -572,17 +578,15 @@ fn mode_id(m: Mode) -> String { serde_json::to_value(m).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() } -/// The name of the spot color of the library (Limit to Library) that new color `c` is. +/// The name of the library swatch (Limit to Library) that `recolor.apply` gives new color `c`, when +/// it is a spot color: the first swatch of the library color nearest `c`. fn spot_of(app: &VectorcraftApp, d: &Dialog, c: &Color) -> Option { let lib = d.str("limitTo"); if lib.is_empty() { return None; } - let k = ColorKey::of(c); - swatchlib::library_swatches(&app.session, &lib)? - .into_iter() - .find(|w| w.spot && w.paint.color().is_some_and(|x| ColorKey::of(&x) == k)) - .map(|w| w.name) + let near = swatchlib::limit_palette(&app.session, &lib)?.nearest(*c); + swatchlib::library_swatches(&app.session, &lib)?.into_iter().find(|w| w.paint.color() == Some(near)).filter(|w| w.spot).map(|w| w.name) } /// The mode the sliders show new color `c` in, `None` for Tint: the mode picked in the menu, else diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index af6991d53a..c4aa85d6e4 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -346,6 +346,73 @@ fn the_tint_slider_sets_a_spot_rows_tint() { } } +/// Makes the swatches of the `swatch.new` params `swatches`, saves them as a library and loads it, +/// removes them from the document again, and returns the library's id. +fn library_of(app: &mut VectorcraftApp, swatches: &[Value]) -> String { + let names: Vec = swatches.iter().map(|s| s["name"].clone()).collect(); + for s in swatches { + app.run("swatch.new", s.clone()).unwrap(); + } + let data = app.run("swatch.library.save", json!({"names": names, "name": "Lib"})).unwrap()["data"].as_str().unwrap().to_string(); + let lib = app.run("swatch.library.load", json!({"data": data, "name": "lib.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string(); + app.run("swatch.delete", json!({"names": names})).unwrap(); + lib +} + +/// When the library's first swatch of a row's new color is a process color, the row shows no Tint, +/// even with a spot color of that color after it: `recolor.apply` gives the art the first one. +#[test] +fn a_process_swatch_before_a_spot_one_of_its_color_shows_no_tint() { + let mut app = app(); + let lib = library_of( + &mut app, + &[ + json!({"name": "Mix Process", "color": {"c": 0, "m": 1, "y": 0, "k": 0}}), + json!({"name": "Mix Ink", "color": {"c": 0, "m": 1, "y": 0, "k": 0}, "spot": true}), + ], + ); + art(&mut app, &["cmyk 0 100 0 0"]); + let mut h = assign_harness(app, json!({"library": lib})); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_none(), "no Tint for a process swatch"); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "C").is_some(), "the CMYK sliders"); +} + +/// A spot color whose components are finer than a row's color key still shows Tint: the row's +/// rounded color snaps back to it, as `recolor.apply` snaps it. +#[test] +fn a_spot_color_finer_than_the_rows_key_shows_tint() { + let mut app = app(); + let lib = library_of(&mut app, &[json!({"name": "Mix Fine", "color": {"c": 0, "m": 0.12345, "y": 0, "k": 0}, "spot": true})]); + art(&mut app, &["cmyk 0 12 0 0"]); + let mut h = assign_harness(app, json!({"library": lib})); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_some(), "the spot row shows Tint"); +} + +/// Reset with the preview on reads the art's own colors again and discards a slider edit: OK then +/// gives RGB art a CMYK color group's color in RGB, as it does without the edit. +#[test] +fn reset_after_a_slider_edit_keeps_the_arts_model() { + let mut app = app(); + app.run("swatch.newGroup", json!({"name": "Mix", "colors": ["cmyk 0 100 0 0"], "keepModel": true})).unwrap(); + art(&mut app, &["#ff00ff"]); + let mut h = assign_harness(app, json!({"group": "Mix"})); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + click_slider(&mut h, "C", 0.5); + assert_eq!(field(h.state(), "__slid"), json!(true), "the sliders edited the row"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset the rows to the artwork's colors").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "rows")[0]["from"], json!(["rgb 255 0 255"]), "Reset reads the art's colors, not the preview's"); + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + assert!(matches!(first_fill(h.state()).color(), Some(Color::Rgb { .. })), "the art stays RGB: {:?}", first_fill(h.state())); +} + /// The dialog keeps its height when the tab or the sliders' color mode changes. #[test] fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { From f242b9caa65d3d4684ea11c74a94600af728213c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 01:55:46 -0700 Subject: [PATCH 023/674] Recolor Artwork: a row's tint stays with its spot color A wheel drag or a harmony rule on the Edit tab now removes a row's tint when it gives the row another new color, as the color sliders, the hex field and the Color Picker already do. With Limit to Library, an edit that snaps back to the row's own color keeps the tint. recolor.randomize moves each row's tint with its new color when it shuffles the order, and removes the tint from a color that saturation and brightness changes. --- crates/engine/src/cmd/recolor.rs | 17 ++++-- crates/engine/src/tests/recolor.rs | 27 ++++++++- crates/ui-egui/src/dialogs/recolor.rs | 73 +++++++++++++++++++++++-- crates/ui-egui/src/tests/recolor.rs | 79 +++++++++++++++++++++++++++ docs/mcp.md | 3 +- 5 files changed, 188 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 5ff152a855..47357437e5 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -555,24 +555,31 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let rows = parse_rows(p, C)?; let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); - let mut news: Vec = rows.iter().filter_map(Row::new_color).collect(); + // Each new colour with its row's tint: a tint moves with its colour, and goes when the colour changes. + let mut news: Vec<(Color, f32)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint))).collect(); if order { rng.shuffle(&mut news); } if saturation_brightness { - news = news.into_iter().map(|c| rng.saturation_brightness(c)).collect(); + news = news + .into_iter() + .map(|(c, tint)| { + let n = rng.saturation_brightness(c); + (n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }) + }) + .collect(); } let mut news = news.into_iter(); let map: Vec = rows .iter() .map(|r| { - let to = if r.new_color().is_some() { news.next() } else { r.to }; + let (to, tint) = if r.new_color().is_some() { news.next().map_or((None, 1.0), |(c, t)| (Some(c), t)) } else { (r.to, r.tint) }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); } - if r.tint < 1.0 { - row["tint"] = json!(f64::from((r.tint * 10_000.0).round()) / 100.0); + if tint < 1.0 { + row["tint"] = json!(f64::from((tint * 10_000.0).round()) / 100.0); } row }) diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index ecf71f91a2..1be1566067 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -538,7 +538,7 @@ fn recolor_to_a_library_spot_colour_links_it_and_adds_the_swatch() { } /// A row's `tint` gives the art linked to the row's spot color that share of its tint; -/// randomize keeps it on the row, and a tint that is not a number is refused. +/// randomize without a change keeps it on the row, and a tint that is not a number is refused. #[test] fn a_rows_tint_tints_the_spot_color_the_art_links_to() { let mut s = session(); @@ -564,6 +564,31 @@ fn a_rows_tint_tints_the_spot_color_the_art_links_to() { assert!(e.to_string().contains("`tint` must be a number"), "{e}"); } +/// Randomize order moves a row's tint with its new color; changing saturation and brightness +/// drops the tint of every color it changes. +#[test] +fn randomize_moves_a_tint_with_its_color_and_drops_it_when_the_color_changes() { + let mut s = session(); + let map = json!([ + {"from": ["rgb 255 0 0"], "to": "cmyk 0 100 0 0", "tint": 40}, + {"from": ["rgb 0 255 0"], "to": "rgb 0 255 0"}, + {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"}, + ]); + let mut moved = false; + for seed in 0..20 { + let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed})); + for row in r["map"].as_array().unwrap() { + let spot = row["to"] == json!("cmyk 0 100 0 0"); + assert_eq!(row.get("tint").cloned(), spot.then(|| json!(40.0)), "seed {seed}: the tint goes with its color: {r}"); + } + moved |= r["map"][0]["to"] != map[0]["to"]; + } + assert!(moved, "some seed moves the tinted color to another row"); + let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true})); + assert_ne!(sb["map"][0]["to"], map[0]["to"], "{sb}"); + assert!(sb["map"][0].get("tint").is_none(), "a changed color has no tint: {sb}"); +} + #[test] fn model_param_chooses_the_model_of_the_new_colour() { // RGB art in a CMYK document: by default a CMYK replacement comes out RGB (#2170). diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 7041f96cae..0deb4007bb 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -215,6 +215,24 @@ fn set_to(row: &mut Value, c: &Color) { } } +/// Set for the frame in which Randomly change color order shuffled the rows' new colors. +const SHUFFLED: &str = "__shuffled"; + +/// Give each row of `rows` whose current colors and new color are those of the same row of +/// `before` that row's tint again, when it has none: a change that snaps back to the same new +/// color keeps the tint of it. +fn keep_tints(before: &[Value], rows: &mut [Value]) { + for (r, b) in rows.iter_mut().zip(before) { + if r["from"] == b["from"] + && r["to"] == b["to"] + && r.get("tint").is_none() + && let Some(t) = b.get("tint") + { + r["tint"] = t.clone(); + } + } +} + fn excluded(row: &Value) -> bool { row["exclude"].as_bool().unwrap_or(false) } @@ -274,6 +292,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { } if changed { snap(app, d, &mut rs); + // A shuffle by `recolor.randomize` has already moved each tint with its color. + if d.fields.remove(SHUFFLED).is_none() { + keep_tints(&rows(d), &mut rs); + } d.fields.insert("rows".into(), Value::Array(rs)); } if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { @@ -299,6 +321,7 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C if let Some(r) = rs.get_mut(i) { set_to(r, &c); snap(app, &d, &mut rs); + keep_tints(&rows(&d), &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); } d @@ -484,6 +507,9 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut match app.session.execute("recolor.randomize", &p) { Ok(r) => { *rows = r["map"].as_array().cloned().unwrap_or_default(); + if !sb { + d.fields.insert(SHUFFLED.into(), json!(true)); + } changed = true; } Err(e) => app.status(e.to_string()), @@ -782,8 +808,8 @@ fn move_color(rows: &mut [Value], i: usize, hsb: [f32; 3], linked: bool) { let mut colors = before.clone(); move_on_wheel(&mut colors, k, hsb, linked); for ((&j, c), old) in active.iter().zip(&colors).zip(&before) { - if c != old { - rows[j]["to"] = key(c); + if key(c) != key(old) { + set_to(&mut rows[j], c); } } } @@ -868,13 +894,17 @@ fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { } /// Give the rows `active` the colours of `rule` from the base colour `b` of row `base` (the base row -/// first, then the others in order, the rule's colours repeating), each in its row's model. +/// first, then the others in order, the rule's colours repeating), each in its row's model. A row +/// whose new colour changes loses its tint. fn apply_rule(rows: &mut [Value], rule: Harmony, base: usize, b: Color, active: &[usize]) { let colors = rule.apply(b); let order = std::iter::once(base).chain(active.iter().copied().filter(|i| *i != base)); for (n, i) in order.enumerate() { let old = to_color(&rows[i]).unwrap_or(b); - rows[i]["to"] = key(&keep_model(old, colors[n % colors.len()])); + let c = keep_model(old, colors[n % colors.len()]); + if key(&c) != rows[i]["to"] { + set_to(&mut rows[i], &c); + } } } @@ -937,6 +967,41 @@ mod tests { assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"]], ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]); } + /// A rule or a wheel move that gives a row a new colour drops the row's tint; a row whose + /// colour stays keeps it. + #[test] + fn a_new_colour_from_the_edit_tab_drops_the_rows_tint() { + let tinted = || { + let mut r = rows(); + for row in &mut r { + row["tint"] = json!(40.0); + } + r + }; + let mut r = tinted(); + apply_rule(&mut r, Harmony::Triad, 0, Color::rgb(1.0, 0.0, 0.0), &[0, 1, 2]); + assert_eq!(r[0]["tint"], json!(40.0), "the base row's colour stays"); + assert!(r[1].get("tint").is_none() && r[2].get("tint").is_none(), "{r:?}"); + let mut r = tinted(); + move_color(&mut r, 0, [120.0, 1.0, 1.0], false); + assert!(r[0].get("tint").is_none(), "the moved row: {:?}", r[0]); + assert_eq!(r[1]["tint"], json!(40.0), "unlinked: the other rows keep theirs"); + } + + /// The Color Picker's OK keeps a row's tint when the row's new color stays, and drops it otherwise. + #[test] + fn a_picked_color_keeps_the_tint_only_of_the_same_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("ui.recolorDialog", json!({"colors": ["#ff0000"]})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("rows".into(), json!([{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0", "tint": 40.0}])); + let same = with_new_color(&app, d.clone(), 0, Color::rgb(1.0, 0.0, 0.0)); + assert_eq!(super::rows(&same)[0]["tint"], json!(40.0)); + let other = with_new_color(&app, d, 0, Color::rgb(0.0, 1.0, 0.0)); + assert!(super::rows(&other)[0].get("tint").is_none(), "{:?}", super::rows(&other)); + } + /// Runs one frame of the open dialog at `time` and returns row `i`'s new color chip, when the /// Recolor Artwork dialog drew it. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec, i: usize) -> Option { diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index c4aa85d6e4..b5c5f874d2 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -346,6 +346,85 @@ fn the_tint_slider_sets_a_spot_rows_tint() { } } +/// A spot row's tint goes when the Edit tab gives the row another new color: after a click on the +/// Brightness slider snaps the row to a second spot color, OK links the art to that one at full +/// strength. A click that snaps back to the same spot color keeps the tint. +#[test] +fn a_new_color_from_the_edit_tab_drops_a_spot_rows_tint() { + let mut app = app(); + let lib = library_of( + &mut app, + &[json!({"name": "Mix Ink", "color": "#ff00ff", "spot": true}), json!({"name": "Mix Dark", "color": "#800080", "spot": true})], + ); + art(&mut app, &["#ff00ff"]); + let mut h = assign_harness(app, json!({"library": lib})); + let mut rows = field(h.state(), "rows"); + rows[0]["tint"] = json!(40.0); + set(h.state_mut(), "rows", rows); + set(h.state_mut(), "tab", json!("edit")); + h.run_steps(4); + click_slider(&mut h, "Brightness", 0.9); + let row = field(h.state(), "rows")[0].clone(); + assert_eq!((&row["to"], &row["tint"]), (&json!("rgb 255 0 255"), &json!(40.0)), "snapped back to the same spot color"); + click_slider(&mut h, "Brightness", 0.4); + let row = field(h.state(), "rows")[0].clone(); + assert_eq!(row["to"], json!("rgb 128 0 128"), "snapped to the darker spot color"); + assert!(row.get("tint").is_none(), "the row's tint went with its old color: {row}"); + h.get_by_label("OK").click(); + h.run_steps(2); + match first_fill(h.state()) { + vectorcraft_color::Paint::Solid { swatch, tint, .. } => { + assert_eq!(swatch.as_deref(), Some("Mix Dark"), "linked to the new spot color"); + assert!((tint - 1.0).abs() < 1e-4, "at full strength: {tint}"); + } + p => panic!("{p:?}"), + } +} + +/// Randomize order moves a tint with its color, also between rows of the same new color: after +/// each click exactly one row is tinted, and some click moves the tint to the other row. +#[test] +fn randomize_order_moves_a_tint_between_rows_of_the_same_color() { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let mut h = assign_harness(app, json!({})); + let mut rows = field(h.state(), "rows"); + for r in rows.as_array_mut().unwrap() { + r["to"] = json!("rgb 0 255 0"); + } + rows[0]["tint"] = json!(40.0); + set(h.state_mut(), "rows", rows); + h.run_steps(2); + let mut moved = false; + for _ in 0..8 { + h.get_by_label("Randomly change color order").click(); + h.run_steps(2); + let rows = field(h.state(), "rows"); + let tinted: Vec = (0..2).filter(|i| rows[*i].get("tint").is_some()).collect(); + assert_eq!(tinted.len(), 1, "one tinted row: {rows}"); + moved |= tinted == [1]; + } + assert!(moved, "some click moves the tint to the other row"); +} + +/// With a one-color library, Randomly change saturation and brightness snaps a spot row back to +/// its spot color, which keeps its tint. +#[test] +fn a_saturation_change_that_snaps_back_keeps_the_tint() { + let mut app = app(); + let lib = library_of(&mut app, &[json!({"name": "Mix Ink", "color": "#ff00ff", "spot": true})]); + art(&mut app, &["#ff00ff"]); + let mut h = assign_harness(app, json!({"library": lib})); + let mut rows = field(h.state(), "rows"); + rows[0]["tint"] = json!(40.0); + set(h.state_mut(), "rows", rows); + h.run_steps(2); + h.get_by_label("Randomly change saturation and brightness").click(); + h.run_steps(2); + let row = field(h.state(), "rows")[0].clone(); + assert_eq!((&row["to"], &row["tint"]), (&json!("rgb 255 0 255"), &json!(40.0)), "{row}"); +} + /// Makes the swatches of the `swatch.new` params `swatches`, saves them as a library and loads it, /// removes them from the document again, and returns the library's id. fn library_of(app: &mut VectorcraftApp, swatches: &[Value]) -> String { diff --git a/docs/mcp.md b/docs/mcp.md index 5363e96fb4..f88a146aa2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1929,7 +1929,8 @@ darker than the row's average become tints and shades) or `hueShift` (the most s the others turn by the same hue). `limitTo` snaps new colours to a swatch library's nearest colour; `recolor.randomize {map, order?, saturationBrightness?, seed?}` shuffles or varies new colours; a row with `exclude: true` keeps its colours. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art -linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo +linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` +moves a row's `tint` with its new color and removes it from a color it changes. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the group together. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still From 333450b862a2da28b01073b6a21f75e7601e896a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 01:18:07 -0800 Subject: [PATCH 024/674] Recolor Artwork: rebuilt rows discard a slider edit's color mode Changing the color count, a Preserve option or Limit to Library rebuilds the rows from the art's colors, which discards a slider edit. The dialog now also forgets that edit, so preview and OK give the art the rebuilt rows' colors in the art's own model instead of the rows' models. --- crates/ui-egui/src/dialogs/recolor.rs | 3 +++ crates/ui-egui/src/tests/recolor.rs | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 0deb4007bb..a5fce35435 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -179,6 +179,9 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { snap(app, d, &mut rows); d.fields.insert("rows".into(), Value::Array(rows)); d.fields.insert("__sel".into(), json!([])); + // The new rows hold no slider edit. + d.fields.remove(SLID); + d.fields.remove(COMPS); } Err(e) => app.status(e.to_string()), } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index b5c5f874d2..277f0bf8f0 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -492,6 +492,28 @@ fn reset_after_a_slider_edit_keeps_the_arts_model() { assert!(matches!(first_fill(h.state()).color(), Some(Color::Rgb { .. })), "the art stays RGB: {:?}", first_fill(h.state())); } +/// A change of the color count rebuilds the rows and discards a slider edit: OK then gives RGB art +/// a CMYK color group's color in RGB, as it does without the edit. +#[test] +fn a_new_color_count_after_a_slider_edit_keeps_the_arts_model() { + let mut app = app(); + app.run("swatch.newGroup", json!({"name": "Mix", "colors": ["cmyk 0 100 0 0", "cmyk 100 0 0 0"], "keepModel": true})).unwrap(); + art(&mut app, &["#ff00ff", "#00ffff"]); + let mut h = assign_harness(app, json!({"group": "Mix"})); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + click_slider(&mut h, "C", 0.5); + assert_eq!(field(h.state(), "__slid"), json!(true), "the sliders edited the row"); + set(h.state_mut(), "colors", json!(1)); + h.run_steps(3); + assert_eq!(field(h.state(), "rows").as_array().map(Vec::len), Some(1), "the rows are rebuilt"); + assert_eq!(field(h.state(), "__slid"), Value::Null, "the slider edit is discarded"); + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + assert!(matches!(first_fill(h.state()).color(), Some(Color::Rgb { .. })), "the art stays RGB: {:?}", first_fill(h.state())); +} + /// The dialog keeps its height when the tab or the sliders' color mode changes. #[test] fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { From 13239653127f983a625c241d718b65a13a9d350e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 01:40:08 -0800 Subject: [PATCH 025/674] Recolor Artwork: Tint shows only with art and previews the color the art takes A dialog opened on a color group or on loose colors no longer offers Tint for a spot color of the library: OK saves only the new colors, so a tint set there was lost. The row shows the process modes instead. The Tint rail and a tinted row's new color chip show a Lab spot color as art linked to it shows it: the working-CMYK equivalent while the Spot Colors options use CMYK values, with its inks scaled. --- crates/ui-egui/src/dialogs/recolor.rs | 55 +++++++++++++++++++++++++-- crates/ui-egui/src/tests/recolor.rs | 15 ++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index a5fce35435..4614b52b5c 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -419,6 +419,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut let mut sel = selection(d); let mut clicked: Option = None; let mut pick: Option = None; + let shown: Vec = rows.iter().map(|r| new_shown(app, d, r)).collect(); widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt("recolor-rows").max_height(TABLE_H).show(ui, |ui| { ui.set_width(ui.available_width()); @@ -451,7 +452,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut let (nr, _) = ui.allocate_exact_size(vec2(46.0, 20.0), Sense::hover()); let nresp = ui.interact(nr, egui::Id::unique((NEW_CHIP, i)), Sense::click()); let to = to_color(row).unwrap_or_default(); - chip(ui, nr, to.tinted(row_tint(row)), off); + chip(ui, nr, shown.get(i).copied().unwrap_or_default(), off); if nresp.clicked() { clicked = Some(i); } @@ -602,6 +603,25 @@ fn row_tint(row: &Value) -> f32 { row["tint"].as_f64().map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32) } +/// Tint `t` (0..1) of spot color `c` as art linked to it shows it: a Lab spot color is the active +/// document's working-CMYK equivalent while the Spot Colors options use CMYK values +/// ([`vectorcraft_doc::Document::linked_color`]), and its inks scale. +fn spot_tinted(app: &VectorcraftApp, c: Color, t: f32) -> Color { + app.session.active().map_or(c, |st| st.doc.linked_color(c, true)).tinted(t) +} + +/// The color row `row`'s new color chip shows: what the art takes, at the row's tint (a spot color +/// of the library as [`spot_tinted`] shows it). +fn new_shown(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Color { + let to = to_color(row).unwrap_or_default(); + // Only a Lab spot color can show another color; the library lookup is skipped for the rest. + if matches!(to, Color::Lab { .. }) && d.bool("__art") && spot_of(app, d, &to).is_some() { + spot_tinted(app, to, row_tint(row)) + } else { + to.tinted(row_tint(row)) + } +} + /// The `sliderMode` id of `m` (`hsb`, `rgb`, `cmyk`, `lab`). fn mode_id(m: Mode) -> String { serde_json::to_value(m).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() @@ -652,7 +672,8 @@ impl SliderTarget { fn of(app: &VectorcraftApp, d: &Dialog, rows: &[Value]) -> Self { let row = selection(d).into_iter().filter(|i| *i < rows.len()).min(); let color = row.and_then(|i| to_color(&rows[i])); - let spot = color.and_then(|c| spot_of(app, d, &c)); + // A row tint acts only on art, so without art a spot color shows the process modes. + let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c)); Self { row, color, spot } } @@ -733,7 +754,7 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] // Tint of the spot color, and its name. let tint = f64::from(row_tint(&rows[i])) * 100.0; let shown = widgets::SliderValue::field(tint, 0.0..=100.0, "%", 0); - if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&c.tinted(x))) { + if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&spot_tinted(app, c, x))) { rows[i]["tint"] = json!(v); changed = true; } @@ -1005,6 +1026,34 @@ mod tests { assert!(super::rows(&other)[0].get("tint").is_none(), "{:?}", super::rows(&other)); } + /// With the Spot Colors options on CMYK values, a row whose new color is a Lab spot color of the + /// library shows the art's color at its tint: the working-CMYK equivalent with its inks scaled. + #[test] + fn a_tinted_lab_spot_row_shows_the_cmyk_color_the_art_takes() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let lab = json!({"l": 50, "a": 60, "b": -20}); + app.run("swatch.new", json!({"name": "Lab Ink", "color": lab, "spot": true})).unwrap(); + let data = app.run("swatch.library.save", json!({"names": ["Lab Ink"], "name": "Inks"})).unwrap()["data"].as_str().unwrap().to_string(); + let lib = app.run("swatch.library.load", json!({"data": data, "name": "inks.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string(); + app.run("swatch.delete", json!({"names": ["Lab Ink"]})).unwrap(); + app.run("swatch.spotOptions", json!({"useLab": false})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": lab})).unwrap(); + app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({"library": lib})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + sync(&mut app, &mut d); + let mut rs = super::rows(&d); + rs[0]["tint"] = json!(50.0); + let c = to_color(&rs[0]).unwrap(); + assert!(matches!(c, Color::Lab { .. }), "{c:?}"); + let cmyk = app.session.doc().unwrap().doc.linked_color(c, true); + assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); + assert_eq!(new_shown(&app, &d, &rs[0]), cmyk.tinted(0.5)); + } + /// Runs one frame of the open dialog at `time` and returns row `i`'s new color chip, when the /// Recolor Artwork dialog drew it. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec, i: usize) -> Option { diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 277f0bf8f0..cdd8a5fdd5 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -458,6 +458,21 @@ fn a_process_swatch_before_a_spot_one_of_its_color_shows_no_tint() { assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "C").is_some(), "the CMYK sliders"); } +/// Opened on a color group without art, a row whose new color is a spot color of the library shows +/// the process modes and no Tint: OK saves only the group's colors, so a tint would be lost. +#[test] +fn a_spot_row_of_a_group_without_art_shows_no_tint() { + let mut app = app(); + let lib = library_of(&mut app, &[json!({"name": "Mix Ink", "color": {"c": 0, "m": 1, "y": 0, "k": 0}, "spot": true})]); + app.run("swatch.newGroup", json!({"name": "Mix", "colors": ["cmyk 0 100 0 0"], "keepModel": true})).unwrap(); + let mut h = assign_harness(app, json!({"group": "Mix", "library": lib})); + assert_ne!(field(h.state(), "__art"), json!(true), "no art"); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_none(), "no Tint without art"); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "C").is_some(), "the CMYK sliders"); +} + /// A spot color whose components are finer than a row's color key still shows Tint: the row's /// rounded color snaps back to it, as `recolor.apply` snaps it. #[test] From 9b853004d5bae0291e32fcc4bdeb1b45265b071b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 02:06:46 -0800 Subject: [PATCH 026/674] Recolor Artwork: a slider edit changes the color mode of its own row only The color sliders now mark the row they edit with `model: "new"` instead of a dialog-wide flag, and `recolor.apply` reads a row's own `model` before the command's. Rows the sliders did not edit keep each color's model, so with RGB art and a CMYK color group, a slider edit of one row no longer turns the other rows' art CMYK. Another edit of the row's new color, Reset and rows reduced again remove the mark, and `recolor.randomize` moves it with its new color. --- crates/engine/src/cmd/recolor.rs | 92 ++++++++++++++++++--------- crates/engine/src/tests/recolor.rs | 34 ++++++++++ crates/ui-egui/src/dialogs/recolor.rs | 39 ++++++------ crates/ui-egui/src/tests/recolor.rs | 36 ++++++++++- docs/control-protocol.md | 5 +- docs/mcp.md | 9 +-- 6 files changed, 157 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 47357437e5..37ed6edd5b 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -263,6 +263,41 @@ struct Row { /// The tint (0..1) of a global or spot swatch the new color is (with `limitTo`): art linked to /// the swatch takes this share of the tint the method gives it. tint: f32, + /// The row's own `model`, which takes the place of the command's for its colors. + model: Option, +} + +/// The color model a row's colors take (`model`): each color's own, the new color's, or the +/// document's. +#[derive(Clone, Copy, PartialEq)] +enum ModelRule { + Keep, + New, + Document, +} + +impl ModelRule { + /// The `model` of `v` (a row or the command's parameters); a given `model` must be a string. + fn param(v: &Value, cmd: &str) -> Result> { + match v.get("model") { + None => Ok(None), + Some(Value::String(m)) => match m.as_str() { + "keep" => Ok(Some(Self::Keep)), + "new" => Ok(Some(Self::New)), + "document" => Ok(Some(Self::Document)), + other => Err(bad(cmd, format!("unknown model `{other}` (keep, new or document)"))), + }, + Some(other) => Err(bad(cmd, format!("bad model {other} (keep, new or document)"))), + } + } + + fn id(self) -> &'static str { + match self { + Self::Keep => "keep", + Self::New => "new", + Self::Document => "document", + } + } } impl Row { @@ -284,7 +319,7 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}"))); match p.get("map") { Some(Value::Object(m)) => { - m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0 })).collect() + m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None })).collect() } Some(Value::Array(rows)) => rows .iter() @@ -295,7 +330,8 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { None => return Err(bad(cmd, "each row needs `from`")), }; let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32; - Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint }) + let model = ModelRule::param(r, cmd)?; + Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model }) }) .collect(), _ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")), @@ -338,8 +374,9 @@ struct ColorMap { impl ColorMap { /// `links`: the swatch of each of `rows`' new colours (as many as `rows`, or none); `group`: the - /// global swatches of the color group being rewritten. - fn new(rows: &[Row], method: Method, own_model: bool, links: &[Option], group: Vec) -> Self { + /// global swatches of the color group being rewritten; `model`: the model rule of a row without + /// its own. + fn new(rows: &[Row], method: Method, model: ModelRule, links: &[Option], group: Vec) -> Self { let mut out = Self { rows: vec![], links: vec![], tos: vec![], group, keys: HashMap::new(), hexes: HashMap::new(), converted: Default::default() }; for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) { @@ -349,7 +386,7 @@ impl ColorMap { let link = links.get(n).cloned().flatten(); // Colors that can't link to the swatch take the row's tint of it too. let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint)); - out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(own_model)); + out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(r.model.unwrap_or(model) != ModelRule::Keep)); out.tos.push(to); out.links.push(link); for m in &r.from { @@ -453,26 +490,14 @@ fn apply(s: &mut Session, p: &Value) -> Result { let scope = Scope { fill: true, stroke: true, ..Scope::of(p) }; let label = if ids.is_empty() { "Edit Color Group" } else { "Recolor Artwork" }; // `model`: keep each colour's model (default), take the new colour's own, or the document's. - // A given `model` must be a string; only a missing one means "keep". - let model = match p.get("model") { - None => "keep", - Some(Value::String(m)) => m.as_str(), - Some(other) => return Err(bad(C, format!("bad model {other} (keep, new or document)"))), - }; - let mut doc_model = None; - let own_model = match model { - "keep" => false, - "new" => true, - "document" => { - let m = s.doc()?.doc.color_mode.model(); - doc_model = Some(m); - for r in &mut rows { - r.to = r.to.map(|c| c.in_model(m)); - } - true - } - other => return Err(bad(C, format!("unknown model `{other}` (keep, new or document)"))), - }; + // A given `model` must be a string; only a missing one means "keep". A row's own `model` + // takes its place for that row. + let model = ModelRule::param(p, C)?.unwrap_or(ModelRule::Keep); + let mode_model = s.doc()?.doc.color_mode.model(); + for r in rows.iter_mut().filter(|r| r.model.unwrap_or(model) == ModelRule::Document) { + r.to = r.to.map(|c| c.in_model(mode_model)); + } + let doc_model = (model == ModelRule::Document).then_some(mode_model); // The colours a colour group takes follow the model too (`document` converts them). let in_doc_model = |c: Color| doc_model.map_or(c, |m| c.in_model(m)); let group_colors = match p.get("groupColors") { @@ -528,7 +553,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .collect() }) .unwrap_or_default(); - let map = ColorMap::new(&rows, method, own_model, &links, kept); + let map = ColorMap::new(&rows, method, model, &links, kept); let f = |c: Color| map.map(c); let lf = |c: &mut Color, link: &mut Option, tint: &mut f32| map.map_link(c, link, tint); let changed = Recolor::with_links(scope, &f, &lf).run(d, &ids); @@ -555,17 +580,18 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let rows = parse_rows(p, C)?; let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); - // Each new colour with its row's tint: a tint moves with its colour, and goes when the colour changes. - let mut news: Vec<(Color, f32)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint))).collect(); + // Each new colour with its row's tint and model: a tint moves with its colour, and goes when + // the colour changes; a model moves with its colour. + let mut news: Vec<(Color, f32, Option)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); if order { rng.shuffle(&mut news); } if saturation_brightness { news = news .into_iter() - .map(|(c, tint)| { + .map(|(c, tint, model)| { let n = rng.saturation_brightness(c); - (n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }) + (n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }, model) }) .collect(); } @@ -573,7 +599,8 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let map: Vec = rows .iter() .map(|r| { - let (to, tint) = if r.new_color().is_some() { news.next().map_or((None, 1.0), |(c, t)| (Some(c), t)) } else { (r.to, r.tint) }; + let (to, tint, model) = + if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); @@ -581,6 +608,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result { if tint < 1.0 { row["tint"] = json!(f64::from((tint * 10_000.0).round()) / 100.0); } + if let Some(m) = model { + row["model"] = json!(m.id()); + } row }) .collect(); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 1be1566067..565405d58e 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -624,6 +624,40 @@ fn model_param_must_be_a_string_when_given() { assert_eq!(fill(&s, art).to_hex(), "#1a1a1a", "nothing changed"); } +/// A row's own `model` takes the place of the command's for that row's colors; a bad one fails +/// before editing; `recolor.randomize` moves it with its new color. +#[test] +fn a_rows_model_applies_to_its_own_colors() { + let mut s = session(); + let (a, b) = (rect(&mut s, json!("#ff00ff")), rect(&mut s, json!("#00ffff"))); + select_all(&mut s); + let row = |from: &str, to: Value| json!({"from": [from], "to": to}); + let mut first = row("#ff00ff", json!({"c": 0, "m": 1, "y": 0, "k": 0})); + first["model"] = json!("new"); + let map = json!([first, row("#00ffff", json!({"c": 1, "m": 0, "y": 0, "k": 0}))]); + run(&mut s, "recolor.apply", json!({"map": map})); + assert_eq!(fill(&s, a), Color::cmyk(0.0, 1.0, 0.0, 0.0), "the row with `new` takes the CMYK color"); + assert_eq!(fill(&s, b).model(), vectorcraft_color::cms::Model::Rgb, "the other row keeps RGB"); + run(&mut s, "edit.undo", json!({})); + let mut keep = map.clone(); + keep[0]["model"] = json!("keep"); + run(&mut s, "recolor.apply", json!({"map": keep, "model": "new"})); + assert_eq!(fill(&s, a).model(), vectorcraft_color::cms::Model::Rgb, "the row's `keep` wins over the command's `new`"); + assert_eq!(fill(&s, b), Color::cmyk(1.0, 0.0, 0.0, 0.0)); + run(&mut s, "edit.undo", json!({})); + for bad in [json!("nope"), json!(42)] { + let mut m = map.clone(); + m[0]["model"] = bad.clone(); + assert!(s.execute("recolor.apply", &json!({"map": m})).is_err(), "{bad}"); + } + assert_eq!(fill(&s, a).to_hex(), "#ff00ff", "nothing changed"); + let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": 1})); + let out = r["map"].as_array().unwrap(); + let moved = out.iter().find(|r| r.get("model").is_some()).expect("the model stays on a row"); + assert_eq!((&moved["to"], &moved["model"]), (&json!("cmyk 0 100 0 0"), &json!("new")), "{r}"); + assert_eq!(out.iter().filter(|r| r.get("model").is_some()).count(), 1, "{r}"); +} + /// Recolor Artwork's commands refuse a parameter of the wrong form, such as `limitTo: 5` or /// `includeImages: "false"`, with an error that names it; the art keeps its color and no undo /// step is recorded. A null counts as a value left out. diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 4614b52b5c..1a3c8eab87 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -73,8 +73,6 @@ const SLIDER_MODES: [Mode; 4] = [Mode::Hsb, Mode::Rgb, Mode::Cmyk, Mode::Lab]; /// Widths of a color slider and of its number field. const SLIDER_W: f32 = 170.0; const SLIDER_FIELD_W: f32 = 48.0; -/// Set once the sliders have edited a new color in a mode: OK then sends `model: "new"`. -const SLID: &str = "__slid"; /// The slider values last shown: `{row, key, mode, v}` (HSB keeps its hue at no saturation). const COMPS: &str = "__comps"; @@ -180,7 +178,6 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { d.fields.insert("rows".into(), Value::Array(rows)); d.fields.insert("__sel".into(), json!([])); // The new rows hold no slider edit. - d.fields.remove(SLID); d.fields.remove(COMPS); } Err(e) => app.status(e.to_string()), @@ -210,11 +207,13 @@ fn to_color(row: &Value) -> Option { color_value(&row["to"]) } -/// Give `row` the new color `c`, without a tint of the spot color it had. +/// Give `row` the new color `c`, without a tint of the spot color it had or the model a slider +/// edit gave it. fn set_to(row: &mut Value, c: &Color) { row["to"] = key(c); if let Some(r) = row.as_object_mut() { r.remove("tint"); + r.remove("model"); } } @@ -222,16 +221,19 @@ fn set_to(row: &mut Value, c: &Color) { const SHUFFLED: &str = "__shuffled"; /// Give each row of `rows` whose current colors and new color are those of the same row of -/// `before` that row's tint again, when it has none: a change that snaps back to the same new -/// color keeps the tint of it. +/// `before` that row's tint and model again, when it has none: a change that snaps back to the +/// same new color keeps the tint of it and the model a slider edit gave it. fn keep_tints(before: &[Value], rows: &mut [Value]) { for (r, b) in rows.iter_mut().zip(before) { - if r["from"] == b["from"] - && r["to"] == b["to"] - && r.get("tint").is_none() - && let Some(t) = b.get("tint") - { - r["tint"] = t.clone(); + if r["from"] != b["from"] || r["to"] != b["to"] { + continue; + } + for k in ["tint", "model"] { + if r.get(k).is_none() + && let Some(v) = b.get(k) + { + r[k] = v.clone(); + } } } } @@ -256,11 +258,8 @@ fn apply_params(d: &Dialog) -> Value { let rename = (!name.trim().is_empty() && name != g).then_some(name); json!({"group": g, "groupColors": colors, "rename": rename}) }); + // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); - // The art takes a color edited with the sliders in the mode they showed. - if d.bool(SLID) { - p["model"] = json!("new"); - } if let (Some(Value::Object(g)), Some(p)) = (group, p.as_object_mut()) { p.extend(g.into_iter().filter(|(_, v)| !v.is_null())); } @@ -522,8 +521,12 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } if widgets::icon_button(ui, "rotate-ccw", tl!("Reset the rows to the artwork's colors"), false, 24.0).clicked() { d.fields.remove("__reduced"); - d.fields.remove(SLID); d.fields.remove(COMPS); + // The rows keep no slider edit, also when they cannot be reduced again. + let saved = d.fields.get_mut("rows").and_then(Value::as_array_mut).into_iter().flatten(); + for r in rows.iter_mut().chain(saved).filter_map(Value::as_object_mut) { + r.remove("model"); + } } let target = SliderTarget::of(app, d, rows); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target)); @@ -780,7 +783,7 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] d.fields.insert("sliderMode".into(), json!(mode_id(mode))); set_to(&mut rows[i], &from_components(mode, &c2)); d.fields.insert(COMPS.into(), json!({"row": i, "key": rows[i]["to"], "mode": mode_id(mode), "v": c2})); - d.fields.insert(SLID.into(), json!(true)); + rows[i]["model"] = json!("new"); changed = true; } }); diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index cdd8a5fdd5..7c20467185 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -497,7 +497,7 @@ fn reset_after_a_slider_edit_keeps_the_arts_model() { set(h.state_mut(), "__sel", json!([0])); h.run_steps(2); click_slider(&mut h, "C", 0.5); - assert_eq!(field(h.state(), "__slid"), json!(true), "the sliders edited the row"); + assert_eq!(field(h.state(), "rows")[0]["model"], json!("new"), "the sliders edited the row"); h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset the rows to the artwork's colors").click(); h.run_steps(3); assert_eq!(field(h.state(), "rows")[0]["from"], json!(["rgb 255 0 255"]), "Reset reads the art's colors, not the preview's"); @@ -518,17 +518,47 @@ fn a_new_color_count_after_a_slider_edit_keeps_the_arts_model() { set(h.state_mut(), "__sel", json!([0])); h.run_steps(2); click_slider(&mut h, "C", 0.5); - assert_eq!(field(h.state(), "__slid"), json!(true), "the sliders edited the row"); + assert_eq!(field(h.state(), "rows")[0]["model"], json!("new"), "the sliders edited the row"); set(h.state_mut(), "colors", json!(1)); h.run_steps(3); assert_eq!(field(h.state(), "rows").as_array().map(Vec::len), Some(1), "the rows are rebuilt"); - assert_eq!(field(h.state(), "__slid"), Value::Null, "the slider edit is discarded"); + assert_eq!(field(h.state(), "rows")[0].get("model"), None, "the slider edit is discarded"); h.get_by_label("OK").click(); h.run_steps(2); assert!(h.state().ui.dialog.is_none()); assert!(matches!(first_fill(h.state()).color(), Some(Color::Rgb { .. })), "the art stays RGB: {:?}", first_fill(h.state())); } +/// The fill of the `n`th object of the document. +fn fill_of(app: &VectorcraftApp, n: usize) -> vectorcraft_color::Paint { + let d = &app.session.doc().unwrap().doc; + let id = d.layers[0].children().unwrap()[n].id; + d.node(id).unwrap().appearance.fill_paint() +} + +/// A slider edit of one row gives only that row's art the slider's mode: with RGB art and a CMYK +/// color group, OK makes the edited row's art CMYK and leaves the other row's art RGB. +#[test] +fn a_slider_edit_changes_the_model_of_its_own_row_only() { + let mut app = app(); + app.run("swatch.newGroup", json!({"name": "Mix", "colors": ["cmyk 0 100 0 0", "cmyk 100 0 0 0"], "keepModel": true})).unwrap(); + art(&mut app, &["#ff00ff", "#00ffff"]); + let mut h = assign_harness(app, json!({"group": "Mix"})); + let rows = field(h.state(), "rows"); + let magenta = (0..2).find(|i| rows[*i]["from"] == json!(["rgb 255 0 255"])).expect("a row of the magenta art"); + set(h.state_mut(), "__sel", json!([magenta])); + h.run_steps(2); + click_slider(&mut h, "C", 0.5); + let rows = field(h.state(), "rows"); + assert_eq!(rows[magenta]["model"], json!("new"), "the edited row: {rows}"); + assert_eq!(rows[1 - magenta].get("model"), None, "the other row: {rows}"); + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + assert!(matches!(fill_of(h.state(), 0).color(), Some(Color::Cmyk { .. })), "the edited row's art is CMYK: {:?}", fill_of(h.state(), 0)); + assert!(matches!(fill_of(h.state(), 1).color(), Some(Color::Rgb { .. })), "the other row's art stays RGB: {:?}", fill_of(h.state(), 1)); +} + /// The dialog keeps its height when the tab or the sliders' color mode changes. #[test] fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 41cfd8378c..8f09432303 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -253,12 +253,13 @@ and spot colours exist; the dialog then stays open. Recolor Artwork: `ui.recolorDialog {colors?, library?, group?}` opens the `recolor` dialog on the selected art (`colors`: a count for an n-colour job, or colours to assign as the new colours; `library`: Limit to Library, a library -or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?}]` +or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?, model?}]` as `recolor.reduce` returns them), `colors` (null for Auto), `method`, `preserveWhite`, `preserveBlack`, `preserveGrays`, `limitTo`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, `sliderMode` (the mode of the color sliders under the rows: `hsb`, `rgb`, `cmyk`, `lab`, or `tint` for a row whose new color is a spot color of the library; unset, they show the new color's own model). The sliders edit the first selected -row's new color; once they have, the preview and confirm send `recolor.apply` with `model: "new"`. Setting +row's new color and give that row `model: "new"`, so the preview and confirm give only that row's art the color in +the sliders' mode; another edit of the row's new color, Reset and rows reduced again remove it. Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, diff --git a/docs/mcp.md b/docs/mcp.md index f88a146aa2..2a62f18a0a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1919,9 +1919,10 @@ tints of a global swatch share its row; White and Black are preserved by default `[{from: [keys], to: key}]` to edit and pass to `recolor.apply {map, method?, model?, limitTo?, group?, groupColors?, rename?}`. For scripts and MCP, `model` selects the replacement color model: `keep` (default) retains each original color's model, `new` takes the replacement's model, and `document` converts replacements -and edited color groups to the document's model. Invalid values fail before editing. The Recolor -Artwork dialog sends `new` once its color sliders have edited a row's new color in a color mode. A -returned `note` reports a model conversion in `keep` mode. +and edited color groups to the document's model. A row's own `model` (the same values) takes the +place of the command's for that row's colors. Invalid values fail before editing. The Recolor +Artwork dialog gives a row `model: "new"` when its color sliders edit the row's new color in a color +mode. A returned `note` reports a model conversion in `keep` mode. `method` says how a row's colours take its new colour: `exact`, `preserveTints` (tints of the row's darkest colour stay tints), `scaleTints` (every colour becomes a tint as light, relative to the darkest), `tintsShades` (lighter and @@ -1930,7 +1931,7 @@ the others turn by the same hue). `limitTo` snaps new colours to a swatch librar `recolor.randomize {map, order?, saturationBrightness?, seed?}` shuffles or varies new colours; a row with `exclude: true` keeps its colours. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` -moves a row's `tint` with its new color and removes it from a color it changes. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo +moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the group together. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still From fc6178d0214f4c238d941d9dd2407ccf18429b83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 05:26:35 -0800 Subject: [PATCH 027/674] Recolor Artwork: spell color the American way in the new comments and test names --- crates/engine/src/cmd/recolor.rs | 4 ++-- crates/ui-egui/src/dialogs/recolor.rs | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 37ed6edd5b..b1fd2489e9 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -580,8 +580,8 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let rows = parse_rows(p, C)?; let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); - // Each new colour with its row's tint and model: a tint moves with its colour, and goes when - // the colour changes; a model moves with its colour. + // Each new color with its row's tint and model: a tint moves with its color, and goes when + // the color changes; a model moves with its color. let mut news: Vec<(Color, f32, Option)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); if order { rng.shuffle(&mut news); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1a3c8eab87..76f3a15e87 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -743,10 +743,10 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] // Nothing to edit: the mode's sliders, disabled. let mode = mode.unwrap_or(Mode::Hsb); let input = Tokens::get(ui.ctx()).input; - let grey = move |_: f32| input; + let gray = move |_: f32| input; for (n, lbl) in mode.labels().iter().enumerate() { let shown = widgets::SliderValue::field(0.0, f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); - slider_cell(ui, n, lbl, shown, mode.suffix(n), &grey); + slider_cell(ui, n, lbl, shown, mode.suffix(n), &gray); if n % 2 == 1 { ui.end_row(); } @@ -922,7 +922,7 @@ fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { /// Give the rows `active` the colours of `rule` from the base colour `b` of row `base` (the base row /// first, then the others in order, the rule's colours repeating), each in its row's model. A row -/// whose new colour changes loses its tint. +/// whose new color changes loses its tint. fn apply_rule(rows: &mut [Value], rule: Harmony, base: usize, b: Color, active: &[usize]) { let colors = rule.apply(b); let order = std::iter::once(base).chain(active.iter().copied().filter(|i| *i != base)); @@ -994,10 +994,10 @@ mod tests { assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"]], ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]); } - /// A rule or a wheel move that gives a row a new colour drops the row's tint; a row whose - /// colour stays keeps it. + /// A rule or a wheel move that gives a row a new color drops the row's tint; a row whose + /// color stays keeps it. #[test] - fn a_new_colour_from_the_edit_tab_drops_the_rows_tint() { + fn a_new_color_from_the_edit_tab_drops_the_rows_tint() { let tinted = || { let mut r = rows(); for row in &mut r { @@ -1007,7 +1007,7 @@ mod tests { }; let mut r = tinted(); apply_rule(&mut r, Harmony::Triad, 0, Color::rgb(1.0, 0.0, 0.0), &[0, 1, 2]); - assert_eq!(r[0]["tint"], json!(40.0), "the base row's colour stays"); + assert_eq!(r[0]["tint"], json!(40.0), "the base row's color stays"); assert!(r[1].get("tint").is_none() && r[2].get("tint").is_none(), "{r:?}"); let mut r = tinted(); move_color(&mut r, 0, [120.0, 1.0, 1.0], false); From 01798d86ab2a04daa549767684b336a413317481 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 05:34:19 -0800 Subject: [PATCH 028/674] 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 1f24099dd99ac67f1ce6c62f80aefd9d320c3e61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:22:13 -0800 Subject: [PATCH 029/674] .ai save: test that a file opens from its VectorCraft document when the editing copy differs A .ai whose editing copy for other apps holds no transparency, while the VectorCraft document it carries holds 50% opacity, opens in VectorCraft with the opacity of the VectorCraft document. Read with native: false, the same file gives the editing copy. --- crates/engine/src/cmd/fileio/tests_pdfedit.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 358c9840c1..7b9f9774f3 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -451,3 +451,29 @@ fn ai_files_carry_an_editing_copy_for_other_apps() { assert_eq!(vectorcraft_pdf::illustrator_data(&b64(&r), None), None); assert!(s.execute("document.export", &json!({"format": "ai", "editingData": "no"})).is_err()); } + +/// A `.ai` whose editing copy for other apps differs from the VectorCraft document it carries (the +/// copy has no transparency) opens in VectorCraft from the VectorCraft document. +#[test] +fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap()); + let opacities = |doc: &vectorcraft_doc::Document| { + let mut out = vec![]; + doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) { + out.push(n.opacity); + } + }); + out + }; + let copy = load::load_with("art.ai", &bytes, &LoadOptions { native: false, trust_editing_data: true, ..Default::default() }).unwrap(); + assert!(copy.editing_data && !copy.restored); + assert_eq!(opacities(©.doc), [1.0]); + let opened = load::load_with("art.ai", &bytes, &LoadOptions::default()).unwrap(); + assert!(opened.restored); + assert_eq!(opacities(&opened.doc), [0.5]); +} From 827e137b5cc0283dd201e52fdca2c2d899117cdb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:42:33 -0800 Subject: [PATCH 030/674] Paste: in front or back of a compound path's member, other art goes beside the compound path With a member of a compound path selected, Paste in Front and Paste in Back put the clipboard's objects next to that member, inside the compound path, whatever they were. A pasted group, compound path or type object then sat inside a compound path, which holds only paths. The model-based test `random_command_sequences` stops on this with "compound #N has a non-path child". When the clipboard holds anything other than paths, the objects now go right above or below the compound path. Paths still go next to the member, inside the compound path. --- crates/engine/src/cmd/edit.rs | 15 ++++++++++-- crates/engine/src/tests/clipboard.rs | 36 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a00f90952a..3427e23f15 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -813,11 +813,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho && (st.doc.paste_remembers_layers || boards.is_some()) && parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer)); // Front/back: relative to the selection (top-most / bottom-most selected object); with - // nothing selected, the top / bottom of the current layer. + // nothing selected, the top / bottom of the current layer. Art other than paths goes beside + // the compound path that holds the selected object, not into it. let anchor = if front || back { let order = st.selection.in_paint_order(&st.doc); let a = if front { order.last() } else { order.first() }; - a.and_then(|id| st.doc.position(*id)) + let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })); + a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id)) } else { None }; @@ -900,6 +902,15 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho })) } +/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only +/// paths (a compound path holds paths only). +fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId { + match doc.parent_of(id) { + Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p, + _ => id, + } +} + /// The first unlocked layer or sublayer called `name` (topmost first), or a new top layer. fn layer_named(d: &mut Document, name: &str) -> NodeId { let mut found = None; diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 410a828b9a..3336d384e1 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -563,6 +563,42 @@ fn front_and_back_without_a_selection_use_the_current_layers_ends() { assert_eq!(&l[i - 2..i], &below[..]); } +#[test] +fn front_and_back_beside_a_compound_paths_member_go_beside_the_compound_path() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + sel(&mut s, &[a, b]); + let c = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let members = |s: &Session| doc(s).node(c).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let before = members(&s); + let layer = |s: &Session| doc(s).layers[0].children().unwrap().iter().map(|n| n.id).collect::>(); + // A compound path and a group, each pasted with one of the compound path's members selected. + let other = rect(&mut s, 40.0, 0.0, 10.0, 10.0); + sel(&mut s, &[other]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + for copied in [c, group] { + copy(&mut s, &[copied]); + sel(&mut s, &[before[0]]); + let above = ids_of(&s.execute("edit.pasteInFront", &json!({})).unwrap()); + let l = layer(&s); + let i = l.iter().position(|id| *id == c).unwrap(); + assert_eq!(&l[i + 1..i + 2], &above[..], "right above the compound path"); + sel(&mut s, &[before[1]]); + let below = ids_of(&s.execute("edit.pasteInBack", &json!({})).unwrap()); + let l = layer(&s); + let i = l.iter().position(|id| *id == c).unwrap(); + assert_eq!(&l[i - 1..i], &below[..], "right below the compound path"); + assert_eq!(members(&s), before, "the compound path keeps its own members"); + } + // A path still goes in front of the member, inside the compound path. + let loose = rect(&mut s, 60.0, 0.0, 10.0, 10.0); + copy(&mut s, &[loose]); + sel(&mut s, &[before[0]]); + let path = ids_of(&s.execute("edit.pasteInFront", &json!({})).unwrap()); + assert_eq!(members(&s), [before[0], path[0], before[1]]); +} + #[test] fn paste_on_all_artboards_keeps_the_offset_to_the_source_artboard() { let mut s = Session::new(); From f1fd255120faf9dfc3b9ce497d75ff80acc20a9a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:41:28 -0800 Subject: [PATCH 031/674] .ai import: version 7 palettes keep their swatches without names Version 7 files write each palette swatch as its paint and `Pc`, with no name. The reader only kept a swatch with a name before `Pc`, so such a palette gave no swatches and the document got the default set. A swatch without a name is now named by its spot color, gradient or pattern, or by its values in the format the swatch import already uses for unnamed colors ("Gray K=25", "C=25 M=0 Y=0 K=0"). `Pn` and a `Pc` with no paint before it add nothing. Named swatches keep their names. An operator the reader does not know, or a `Pg`, now ends the paint before it, so a later `(name) Pc` no longer takes that paint. The swatch limit is kept with a running count instead of summing every group at each `Pc`. --- crates/engine/tests/import_fuzz.rs | 12 +- crates/eps/src/import/ai/palette.rs | 123 +++++++++++++++++---- crates/eps/src/import/tests_illustrator.rs | 37 +++++++ docs/file-format-parity.md | 2 + 4 files changed, 149 insertions(+), 25 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 19c6ef93af..931963de39 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2623,11 +2623,12 @@ fn ascii85(data: &[u8]) -> String { const PATTERN: &str = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 6 6\n%_0 A\n%_0 Ae\n%_u\n%_0 0 m\n%_0 6 L\n%_6 6 L\n%_6 0 L\n%_n\n%_0 0 0 1 K\n%_1 J 1 w\n%_3 3 m\n%_3 3 L\n%_S\n%_U\n%_9 () XW\nE\n%AI3_EndPattern\n"; /// The swatches in editing data: process, spot (one the art doesn't use), global, a gradient that -/// isn't defined and a pattern, a colour group, and versioned content read once. -const PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n%AI17_Begin_Content_if_version_gt:24 15\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n\ +/// isn't defined and a pattern, a colour group, versioned content read once, and the None swatch +/// and a swatch without a name, as version 7 files write them. +const PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\nPn\nPc\n%AI17_Begin_Content_if_version_gt:24 15\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n\ 0 0 0 1 k\n(Black)\nPc\n0.1 0.9 0.8 0 (Unused ink) 0 x\n(Unused ink)\nPc\n0 0 0 1 0 0 0 (Black global) 0 1 Xk\n(Black global)\nPc\n\ Bb\n2 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(G)\nPc\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Dots)\nPc\n\ - %AI17_Alternate_Content\n0 0 0 1 k\n(Black)\nPc\n%AI17_End_Versioned_Content\n1 (Greys) 1 Pg\n0 0 0 0.5 k\n(K50)\nPc\nPB\n%AI5_EndPalette\n"; + %AI17_Alternate_Content\n0 0 0 1 k\n(Black)\nPc\n%AI17_End_Versioned_Content\n1 (Greys) 1 Pg\n0 0 0 0.5 k\n(K50)\nPc\n0.75 g\nPc\nPB\n%AI5_EndPalette\n"; /// The editing data of a file with every sort of object the layers reader knows, and some it doesn't. fn editing_text() -> String { @@ -2697,8 +2698,9 @@ fn the_editing_fixture_reads_its_palette() { let swatches: Vec<&str> = doc.swatches.iter().map(|s| s.name.as_str()).collect(); assert_eq!(swatches, ["[None]", "Black", "Unused ink", "Black global", "Dots"]); assert!(doc.swatch("Unused ink").is_some_and(|s| s.spot && s.global)); - let groups: Vec<(&str, usize)> = doc.swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.len())).collect(); - assert_eq!(groups, [("Greys", 1)]); + let groups: Vec<(&str, Vec<&str>)> = + doc.swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|s| s.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Greys", vec!["K50", "Gray K=25"])], "the swatch without a name is named by its values"); } /// The fuzzed editing data, as it is, reads its CMYK image with its ink amounts and its alpha diff --git a/crates/eps/src/import/ai/palette.rs b/crates/eps/src/import/ai/palette.rs index 43955d5fc3..9a4ba72ebc 100644 --- a/crates/eps/src/import/ai/palette.rs +++ b/crates/eps/src/import/ai/palette.rs @@ -2,10 +2,13 @@ //! `%AI5_EndPalette`, as written in files users sent. //! //! - `0 0 Pb` starts the swatches and `PB` ends them. -//! - Each swatch is its paint, then `(name) Pc`. The paint is a colour operator (`g`, `k`, `Xa`: a -//! process colour; `x`, `Xx`: a spot colour; `Xk`: a global process colour), a gradient -//! (`Bb` … `flag (gradient) … Bg` … `BB`) or a pattern (`(pattern) … p`). `Xs` and `Xz` paint -//! with Registration, which every document has. +//! - Each swatch is its paint, then an optional `(name)`, then `Pc`. The paint is a colour operator +//! (`g`, `k`, `Xa`: a process colour; `x`, `Xx`: a spot colour; `Xk`: a global process colour), a +//! gradient (`Bb` … `flag (gradient) … Bg` … `BB`) or a pattern (`(pattern) … p`). `Xs` and `Xz` +//! paint with Registration, which every document has. +//! - A swatch without a name (version 7 files write none) is named by its spot colour, gradient or +//! pattern, or by its values as [`color_name`] gives them. `Pn` (the None swatch) and a `Pc` with +//! no paint before it add nothing: the document has `[None]` already. //! - `flag (name) count Pg` starts a colour group: the swatches up to the next `Pg` or `PB` are //! its own. //! - Newer files write the swatches between `%AI17_Begin_Content_if_version_gt` and @@ -13,9 +16,14 @@ //! the first are read, the others skipped. //! //! Anything else in the section (an operator it doesn't know) is left alone: the swatches around -//! it still come in. +//! it still come in, and a paint before it makes no swatch. +//! +//! "AI7 spec": Adobe Illustrator File Format Specification, version 7.0 (1998), listed by PRONOM at +//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §11 documents the palette operators, and its +//! example writes the swatches without names. use vectorcraft_color::Color; +use vectorcraft_doc::swatches::color_name; use super::lex::{Lexer, Tok}; use super::obj::V; @@ -55,9 +63,6 @@ impl Palette { pub fn is_empty(&self) -> bool { self.swatches.is_empty() && self.groups.iter().all(|(_, s)| s.is_empty()) } - fn len(&self) -> usize { - self.swatches.len() + self.groups.iter().map(|(_, s)| s.len()).sum::() - } } /// The palette of `data`: what follows `%AI5_BeginPalette`, up to its end. @@ -65,8 +70,10 @@ pub(super) fn palette(data: &[u8]) -> Palette { let mut lex = Lexer::new(data); let mut out = Palette::default(); let mut vals: Vec = Vec::new(); - // The paint of the swatch being read. - let mut cell: Option = None; + // The paint of the swatch being read, with the name it gets when `Pc` gives none. + let mut cell: Option = None; + // How many swatches have been read. + let mut count = 0usize; // Inside a gradient's `Bb` … `BB`. let mut in_gradient = false; // How deep in versioned content, and the depth of the block whose later alternatives (which @@ -111,19 +118,20 @@ pub(super) fn palette(data: &[u8]) -> Palette { } "Bg" if in_gradient => { if let Some(name) = last_text(&vals) { - cell = Some(Cell::Gradient(name)); + cell = Some(Entry { cell: Cell::Gradient(name.clone()), name }); } } "BB" => in_gradient = false, - "p" => cell = first_text(&vals).map(Cell::Pattern), + "p" => cell = first_text(&vals).map(|name| Entry { cell: Cell::Pattern(name.clone()), name }), "Xs" | "Xz" | "XS" | "XZ" => cell = None, "g" | "k" | "x" | "Xa" | "Xx" | "Xk" => { cell = paint::color_op(w, &vals).and_then(|(p, named)| match named { - Some(Named { color, spot, .. }) => Some(Cell::Color { color, global: true, spot }), - None => p.color().map(|color| Cell::Color { color, global: false, spot: false }), + Some(Named { name, color, spot, .. }) => Some(Entry { name, cell: Cell::Color { color, global: true, spot } }), + None => p.color().map(|color| Entry { name: color_name(color), cell: Cell::Color { color, global: false, spot: false } }), }); } "Pg" => { + cell = None; // Capped as swatches are: a file of many `Pg` would make as many empty groups. if let Some(name) = first_text(&vals) && out.groups.len() < MAX_SWATCHES @@ -132,19 +140,27 @@ pub(super) fn palette(data: &[u8]) -> Palette { } } "Pc" => { - if let (Some(name), Some(c)) = (last_text(&vals), cell.take()) - && !name.starts_with('[') - && out.len() < MAX_SWATCHES + // The name before `Pc`, or the one the paint gives; `[Registration]` and the other + // built-in swatches every document has are left out. + let name = last_text(&vals); + if let Some(mut e) = cell.take() + && !name.as_ref().is_some_and(|n| n.starts_with('[')) + && count < MAX_SWATCHES { - let e = Entry { name, cell: c }; + if let Some(name) = name { + e.name = name; + } + count += 1; match out.groups.last_mut() { Some((_, g)) => g.push(e), None => out.swatches.push(e), } } - cell = None; } - _ => {} + // A gradient's other operators (its focal point, its matrices) are part of its paint. + _ if in_gradient => {} + // Anything else ends the paint before it, which no `Pc` then makes a swatch of. + _ => cell = None, } vals.clear(); } @@ -235,4 +251,71 @@ mod tests { let p = palette(b"0 0 Pb\n1 2 3 Zz\n(Odd)\nPc\n(no paint) Pc\n0 0 0 1 k\n(Black)\nPc\nPB\n"); assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["Black"]); } + + /// An operator it doesn't know after a paint ends that paint: the `Pc` after it makes no swatch. + #[test] + fn a_paint_before_an_unknown_operator_makes_no_swatch() { + let p = palette(b"0 0 Pb\n0 1 1 0 k\nZz\n(Odd)\nPc\n0.5 g\n1 (Group) 1 Pg\nPc\n0 0 0 1 k\n(Black)\nPc\nPB\n"); + assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), Vec::<&str>::new()); + let groups: Vec<(&str, Vec<&str>)> = p.groups.iter().map(|(n, s)| (n.as_str(), s.iter().map(|e| e.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Group", vec!["Black"])]); + } + + /// The palette of the AI7 spec's example (§11): `Pn`, then each swatch's paint and `Pc` with no + /// name, then a last `Pc`. Each swatch is named by its spot colour or gradient, or by its values; + /// `1 g` is white (§5.4.1). + #[test] + fn swatches_without_names_are_named_by_their_paint() { + let p = palette( + b"0 0 Pb\nPn\nPc\n1 g\nPc\n0 g\nPc\n0 0 0 0 k\nPc\n0.75 g\nPc\n\ + Bb\n2 (B&W) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n0.25 0 0 0 k\nPc\n\ + 0 1 1 0 (Spot A) 0 x\nPc\n0.75 g\nPc\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\nPc\nPB\n", + ); + assert!(p.groups.is_empty()); + assert_eq!( + p.swatches, + vec![ + color("Gray K=0", Color::gray(0.0), false, false), + color("Gray K=100", Color::gray(1.0), false, false), + color("C=0 M=0 Y=0 K=0", Color::cmyk(0.0, 0.0, 0.0, 0.0), false, false), + color("Gray K=25", Color::gray(0.25), false, false), + Entry { name: "B&W".into(), cell: Cell::Gradient("B&W".into()) }, + color("C=25 M=0 Y=0 K=0", Color::cmyk(0.25, 0.0, 0.0, 0.0), false, false), + color("Spot A", Color::cmyk(0.0, 1.0, 1.0, 0.0), true, true), + color("Gray K=25", Color::gray(0.25), false, false), + Entry { name: "Dots".into(), cell: Cell::Pattern("Dots".into()) }, + ] + ); + // RGB and global process colours too. + let p = palette(b"0 0 Pb\n0 0 0 0 1 0.5 0 Xa\nPc\n0 0.5 1 0 1 0.5 0 (Brand) 0 1 Xk\nPc\nPB\n"); + assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["R=255 G=128 B=0", "Brand"]); + } + + /// Named and unnamed swatches in one palette: the named ones keep their names, and built-in + /// swatches are still left out. + #[test] + fn named_swatches_keep_their_names_beside_unnamed_ones() { + let p = palette( + b"0 0 Pb\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n0 0 0 1 k\n(Black)\nPc\n0 0 0 0.5 k\nPc\n\ + 1 (Greys) 1 Pg\n0.4 g\n(Mid)\nPc\n0.4 g\nPc\nPB\n", + ); + assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["Black", "C=0 M=0 Y=0 K=50"]); + let groups: Vec<(&str, Vec<&str>)> = p.groups.iter().map(|(n, s)| (n.as_str(), s.iter().map(|e| e.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Greys", vec!["Mid", "Gray K=60"])]); + } + + /// No more than `MAX_SWATCHES` swatches, counted across the colour groups. + #[test] + fn swatches_are_capped_across_groups() { + let mut data = b"0 0 Pb\n".to_vec(); + for i in 0..MAX_SWATCHES / 1000 + 1 { + data.extend(format!("1 (G{i}) 1 Pg\n").as_bytes()); + data.extend("0.5 g\nPc\n".repeat(1000).as_bytes()); + } + data.extend(b"PB\n"); + let p = palette(&data); + assert_eq!(p.groups.len(), MAX_SWATCHES / 1000 + 1); + assert_eq!(p.swatches.len() + p.groups.iter().map(|(_, s)| s.len()).sum::(), MAX_SWATCHES); + assert!(p.groups.last().is_some_and(|(_, s)| s.is_empty())); + } } diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 19c79deeb8..7543e51588 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -3,6 +3,7 @@ use std::sync::Arc; +use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::clipnest::MAX_NEST; use vectorcraft_doc::{LayerColor, LineCap, Node, NodeKind}; use vectorcraft_geom::Rect; @@ -26,6 +27,16 @@ fn ai(header: &str, ugroup: &str, body: &str) -> Vec { /// published specification documents; see the `import` module docs). const AI8: &str = "%%Creator: Adobe Illustrator(R) 8.0\n%AI5_FileFormat 4.0\n"; +/// The editing text of a version 7 file (`%AI5_FileFormat 3`), no prolog: `setup` in its setup, +/// then `body`. +fn stream7(setup: &str, body: &str) -> Vec { + format!( + "%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 100 100\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 100 100\n%%EndComments\n\ + %%BeginProlog\n%%EndProlog\n%%BeginSetup\n{setup}%%EndSetup\n{body}%%PageTrailer\n%%Trailer\n%%EOF\n" + ) + .into_bytes() +} + /// A triangle filled at `x`. fn tri(x: u32) -> String { format!("{x} {x} m {} {x} L {} {} L f", x + 5, x + 5, x + 5) @@ -209,6 +220,32 @@ fn a_legacy_file_with_its_prolog_comes_in_through_its_layers() { assert_eq!(page.document.layers[0].name.as_deref(), Some("Layer 1")); } +/// A version 7 palette writes no swatch names (the AI7 spec's §11 example): its swatches come in +/// named by their paint, in its order, in place of the defaults. +#[test] +fn a_version_7_palette_keeps_its_swatches_without_names() { + let setup = "%AI5_BeginGradient: (B&W)\n(B&W) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n\ + %AI5_BeginPalette\n0 0 Pb\nPn\nPc\n1 g\nPc\n0 g\nPc\n0 0 0 0 k\nPc\n0.75 g\nPc\n\ + Bb\n2 (B&W) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n0.25 0 0 0 k\nPc\n0 1 1 0 (Spot A) 0 x\nPc\n0.75 g\nPc\nPc\nPB\n%AI5_EndPalette\n"; + let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 -1 79 128 255 0 50 0 Lb\n(Art) Ln\n0 A\n0 Xw\n0 0 0 1 k\n{}\nLB\n%AI5_EndLayer--\n", tri(10)); + let r = import(&stream7(setup, &body)).unwrap(); + let d = &r.document; + assert_eq!(d.layers.len(), 1, "{:?}", r.warnings); + let names: Vec<&str> = d.swatches.iter().map(|s| s.name.as_str()).collect(); + assert_eq!( + names, + ["[None]", "Gray K=0", "Gray K=100", "C=0 M=0 Y=0 K=0", "Gray K=25", "B&W", "C=25 M=0 Y=0 K=0", "Spot A", "Gray K=25"], + "{:?}", + r.warnings + ); + assert!(d.swatch_groups.is_empty()); + let spot = d.swatch("Spot A").unwrap(); + assert!(spot.spot && spot.global, "{spot:?}"); + assert!(d.swatches.iter().filter(|s| s.name != "Spot A").all(|s| !s.spot && !s.global)); + assert!(matches!(&d.swatch("B&W").unwrap().paint, Paint::Gradient(g) if g.swatch.as_deref() == Some("B&W"))); + assert_eq!(d.swatch("Gray K=0").unwrap().paint.color(), Some(Color::gray(0.0)), "1 g is white"); +} + #[test] fn unbalanced_and_runaway_groups_are_read_safely() { // Ends without a beginning end nothing; groups left open hold the rest. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index de7e1cfce0..c868252dd1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -49,6 +49,8 @@ private editing data. VectorCraft: A PDF-compatible `.ai` opens on its PDF part's trim boxes (its artboards), the bleed boxes round them becoming the document's bleed, so art in the bleed shows outside the artboard, within the bleed guide (#1266). A PDF saved with its editing data (`AIPDFPrivateData`) opens the same way. + The swatches of a version 7 `.ai` palette, which carry no names, come in named by their spot color, gradient or + values. - **Writes** a PDF-compatible `.ai` (Save As › `ai`): Illustrator opens it as plain art. It never writes Illustrator's private editing data, which is undocumented. - **Writes** a legacy `.ai` of version 7 (Save As › `ai` › Version: Legacy (version 7), `aiVersion: "7"`): the From f98b086c5f017b2198f14285e2248049bca7f5a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:23:40 -0800 Subject: [PATCH 032/674] Variables: Rename reports a missing variable or data set before a taken name variable.rename and dataset.rename checked whether newName was taken before checking that name exists, so renaming a missing name onto a taken one said the new name already exists. Both now report the missing name first. --- crates/engine/src/cmd/variablecmds.rs | 6 ++++++ crates/engine/src/tests/variables.rs | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 116149ec78..da1eb33a7b 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -160,6 +160,9 @@ fn rename(s: &mut Session, p: &Value) -> Result { let from = var_name(p, C)?; let to = named(p.get("newName").and_then(Value::as_str), "newName", C)?; let st = s.doc()?; + if st.doc.variables.variable(&from).is_none() { + return Err(bad(C, format!("no variable named `{from}`"))); + } if st.doc.variables.variable(&to).is_some() { return Err(bad(C, format!("variable `{to}` already exists"))); } @@ -357,6 +360,9 @@ fn dataset_rename(s: &mut Session, p: &Value) -> Result { let from = var_name(p, C)?; let to = named(p.get("newName").and_then(Value::as_str), "newName", C)?; let st = s.doc()?; + if st.doc.variables.dataset(&from).is_none() { + return Err(bad(C, format!("no dataset named `{from}`"))); + } if st.doc.variables.dataset(&to).is_some() { return Err(bad(C, format!("dataset `{to}` already exists"))); } diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index bdacd0e1bf..fd502d1b83 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -652,6 +652,20 @@ fn renaming_carries_the_bindings_and_values_with_it() { assert!(s.execute("dataset.rename", &json!({"name": "Title", "newName": "Taken"})).is_err()); } +/// Renaming a name that does not exist onto one that does reports the missing name, the same +/// error a rename to a free name gives. +#[test] +fn renaming_a_missing_name_onto_a_taken_one_reports_the_missing_name() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "A", "kind": "text"})).unwrap(); + s.execute("dataset.new", &json!({"name": "A"})).unwrap(); + + let e = s.execute("variable.rename", &json!({"name": "Nope", "newName": "A"})).unwrap_err().to_string(); + assert!(e.contains("no variable named `Nope`"), "{e}"); + let e = s.execute("dataset.rename", &json!({"name": "Nope", "newName": "A"})).unwrap_err().to_string(); + assert!(e.contains("no dataset named `Nope`"), "{e}"); +} + /// `dataset.set` is how a value changes after the row exists: replacing it must not need the /// dataset to be deleted and rebuilt (which loses its place in the list and the active one). #[test] From 07282d95e0f9d5f24a2a6aebae51f76a093b6084 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:38:15 -0800 Subject: [PATCH 033/674] Variables: a graph variable's data set applies its CSV as graph.setData does Choosing a data set gave a graph variable's CSV to the graph without the two steps graph.setData takes after new data: rows with neither a label nor a value were kept and drawn as empty slots, and a right-axis series the new data no longer had stayed assigned, so a series added by a later row started on the right axis. The data set now goes through the same steps. --- crates/engine/src/cmd/graph/data.rs | 20 +++++++++++--------- crates/engine/src/tests/variables.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index e81f24febd..362f988f07 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -86,7 +86,8 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { g.to_csv() } -/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge). +/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with +/// `csv` does. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { let Some(node) = d.node(id) else { return Err(EngineError::NoNode(id)); @@ -94,13 +95,17 @@ pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { let Some(mut spec) = node.extras().graph.as_deref().cloned() else { return Err(bad("graph.applyCsv", format!("node {} is not a graph", id.0))); }; - let (series, categories, rows) = parse_csv(csv); - spec.series = series; - spec.categories = categories; - spec.set_cells(rows); + apply_data(&mut spec, &json!({ "csv": csv })); + keep_right_series(&mut spec); regenerate(d, id, spec) } +/// Drop right-axis series the data no longer has, so a series added later starts on the left. +fn keep_right_series(g: &mut GraphSpec) { + let count = g.rows.iter().map(Vec::len).max().unwrap_or(0); + g.right_series.retain(|i| *i < count); +} + pub(super) fn apply_data(g: &mut GraphSpec, p: &Value) -> bool { let mut changed = false; if let Some(csv) = str_param(p, "csv") { @@ -185,10 +190,7 @@ pub(super) fn set_data(s: &mut Session, p: &Value) -> Result { // Blank cells come back as null, so the rows can be edited and sent back as they are. return Ok(json!({ "csv": to_csv(&spec), "series": spec.series, "categories": spec.categories, "rows": spec.cells() })); } - // Series assigned to the right axis that the new data no longer has are dropped, so a series added later starts - // on the left. - let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0); - spec.right_series.retain(|i| *i < count); + keep_right_series(&mut spec); s.edit("Graph Data", |d, _| regenerate(d, id, spec))?; Ok(json!({ "id": id.0 })) } diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index bdacd0e1bf..fb252d8545 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1632,6 +1632,34 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() { assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::>(), ["B"]); } +/// A graph variable's data set applies its CSV as `graph.setData` does: a right-axis series the row's data no longer +/// has is dropped, and a row with neither a label nor a value is not drawn as an empty slot. +#[test] +fn graph_variable_applies_csv_as_set_data() { + let mut s = session(); + let create = json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",a,b\nQ1,10,1000\nQ2,5,500"}); + let id = s.execute("graph.create", &create).unwrap()["id"].as_u64().unwrap(); + let other = s.execute("graph.create", &create).unwrap()["id"].as_u64().unwrap(); + for g in [id, other] { + s.execute("graph.setType", &json!({"id": g, "seriesIndexes": [1], "valueAxis": "right"})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("variable.makeGraphDynamic", &json!({})).unwrap(); + let name = s.execute("variable.list", &json!({})).unwrap()["variables"][0]["name"].as_str().unwrap().to_string(); + let spec = |s: &Session, g: u64| s.doc().unwrap().doc.node(NodeId(g)).unwrap().extras().graph.as_deref().unwrap().clone(); + for (row, csv) in [("One", ",a\nQ1,10\nQ2,5"), ("Blank", ",a\nQ1,10\n,\nQ2,5")] { + s.execute("dataset.new", &json!({"name": row, "values": {name.clone(): csv}})).unwrap(); + s.execute("dataset.select", &json!({"name": row})).unwrap(); + s.execute("graph.setData", &json!({"id": other, "csv": csv})).unwrap(); + let (merged, set) = (spec(&s, id), spec(&s, other)); + assert_eq!(merged.right_series, set.right_series, "{row}"); + assert_eq!(merged.categories, set.categories, "{row}"); + assert_eq!(merged.cells(), set.cells(), "{row}"); + } + assert!(spec(&s, id).right_series.is_empty()); + assert_eq!(spec(&s, id).categories, ["Q1", "Q2"]); +} + #[test] fn graph_variable_applies_csv_and_captures() { let mut s = session(); From e49e102032735b263b027868caa480748eb43121 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:43:56 -0800 Subject: [PATCH 034/674] Variables: Lock Variables' description names the refused import variable.lock's params text and the doc comment on Variables::locked said every dataset command still runs while the variables are locked. dataset.import is refused when its header would define a variable; both texts now say so, as docs/mcp.md and dataset.import's params already do. --- crates/doc/src/variables.rs | 3 ++- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/tests/variables.rs | 11 ++++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/variables.rs b/crates/doc/src/variables.rs index 96bccbd0a5..09682a1061 100644 --- a/crates/doc/src/variables.rs +++ b/crates/doc/src/variables.rs @@ -117,7 +117,8 @@ pub struct Variables { #[serde(default, skip_serializing_if = "Option::is_none")] pub active_dataset: Option, /// Lock Variables: while set, variables can't be defined, deleted or renamed. Objects can - /// still be bound to them and unbound, and datasets still change and apply. + /// still be bound to them and unbound, and datasets still change and apply, except that an + /// import whose header would define a variable is refused. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub locked: bool, } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 116149ec78..0d78832275 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -641,7 +641,7 @@ pub fn specs() -> Vec { "Lock Variables", ["Window", "Variables"], None, - "{locked?: bool} lock or unlock the variables (default: toggle); saved with the document; a change is one undo step. While locked, variable.define, variable.delete, variable.rename, variable.make…Dynamic and a variable.loadLibrary that would delete or define a variable are refused; binding, unbinding and the dataset commands still run → {locked}", + "{locked?: bool} lock or unlock the variables (default: toggle); saved with the document; a change is one undo step. While locked, variable.define, variable.delete, variable.rename, variable.make…Dynamic and a variable.loadLibrary that would delete or define a variable are refused; binding, unbinding and the dataset commands still run, except a dataset.import whose header would define a variable → {locked}", has_doc, lock ), diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index bdacd0e1bf..73cdccb85e 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -409,7 +409,8 @@ fn make_dynamic_errors_name_the_command() { } /// Lock Variables refuses defining, deleting and renaming variables, Make … Dynamic included, -/// while binding, unbinding and the dataset commands still run. +/// while binding, unbinding and the dataset commands still run (an import that would define a +/// variable is refused; see `locked_variables_refuse_header_cells_that_define_variables`). #[test] fn locked_variables_refuse_new_deleted_and_renamed_variables() { let mut s = session(); @@ -1324,6 +1325,14 @@ fn locked_variables_refuse_header_cells_that_define_variables() { assert_eq!(imp["defined"], json!(["New"])); } +/// `variable.lock`'s params text names the dataset command it refuses: an import whose header +/// would define a variable. +#[test] +fn the_lock_params_text_names_the_refused_import() { + let params = cmd::find_command("variable.lock").unwrap().params; + assert!(params.contains("the dataset commands still run, except a dataset.import whose header would define a variable"), "{params}"); +} + /// Import / export datasets as CSV: header `name` then variables; round-trip keeps values. #[test] fn datasets_csv_round_trips_and_rejects_bad_input() { From be20929877974949c4eff9bfdb46fa730aa4d139 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:58:35 -0800 Subject: [PATCH 035/674] Variables: a text value on threaded type replaces the whole story Applying a data set wrote a text value into the bound frame only, and the thread's reflow then joined it with the other frames' old text. The art no longer matched the row it had just applied, a captured row applied back lost text, and a value bound to a later frame deleted the rest of the story. - A text value bound to any frame of threaded text replaces the whole story, which then flows through the frames again. `overflow` names the story's last frame. - Capture Data Set, Update Data Set and the Variables panel's match check read such a frame as the whole story, frames joined in thread order. - When any frame of the story is locked, the text value is skipped and counted in `skipped`, and the story is not read. - Two text variables bound in one story apply in definition order, as for two on one object: the one defined last wins. Docs: docs/mcp.md. --- crates/doc/src/variables.rs | 41 ++++++++-- crates/engine/src/cmd/textedit.rs | 42 ++++++++++ crates/engine/src/cmd/variablecmds.rs | 20 +++-- crates/engine/src/tests/variables.rs | 107 ++++++++++++++++++++++++++ docs/mcp.md | 7 ++ 5 files changed, 203 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/variables.rs b/crates/doc/src/variables.rs index 96bccbd0a5..ca0b2ea177 100644 --- a/crates/doc/src/variables.rs +++ b/crates/doc/src/variables.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use super::{Document, NodeId, NodeKind}; +use super::{Document, NodeId, NodeKind, TextKind}; /// What a variable drives. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -202,17 +202,46 @@ impl Document { self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked))) } - /// What the object `id` holds for the variable of `kind`: its characters, whether it shows, - /// or a linked image's path. `None` when the object is gone, is not of that kind, has no - /// link path yet (an embedded image), or is locked or in a locked layer or group (the - /// document's value is whatever it was left at). + /// The type objects of the story that the type object `id` belongs to, in thread order: the + /// frames of its threaded text (area type and type on a path), else `id` alone. + pub fn story_of(&self, id: NodeId) -> Vec { + let frame = |f: &NodeId| matches!(self.node(*f).map(|n| &n.kind), Some(NodeKind::Text(t)) if !matches!(t.kind, TextKind::Point)); + match self.text_threads.iter().find(|thread| thread.contains(&id)) { + Some(thread) if frame(&id) => thread.iter().filter(|f| frame(f)).copied().collect(), + _ => vec![id], + } + } + + /// The characters of the story that the type object `id` belongs to ([`Document::story_of`]): + /// every frame's text joined in thread order. + pub fn story_text(&self, id: NodeId) -> String { + self.story_of(id) + .into_iter() + .filter_map(|f| match self.node(f).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t.plain_text()), + _ => None, + }) + .collect() + } + + /// Whether a data set reads and rewrites the text of the type object `id`: every frame of its + /// story ([`Document::story_of`]) is a [`Document::dataset_target`]. + pub fn story_target(&self, id: NodeId) -> bool { + self.story_of(id).into_iter().all(|f| self.dataset_target(f)) + } + + /// What the object `id` holds for the variable of `kind`: its characters (the whole story + /// for a frame of threaded text), whether it shows, or a linked image's path. `None` when the + /// object is gone, is not of that kind, has no link path yet (an embedded image), or is locked + /// or in a locked layer or group, or for text when a frame of its story is (the document's + /// value is whatever it was left at). pub fn variable_value(&self, id: NodeId, kind: VariableKind) -> Option { if !self.dataset_target(id) { return None; } let node = self.node(id)?; match (kind, &node.kind) { - (VariableKind::Text, NodeKind::Text(t)) => Some(DataValue::Text(t.plain_text())), + (VariableKind::Text, NodeKind::Text(_)) if self.story_target(id) => Some(DataValue::Text(self.story_text(id))), (VariableKind::Visibility, _) => Some(DataValue::Visible(node.visible)), (VariableKind::Image, NodeKind::Image(im)) => im.link.as_ref().map(|l| DataValue::Image(l.path.clone())), (VariableKind::Graph, _) => node.extras().graph.as_ref().map(|g| DataValue::Graph(g.to_csv())), diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index c028e29b1f..88f1b6a59a 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -186,6 +186,48 @@ pub(crate) fn set_plain_text(d: &mut vectorcraft_doc::Document, id: NodeId, text Ok(()) } +/// Replace the whole story of the type object `id` as [`set_plain_text`] replaces one type +/// object's content: for a frame of threaded text, every frame's text. The new text goes into the +/// thread's first frame and the other frames are emptied; the edit's reflow then pours it through +/// them. → the story's last frame, which holds any text that does not fit. +pub(crate) fn set_story_text(d: &mut vectorcraft_doc::Document, id: NodeId, text: &str) -> Result { + let story = d.story_of(id); + let (Some((&first, rest)), Some(&last)) = (story.split_first(), story.last()) else { + return Err(EngineError::NoNode(id)); + }; + if rest.is_empty() { + set_plain_text(d, id, text)?; + return Ok(id); + } + let frames: Vec = story + .iter() + .filter_map(|f| match d.node(*f).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some((**t).clone()), + _ => None, + }) + .collect(); + let refs: Vec<&TextObject> = frames.iter().collect(); + // The first frame takes the whole story first, so the replace keeps the story's first style + // and paragraph styles follow as for one type object. + let t = text_mut(d, first).ok_or(EngineError::NoNode(first))?; + t.runs = vectorcraft_text::thread::story(&refs); + t.set_paragraph_styles(vectorcraft_text::thread::story_paras(&refs, &[])); + set_plain_text(d, first, text)?; + // An emptied frame's paragraph takes the new text's last paragraph style, so it does not + // restyle that paragraph when the story is joined again. + let tail = match d.node(first).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.paragraph_styles().last().cloned().unwrap_or_default(), + _ => Default::default(), + }; + for f in rest { + let t = text_mut(d, *f).ok_or(EngineError::NoNode(*f))?; + t.runs.clear(); + t.set_paragraph_styles(vec![tail.clone()]); + refresh_bounds(t); + } + Ok(last) +} + /// The byte offset that `k` holds, read with [`index`]. fn byte_param(p: &Value, k: &str) -> Option { p.get(k).and_then(Value::as_u64).map(index) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 116149ec78..adbfe6aa04 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -18,7 +18,7 @@ use vectorcraft_doc::{DataSet, DataValue, NodeId, NodeKind, Variable, VariableKi use super::edit::selected_roots; use super::fileio::{absolute_path, read_file_head, write_file}; -use super::textedit::set_plain_text; +use super::textedit::set_story_text; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param}; mod csv; @@ -487,16 +487,20 @@ fn apply_dataset(s: &mut Session, name: &str) -> Result { }; // Locked art, art in a locked layer or group, and text whose object is gone, can't be // rewritten: skipped and counted, like the rest. Hidden art is rewritten, in a hidden - // layer or group too, and stays hidden unless a visibility value shows it. - if !d.dataset_target(id) { + // layer or group too, and stays hidden unless a visibility value shows it. A text value + // rewrites the whole story of threaded text, so it skips when any frame of it is locked. + let target = if kind == VariableKind::Text { d.story_target(id) } else { d.dataset_target(id) }; + if !target { skipped += 1; continue; } let done = match (kind, &value) { // The Type tool's own whole-range replace, so a dataset's text is styled and - // laid out exactly as typing it would be. - (VariableKind::Text, DataValue::Text(text)) => set_plain_text(d, id, text).is_ok_and(|()| { - typed.push(id); + // laid out exactly as typing it would be. A frame of threaded text has its whole + // story replaced, the value capture reads from it; the story's last frame is the + // one that overflows. + (VariableKind::Text, DataValue::Text(text)) => set_story_text(d, id, text).is_ok_and(|last| { + typed.push(last); true }), (VariableKind::Visibility, DataValue::Visible(show)) => d.node_mut(id).is_some_and(|n| { @@ -670,7 +674,7 @@ pub fn specs() -> Vec { "Capture Data Set", ["Window", "Variables"], None, - "{name?} record what the bound objects hold right now as a new dataset (Data Set 1…), and make it the active one", + "{name?} record what the bound objects hold right now as a new dataset (Data Set 1…), and make it the active one; a frame of threaded text holds its whole story, every frame's text in thread order", has_doc, dataset_capture ), @@ -706,7 +710,7 @@ pub fn specs() -> Vec { "Select Data Set", ["Window", "Variables"], None, - "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too) → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}", + "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too); a text value bound to a frame of threaded text replaces the whole story → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits, the story's last frame for threaded text; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}", has_doc, dataset_select ), diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index bdacd0e1bf..738f183ae3 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -114,6 +114,113 @@ fn applying_a_dataset_reports_the_area_type_it_overflows() { assert_eq!((&v["name"], &v["overflow"]), (&json!("Long"), &json!([a.0])), "{v}"); } +/// Area type threaded into a rectangle → (session, first frame, second frame, the story). +fn threaded(second_height: u32) -> (Session, NodeId, NodeId, String) { + let mut s = session(); + let story = "The quick brown fox jumps over the lazy dog and keeps running. ".repeat(3) + "\nSecond paragraph.\nThird."; + let r = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap(); + let a = NodeId(r["id"].as_u64().unwrap()); + let r = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": second_height})).unwrap(); + let b = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + (s, a, b, story) +} + +/// Whether `dataset.list` says the data set `name` matches the art. +fn matches(s: &mut Session, name: &str) -> bool { + let sets = s.execute("dataset.list", &json!({})).unwrap(); + let set = sets["datasets"].as_array().unwrap().iter().find(|d| d["name"] == name).unwrap().clone(); + set["matches"].as_bool().unwrap() +} + +#[test] +fn a_text_value_on_a_frame_of_threaded_type_replaces_the_whole_story() { + let (mut s, a, b, story) = threaded(200); + assert!(!plain(&s, a).is_empty() && !plain(&s, b).is_empty()); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap(); + // A capture reads the whole story, every frame's text in thread order. + s.execute("dataset.capture", &json!({"name": "Orig"})).unwrap(); + let orig = s.doc().unwrap().doc.variables.dataset("Orig").unwrap().values.get("Name").cloned(); + assert_eq!(orig, Some(vectorcraft_doc::DataValue::Text(story.clone()))); + s.execute("dataset.new", &json!({"name": "B", "values": {"Name": "Bob"}})).unwrap(); + + let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64()), (Some(1), Some(0))); + assert_eq!((plain(&s, a), plain(&s, b)), ("Bob".to_string(), String::new())); + assert!(matches(&mut s, "B")); + // The captured row applied back gives the story back, every time. + for _ in 0..2 { + s.execute("dataset.select", &json!({"name": "Orig"})).unwrap(); + assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), story); + assert!(!plain(&s, b).is_empty()); + assert!(matches(&mut s, "Orig")); + s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), "Bob"); + } +} + +#[test] +fn a_text_value_on_a_later_frame_of_threaded_type_replaces_the_whole_story() { + let (mut s, a, b, story) = threaded(200); + s.execute("variable.define", &json!({"name": "Tail", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Tail", "ids": [b.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Orig"})).unwrap(); + s.execute("dataset.new", &json!({"name": "T", "values": {"Tail": "END"}})).unwrap(); + + let v = s.execute("dataset.select", &json!({"name": "T"})).unwrap(); + assert_eq!(v["applied"].as_u64(), Some(1)); + assert_eq!((plain(&s, a), plain(&s, b)), ("END".to_string(), String::new())); + assert!(matches(&mut s, "T")); + s.execute("dataset.select", &json!({"name": "Orig"})).unwrap(); + assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), story); + assert!(matches(&mut s, "Orig")); +} + +#[test] +fn a_story_with_a_locked_frame_is_neither_read_nor_rewritten() { + let (mut s, a, b, story) = threaded(200); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "B", "values": {"Name": "Bob"}})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + + let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64()), (Some(0), Some(1))); + assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), story); + assert!(s.doc().unwrap().doc.captured_values().is_empty()); +} + +#[test] +fn two_text_variables_in_one_story_apply_in_definition_order() { + let (mut s, a, b, _) = threaded(200); + s.execute("variable.define", &json!({"name": "Head", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "Tail", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Tail", "ids": [a.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Head", "ids": [b.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "R", "values": {"Head": "one", "Tail": "two"}})).unwrap(); + + let v = s.execute("dataset.select", &json!({"name": "R"})).unwrap(); + assert_eq!(v["applied"].as_u64(), Some(2)); + assert_eq!(format!("{}{}", plain(&s, a), plain(&s, b)), "two"); +} + +#[test] +fn applying_a_dataset_to_threaded_type_reports_overflow_on_the_last_frame() { + let (mut s, a, b, _) = threaded(40); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "Long", "values": {"Name": "word ".repeat(120)}})).unwrap(); + s.execute("dataset.new", &json!({"name": "Short", "values": {"Name": "Ann"}})).unwrap(); + + let v = s.execute("dataset.select", &json!({"name": "Long"})).unwrap(); + assert_eq!(&v["overflow"], &json!([b.0]), "{v}"); + let v = s.execute("dataset.select", &json!({"name": "Short"})).unwrap(); + assert!(v.get("overflow").is_none(), "{v}"); +} + #[test] fn mismatched_and_missing_bindings_are_skipped_and_counted() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index fa8e05fab3..6ef4071d89 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1747,6 +1747,13 @@ layer is shown again, its type holds the data set's text. They apply the values defined. Of two variables of the same kind on one object, the one defined last wins. `dataset.list`, `dataset.capture` and `dataset.update` read hidden objects and objects inside a hidden layer or group as well. +A text value bound to any frame of threaded text replaces the whole story, and the text flows through the frames +again; `overflow` names the story's last frame when the text does not fit. `dataset.capture`, `dataset.update` and +`dataset.list` read such a frame as the whole story, every frame's text joined in thread order. When any frame of +the story is locked or inside a locked layer or group, the text value is skipped and counted in `skipped`, and the +story is not read. Two text variables +bound in one story apply in the order they are defined, and the one defined last wins. + ```json {"name":"run_command","arguments":{"command":"symbol.list","params":{}}} {"name":"run_command","arguments":{"command":"brush.list","params":{}}} From 77274ac5ffb04809c6c2e10c78d785b11a0c9c66 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 1 Nov 2026 12:29:58 -0500 Subject: [PATCH 036/674] docs: sync Craft App Suite list with ArtCraft Launcher --- README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0b7b9932bb..8a3c453c5c 100644 --- a/README.md +++ b/README.md @@ -328,12 +328,21 @@ stand on its own. | | App | What it's for | Code | Learn more | |:-:|---|---|---|---| | | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | -| | **VectorCraft** | **Vector illustration · you are here** | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | +| | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | | | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | | | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. From 637229931f546f381c4c9299c90d96522d6cb9c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 10:18:06 -0800 Subject: [PATCH 037/674] Paste: Paste in Back keeps a clip group's clipping path at the bottom With the clipping path of a clip group or a clipping layer selected, or a member of a compound path that is the clipping path, Paste in Back put the clipboard's objects below it. The bottom pasted object then became the clipping path. With nothing selected in a clipping layer, Paste in Back did the same at the bottom of the layer. Paste in Back now puts the objects right above the clipping path, as Send to Back keeps art above it. --- crates/engine/src/cmd/edit.rs | 7 ++++-- crates/engine/src/tests/clipboard.rs | 33 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3427e23f15..62a17bda3b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -862,17 +862,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))), _ => None, }; + // In a clip group or a clipping layer the bottom child is the clipping path: art pasted + // in back goes above it, not below it. + let floor = |d: &Document, par: Option| usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); let (par, idx) = match (into, anchor, layer) { // Inside the object Draw Inside draws into, on top of what is in it already. (Some(group), ..) => (Some(group), usize::MAX), // Next to the anchor, unless the object goes back to another layer. (None, Some((par, i, _)), l) if l.is_none() || l == par => { let k = placed.get(&par).copied().unwrap_or(0); - (par, if front { i + 1 + k } else { i + k }) + (par, if front { i + 1 + k } else { i.max(floor(d, par)) + k }) } (None, _, l) => { let par = l.or(parent); - (par, if back { placed.get(&par).copied().unwrap_or(0) } else { usize::MAX }) + (par, if back { floor(d, par) + placed.get(&par).copied().unwrap_or(0) } else { usize::MAX }) } }; *placed.entry(par).or_default() += 1; diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 3336d384e1..e7ddbc7c08 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -599,6 +599,39 @@ fn front_and_back_beside_a_compound_paths_member_go_beside_the_compound_path() { assert_eq!(members(&s), [before[0], path[0], before[1]]); } +#[test] +fn paste_in_back_of_a_clipping_path_keeps_it_the_clipping_path() { + let mut s = session(); + let children = |s: &Session, g: NodeId| doc(s).node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let loose = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + let other = rect(&mut s, 220.0, 0.0, 10.0, 10.0); + sel(&mut s, &[other]); + let group = id_of(&s.execute("object.group", &json!({})).unwrap()); + // A path as the clipping path, and a compound path as the clipping path (a group pasted in back + // of a member goes beside the compound path). + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let mask = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + sel(&mut s, &[art, mask]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + let art2 = rect(&mut s, 0.0, 120.0, 100.0, 100.0); + let (a, b) = (rect(&mut s, 10.0, 130.0, 20.0, 20.0), rect(&mut s, 40.0, 130.0, 20.0, 20.0)); + sel(&mut s, &[a, b]); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + sel(&mut s, &[art2, c]); + let g2 = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + for (g, clipping, target, copies) in [(g, mask, mask, vec![loose, group]), (g2, c, a, vec![group])] { + assert_eq!(children(&s, g)[0], clipping); + for copied in copies { + copy(&mut s, &[copied]); + sel(&mut s, &[target]); + let pasted = ids_of(&s.execute("edit.pasteInBack", &json!({})).unwrap()); + let ch = children(&s, g); + assert_eq!(ch[0], clipping, "the clipping path stays the bottom child"); + assert_eq!(&ch[1..2], &pasted[..], "right above the clipping path"); + } + } +} + #[test] fn paste_on_all_artboards_keeps_the_offset_to_the_source_artboard() { let mut s = Session::new(); From b104efc53c28d418a04dd05101d3d0ec97b5e8d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 10:19:45 -0800 Subject: [PATCH 038/674] Graph data: a dropped empty row adds no blank series Dropping rows with neither a label nor a value read the data padded to the widest row, so a dropped row wider than the rest (`,,`) left every kept row one blank cell wider. The graph then had an extra blank series, and a right-axis assignment to that index was kept. Each kept row now keeps its own width. This applies to graph.setData and to a graph variable's data set. --- crates/engine/src/cmd/graph/data.rs | 12 ++++++++++-- crates/engine/src/tests/variables.rs | 5 ++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 362f988f07..0e69e0240e 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -136,9 +136,17 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value) -> bool { changed } -/// Drop rows with neither a value nor a label; a label-only row stays, its values blank. +/// Drop rows with neither a value nor a label; a label-only row stays, its values blank. Each kept row keeps its own +/// width, so a dropped row wider than the rest adds no blank series. fn drop_empty_rows(g: &mut GraphSpec) { - let mut cells = g.cells(); + let blank: std::collections::HashSet<[usize; 2]> = g.blanks.iter().copied().collect(); + let mut cells: Vec>> = g + .rows + .iter() + .take(vectorcraft_doc::MAX_GRAPH_CATEGORIES) + .enumerate() + .map(|(c, r)| r.iter().take(vectorcraft_doc::MAX_GRAPH_SERIES).enumerate().map(|(s, v)| (!blank.contains(&[c, s])).then_some(*v)).collect()) + .collect(); let keep: Vec = (0..cells.len()) .map(|c| cells.get(c).is_some_and(|r| r.iter().any(Option::is_some)) || g.categories.get(c).is_some_and(|l| !l.is_empty())) .collect(); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index fb252d8545..07ac4aed0d 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1647,7 +1647,8 @@ fn graph_variable_applies_csv_as_set_data() { s.execute("variable.makeGraphDynamic", &json!({})).unwrap(); let name = s.execute("variable.list", &json!({})).unwrap()["variables"][0]["name"].as_str().unwrap().to_string(); let spec = |s: &Session, g: u64| s.doc().unwrap().doc.node(NodeId(g)).unwrap().extras().graph.as_deref().unwrap().clone(); - for (row, csv) in [("One", ",a\nQ1,10\nQ2,5"), ("Blank", ",a\nQ1,10\n,\nQ2,5")] { + // A dropped empty row wider than the others (`,,`) adds no blank series, so the right axis keeps nothing. + for (row, csv) in [("Wide", ",a\nQ1,10\n,,\nQ2,5"), ("One", ",a\nQ1,10\nQ2,5"), ("Blank", ",a\nQ1,10\n,\nQ2,5")] { s.execute("dataset.new", &json!({"name": row, "values": {name.clone(): csv}})).unwrap(); s.execute("dataset.select", &json!({"name": row})).unwrap(); s.execute("graph.setData", &json!({"id": other, "csv": csv})).unwrap(); @@ -1655,6 +1656,8 @@ fn graph_variable_applies_csv_as_set_data() { assert_eq!(merged.right_series, set.right_series, "{row}"); assert_eq!(merged.categories, set.categories, "{row}"); assert_eq!(merged.cells(), set.cells(), "{row}"); + assert!(merged.right_series.is_empty(), "{row}"); + assert_eq!(merged.cells(), [[Some(10.0)], [Some(5.0)]], "{row}"); } assert!(spec(&s, id).right_series.is_empty()); assert_eq!(spec(&s, id).categories, ["Q1", "Q2"]); From 5628de96f866185d8eb289b167b89691f213c0c3 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 1 Nov 2026 13:59:17 -0500 Subject: [PATCH 039/674] Release 0.20.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 56 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 248679aaca..692dd5a91a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6061,7 +6061,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.19.0" +version = "0.20.0" dependencies = [ "arboard", "block2 0.6.2", @@ -6106,7 +6106,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.19.0" +version = "0.20.0" dependencies = [ "crc32fast", "flate2", @@ -6117,7 +6117,7 @@ dependencies = [ [[package]] name = "vectorcraft-brush" -version = "0.19.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "serde", @@ -6129,7 +6129,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.19.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6145,7 +6145,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.19.0" +version = "0.20.0" dependencies = [ "log", "objc2-core-foundation", @@ -6167,7 +6167,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.19.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -6179,7 +6179,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.19.0" +version = "0.20.0" dependencies = [ "chrono", "hayro-ccitt", @@ -6198,7 +6198,7 @@ dependencies = [ [[package]] name = "vectorcraft-effects" -version = "0.19.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6214,7 +6214,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.19.0" +version = "0.20.0" dependencies = [ "cfb", "craft-docpath", @@ -6255,7 +6255,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.19.0" +version = "0.20.0" dependencies = [ "fax", "flate2", @@ -6279,7 +6279,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.19.0" +version = "0.20.0" dependencies = [ "flate2", "proptest", @@ -6294,7 +6294,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.19.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -6306,7 +6306,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.19.0" +version = "0.20.0" dependencies = [ "image", "log", @@ -6325,7 +6325,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.19.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6339,7 +6339,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.19.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -6351,7 +6351,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.19.0" +version = "0.20.0" dependencies = [ "aes", "chrono", @@ -6383,7 +6383,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.19.0" +version = "0.20.0" dependencies = [ "serde", "serde_json", @@ -6397,7 +6397,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.19.0" +version = "0.20.0" dependencies = [ "flate2", "gif 0.14.2", @@ -6427,14 +6427,14 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.19.0" +version = "0.20.0" dependencies = [ "proptest", ] [[package]] name = "vectorcraft-svg" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-docpath", "flate2", @@ -6459,7 +6459,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.19.0" +version = "0.20.0" dependencies = [ "fax", "image", @@ -6477,7 +6477,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.19.0" +version = "0.20.0" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -6498,7 +6498,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.19.0" +version = "0.20.0" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -6506,7 +6506,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.19.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6523,7 +6523,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.19.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6535,7 +6535,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.19.0" +version = "0.20.0" dependencies = [ "bytemuck", "craft-keymap", @@ -6573,7 +6573,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.19.0" +version = "0.20.0" dependencies = [ "eframe", "egui", @@ -7704,7 +7704,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.19.0" +version = "0.20.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index b5b4312eae..3088b469b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.19.0" +version = "0.20.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 39e69e8446f5815859d0ddc912e998c5ee9527b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 11:48:41 -0800 Subject: [PATCH 040/674] Tests: move the lock params text test next to the lock test --- crates/engine/src/tests/variables.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 73cdccb85e..cfcdbe6bbc 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -454,6 +454,14 @@ fn locked_variables_refuse_new_deleted_and_renamed_variables() { s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap(); } +/// `variable.lock`'s params text names the dataset command it refuses: an import whose header +/// would define a variable. +#[test] +fn the_lock_params_text_names_the_refused_import() { + let params = cmd::find_command("variable.lock").unwrap().params; + assert!(params.contains("the dataset commands still run, except a dataset.import whose header would define a variable"), "{params}"); +} + /// Locking is an undo step only when it changes the state, and the lock is saved with the /// document: a file saved locked opens locked, and a file without the key opens unlocked. #[test] @@ -1325,14 +1333,6 @@ fn locked_variables_refuse_header_cells_that_define_variables() { assert_eq!(imp["defined"], json!(["New"])); } -/// `variable.lock`'s params text names the dataset command it refuses: an import whose header -/// would define a variable. -#[test] -fn the_lock_params_text_names_the_refused_import() { - let params = cmd::find_command("variable.lock").unwrap().params; - assert!(params.contains("the dataset commands still run, except a dataset.import whose header would define a variable"), "{params}"); -} - /// Import / export datasets as CSV: header `name` then variables; round-trip keeps values. #[test] fn datasets_csv_round_trips_and_rejects_bad_input() { From 872effcf77f11c020df08de09ca1c5909ef4b689 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 1 Nov 2026 15:12:13 -0500 Subject: [PATCH 041/674] Recolor: docs say a map row's model can't be null either Co-Authored-By: Claude Opus 5.5 --- docs/mcp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 2a62f18a0a..4b44a149b7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1945,7 +1945,7 @@ error for an unknown library or method. Other wrong-form parameters get an error `includeImages`, `includePatterns`, a row's `exclude`, `order`, `saturationBrightness` and the `white`, `black` and `grays` switches of `preserve` must be true or false; `colors` and `seed` must be whole numbers; `group` and `rename` must be strings, `groupColors` must be an array and `preserve` must be an object. Each refusal leaves the document unchanged and records no undo step. A `null` -counts as a value left out except for `recolor.apply`'s `model`, which must be a string when given. +counts as a value left out except for `recolor.apply`'s `model` and a `map` row's `model`, which must be strings when given. ```json {"name":"run_command","arguments":{"command":"recolor.reduce","params":{"colors":2,"preserve":{"grays":true}}}} From a055ebcbc73cb7f78034ab876d983ca31346ce00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 13:30:34 -0800 Subject: [PATCH 042/674] Fix #3818: the chosen brightness holds when the system theme differs The theme's colors went into egui's style for the current system theme only. When the system's light or dark setting differed from it or changed while the app ran, egui switched to its other style, which held egui's defaults: tool tips became a white box with gray text, or with the theme's light text. Applying a brightness now sets egui's theme to match, starting from the current style so settings such as the tool tip delay carry over. --- crates/ui-egui/src/theme.rs | 60 +++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e6c06e5dd9..3b1a0524d8 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -587,6 +587,15 @@ pub fn apply(ctx: &egui::Context, b: Brightness) { pub fn apply_with(ctx: &egui::Context, b: Brightness, accent: Accent, scheme: Scheme) { let t = Tokens::for_scheme(scheme, b, accent); ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t)); + // egui keeps a style for each system theme and by default follows the system's setting. The + // chosen brightness sets egui's theme, so these colors stay in force when the system's setting + // differs or changes. A change of theme starts from the current style, which keeps settings + // such as the tool tip delay. + let theme = if t.dark { egui::Theme::Dark } else { egui::Theme::Light }; + if ctx.theme() != theme { + ctx.set_style_of(theme, ctx.global_style()); + } + ctx.set_theme(theme); let mut v = if t.dark { Visuals::dark() } else { Visuals::light() }; v.panel_fill = t.panel; v.window_fill = t.panel; @@ -669,4 +678,55 @@ mod tests { assert_eq!(Scheme::parse(Scheme::Classic.id()), Some(Scheme::Classic)); } } + + /// #3818: the brightness chosen in Preferences stays in force when the system's light or dark + /// setting differs from it or changes while the app runs. Tool tips keep the theme's panel fill + /// and text color instead of egui's own white box and gray text. + #[test] + fn the_theme_holds_whatever_the_system_theme() { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 400.0)); + for b in Brightness::ALL { + for scheme in Scheme::ALL { + for (first, then) in [(egui::Theme::Dark, egui::Theme::Light), (egui::Theme::Light, egui::Theme::Dark)] { + let t = Tokens::for_scheme(scheme, b, Accent::default()); + let ctx = egui::Context::default(); + let mut time = 0.0; + let mut tip = None; + for i in 0..5 { + time += 0.5; + let system_theme = Some(if i == 0 { first } else { then }); + let events = if i == 1 { vec![egui::Event::PointerMoved(egui::pos2(30.0, 15.0))] } else { vec![] }; + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), events, system_theme, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + if i == 0 { + apply_with(ui.ctx(), b, Accent::default(), scheme); + ui.ctx().global_style_mut(|s| s.interaction.tooltip_delay = 0.0); + } + ui.button("Hover me").on_hover_text("Tip text"); + }); + out.textures_delta.clear(); + tip = out.shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Text(s) if s.galley.text() == "Tip text" => Some(s.fallback_color), + _ => None, + }); + } + let v = ctx.global_style().visuals.clone(); + assert_eq!((v.window_fill, v.override_text_color), (t.panel, Some(t.text)), "{scheme:?} {b:?}, system {first:?} then {then:?}"); + assert_eq!(tip, Some(t.text), "{scheme:?} {b:?}, system {first:?} then {then:?}: the tool tip's text"); + } + } + } + } + + /// Changing brightness keeps the interface settings made after the theme was applied, such as + /// General › Show Tool Tips' delay. + #[test] + fn changing_brightness_keeps_other_interface_settings() { + let ctx = egui::Context::default(); + apply(&ctx, Brightness::Dark); + ctx.global_style_mut(|s| s.interaction.tooltip_delay = f32::INFINITY); + apply(&ctx, Brightness::Light); + assert_eq!(ctx.global_style().interaction.tooltip_delay, f32::INFINITY); + assert_eq!(ctx.global_style().visuals.window_fill, Tokens::for_brightness(Brightness::Light).panel); + } } From b473716e3e3ac029d2e8368834ee45766ab1cd0e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 14:10:29 -0800 Subject: [PATCH 043/674] Fix #2089: Affinity strokes keep their Width tool profile An Affinity stroke shaped with the Width tool stores its pressure curve (LDeP: position along the path against width). The importer warned and drew the stroke at full width all along. - The pressure curve is read and sampled into the stroke's width profile (2 to 8 points per segment, 256 segments at most, widths up to the full weight). A curve at full width all along stays a plain stroke; one that can't be read is warned about. - Brush strokes keep their own warning. - The pinned Affinity 3 signatures for the five corpus files with such strokes are updated. --- crates/affinity/README.md | 3 +- crates/affinity/src/geometry.rs | 49 +++++++++ crates/affinity/src/paint.rs | 19 +++- .../tests/support/affinity3-signatures.txt | 10 +- crates/engine/src/cmd/fileio/affinity.rs | 2 +- .../engine/src/cmd/fileio/affinity/paint.rs | 3 +- .../engine/src/cmd/fileio/tests_affinity.rs | 102 ++++++++++++++++++ 7 files changed, 177 insertions(+), 11 deletions(-) diff --git a/crates/affinity/README.md b/crates/affinity/README.md index f0339d6985..90c078023e 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -23,6 +23,7 @@ Affinity files. | Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | fill appearance (alpha as fill opacity) | | Linear, elliptical and radial gradients with Affinity's midpoint bias | gradients (the bias as the midpoint where the blend is half way) | | Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill; a stroke whose style is None (every shape stores one, black and 1 px) is left out | stroke appearance | +| A stroke's pressure curve (`LDeP`: position along the path against width) | the stroke's width profile, the curve sampled at 2 to 8 points per segment (256 segments at most), widths up to the full weight | | Fill layers (`FRst`) | filled rectangles | | Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, underline, strikethrough, size, tracking, horizontal scale, fixed leading, colour, outlined characters, first baseline; each paragraph's alignment, indents, space before and after, fixed and automatic leading; frame text sized by its text scale (`FTxS`), not its frame's transform | point type and area type, one paragraph style per paragraph; artistic text whose paragraphs align differently keeps them aligned within its longest line (by indents), as Affinity draws it; a frame's first line hangs from its capitals' tops, and a frame whose last lines' descenders hang out of it is made just tall enough to show them; line breaks inside a paragraph become paragraphs without spacing between them; table cells place their text as Affinity does (centred from the capitals' tops to the last baseline, reaching out of a cell too short for it) | | Tables (`TxtT`): grid, cell text, merged cells, cell insets and vertical alignment, the line on every cell edge | a group of area type per cell and a stroked line per edge (VectorCraft has no tables) | @@ -33,7 +34,7 @@ Affinity files. | Opacity, visibility, lock, names, the blend modes VectorCraft has | the same | Everything else is reported in the import warnings, one line per kind with a count, never -dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush and pressure strokes, +dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read, transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial), special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner types other than round or straight, stars with rounded points, several fills or strokes on one object (the diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index 8e84e48077..83ea854280 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -169,6 +169,55 @@ fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option Option> { + let s = r.s; + let data = s.obj(crvd, b"Data")?; + let records = s.positional(data).find_map(|v| if let Value::Array(a) = v { Some(a) } else { None })?; + // Every segment takes at least an anchor record. + if records.len() > MAX_PRESSURE_SEGMENTS * 3 + 1 { + return None; + } + let curve = subpath(&anchors(records)?, false, None)?; + if curve.segments.len() > MAX_PRESSURE_SEGMENTS { + return None; + } + let steps = u32::try_from((PRESSURE_POINTS / curve.segments.len().max(1)).clamp(2, 8)).unwrap_or(2); + let mut samples = vec![(curve.start.x, curve.start.y)]; + let mut from = curve.start; + for [c1, c2, to] in &curve.segments { + for i in 1..=steps { + let t = f64::from(i) / f64::from(steps); + let u = 1.0 - t; + let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; + samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y))); + } + from = *to; + } + let mut last = 0.0f64; + Some( + samples + .into_iter() + .map(|(x, y)| { + last = x.clamp(last, 1.0); + (last, y.clamp(0.0, 1.0)) + }) + .collect(), + ) +} + struct Anchor { p: Point, inh: Option, diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs index 1dfdb65759..144357ab78 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -121,6 +121,9 @@ pub struct Stroke { pub dash: Option<(Vec, f64)>, /// Painted below the fill instead of above it. pub behind: bool, + /// The pressure curve: (position 0..1 along the path, width as a fraction of `width`) in + /// order along the path, `None` for a stroke of the same width all along. + pub profile: Option>, } /// Gradient stops per gradient. @@ -350,10 +353,20 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh } _ => None, }; - if s.obj(lsty, b"Brus").is_some() || s.obj(ldsc, b"LDeP").is_some() { - r.warn("brush and pressure strokes (imported as plain strokes)"); + if s.obj(lsty, b"Brus").is_some() { + r.warn("brush strokes (imported as plain strokes)"); } - Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind }) + // The pressure curve sets the width along the path; one at full width all along is a plain + // stroke. + let profile = match s.obj(ldsc, b"LDeP").map(|p| crate::geometry::pressure(r, p)) { + Some(Some(points)) => (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-3)).then_some(points), + Some(None) => { + r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)"); + None + } + None => None, + }; + Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind, profile }) } #[cfg(test)] diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 779a58552e..462d321727 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -1,7 +1,7 @@ -affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=d23a6900;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)", "brush and pressure strokes (imported as plain strokes) (114×)"] -affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=b8cecb1c;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)", "brush and pressure strokes (imported as plain strokes) (534×)"] -affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=23d1e39c;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)", "brush and pressure strokes (imported as plain strokes) (54×)"] -affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=cafb7572;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush and pressure strokes (imported as plain strokes)"] +affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=ce96643c;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] +affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=08a70ca5;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] +affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=557d4a95;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] +affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] @@ -30,4 +30,4 @@ patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"] patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] -patchy-vector.af dpi=72;spreads=1;model_crc32=b36a9767;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] +patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] diff --git a/crates/engine/src/cmd/fileio/affinity.rs b/crates/engine/src/cmd/fileio/affinity.rs index 671bc04b63..c8ef3235ec 100644 --- a/crates/engine/src/cmd/fileio/affinity.rs +++ b/crates/engine/src/cmd/fileio/affinity.rs @@ -12,7 +12,7 @@ use serde_json::json; use vectorcraft_affinity::model::{self as af, Align as AfAlign, Blend, Kind, Pixels}; use vectorcraft_affinity::paint::{self as ap, Cap, GradientKind as AfKind, Join}; use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; -use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, Effect, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer}; +use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, Effect, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile}; use vectorcraft_doc::geom::{FillRule, PathData, shapes}; use vectorcraft_doc::text::{CharStyle, FirstBaseline, Justify, TextKind, TextObject, TextRun, VerticalAlign}; use vectorcraft_doc::{Artboard, Document, ImageObject, LayerColor, Node, NodeKind, OpacityMask}; diff --git a/crates/engine/src/cmd/fileio/affinity/paint.rs b/crates/engine/src/cmd/fileio/affinity/paint.rs index ce798dcfbb..ed2b44ad3a 100644 --- a/crates/engine/src/cmd/fileio/affinity/paint.rs +++ b/crates/engine/src/cmd/fileio/affinity/paint.rs @@ -4,7 +4,7 @@ use super::text::Placement; use super::{ AfKind, Affine, Appearance, AppearanceItem, Arc, BezPath, Builder, Cap, Color, Dash, Effect, FillLayer, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, ImageObject, Join, LineCap, LineJoin, NodeKind, Paint, PathData, Pixels, Point, StrokeAlign, StrokeLayer, - TextObject, Vec2, af, ap, json, + TextObject, Vec2, WidthProfile, af, ap, json, }; impl Builder { @@ -232,6 +232,7 @@ impl Builder { offset: phase * self.k, align_corners: false, }); + l.profile = s.profile.as_ref().map(|p| WidthProfile { points: p.iter().map(|&(t, w)| (t, w, w)).collect() }); Some(l) } diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rs index ae8f6cc452..a288c5ec12 100644 --- a/crates/engine/src/cmd/fileio/tests_affinity.rs +++ b/crates/engine/src/cmd/fileio/tests_affinity.rs @@ -300,6 +300,108 @@ mod native { } } + /// A version-12 document holding an open curve with an 8 px stroke whose pressure curve (`LDeP`) + /// is made of `records`. + fn pressure_document(records: Vec>) -> Vec { + let line = F::Def( + 20, + vec![tag(b"PCrv"), tag(b"VNod"), tag(b"Node")], + vec![ + ( + tag(b"Crvs"), + F::Obj( + tag(b"PCvD"), + vec![( + tag(b"Data"), + F::Pos(vec![F::U8(0), F::U32(1), F::Bool(false), F::Records(18, vec![node(0.0, 0.0, 1, 0), node(100.0, 0.0, 1, 0)])]), + )], + ), + ), + (tag(b"LIFl"), F::Shared(vec![solid(24, rgba(0.0, 0.0, 0.0, 1.0))])), + ( + tag(b"LILn"), + F::Shared(vec![F::Def( + 27, + vec![tag(b"LDsc")], + vec![ + (tag(b"LDeL"), F::Def(28, vec![tag(b"LSty")], vec![(tag(b"Wght"), F::F64(8.0))])), + (tag(b"LDSc"), F::Bool(false)), + ( + tag(b"LDeP"), + F::Obj(tag(b"CrvD"), vec![(tag(b"Data"), F::Pos(vec![F::U32(0), F::Bool(false), F::Records(18, records)]))]), + ), + ], + )]), + ), + ], + ); + let spread = + F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 100.0])), (tag(b"Chld"), F::Shared(vec![line]))]); + let doc = synth::stream(&[ + (tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(72.0))])), + (tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])), + ]); + synth::container(&[("doc.dat", &doc, Method::Zstd)], Some(&png())) + } + + /// The width profile of the only stroked path in `d`. + fn stroke_of(d: &vectorcraft_doc::Document) -> vectorcraft_doc::appearance::StrokeLayer { + let mut found = None; + d.walk(|n| { + if let Some(AppearanceItem::Stroke(k)) = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + found = Some(k.clone()); + } + }); + found.unwrap_or_else(|| panic!("no stroke in {:?}", d.layers)) + } + + #[test] + fn a_pressure_curve_becomes_the_strokes_width_profile() { + // Thin at the start, full width from half way: anchor (0, 0), handles (0.25, 0.5) and + // (0.5, 1), anchor (0.5, 1), then straight on to anchor (1, 1). + let curve = vec![node(0.0, 0.0, 4, 0), node(0.25, 0.5, 0, 1), node(0.5, 1.0, 0, 2), node(0.5, 1.0, 4, 0), node(1.0, 1.0, 4, 0)]; + let r = load("pressure.af", &pressure_document(curve)).unwrap(); + assert!(!r.preview_only); + assert!(r.warnings.iter().all(|w| !w.contains("pressure")), "{:?}", r.warnings); + let k = stroke_of(&r.doc); + assert_eq!(k.width, 8.0); + let profile = k.profile.unwrap_or_else(|| panic!("the pressure curve is read: {:?}", r.warnings)); + assert_eq!(profile.points.first(), Some(&(0.0, 0.0, 0.0))); + assert_eq!(profile.points.last(), Some(&(1.0, 1.0, 1.0))); + assert!(profile.points.windows(2).all(|w| w[0].0 <= w[1].0), "positions go forward: {:?}", profile.points); + let (left, right) = profile.at(0.25); + assert!(left > 0.25 && left < 1.0 && left == right, "{left} {right}"); + assert_eq!(profile.at(0.75), (1.0, 1.0)); + + // Widths past the full weight are held at it. + let huge = vec![node(0.0, 0.0, 4, 0), node(0.5, 1e300, 4, 0), node(1.0, 0.0, 4, 0)]; + let profile = stroke_of(&load("huge.af", &pressure_document(huge)).unwrap().doc).profile.unwrap(); + assert!(profile.points.iter().all(|p| (0.0..=1.0).contains(&p.1)), "{:?}", profile.points); + assert_eq!(profile.at(0.5), (1.0, 1.0)); + + // Each segment is sampled inside too: anchors at full width whose handles dip to nothing + // still narrow the stroke, with 256 segments. + let mut dips = vec![node(0.0, 1.0, 4, 0)]; + for i in 1..=256 { + let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0); + dips.extend([node(a + (b - a) / 3.0, 0.0, 0, 1), node(b - (b - a) / 3.0, 0.0, 0, 2), node(b, 1.0, 4, 0)]); + } + let profile = stroke_of(&load("dips.af", &pressure_document(dips)).unwrap().doc).profile.unwrap(); + assert!(profile.points.iter().any(|p| p.1 < 0.5), "{:?}", profile.points); + + // A curve of more than 256 segments is left out, with a warning. + let long: Vec> = (0..=300).map(|i| node(f64::from(i) / 300.0, f64::from(i % 2), 4, 0)).collect(); + let r = load("long.af", &pressure_document(long)).unwrap(); + assert!(stroke_of(&r.doc).profile.is_none()); + assert!(r.warnings.iter().any(|w| w.contains("pressure curve can't be read")), "{:?}", r.warnings); + + // A pressure curve at full width all along leaves the stroke plain. + let flat = vec![node(0.0, 1.0, 4, 0), node(1.0, 1.0, 4, 0)]; + let r = load("flat.af", &pressure_document(flat)).unwrap(); + assert!(stroke_of(&r.doc).profile.is_none()); + assert!(r.warnings.iter().all(|w| !w.contains("pressure")), "{:?}", r.warnings); + } + #[test] fn native_documents_save_reopen_export_place_and_template() { let bytes = document(Method::Zstd); From d5004b7dae1e0849023f8c41cbc0b7d809bcdd0f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 14:42:42 -0800 Subject: [PATCH 044/674] Fix #3437: Spiral segments follow the spiral The Spiral tool places its anchors on a logarithmic spiral, with the radius shrinking by the decay each quarter turn, but gave every handle the direction of a circle's tangent and a length from an averaged radius. The curve bulged off the spiral between anchors and turned at each anchor, so the spiral looked squared: up to 2.8% off its radius at the default 80% decay and 23% at 30%. The handles now follow the spiral's own tangent, with lengths that differ at each segment's outer and inner end. The curve stays within 0.03% of the spiral at 80% decay and 0.8% at 20%. Anchor positions and counts are unchanged. --- crates/geom/src/shapes.rs | 48 +++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index cba634aaa9..557ae3294a 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -210,21 +210,27 @@ pub fn arc(a: Point, b: Point, slope: f64, closed: bool, _base_along_x: bool) -> PathData::single(SubPath::new(anchors, closed)) } -/// Archimedean-style spiral approximating Illustrator's Spiral tool (decay-based, `segments` quarter turns). +/// Logarithmic spiral approximating the reference app's Spiral tool (decay-based, `segments` quarter turns). pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clockwise: bool) -> PathData { let decay = (decay_percent / 100.0).clamp(0.05, 0.9999); let dir = if clockwise { 1.0 } else { -1.0 }; + // The radius shrinks by `decay` each quarter turn: r(φ) = radius · e^(kφ) after turning φ. + let k = decay.ln() / (PI / 2.0); + // Handle lengths per unit of the derivative below, at a segment's outer and inner end: √r + // changes evenly with the curve's parameter along each quarter turn. Both are KAPPA when the + // radius does not shrink, and the curve stays within 0.8% of the spiral's radius at 20% decay. + let outer = 2.0 * KAPPA * (decay.sqrt() - 1.0) / decay.ln(); + let inner = outer / decay.sqrt(); let mut anchors = Vec::new(); let mut r = radius; for i in 0..=segments { let a = dir * (i as f64) * PI / 2.0; let p = Point::new(center.x + r * a.cos(), center.y + r * a.sin()); - // Tangent direction for a quarter arc of radius r. - let t = Vec2::new(-a.sin(), a.cos()) * dir; - let r_prev = r / decay; - let r_next = r * decay; - let h_in = p - t * (KAPPA * (r + r_prev) / 2.0); - let h_out = p + t * (KAPPA * (r + r_next) / 2.0); + // The spiral's derivative by the angle turned: the radius changes along the radial + // direction while the point turns along the circle's tangent. + let d = Vec2::new(a.cos(), a.sin()) * (r * k) + Vec2::new(-a.sin(), a.cos()) * (r * dir); + let h_in = p - d * inner; + let h_out = p + d * outer; anchors.push(Anchor { p, h_in: if i == 0 { p } else { h_in }, h_out: if i == segments { p } else { h_out }, kind: AnchorKind::Smooth }); r *= decay; } @@ -460,6 +466,34 @@ mod tests { assert!(!p.subpaths[0].closed); } + /// #3437: every segment stays on the spiral through its anchors, whose radius shrinks by + /// `decay` each quarter turn, for strong and weak decay and both directions. + #[test] + fn spiral_segments_follow_the_spiral() { + let center = Point::new(40.0, -25.0); + for decay in [20.0, 30.0, 50.0, 80.0, 95.0] { + for clockwise in [true, false] { + let p = spiral(center, 100.0, decay, 8, clockwise); + let anchors = &p.subpaths[0].anchors; + let k = (decay / 100.0_f64).ln() / (PI / 2.0); + let mut worst = 0.0_f64; + for pair in anchors.windows(2) { + let c = kurbo::CubicBez::new(pair[0].p, pair[0].h_out, pair[1].h_in, pair[1].p); + let r0 = (pair[0].p - center).hypot(); + let a0 = (pair[0].p - center).atan2(); + for step in 1..20 { + let q = kurbo::ParamCurve::eval(&c, f64::from(step) / 20.0) - center; + // The angle turned from the segment's start, toward the outer end. + let turned = (q.atan2() - a0 + 3.0 * PI).rem_euclid(TAU) - PI; + let want = r0 * (-k * turned.abs()).exp(); + worst = worst.max((q.hypot() - want).abs() / want); + } + } + assert!(worst < 0.008, "decay {decay} clockwise {clockwise}: radius off by {:.2}%", worst * 100.0); + } + } + } + #[test] fn grids() { let r = Rect::new(0.0, 0.0, 10.0, 10.0); From 0067aee519d9b447b99f112a9c3f6330b34e42ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 14:45:35 -0800 Subject: [PATCH 045/674] Tests: the tool tip's box keeps the theme's fill and contrast The test for #3818 checked the tool tip's text color and the style's window fill. It now also checks the fill of the box drawn behind the tool tip's text, and that the text and the box have a contrast ratio of at least 4.5, for every brightness and scheme. --- crates/ui-egui/src/theme.rs | 39 +++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 3b1a0524d8..0ca446b4d1 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -705,19 +705,50 @@ mod tests { ui.button("Hover me").on_hover_text("Tip text"); }); out.textures_delta.clear(); - tip = out.shapes.iter().find_map(|c| match &c.shape { - egui::Shape::Text(s) if s.galley.text() == "Tip text" => Some(s.fallback_color), + // The tool tip's text color, and the fill of the box drawn behind it. + let mut shapes: Vec<&egui::Shape> = Vec::new(); + let mut open: Vec<&egui::Shape> = out.shapes.iter().rev().map(|c| &c.shape).collect(); + while let Some(shape) = open.pop() { + match shape { + egui::Shape::Vec(inner) => open.extend(inner.iter().rev()), + shape => shapes.push(shape), + } + } + tip = shapes.iter().enumerate().find_map(|(n, shape)| match shape { + egui::Shape::Text(s) if s.galley.text() == "Tip text" => { + let fill = shapes[..n].iter().rev().find_map(|behind| match behind { + egui::Shape::Rect(r) if r.rect.contains(s.pos) && r.fill.a() > 0 => Some(r.fill), + _ => None, + }); + Some((s.fallback_color, fill)) + } _ => None, }); } let v = ctx.global_style().visuals.clone(); - assert_eq!((v.window_fill, v.override_text_color), (t.panel, Some(t.text)), "{scheme:?} {b:?}, system {first:?} then {then:?}"); - assert_eq!(tip, Some(t.text), "{scheme:?} {b:?}, system {first:?} then {then:?}: the tool tip's text"); + let what = format!("{scheme:?} {b:?}, system {first:?} then {then:?}"); + assert_eq!((v.window_fill, v.override_text_color), (t.panel, Some(t.text)), "{what}"); + assert_eq!(tip, Some((t.text, Some(t.panel))), "{what}: the tool tip's text and box"); + assert!(contrast(t.text, t.panel) >= 4.5, "{what}: the tool tip's text against its box, {}", contrast(t.text, t.panel)); } } } } + /// The contrast ratio of two opaque colors, from 1 (the same) to 21 (black on white), as WCAG 2 + /// defines it. + fn contrast(a: egui::Color32, b: egui::Color32) -> f32 { + let luminance = |c: egui::Color32| { + let channel = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b()) + }; + let (a, b) = (luminance(a), luminance(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) + } + /// Changing brightness keeps the interface settings made after the theme was applied, such as /// General › Show Tool Tips' delay. #[test] From 6024f86da12b123b80efd621b24c74573f1b32e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 15:05:54 -0800 Subject: [PATCH 046/674] Artwork Cleanup: Empty Text and Off-Artboard Art leave type that clips art A clipping path hides the art outside it. Empty Text removed empty type that clips a clipping group, and Off-Artboard Art removed type that clips a layer from off every artboard, so the art they hid showed. Both now leave type that is a clipping path, as the other kinds already did, also when the clipping path itself is selected. Docs: docs/mcp.md (Artwork Cleanup kinds table). --- .../engine/src/cmd/addons/cleanup/checks.rs | 13 ++++-- crates/engine/src/cmd/addons/cleanup/tests.rs | 43 +++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs index c3abd029be..4b03f0e433 100644 --- a/crates/engine/src/cmd/addons/cleanup/checks.rs +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -120,12 +120,12 @@ impl Kind { let removable = !place.clips && !is_guide_or_clip(n); let gone = |is: bool| is.then(Vec::new); match self { - Kind::EmptyText => gone(matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())), + Kind::EmptyText => gone(removable && matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())), Kind::StrayPoints => gone(removable && matches!(&n.kind, NodeKind::Path { path, .. } if path.anchor_count() <= 1)), Kind::Unpainted => gone(removable && !place.in_compound && is_shape(n) && !is_painted(&n.appearance)), Kind::ZeroOpacity => gone(removable && !place.in_compound && n.opacity <= 0.0), Kind::DuplicateObjects => gone(removable && duplicates_the_one_below(cx.d, n)), - Kind::OffArtboard => gone(place.top && !is_guide_or_clip(n) && off_artboards(cx, n)), + Kind::OffArtboard => gone(place.top && removable && off_artboards(cx, n)), Kind::NeedlessGroups => needless_group(n), Kind::NeedlessCompounds => needless_compound(n), Kind::NeedlessClipGroups => needless_clip_group(cx, n), @@ -175,7 +175,9 @@ fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> { let top = Place { top: true, ..Place::default() }; match scope { Scope::Document => d.layers.iter().for_each(|l| visit(l, top, &mut out)), - Scope::Objects(ids) => ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, top, &mut out)), + Scope::Objects(ids) => { + ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, Place { clips: is_clipping_path(d, n.id), ..top }, &mut out)) + } } let editable = d.editable(); out.retain(|(n, _)| editable(n.id)); @@ -202,6 +204,11 @@ fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) { } } +/// Is `id` the clipping path of its group or layer? +fn is_clipping_path(d: &Document, id: NodeId) -> bool { + d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips)) +} + /// A group that stands for live or generated art: its members aren't loose art to clean. fn is_generated(n: &Node) -> bool { let e = n.extras(); diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index d02e1e4c09..2860d39e78 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -226,6 +226,49 @@ fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() { } } +/// The pixel at (100, 100) of the document drawn on white. +fn pixel(s: &Session) -> [u8; 4] { + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 300, vectorcraft_geom::Affine::IDENTITY, &opts).pixel(100, 100) +} + +/// A clipping path hides the art outside it: empty type that clips a group, and type off every +/// artboard that clips a layer, stay, and the art stays hidden. +#[test] +fn clipping_type_stays_with_the_art_it_hides() { + const WHITE: [u8; 4] = [255, 255, 255, 255]; + let mut s = session(); + let art = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 60, "y": 80, "text": " ", "size": 40})).unwrap()); + select(&mut s, &[art, t]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + select(&mut s, &[]); + assert_eq!(pixel(&s), WHITE); + assert_eq!(found(&mut s, "emptyText", "document"), 0); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + select(&mut s, &[t]); + assert_eq!(found(&mut s, "emptyText", "selection"), 0, "the clipping path selected"); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0); + assert!(node(&s, t).is_some()); + assert_eq!(pixel(&s), WHITE); + + let mut s = session(); + rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": -300, "y": -300, "text": "Clip", "size": 40})).unwrap()); + s.execute("layer.clippingMask.toggle", &json!({})).unwrap(); + select(&mut s, &[]); + assert_eq!(pixel(&s), WHITE); + assert_eq!(found(&mut s, "offArtboard", "document"), 0); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + select(&mut s, &[t]); + assert_eq!(found(&mut s, "offArtboard", "selection"), 0, "the clipping path selected"); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0); + assert!(node(&s, t).is_some()); + assert_eq!(pixel(&s), WHITE); +} + /// Type set twice in the same place (from a PDF, or for a fake bold) is a duplicate within a point: /// Show selects the upper copy and Fix removes it. Other text, or the same text further off, stays. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..20a3f2720a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5936,12 +5936,12 @@ envelopes, graphs, symbols), are left out. | Kind | Finds | Fix | |---|---|---| -| `emptyText` | Text with no characters, or only spaces | Removes it | +| `emptyText` | Text with no characters, or only spaces (not clipping paths) | Removes it | | `strayPoints` | Paths of one anchor (not clipping paths) | Removes them | | `unpainted` | Paths and compound paths with no fill and no stroke | Removes them | | `zeroOpacity` | Objects at 0 % opacity | Removes them | | `duplicateObjects` | A path stacked directly on an identical one (geometry, paint, opacity), or type stacked directly on the same type (text, styles, paint) within 1 pt of it | Removes the upper one | -| `offArtboard` | Top-level objects that touch no artboard | Removes them | +| `offArtboard` | Top-level objects that touch no artboard (not clipping paths) | Removes them | | `duplicateAnchors` | Neighbouring anchors within 0.01 pt | Merges them | | `tinyHandles` | Handles shorter than 0.01 pt | Retracts them | | `collinearAnchors` | Corner anchors on a straight run (turning by a sine of 0.005 or less) | Removes them | From e441d3ba1879e277621b9a5bf31851a2700b1030 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 15:28:59 -0800 Subject: [PATCH 047/674] Affinity: pressure curves keep dips between samples and stay within a document-wide limit - Each segment of a pressure curve is also sampled where its width stops rising or falling, so a dip between the regular samples of a long curve is kept. The segment's values are scaled into -1..1 before that is solved, so huge values in a file can't overflow it. - A curve counts as full width only within 1e-9 of it, so a curve just under full width keeps its profile. - The pressure points of all strokes in one read are limited to about a million, as for characters and table cells. Curves at full width count too, and once the limit is reached no more curves are read; the strokes past it are imported as plain strokes with a warning. --- crates/affinity/README.md | 2 +- crates/affinity/src/geometry.rs | 59 +++++++- crates/affinity/src/model/read.rs | 13 +- crates/affinity/src/paint.rs | 22 ++- .../tests/support/affinity3-signatures.txt | 6 +- .../engine/src/cmd/fileio/tests_affinity.rs | 128 +++++++++++++----- 6 files changed, 182 insertions(+), 48 deletions(-) diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 90c078023e..fd2d6dc71a 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -34,7 +34,7 @@ Affinity files. | Opacity, visibility, lock, names, the blend modes VectorCraft has | the same | Everything else is reported in the import warnings, one line per kind with a count, never -dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read, +dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read or that go past the million points one document may hold, transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial), special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner types other than round or straight, stars with rounded points, several fills or strokes on one object (the diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index 83ea854280..945c3040f9 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -172,16 +172,19 @@ fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option Option> { let s = r.s; let data = s.obj(crvd, b"Data")?; @@ -198,8 +201,11 @@ pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option> { let mut samples = vec![(curve.start.x, curve.start.y)]; let mut from = curve.start; for [c1, c2, to] in &curve.segments { - for i in 1..=steps { - let t = f64::from(i) / f64::from(steps); + let mut ts: Vec = (1..=steps).map(|i| f64::from(i) / f64::from(steps)).collect(); + ts.extend(turning_points(from.y, c1.y, c2.y, to.y).into_iter().flatten()); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + for t in ts { let u = 1.0 - t; let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y))); @@ -218,6 +224,29 @@ pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option> { ) } +/// The parameters strictly between 0 and 1 where the cubic Bézier with control values `a`, `b`, +/// `c` and `d` stops rising or falling (where its derivative is 0). The values are scaled into +/// -1..1 first, so huge ones can't overflow the discriminant. +fn turning_points(a: f64, b: f64, c: f64, d: f64) -> [Option; 2] { + let scale = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); + if !(scale.is_finite() && scale > 0.0) { + return [None, None]; + } + let (a, b, c, d) = (a / scale, b / scale, c / scale, d / scale); + let (d0, d1, d2) = (b - a, c - b, d - c); + let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); + let inside = |t: f64| (t.is_finite() && t > 0.0 && t < 1.0).then_some(t); + if qa.abs() < 1e-12 { + return [if qb.abs() < 1e-12 { None } else { inside(-qc / qb) }, None]; + } + let disc = qb * qb - 4.0 * qa * qc; + if disc < 0.0 { + return [None, None]; + } + let root = disc.sqrt(); + [inside((-qb - root) / (2.0 * qa)), inside((-qb + root) / (2.0 * qa))] +} + struct Anchor { p: Point, inh: Option, @@ -309,3 +338,19 @@ fn corner_radii(fields: Vec<&Value>) -> Option> { .collect(), ) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn turning_points_of_huge_control_values_are_found() { + let small = turning_points(1.0, -3.0, 3.0, 1.0); + let huge = turning_points(1e200, -3e200, 3e200, 1e200); + assert!(small.iter().all(Option::is_some), "{small:?}"); + for (s, h) in small.iter().zip(&huge) { + let (Some(s), Some(h)) = (s, h) else { panic!("{huge:?}") }; + assert!((s - h).abs() < 1e-12, "{small:?} {huge:?}"); + } + } +} diff --git a/crates/affinity/src/model/read.rs b/crates/affinity/src/model/read.rs index f94de75b93..00910baabd 100644 --- a/crates/affinity/src/model/read.rs +++ b/crates/affinity/src/model/read.rs @@ -26,6 +26,9 @@ const MAX_DOCUMENT_CHARS: usize = 16 << 20; /// Table cells of all tables together (each becomes a text object with its edge lines). const MAX_DOCUMENT_CELLS: usize = 1 << 18; +/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers). +const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20; + /// What a whole read may still use. Shared objects can be linked from many layers, and embedded /// documents are read with what their embedding document left, so linking or embedding the /// same content many times can't multiply the work. @@ -39,10 +42,18 @@ pub(crate) struct Budget { pub(crate) chars: usize, /// Table cells ([`MAX_DOCUMENT_CELLS`] in all). pub(crate) cells: usize, + /// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all). + pub(crate) pressure: usize, } impl Budget { - pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS }; + pub(crate) const FULL: Budget = Budget { + nodes: MAX_NODES, + pixels: MAX_LAYER_PIXELS, + chars: MAX_DOCUMENT_CHARS, + cells: MAX_DOCUMENT_CELLS, + pressure: MAX_DOCUMENT_PRESSURE_POINTS, + }; } /// Read a document: archive, `doc.dat` and the model. diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs index 144357ab78..cfc95b8dda 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -357,9 +357,25 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh r.warn("brush strokes (imported as plain strokes)"); } // The pressure curve sets the width along the path; one at full width all along is a plain - // stroke. - let profile = match s.obj(ldsc, b"LDeP").map(|p| crate::geometry::pressure(r, p)) { - Some(Some(points)) => (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-3)).then_some(points), + // stroke. Every curve read, full width or not, counts against the document's points, and once + // they are used up the rest are not read. + const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)"; + let ldep = s.obj(ldsc, b"LDeP"); + if ldep.is_some() && r.budget.pressure == 0 { + r.warn(BEYOND); + } + let profile = match ldep.filter(|_| r.budget.pressure > 0).map(|p| crate::geometry::pressure(r, p)) { + Some(Some(points)) => match r.budget.pressure.checked_sub(points.len()) { + Some(left) => { + r.budget.pressure = left; + (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-9)).then_some(points) + } + None => { + r.budget.pressure = 0; + r.warn(BEYOND); + None + } + }, Some(None) => { r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)"); None diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 462d321727..13e8f0c53a 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -1,6 +1,6 @@ -affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=ce96643c;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] -affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=08a70ca5;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] -affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=557d4a95;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] +affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] +affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] +affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rs index a288c5ec12..a57da79fcb 100644 --- a/crates/engine/src/cmd/fileio/tests_affinity.rs +++ b/crates/engine/src/cmd/fileio/tests_affinity.rs @@ -303,40 +303,52 @@ mod native { /// A version-12 document holding an open curve with an 8 px stroke whose pressure curve (`LDeP`) /// is made of `records`. fn pressure_document(records: Vec>) -> Vec { - let line = F::Def( - 20, - vec![tag(b"PCrv"), tag(b"VNod"), tag(b"Node")], - vec![ - ( - tag(b"Crvs"), - F::Obj( - tag(b"PCvD"), - vec![( - tag(b"Data"), - F::Pos(vec![F::U8(0), F::U32(1), F::Bool(false), F::Records(18, vec![node(0.0, 0.0, 1, 0), node(100.0, 0.0, 1, 0)])]), - )], - ), - ), - (tag(b"LIFl"), F::Shared(vec![solid(24, rgba(0.0, 0.0, 0.0, 1.0))])), - ( - tag(b"LILn"), - F::Shared(vec![F::Def( - 27, - vec![tag(b"LDsc")], - vec![ - (tag(b"LDeL"), F::Def(28, vec![tag(b"LSty")], vec![(tag(b"Wght"), F::F64(8.0))])), - (tag(b"LDSc"), F::Bool(false)), - ( - tag(b"LDeP"), - F::Obj(tag(b"CrvD"), vec![(tag(b"Data"), F::Pos(vec![F::U32(0), F::Bool(false), F::Records(18, records)]))]), + pressure_documents(records, 1) + } + + /// [`pressure_document`] with `copies` curves, all linking the first one's fill and stroke. + fn pressure_documents(records: Vec>, copies: u32) -> Vec { + let mut style = Some(( + solid(24, rgba(0.0, 0.0, 0.0, 1.0)), + F::Def( + 27, + vec![tag(b"LDsc")], + vec![ + (tag(b"LDeL"), F::Def(28, vec![tag(b"LSty")], vec![(tag(b"Wght"), F::F64(8.0))])), + (tag(b"LDSc"), F::Bool(false)), + (tag(b"LDeP"), F::Obj(tag(b"CrvD"), vec![(tag(b"Data"), F::Pos(vec![F::U32(0), F::Bool(false), F::Records(18, records)]))])), + ], + ), + )); + let lines = (0..copies) + .map(|i| { + let (fill, line) = style.take().unwrap_or((F::Ref(24), F::Ref(27))); + F::Def( + if i == 0 { 20 } else { 1000 + i }, + vec![tag(b"PCrv"), tag(b"VNod"), tag(b"Node")], + vec![ + ( + tag(b"Crvs"), + F::Obj( + tag(b"PCvD"), + vec![( + tag(b"Data"), + F::Pos(vec![ + F::U8(0), + F::U32(1), + F::Bool(false), + F::Records(18, vec![node(0.0, 0.0, 1, 0), node(100.0, 0.0, 1, 0)]), + ]), + )], ), - ], - )]), - ), - ], - ); - let spread = - F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 100.0])), (tag(b"Chld"), F::Shared(vec![line]))]); + ), + (tag(b"LIFl"), F::Shared(vec![fill])), + (tag(b"LILn"), F::Shared(vec![line])), + ], + ) + }) + .collect(); + let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 100.0])), (tag(b"Chld"), F::Shared(lines))]); let doc = synth::stream(&[ (tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(72.0))])), (tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])), @@ -402,6 +414,56 @@ mod native { assert!(r.warnings.iter().all(|w| !w.contains("pressure")), "{:?}", r.warnings); } + #[test] + fn a_dip_between_the_samples_of_a_long_pressure_curve_is_kept() { + // 256 segments at full width, except one whose handles sit at widths 0 and 2: its width is + // 1 at its middle and end but 0.71875 a quarter of the way along. + let mut curve = vec![node(0.0, 1.0, 4, 0)]; + for i in 1..=256 { + let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0); + let (h1, h2) = if i == 100 { (0.0, 2.0) } else { (1.0, 1.0) }; + curve.extend([node(a + (b - a) / 3.0, h1, 0, 1), node(b - (b - a) / 3.0, h2, 0, 2), node(b, 1.0, 4, 0)]); + } + let profile = stroke_of(&load("dip.af", &pressure_document(curve)).unwrap().doc).profile.unwrap_or_else(|| panic!("the dip is kept")); + let narrowest = profile.points.iter().map(|p| p.1).fold(1.0, f64::min); + assert!((narrowest - 0.71).abs() < 0.02, "{narrowest}"); + } + + #[test] + fn a_pressure_curve_just_under_full_width_is_kept() { + let curve = vec![node(0.0, 0.9995, 4, 0), node(1.0, 0.9995, 4, 0)]; + let profile = stroke_of(&load("near.af", &pressure_document(curve)).unwrap().doc).profile.unwrap_or_else(|| panic!("the curve is kept")); + assert_eq!(profile.at(0.5), (0.9995, 0.9995)); + } + + #[test] + fn pressure_curves_stay_within_the_points_of_one_document() { + // One 256-segment curve linked from 2100 strokes: more than a million points in all. + let mut curve = vec![node(0.0, 1.0, 4, 0)]; + for i in 1..=256 { + let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0); + curve.extend([node(a + (b - a) / 3.0, 0.0, 0, 1), node(b - (b - a) / 3.0, 0.0, 0, 2), node(b, 1.0, 4, 0)]); + } + let r = load("many.af", &pressure_documents(curve, 2100)).unwrap(); + let mut profiles = Vec::new(); + r.doc.walk(|n| { + if let Some(AppearanceItem::Stroke(k)) = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + profiles.push(k.profile.as_ref().map_or(0, |p| p.points.len())); + } + }); + assert_eq!(profiles.len(), 2100); + assert!(profiles.iter().sum::() <= 1 << 20, "{}", profiles.iter().sum::()); + assert!(profiles.iter().filter(|n| **n > 0).count() > 1000); + assert!(profiles.contains(&0)); + assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings); + + // Curves at full width count too, so linking one from many strokes can't repeat its work + // without bound. + let flat: Vec> = (0..=768).map(|i| node(f64::from(i) / 768.0, 1.0, if i % 3 == 0 { 4 } else { 0 }, (i % 3) as u8)).collect(); + let r = load("flat-many.af", &pressure_documents(flat, 2100)).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings); + } + #[test] fn native_documents_save_reopen_export_place_and_template() { let bytes = document(Method::Zstd); From 2adf5a9a61fa877fb5f452620e691532dd5bb2d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:24:33 -0800 Subject: [PATCH 048/674] Symbols: Replace Symbol clears the old symbol's dynamic overrides An override on a dynamic symbol instance names an object of its symbol's art by path. Replace Symbol kept every override whose path the new symbol's art also had, so a change made to one object of the old symbol was applied to an unrelated object of the new one. An instance given a different symbol now drops its overrides; an instance replaced with its own symbol keeps them. Undo brings them back. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 11 ++++++++--- crates/engine/src/tests/dynamic_symbols.rs | 22 ++++++++++++++++++++++ docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 5 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index a1f03b6a35..7386f77186 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -247,7 +247,7 @@ pub fn specs() -> Vec { "Replace Symbol", [], None, - "{name, ids?|id?} swap the symbol of the selected instances (they keep their appearance changes to the objects at paths a dynamic new symbol's art has) → {ids}", + "{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them) → {ids}", has_selection, symbol_replace ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 0b69b7f8ac..9bfbb902a7 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -590,14 +590,19 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result { s.edit("Replace Symbol", |d, _| { let new = natural_size(d, &name); for id in &ids { - let old = match d.node(*id).map(|n| &n.kind) { - Some(NodeKind::SymbolInstance { symbol, .. }) => natural_size(d, symbol), + let (old, other) = match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => (natural_size(d, symbol), *symbol != name), _ => continue, }; - if let Some(NodeKind::SymbolInstance { symbol, xf }) = d.node_mut(*id).map(|n| &mut n.kind) { + let Some(n) = d.node_mut(*id) else { continue }; + if let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind { *symbol = name.clone(); *xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1); } + // An override's path names an object of the old symbol's art. + if other && !n.extras().symbol_overrides.is_empty() { + n.extras_mut().symbol_overrides.clear(); + } } fit_overrides(d, &ids); Ok(()) diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index aff7690c1d..1c46d5302f 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -111,6 +111,28 @@ fn redefining_the_symbol_keeps_the_changes_whose_objects_remain() { assert_eq!(overrides(&s, inst), 0); } +#[test] +fn replace_symbol_drops_the_changes_made_for_the_old_symbol() { + let mut s = session(); + // "Other": two blue squares in the same places, the instance taken off the canvas. + let (a, b) = (square(&mut s, 10.0), square(&mut s, 60.0)); + let first = id(&s.execute("symbol.new", &json!({"name": "Other", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()); + s.execute("edit.clear", &json!({"ids": [first.0]})).unwrap(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": "#ff0000"})).unwrap(); + // The same symbol: nothing changes. + s.execute("symbol.replace", &json!({"name": "Pair", "ids": [inst.0]})).unwrap(); + assert_eq!(overrides(&s, inst), 1); + assert_eq!(pixel(&s, 80, 30), RED); + s.execute("symbol.replace", &json!({"name": "Other", "ids": [inst.0]})).unwrap(); + assert_eq!(overrides(&s, inst), 0, "the change named an object of Pair's art"); + assert_eq!(pixel(&s, 80, 30), BLUE, "Other's art draws as the symbol has it"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(matches!(&node(&s, inst).kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Pair")); + assert_eq!(overrides(&s, inst), 1); + assert_eq!(pixel(&s, 80, 30), RED); +} + #[test] fn reset_and_static_drop_the_changes_and_undo_brings_them_back() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..c059e67629 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1586,7 +1586,8 @@ already walks Image Trace. Short agent entry points: a path that names no object. `symbol.instance.reset {ids?}` drops the selected instances' changes (the Properties panel's Reset). Redefining the symbol (`symbol.update`) reshapes every instance and keeps each change whose path the new art still has; `symbol.breakLink` bakes the changes into the expanded art; `symbol.edit` edits the symbol's own - art, and each edit there keeps the changes whose path the art still has; making the symbol static drops them. + art, and each edit there keeps the changes whose path the art still has; making the symbol static drops them, and + so does `symbol.replace` with a different symbol (a replace with the instance's own symbol keeps them). ```json {"name":"run_command","arguments":{"command":"symbol.instance.setAppearance","params":{"id":42,"path":[1],"fill":"#d0021b","opacity":80}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..edd3ca93d3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1454,7 +1454,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Dynamic symbols (2026-11-01) -Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own fill, stroke, opacity and blend for any object of the symbol's art, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol expands the symbol's own art; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: Direct Selection of an object inside a dynamic instance on the canvas (with the Fill/Stroke controls then setting its change), and reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. +Symbols area (#4938), from the public symbol documentation ([create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html), [edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html)). Symbol Options has Symbol Type (Dynamic Symbol / Static Symbol; the dialog's default is Dynamic, `symbol.new`'s `type` defaults to static so scripts behave as before). An instance of a dynamic symbol keeps its own fill, stroke, opacity and blend for any object of the symbol's art, named by a child-index path (`symbol.instance.setAppearance`), and stays an instance: the canvas, SVG, PDF, EPS, legacy `.ai`, EMF/WMF and DXF writers, effects and Expand draw the art with those changes. Redefining the symbol reshapes every instance and keeps each change whose object the new art still has; Break Link bakes the changes into the art; Edit Symbol expands the symbol's own art; Reset (`symbol.instance.reset`: the Properties panel's Quick Actions and the Symbols panel menu) and making the symbol static drop them, and Replace Symbol drops them when it gives the instance a different symbol. The type is stored on the symbol and the changes on the instance in the native format, both left out when unset, so documents without them save byte for byte as before. Remaining: Direct Selection of an object inside a dynamic instance on the canvas (with the Fill/Stroke controls then setting its change), and reading and writing the type and changes in `.ai` files. Evidence: `crates/engine/src/tests/dynamic_symbols.rs`, `crates/doc/src/symbol_overrides.rs` tests. Score unchanged at 87% (estimated); hours 5–9 → 4–8. ## Document Tools add-on: Export All Open Documents (2026-11-01) From 387197c037a57e6ad68ac85cc67116d6a2d63aa3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:28:09 -0800 Subject: [PATCH 049/674] Separations Preview: Gamut Check counts colors in the singular and the plural Gamut Check reported "1 colour(s) are out of the CMYK gamut". It now reports "1 color is out of the CMYK gamut", "3 colors are out of the CMYK gamut" and "All colors are within the CMYK gamut", and the status bar shows them in the interface language through new @msg and @msgplural rows in every catalog. The plain catalog rows for the old British text are removed, since the status bar does not read them. --- crates/ui-egui/src/i18n/bg.tsv | 3 ++- 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 | 3 ++- 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 | 3 ++- 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 | 3 ++- 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/tests.rs | 23 +++++++++++++++++++++++ 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 ++- crates/ui-egui/src/panels/separations.rs | 12 ++++++++++-- docs/target-app-parity.md | 1 + 29 files changed, 86 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f3f6cbfbb6..bf1a723622 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -151,7 +151,6 @@ All Artwork Above Всички графични елементи отгоре All Caps Всички главни букви All Categories Всички категории - All colours are within the CMYK gamut Всички цветове са в CMYK цветовата гама All on Active Artboard Всички на активната работна област All on Same Layers Всички на същите слоеве All printer's marks Всички печатарски марки @@ -4409,6 +4408,8 @@ axis Both И двете @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Копиран е CSS кодът на {n} обект|Копиран е CSS кодът на {n} обекта @msgplural Downloaded {n} file|Downloaded {n} files Изтеглен е {n} файл|Изтеглени са {n} файла @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Експортиран е {n} файл в {folder}|Експортирани са {n} файла в {folder} +@msg All colors are within the CMYK gamut Всички цветове са в CMYK цветовата гама +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} цвят е извън CMYK цветовата гама|{n} цвята са извън CMYK цветовата гама @msg Unembedded to {_1} Извадено от вграждане в {_1} @msg Reset {_1} Нулирано: {_1} @msg Sent to {_1} Изпратено към {_1} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7efa9c0e7..956524aab3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1895,7 +1895,6 @@ digits Malayalam Malajalam Smart Guides (⌘U) Pametne vodilice (⌘U) Snap Options Opcije hvatanja Type: Vrsta: - All colours are within the CMYK gamut Sve boje su unutar CMYK gamuta Assign: Dodijeli: Color Settings Postavke boja Gamut Check Provjera gamuta @@ -4811,6 +4810,8 @@ imageTrace Outline Obris @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopiran je CSS {n} objekta|Kopiran je CSS {n} objekta|Kopiran je CSS {n} objekata @msgplural Downloaded {n} file|Downloaded {n} files Preuzeta je {n} datoteka|Preuzete su {n} datoteke|Preuzeto je {n} datoteka @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Izvezena je {n} datoteka u {folder}|Izvezene su {n} datoteke u {folder}|Izvezeno je {n} datoteka u {folder} +@msg All colors are within the CMYK gamut Sve boje su unutar CMYK gamuta +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} boja je izvan CMYK gamuta|{n} boje su izvan CMYK gamuta|{n} boja je izvan CMYK gamuta @msg Unembedded to {_1} Ugrađivanje poništeno u {_1} @msg Reset {_1} Vrati na početno: {_1} @msg Sent to {_1} Poslano na {_1} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd6172d6a6..d555bc2a03 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -249,7 +249,6 @@ All Artwork Above Tot l’art superior All Caps Totes majúscules All Categories Totes les categories - All colours are within the CMYK gamut Tots els colors són dins de la gamma CMYK All in One Folder Tot en una carpeta All Layers Totes les capes All on Active Artboard Tot al tauler actiu @@ -5341,6 +5340,8 @@ digits Malayalam Malaiàlam @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects S’ha copiat el CSS de {n} objecte|S’ha copiat el CSS de {n} objectes @msgplural Downloaded {n} file|Downloaded {n} files S’ha baixat {n} fitxer|S’han baixat {n} fitxers @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} S’ha exportat {n} fitxer a {folder}|S’han exportat {n} fitxers a {folder} +@msg All colors are within the CMYK gamut Tots els colors són dins de la gamma CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} color és fora de la gamma CMYK|{n} colors són fora de la gamma CMYK @msg Reload the page to go on (changes not saved yet may be lost). Recarrega la pàgina per continuar (els canvis encara no desats es poden perdre). @msg Replace Spine: select a blend and a path Substitueix l’espina: selecciona una fusió i un traçat @msg replace: the object to replace was changed or deleted replace: l’objecte que s’havia de substituir s’ha canviat o suprimit diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 34c7f4e035..2093e072d0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1921,7 +1921,6 @@ digits Malayalam Malajálamské Smart Guides (⌘U) Chytrá vodítka (⌘U) Snap Options Možnosti přichytávání Type: Typ: - All colours are within the CMYK gamut Všechny barvy jsou v gamutu CMYK Assign: Přiřadit: Color Settings Nastavení barev Gamut Check Kontrola gamutu @@ -4851,6 +4850,8 @@ imageTrace Outline Obrys @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Zkopírováno CSS {n} objektu|Zkopírováno CSS {n} objektů|Zkopírováno CSS {n} objektů @msgplural Downloaded {n} file|Downloaded {n} files Stažen {n} soubor|Staženy {n} soubory|Staženo {n} souborů @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exportován {n} soubor do {folder}|Exportovány {n} soubory do {folder}|Exportováno {n} souborů do {folder} +@msg All colors are within the CMYK gamut Všechny barvy jsou v gamutu CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} barva je mimo gamut CMYK|{n} barvy jsou mimo gamut CMYK|{n} barev je mimo gamut CMYK @msg Unembedded to {_1} Vložení zrušeno, uloženo do: {_1} @msg Reset {_1} Obnoveno: {_1} @msg Sent to {_1} Odesláno do {_1} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5a23913424..06c7829677 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1726,7 +1726,6 @@ digits Malayalam Malayalam Smart Guides (⌘U) Smarte hjælpelinjer (⌘U) Snap Options Fastgørelsesindstillinger Type: Type: - All colours are within the CMYK gamut Alle farver er inden for CMYK-farveomfanget Assign: Tildel: Color Settings Farveindstillinger Gamut Check Farveomfangskontrol @@ -4505,6 +4504,8 @@ imageTrace Outline Kontur @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopierede CSS fra {n} objekt|Kopierede CSS fra {n} objekter @msgplural Downloaded {n} file|Downloaded {n} files Downloadede {n} fil|Downloadede {n} filer @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Eksporterede {n} fil til {folder}|Eksporterede {n} filer til {folder} +@msg All colors are within the CMYK gamut Alle farver er inden for CMYK-farveomfanget +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} farve er uden for CMYK-farveomfanget|{n} farver er uden for CMYK-farveomfanget @msg Unembedded to {_1} Fjernede indlejring til {_1} @msg Reset {_1} Nulstillede {_1} @msg Sent to {_1} Sendte til {_1} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 101bbefac6..4c2b629c7d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -140,7 +140,6 @@ All Artwork Above Gesamte Grafik darüber All Caps Großbuchstaben All Categories Alle Kategorien - All colours are within the CMYK gamut Alle Farben liegen im CMYK-Farbumfang All on Active Artboard Alles auf der aktiven Zeichenfläche All on Same Layers Alles auf denselben Ebenen All printer's marks Alle Druckermarken @@ -4460,6 +4459,8 @@ theme Appearance Erscheinungsbild @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS von {n} Objekt kopiert|CSS von {n} Objekten kopiert @msgplural Downloaded {n} file|Downloaded {n} files {n} Datei heruntergeladen|{n} Dateien heruntergeladen @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} Datei nach {folder} exportiert|{n} Dateien nach {folder} exportiert +@msg All colors are within the CMYK gamut Alle Farben liegen im CMYK-Farbumfang +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} Farbe liegt außerhalb des CMYK-Farbumfangs|{n} Farben liegen außerhalb des CMYK-Farbumfangs @msg Unembedded to {_1} Einbettung aufgehoben, gespeichert unter {_1} @msg Reset {_1} {_1} zurückgesetzt @msg Sent to {_1} An {_1} gesendet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e704faade5..7cc3d3c18c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -145,7 +145,6 @@ All Artwork Above Όλα τα γραφικά στοιχεία παραπάνω All Caps Όλα κεφαλαία All Categories Όλες οι κατηγορίες - All colours are within the CMYK gamut Όλα τα χρώματα βρίσκονται εντός της χρωματικής γκάμας CMYK All on Active Artboard Όλα στον ενεργό πίνακα σχεδίασης All on Same Layers Όλα στα ίδια επίπεδα All printer's marks Όλα τα σημάδια εκτύπωσης @@ -4493,6 +4492,8 @@ digits Malayalam Μαλαγιάλαμ @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Αντιγράφηκαν οι κανόνες CSS από {n} αντικείμενο|Αντιγράφηκαν οι κανόνες CSS από {n} αντικείμενα @msgplural Downloaded {n} file|Downloaded {n} files Έγινε λήψη {n} αρχείου|Έγινε λήψη {n} αρχείων @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Εξήχθη {n} αρχείο στον φάκελο {folder}|Εξήχθησαν {n} αρχεία στον φάκελο {folder} +@msg All colors are within the CMYK gamut Όλα τα χρώματα βρίσκονται εντός της χρωματικής γκάμας CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} χρώμα βρίσκεται εκτός της χρωματικής γκάμας CMYK|{n} χρώματα βρίσκονται εκτός της χρωματικής γκάμας CMYK @msg Unembedded to {_1} Καταργήθηκε η ενσωμάτωση στο {_1} @msg Reset {_1} Επαναφορά {_1} @msg Sent to {_1} Στάλθηκε στο {_1} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4ebddbe9a9..da29f385eb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -165,7 +165,6 @@ All Artwork Above Toda la ilustración superior All Caps Shiftculas All Categories Todas las categorías - All colours are within the CMYK gamut Todos los colores están dentro de la gama CMYK All on Active Artboard Todo en la mesa de trabajo activa All on Same Layers Todo en las mismas capas All printer's marks Todas las marcas de impresora @@ -4545,6 +4544,8 @@ axis Both Ambos @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Se copió el CSS de {n} objeto|Se copió el CSS de {n} objetos @msgplural Downloaded {n} file|Downloaded {n} files Se descargó {n} archivo|Se descargaron {n} archivos @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Se exportó {n} archivo a {folder}|Se exportaron {n} archivos a {folder} +@msg All colors are within the CMYK gamut Todos los colores están dentro de la gama CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} color está fuera de la gama CMYK|{n} colores están fuera de la gama CMYK @msg Unembedded to {_1} Se desincrustó en {_1} @msg Reset {_1} Se restableció {_1} @msg Sent to {_1} Se envió a {_1} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7042b21f22..ed94877b69 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1882,7 +1882,6 @@ digits Malayalam Malajalam Smart Guides (⌘U) Älykkäät apuviivat (⌘U) Snap Options Tartunta-asetukset Type: Tyyppi: - All colours are within the CMYK gamut Kaikki värit ovat CMYK-väriavaruuden sisällä Assign: Määritä: Color Settings Väriasetukset Gamut Check Väriavaruuden tarkistus @@ -4753,6 +4752,8 @@ imageTrace Outline Ääriviiva @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopioitiin {n} objektin CSS|Kopioitiin {n} objektin CSS @msgplural Downloaded {n} file|Downloaded {n} files Ladattiin {n} tiedosto|Ladattiin {n} tiedostoa @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Vietiin {n} tiedosto kansioon {folder}|Vietiin {n} tiedostoa kansioon {folder} +@msg All colors are within the CMYK gamut Kaikki värit ovat CMYK-väriavaruuden sisällä +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} väri on CMYK-väriavaruuden ulkopuolella|{n} väriä on CMYK-väriavaruuden ulkopuolella @msg Unembedded to {_1} Upotus purettiin kohteeseen {_1} @msg Reset {_1} Palautettiin oletukseksi {_1} @msg Sent to {_1} Lähetettiin kohteeseen {_1} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 48eb621eb9..3bf7a3da8f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -166,7 +166,6 @@ All Artwork Above Toute l’illustration au-dessus All Caps Tout en capitales All Categories Toutes les catégories - All colours are within the CMYK gamut Toutes les couleurs sont dans la gamme CMJN All on Active Artboard Tout sur le plan de travail actif All on Same Layers Tout sur les mêmes calques All printer's marks Tous les repères d’impression @@ -4535,6 +4534,8 @@ axis Both Les deux @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS de {n} objet copié|CSS de {n} objets copié @msgplural Downloaded {n} file|Downloaded {n} files {n} fichier téléchargé|{n} fichiers téléchargés @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} fichier exporté vers {folder}|{n} fichiers exportés vers {folder} +@msg All colors are within the CMYK gamut Toutes les couleurs sont dans la gamme CMJN +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} couleur est hors de la gamme CMJN|{n} couleurs sont hors de la gamme CMJN @msg Unembedded to {_1} Incorporation annulée vers {_1} @msg Reset {_1} {_1} réinitialisé @msg Sent to {_1} Envoyé à {_1} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 81f9482631..d551ba5fa2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -236,7 +236,6 @@ All Artwork Above Az összes fölötte lévő grafika All Caps Csupa nagybetű All Categories Összes kategória - All colours are within the CMYK gamut Minden szín a CMYK-színtartományon belül van All Layers Összes réteg All on Active Artboard Az összes az aktív rajztáblán All on Same Layers Az összes ugyanazokon a rétegeken @@ -5037,6 +5036,8 @@ imageTrace Outline Körvonal @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS másolva, objektumok: {n} @msgplural Downloaded {n} file|Downloaded {n} files Letöltött fájlok: {n} @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exportált fájlok: {n}, mappa: {folder} +@msg All colors are within the CMYK gamut Minden szín a CMYK-színtartományon belül van +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} szín a CMYK-színtartományon kívül van @msg Reload the page to go on (changes not saved yet may be lost). A folytatáshoz töltsd újra az oldalt (a még nem mentett módosítások elveszhetnek). @msg Replace Spine: select a blend and a path Gerinc cseréje: jelölj ki egy összemosást és egy útvonalat @msg Reset {_1} Visszaállítva: {_1} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 89633ae991..b1a6a6b838 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1726,7 +1726,6 @@ digits Malayalam Malayalam Smart Guides (⌘U) Panduan cerdas (⌘U) Snap Options Opsi snap Type: Jenis: - All colours are within the CMYK gamut Semua warna berada dalam gamut CMYK Assign: Tetapkan: Color Settings Pengaturan warna Gamut Check Pemeriksaan gamut @@ -4505,6 +4504,8 @@ imageTrace Outline Kontur @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Berhasil menyalin CSS dari {n} objek @msgplural Downloaded {n} file|Downloaded {n} files Berhasil mengunduh {n} file @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Berhasil mengekspor {n} file ke {folder} +@msg All colors are within the CMYK gamut Semua warna berada dalam gamut CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} warna berada di luar gamut CMYK @msg Unembedded to {_1} Gambar tersemat dilepas ke {_1} @msg Reset {_1} {_1} diatur ulang @msg Sent to {_1} Dikirim ke {_1} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6acfaf3c9a..a00301d770 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -165,7 +165,6 @@ All Artwork Above Tutta la grafica soprastante All Caps Tutto maiuscolo All Categories Tutte le categorie - All colours are within the CMYK gamut Tutti i colori rientrano nella gamma CMYK All on Active Artboard Tutto nella tavola da disegno attiva All on Same Layers Tutto sugli stessi livelli All printer's marks Tutti i segni di stampa @@ -4586,6 +4585,8 @@ axis Both Entrambi @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Copiato il CSS di {n} oggetto|Copiato il CSS di {n} oggetti @msgplural Downloaded {n} file|Downloaded {n} files Scaricato {n} file|Scaricati {n} file @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Esportato {n} file in {folder}|Esportati {n} file in {folder} +@msg All colors are within the CMYK gamut Tutti i colori rientrano nella gamma CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} colore è fuori dalla gamma CMYK|{n} colori sono fuori dalla gamma CMYK @msg Unembedded to {_1} Incorporamento rimosso, salvato in {_1} @msg Reset {_1} Reimpostato {_1} @msg Sent to {_1} Inviato a {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bf3cd6bd1..5516eed086 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3383,7 +3383,6 @@ gradient-kind Radial 円形 Align center 中央揃え Align left 左揃え Align right 右揃え - All colours are within the CMYK gamut すべてのカラーが CMYK の色域内です Alt Alt Amount 量 Area Type Options エリア内文字オプション @@ -4646,6 +4645,8 @@ swatch Bright Violet ビビッドバイオレット @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects {n} 個のオブジェクトの CSS をコピーしました @msgplural Downloaded {n} file|Downloaded {n} files {n} 個のファイルをダウンロードしました @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} 個のファイルを {folder} に書き出しました +@msg All colors are within the CMYK gamut すべてのカラーが CMYK の色域内です +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個のカラーが CMYK の色域外です @msg Unembedded to {_1} 埋め込みを解除して {_1} に保存しました @msg no swatch library `{l}` (see swatch.library.list) スウォッチライブラリ `{l}` が見つかりません (swatch.library.list を参照) @msg no user library folder here この環境にはユーザーライブラリフォルダーがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cf411b072c..439229dd9f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1629,7 +1629,6 @@ digits Malayalam მალაიალამური Smart Guides (⌘U) ჭკვიანი დამხმარე ხაზები (⌘U) Snap Options მიბმის პარამეტრები Type: ტიპი: - All colours are within the CMYK gamut ყველა ფერი CMYK-ის გამის ფარგლებშია Assign: მინიჭება: Color Settings ფერის პარამეტრები Gamut Check გამის შემოწმება @@ -4292,6 +4291,8 @@ font-technology Variable ცვლადი @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects კოპირებულია ობიექტის CSS ({n}) @msgplural Downloaded {n} file|Downloaded {n} files ჩამოტვირთულია ფაილი ({n}) @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} ექსპორტირებულია ფაილი ({n}) საქაღალდეში {folder} +@msg All colors are within the CMYK gamut ყველა ფერი CMYK-ის გამის ფარგლებშია +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut CMYK-ის გამის ფარგლებს გარეთაა ფერი ({n}) @msg Unembedded to {_1} ჩაშენება მოხსნილია: {_1} @msg Reset {_1} ჩამოყრილია: {_1} @msg Sent to {_1} გაგზავნილია: {_1} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81f6c600c6..37ea4cc346 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3371,7 +3371,6 @@ gradient-kind Radial 방사형 Align center 가운데 정렬 Align left 왼쪽 정렬 Align right 오른쪽 정렬 - All colours are within the CMYK gamut 모든 색상이 CMYK 색상 범위 안에 있습니다 Alt Alt Amount 양 Area Type Options 영역 문자 옵션 @@ -4573,6 +4572,8 @@ theme Appearance 외관 @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 개체 {n}개의 CSS를 복사했습니다 @msgplural Downloaded {n} file|Downloaded {n} files 파일 {n}개를 다운로드했습니다 @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 파일 {n}개를 {folder}에 내보냈습니다 +@msg All colors are within the CMYK gamut 모든 색상이 CMYK 색상 범위 안에 있습니다 +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut 색상 {n}개가 CMYK 색상 범위를 벗어났습니다 @msg Unembedded to {_1} {_1}에 포함 해제했습니다 @msg no swatch library `{l}` (see swatch.library.list) 견본 라이브러리 `{l}`이(가) 없습니다(swatch.library.list 참조) @msg no user library folder here 여기에는 사용자 라이브러리 폴더가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3448536832..9d8f5b2cfe 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1740,7 +1740,6 @@ digits Malayalam Malayalam Smart Guides (⌘U) Slimme hulplijnen (⌘U) Snap Options Snapopties Type: Type: - All colours are within the CMYK gamut Alle kleuren vallen binnen het CMYK-gamut Assign: Toewijzen: Color Settings Kleurinstellingen Gamut Check Gamutcontrole @@ -4517,6 +4516,8 @@ imageTrace Outline Contour @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS van {n} object gekopieerd|CSS van {n} objecten gekopieerd @msgplural Downloaded {n} file|Downloaded {n} files {n} bestand gedownload|{n} bestanden gedownload @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} bestand geëxporteerd naar {folder}|{n} bestanden geëxporteerd naar {folder} +@msg All colors are within the CMYK gamut Alle kleuren vallen binnen het CMYK-gamut +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kleur valt buiten het CMYK-gamut|{n} kleuren vallen buiten het CMYK-gamut @msg Unembedded to {_1} Extern gemaakt: {_1} @msg Reset {_1} {_1} opnieuw ingesteld @msg Sent to {_1} Verzonden naar {_1} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14825f83cf..7d3505f3ec 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1840,7 +1840,6 @@ digits Malayalam Malajalam Smart Guides (⌘U) Inteligentne linie pomocnicze (⌘U) Snap Options Opcje przyciągania Type: Typ: - All colours are within the CMYK gamut Wszystkie kolory mieszczą się w gamucie CMYK Assign: Przypisz: Color Settings Ustawienia kolorów Gamut Check Sprawdzanie gamutu @@ -4677,6 +4676,8 @@ imageTrace Outline Kontur @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Skopiowano CSS {n} obiektu|Skopiowano CSS {n} obiektów|Skopiowano CSS {n} obiektów @msgplural Downloaded {n} file|Downloaded {n} files Pobrano {n} plik|Pobrano {n} pliki|Pobrano {n} plików @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Wyeksportowano {n} plik do {folder}|Wyeksportowano {n} pliki do {folder}|Wyeksportowano {n} plików do {folder} +@msg All colors are within the CMYK gamut Wszystkie kolory mieszczą się w gamucie CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kolor nie mieści się w gamucie CMYK|{n} kolory nie mieszczą się w gamucie CMYK|{n} kolorów nie mieści się w gamucie CMYK @msg Unembedded to {_1} Wyodrębniono do {_1} @msg Reset {_1} Zresetowano {_1} @msg Sent to {_1} Wysłano do {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 96a31c3e57..607759936a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4116,6 +4116,8 @@ axis Both Ambos @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS de {n} objeto copiado|CSS de {n} objetos copiado @msgplural Downloaded {n} file|Downloaded {n} files {n} arquivo baixado|{n} arquivos baixados @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} arquivo exportado para {folder}|{n} arquivos exportados para {folder} +@msg All colors are within the CMYK gamut Todas as cores estão dentro do gamut CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} cor está fora do gamut CMYK|{n} cores estão fora do gamut CMYK @msg Unembedded to {_1} Desincorporado para {_1} @msg Reset {_1} Redefinir {_1} @msg Sent to {_1} Enviado para {_1} @@ -4355,7 +4357,6 @@ axis Both Ambos Align center Alinhar ao Centro Align left Alinhar à Esquerda Align right Alinhar à Direita - All colours are within the CMYK gamut Todas as cores estão dentro do gamut CMYK Alt Alt Amount Quantidade Area Type Options Opções de Texto de Área diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fdb51b80df..887faee217 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -163,7 +163,6 @@ All Artwork Above Весь рисунок выше All Caps Все прописные All Categories Все категории - All colours are within the CMYK gamut Все цвета входят в цветовой охват CMYK All on Active Artboard Всё на активной монтажной области All on Same Layers Всё на тех же слоях All printer's marks Все типографские метки @@ -4581,6 +4580,8 @@ axis Both Оба @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Скопирован CSS {n} объекта|Скопирован CSS {n} объектов|Скопирован CSS {n} объектов @msgplural Downloaded {n} file|Downloaded {n} files Скачан {n} файл|Скачано {n} файла|Скачано {n} файлов @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Экспортирован {n} файл в {folder}|Экспортировано {n} файла в {folder}|Экспортировано {n} файлов в {folder} +@msg All colors are within the CMYK gamut Все цвета входят в цветовой охват CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} цвет выходит за пределы цветового охвата CMYK|{n} цвета выходят за пределы цветового охвата CMYK|{n} цветов выходят за пределы цветового охвата CMYK @msg Unembedded to {_1} Извлечено в {_1} @msg Reset {_1} Сброшено: {_1} @msg Sent to {_1} Отправлено в {_1} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e2dddf022b..72803496c4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -153,7 +153,6 @@ All Artwork Above All grafik ovanför All Caps Versaler All Categories Alla kategorier - All colours are within the CMYK gamut Alla färger ligger inom CMYK-färgomfånget All on Active Artboard Alla på aktiv rityta All on Same Layers Alla på samma lager All printer's marks Alla tryckmärken @@ -4444,6 +4443,8 @@ axis Both Båda @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopierade CSS för {n} objekt|Kopierade CSS för {n} objekt @msgplural Downloaded {n} file|Downloaded {n} files Hämtade {n} fil|Hämtade {n} filer @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exporterade {n} fil till {folder}|Exporterade {n} filer till {folder} +@msg All colors are within the CMYK gamut Alla färger ligger inom CMYK-färgomfånget +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} färg ligger utanför CMYK-färgomfånget|{n} färger ligger utanför CMYK-färgomfånget @msg Unembedded to {_1} Extraherad till {_1} @msg Reset {_1} Återställ {_1} @msg Sent to {_1} Skickat till {_1} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7e5ca938c6..6c80beb0db 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1528,6 +1528,29 @@ fn messages_with_a_count_take_the_plural_form() { assert_eq!(message(cs, "Packaged 21 files"), "Zabaleno 21 souborů"); } +/// The Gamut Check status line names a count of 1 in the singular and other counts in the plural, +/// and every complete catalog translates it, in the form its plural rule picks. +#[test] +fn gamut_check_status_takes_the_plural_form() { + use crate::panels::separations::gamut_check_status; + assert_eq!(gamut_check_status(0), "All colors are within the CMYK gamut"); + assert_eq!(gamut_check_status(1), "1 color is out of the CMYK gamut"); + assert_eq!(gamut_check_status(3), "3 colors are out of the CMYK gamut"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for n in [0, 1, 3] { + let s = gamut_check_status(n); + assert_ne!(message(lang, &s), s, "{code}: {s}"); + } + } + assert_eq!(message(de(), &gamut_check_status(1)), "1 Farbe liegt außerhalb des CMYK-Farbumfangs"); + assert_eq!(message(de(), &gamut_check_status(3)), "3 Farben liegen außerhalb des CMYK-Farbumfangs"); + let cs = cs(); + assert_eq!(message(cs, &gamut_check_status(1)), "1 barva je mimo gamut CMYK"); + assert_eq!(message(cs, &gamut_check_status(3)), "3 barvy jsou mimo gamut CMYK"); + assert_eq!(message(cs, &gamut_check_status(5)), "5 barev je mimo gamut CMYK"); +} + /// The link, font and export status messages with a count, in English for a count of 1 and of 2. const COUNTED_STATUS_MESSAGES: &[(&str, &str)] = &[ ("1 linked file can't be read here: its preview shows", "2 linked files can't be read here: their previews show"), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9ecf2ccf93..7a60100483 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -150,7 +150,6 @@ All Artwork Above Yukarıdaki Tüm Sanat Eserleri All Caps Tamamı Büyük Harf All Categories Tüm Kategoriler - All colours are within the CMYK gamut Tüm renkler CMYK gamındadır All on Active Artboard Hepsi Aktif Çalışma Yüzeyinde All on Same Layers Hepsi Aynı Katmanlarda All printer's marks Tüm yazıcı işaretleri @@ -4287,6 +4286,8 @@ axis Both Her İkisi @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects {n} nesnenin CSS'si kopyalandı @msgplural Downloaded {n} file|Downloaded {n} files {n} dosya indirildi @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} dosya {folder} klasörüne aktarıldı +@msg All colors are within the CMYK gamut Tüm renkler CMYK gamındadır +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} renk CMYK gamının dışında @msg Unembedded to {_1} {_1}'ye gömülü değil @msg Reset {_1} {_1}'yi sıfırla @msg Sent to {_1} {_1}'ye gönderildi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d348440a2c..007750e663 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -159,7 +159,6 @@ All Artwork Above Весь малюнок вище All Caps Всі великі All Categories Усі категорії - All colours are within the CMYK gamut Усі кольори входять у колірне охоплення CMYK All on Active Artboard Все на активній монтажній області All on Same Layers Все на тих же шарах All printer's marks Усі друкарські мітки @@ -4570,6 +4569,8 @@ axis Both Обидві @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Скопійовано CSS {n} об’єкта|Скопійовано CSS {n} об’єктів|Скопійовано CSS {n} об’єктів @msgplural Downloaded {n} file|Downloaded {n} files Завантажено {n} файл|Завантажено {n} файли|Завантажено {n} файлів @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Експортовано {n} файл до {folder}|Експортовано {n} файли до {folder}|Експортовано {n} файлів до {folder} +@msg All colors are within the CMYK gamut Усі кольори входять у колірне охоплення CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} колір виходить за межі колірного охоплення CMYK|{n} кольори виходять за межі колірного охоплення CMYK|{n} кольорів виходять за межі колірного охоплення CMYK @msg Unembedded to {_1} Вилучено у {_1} @msg Reset {_1} Скинуто: {_1} @msg Sent to {_1} Відправлено до {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 09652ede2b..9e2471f85c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -181,7 +181,6 @@ All Artwork Above Tất cả tác phẩm phía trên All Caps Viết hoa toàn bộ All Categories Tất cả danh mục - All colours are within the CMYK gamut Tất cả màu nằm trong gam CMYK All on Active Artboard Tất cả trên bảng vẽ hiện hoạt All on Same Layers Tất cả trên cùng lớp All printer's marks Tất cả dấu máy in @@ -4691,6 +4690,8 @@ theme Appearance Giao diện @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Đã sao chép CSS của {n} đối tượng @msgplural Downloaded {n} file|Downloaded {n} files Đã tải xuống {n} tệp @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Đã xuất {n} tệp vào {folder} +@msg All colors are within the CMYK gamut Tất cả màu nằm trong gam CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} màu nằm ngoài gam CMYK @msg Reload the page to go on (changes not saved yet may be lost). Tải lại trang để tiếp tục (các thay đổi chưa lưu có thể bị mất). @msg Replace Spine: select a blend and a path Thay thế trục: chọn một đối tượng hòa trộn và một đường dẫn @msg Reset {_1} Đã đặt lại {_1} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 841bd4528a..e89f3a7953 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -115,7 +115,6 @@ All Artwork Above 上方所有图稿 All Caps 全部大写 All Categories 所有类别 - All colours are within the CMYK gamut 所有颜色皆在 CMYK 色域内 All on Active Artboard 当前画板上的所有对象 All on Same Layers 同层上的所有对象 All printer's marks 所有打印机标记 @@ -4363,6 +4362,8 @@ imageTrace Outline 轮廓 @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 已复制 {n} 个对象的 CSS @msgplural Downloaded {n} file|Downloaded {n} files 已下载 {n} 个文件 @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 已将 {n} 个文件导出到 {folder} +@msg All colors are within the CMYK gamut 所有颜色皆在 CMYK 色域内 +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 个颜色超出 CMYK 色域 @msg Unembedded to {_1} 已取消嵌入到 {_1} @msg no swatch library `{l}` (see swatch.library.list) 没有色板库 `{l}` (请参阅 swatch.library.list) @msg no user library folder here 此处没有用户库文件夹 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a515d59a74..e9230ccd93 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -123,7 +123,6 @@ All Artwork Above 上方所有圖稿 All Caps 全部大寫 All Categories 所有類別 - All colours are within the CMYK gamut 所有顏色皆在 CMYK 色域內 All on Active Artboard 作用中工作區域上的全部 All on Same Layers 相同圖層上的全部 All printer's marks 所有印表機標記 @@ -2286,6 +2285,8 @@ file-filter Templates 範本 @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 已複製 {n} 個物件的 CSS @msgplural Downloaded {n} file|Downloaded {n} files 已下載 {n} 個檔案 @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 已將 {n} 個檔案匯出至 {folder} +@msg All colors are within the CMYK gamut 所有顏色皆在 CMYK 色域內 +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個顏色超出 CMYK 色域 @msg Unembedded to {_1} 已取消內嵌至 {_1} @msg no swatch library `{l}` (see swatch.library.list) 沒有色票資料庫 `{l}` (請參閱 swatch.library.list) @msg no user library folder here 此處沒有使用者資料庫資料夾 diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index e50db115ea..38cfa604e2 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -122,8 +122,7 @@ fn settings_section(app: &mut VectorcraftApp, ui: &mut Ui) { match app.run("color.gamutCheck", json!({})) { Ok(r) => { let n = r["outOfGamut"].as_array().map_or(0, Vec::len); - app.ui.status = - if n == 0 { "All colours are within the CMYK gamut".into() } else { format!("{n} colour(s) are out of the CMYK gamut") }; + app.ui.status = gamut_check_status(n); } Err(e) => app.ui.status = e, } @@ -142,6 +141,15 @@ fn settings_section(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The status bar's line after Gamut Check finds `n` colors outside the CMYK gamut. +pub(crate) fn gamut_check_status(n: usize) -> String { + if n == 0 { + "All colors are within the CMYK gamut".into() + } else { + crate::i18n::msg_n(n as u64, "{n} color is out of the CMYK gamut", "{n} colors are out of the CMYK gamut", &[]) + } +} + fn proof_section(app: &mut VectorcraftApp, ui: &mut Ui) { let v = proof::view(); widgets::section_header(ui, tl!("Proof Setup")); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..2d552390ab 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -959,6 +959,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). A Cmd/Ctrl-click on the Color panel's spectrum applies Complement and a Cmd/Ctrl+Shift-click applies Invert to the active Fill or Stroke (`paint.complement`, `paint.invert`); with Alt also held, the click recolors the inactive one, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) list them. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. + The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. From 589c56da2280d9ff9512b038ef0e5f3600567184 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:19:16 -0800 Subject: [PATCH 050/674] PDF export: a white stop linked to a process swatch keeps a spot gradient on its ink A gradient of one spot ink's tints and paper white is written as a Separation shading in that ink, with each white stop at 0% of it. A white stop linked to a swatch that is not a spot color (a global White swatch, for example) did not count as paper white. In an RGB document the spot ink was then dropped: a Classic gradient was written in the stops' own colors, and a Perceptual one was exported as an image in process colors. Such a stop now counts as paper white in the Separation and DeviceN paths and in the checks that pick them, as an unlinked white stop does. A stop linked to a white spot color is still a stop of that ink. --- crates/engine/src/tests/linked_stops.rs | 29 +++++++++++++++++++++++++ crates/pdf/src/export/paint.rs | 27 +++++++++++++---------- docs/target-app-parity.md | 2 ++ 3 files changed, 46 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 666d317fe3..61bc3a4d24 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -140,6 +140,35 @@ fn spot_gradients_export_as_separation_shadings() { assert!(warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); } +#[test] +fn white_stops_linked_to_process_swatches_are_paper_in_spot_gradients() { + let (mut s, _) = setup(); + run(&mut s, "swatch.new", json!({"name": "Paper", "color": "#ffffff", "global": true})); + let ink_to_paper = json!({"stops": [{"offset": 0, "swatch": "Ink", "tint": 80}, {"offset": 1, "swatch": "Paper"}]}); + // As Ink → unlinked white: a Separation shading from 80 % to 0 %. + run(&mut s, "paint.editGradient", ink_to_paper.clone()); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "a Separation shading"); + assert!(!pdf.contains("/DeviceN") && pdf.contains("/C0[0.8]/C1[0]"), "the shading's tints"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); + // A Perceptual one too. + run(&mut s, "paint.editGradient", with(ink_to_paper, json!({"method": "perceptual"}))); + let (pdf, _) = pdf_of(&s); + assert!(!pdf.contains("/Subtype/Image") && !pdf.contains("/DeviceN") && pdf.contains("/Separation/Ink/DeviceCMYK"), "Perceptual"); + // With process yellow, the linked white stop adds no ink: Yellow and Ink only. + let yellow = json!({"c": 0, "m": 0, "y": 0.6, "k": 0}); + let three = + json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 0.5, "swatch": "Paper"}, {"offset": 1, "color": yellow}], "method": "classic"}); + run(&mut s, "paint.editGradient", three); + let (pdf, _) = pdf_of(&s); + assert!(pdf.contains("/DeviceN[/Yellow/Ink]/DeviceCMYK") && pdf.contains("/C0[0 1]/C1[0 0]"), "Yellow and Ink"); + // A white spot ink is an ink, not paper: a DeviceN shading of both spot inks. + run(&mut s, "swatch.new", json!({"name": "Opaque", "color": "#ffffff", "spot": true})); + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "Opaque"}]})); + let (pdf, _) = pdf_of(&s); + assert!(pdf.contains("/DeviceN[/Ink/Opaque]/DeviceCMYK"), "a white spot ink keeps its plate"); +} + #[test] fn spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { let (mut s, _) = setup(); diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 665efe272d..b68066ef6b 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -69,13 +69,12 @@ impl Exporter<'_> { /// gets [`Self::device_n_stops`]. `None` for gradients without a spot ink. fn spot_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option> { let ink = g.stops.iter().find_map(|s| s.swatch.as_deref().filter(|n| self.doc.swatch(n).is_some_and(|w| w.spot)))?; - let paper = |c: &Color| c.to_rgba8(1.0)[..3] == [255; 3]; let tints: Option> = g .stops .iter() .map(|s| match s.swatch.as_deref() { Some(n) if n == ink => Some(s.tint), - None if paper(&s.color) => Some(0.0), + _ if self.paper_stop(s) => Some(0.0), _ => None, }) .collect(); @@ -106,7 +105,6 @@ impl Exporter<'_> { /// the gradient is then written in the colors of its stops. fn device_n_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option> { use krilla::color::device_n::{Color as DnColor, Colorant, DeviceNSpace, Process}; - let paper = |c: &Color| c.to_rgba8(1.0)[..3] == [255; 3]; let doc = self.doc; fn spot_of<'s>(doc: &vectorcraft_doc::Document, s: &'s vectorcraft_color::GradientStop) -> Option<&'s str> { s.swatch.as_deref().filter(|n| doc.swatch(n).is_some_and(|w| w.spot)) @@ -128,7 +126,7 @@ impl Exporter<'_> { let i = spots.iter().position(|(m, _)| m == n)?; v[4 + i] = s.tint; } - None if s.swatch.is_none() && paper(&s.color) => {} + None if self.paper_stop(s) => {} None => match self.page_color(&s.color) { Color::Cmyk { c, m, y, k } => v[..4].copy_from_slice(&[c, m, y, k]), Color::Gray { k } => v[3] = k, @@ -348,25 +346,30 @@ impl Exporter<'_> { Some(krilla::paint::Pattern { stream: sb.finish(), transform: xf(at), width: pw as f32, height: ph as f32 }.into()) } - /// The spot swatch whose tints are every stop of `g` that isn't paper white, unlinked; `None` - /// when no stop is linked to a spot swatch or a stop has another color. + /// Is stop `s` paper white: white, unlinked or linked to a swatch that isn't a spot color (a + /// white spot color is an ink of its own)? It adds no ink to a Separation or DeviceN shading. + fn paper_stop(&self, s: &vectorcraft_color::GradientStop) -> bool { + !s.swatch.as_deref().is_some_and(|n| self.doc.swatch(n).is_some_and(|w| w.spot)) && s.color.to_rgba8(1.0)[..3] == [255; 3] + } + + /// The spot swatch whose tints are every stop of `g` that isn't paper white + /// ([`Self::paper_stop`]); `None` when no stop is linked to a spot swatch or a stop has + /// another color. fn one_spot_ink<'g>(&self, g: &'g vectorcraft_color::Gradient) -> Option<&'g str> { let spot = |s: &'g vectorcraft_color::GradientStop| s.swatch.as_deref().filter(|n| self.doc.swatch(n).is_some_and(|w| w.spot)); let ink = g.stops.iter().find_map(spot)?; - let paper = |s: &vectorcraft_color::GradientStop| s.swatch.is_none() && s.color.to_rgba8(1.0)[..3] == [255; 3]; - g.stops.iter().all(|s| spot(s) == Some(ink) || paper(s)).then_some(ink) + g.stops.iter().all(|s| spot(s) == Some(ink) || self.paper_stop(s)).then_some(ink) } /// Can every stop of `g` be inks of a DeviceN space ([`Self::device_n_stops`]): is a stop - /// linked to a spot swatch, and is every other stop paper white, unlinked, or written in CMYK - /// or gray? + /// linked to a spot swatch, and is every other stop paper white ([`Self::paper_stop`]) or + /// written in CMYK or gray? fn device_n_inks_only(&self, g: &vectorcraft_color::Gradient) -> bool { let doc = self.doc; let cmyk_doc = doc.color_mode == vectorcraft_doc::ColorMode::Cmyk; let spot = |s: &vectorcraft_color::GradientStop| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot)); let inks = |s: &vectorcraft_color::GradientStop| { - (s.swatch.is_none() && s.color.to_rgba8(1.0)[..3] == [255; 3]) - || matches!(self.out.color(&s.color, self.intent, cmyk_doc, self.convert), Color::Cmyk { .. } | Color::Gray { .. }) + self.paper_stop(s) || matches!(self.out.color(&s.color, self.intent, cmyk_doc, self.convert), Color::Cmyk { .. } | Color::Gray { .. }) }; g.stops.iter().any(spot) && g.stops.iter().all(|s| spot(s) || inks(s)) } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..3fc42861d4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1280,6 +1280,8 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html): "Gradient colors can be assigned as CMYK process colors, RGB colors, or a Spot color."; [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html): "a separate plate is created for each spot color"). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there (VectorCraft's own rule). Dithered fills, freeform gradients and Perceptual gradients that mix a spot color with RGB or Lab stops are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve` and `ink_mixes_follow_the_perceptual_curve`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. +In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`. + ## Artwork Cleanup add-on (2026-10-30) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Artwork Cleanup and its From 79846064718ee0bac6e9581010c6ce45e1bc5d46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:26:47 -0800 Subject: [PATCH 051/674] EPS: spot inks named All or None print as spot inks A Separation space whose colorant is named All paints every plate, and one named None paints nothing (ISO 32000-1:2008, 8.6.6.4). EPS export wrote a spot swatch's name as its colorant, so a spot color named All printed on every plate and one named None did not print. Such an ink is now written as All Spot or None Spot, numbered All Spot 2 and on when a spot swatch already has that name, in its Separation space, DeviceN spaces and the %%DocumentCustomColors and %%CMYKCustomColor comments. At PostScript Level 3, a gradient that mixes one of these inks with another spot ink or with process or gray stops is now a DeviceN shading instead of process colors. Registration still writes All. --- crates/eps/src/scene.rs | 62 ++++++++++++++++++++++++++++----------- crates/eps/src/tests.rs | 46 +++++++++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 3 files changed, 90 insertions(+), 20 deletions(-) diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index b5437b6700..e07e318b10 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -142,8 +142,9 @@ pub(crate) struct Scene<'a> { cms: Arc, body: String, setup: String, - /// Spot colour spaces defined in the setup (`VCsp`): swatch name and CMYK equivalent. - spots: Vec<(String, [f32; 4])>, + /// Spot colour spaces defined in the setup (`VCsp`): swatch name, colorant name + /// ([`Scene::colorant_name`]) and CMYK equivalent. + spots: Vec<(String, String, [f32; 4])>, /// DeviceN color spaces defined in the setup (`VCdn`), as their definitions. device_n: Vec, warnings: Vec, @@ -191,7 +192,12 @@ impl<'a> Scene<'a> { } fn page(self) -> Page { - let custom = self.spots.iter().filter(|(n, _)| n != vectorcraft_color::swatch::REGISTRATION).cloned().collect(); + let custom = self + .spots + .iter() + .filter(|(n, ..)| n != vectorcraft_color::swatch::REGISTRATION) + .map(|(_, colorant, cmyk)| (colorant.clone(), *cmyk)) + .collect(); Page { setup: self.setup, body: self.body, custom, warnings: self.warnings } } @@ -235,7 +241,7 @@ impl<'a> Scene<'a> { /// The index of the Separation colour space of spot swatch (or Registration) `name`, defined /// in the setup the first time; `None` when `name` is neither. fn spot_space(&mut self, name: &str) -> Option { - if let Some(i) = self.spots.iter().position(|(n, _)| n == name) { + if let Some(i) = self.spots.iter().position(|(n, ..)| n == name) { return Some(i); } let registration = name == vectorcraft_color::swatch::REGISTRATION; @@ -249,17 +255,37 @@ impl<'a> Scene<'a> { }; let i = self.spots.len(); let _ = write!(self.setup, "/VCsp{i} [/Separation "); - if registration { + let colorant = if registration { self.setup.push_str("/All /DeviceCMYK {dup dup dup}"); + "All".to_string() } else { + let colorant = self.colorant_name(name); let [c, m, y, k] = cmyk.map(|v| ps::num(f64::from(v))); - let _ = write!(self.setup, "{} cvn /DeviceCMYK {{dup {c} mul exch dup {m} mul exch dup {y} mul exch {k} mul}}", ps::string(name)); - } + let _ = write!(self.setup, "{} cvn /DeviceCMYK {{dup {c} mul exch dup {m} mul exch dup {y} mul exch {k} mul}}", ps::string(&colorant)); + colorant + }; self.setup.push_str("] def\n"); - self.spots.push((name.to_string(), cmyk)); + self.spots.push((name.to_string(), colorant, cmyk)); Some(i) } + /// The colorant name spot swatch `name` is written under: its own name, except that `All` + /// (every plate in PostScript) and `None` (no plate) become `All Spot` and `None Spot`, + /// numbered `All Spot 2`, `All Spot 3`, … past the names of the document's spot swatches. + fn colorant_name(&self, name: &str) -> String { + if name != "All" && name != "None" { + return name.to_string(); + } + let taken = |c: &str| self.doc.swatches_iter().any(|s| s.spot && s.name == c); + let mut colorant = format!("{name} Spot"); + let mut n = 2; + while taken(&colorant) { + colorant = format!("{name} Spot {n}"); + n += 1; + } + colorant + } + fn set_ink(&mut self, ink: Ink) { match ink { Ink::Process(space, v) => { @@ -819,26 +845,28 @@ impl<'a> Scene<'a> { } /// A DeviceN color space of process inks `process` (indices into CMYK) and spot inks `names`, - /// defined in the setup the first time, each spot ink with the CMYK equivalent its Separation - /// space has. `None` when a spot ink has no Separation space, two colorants share a name, a - /// spot ink has the name of a process ink, `All` or `None`, or there are more than - /// [`MAX_DEVICE_N`] colorants. + /// defined in the setup the first time, each spot ink under the colorant name and with the + /// CMYK equivalent its Separation space has. `None` when a spot ink has no Separation space, + /// two colorants share a name, a spot ink's colorant has the name of a process ink, `All` or + /// `None`, or there are more than [`MAX_DEVICE_N`] colorants. fn device_n_space(&mut self, process: &[usize], names: &[String]) -> Option { const PROCESS: [&str; 4] = ["Cyan", "Magenta", "Yellow", "Black"]; if process.len() + names.len() > MAX_DEVICE_N { return None; } - let mut colorants: Vec<&str> = process.iter().map(|&i| PROCESS[i]).collect(); + let mut colorants: Vec = process.iter().map(|&i| PROCESS[i].to_string()).collect(); let mut weights: Vec<[f32; 4]> = process.iter().map(|&i| [0, 1, 2, 3].map(|j| if i == j { 1.0 } else { 0.0 })).collect(); - for (i, name) in names.iter().enumerate() { - if PROCESS.contains(&name.as_str()) || name == "All" || name == "None" || names[..i].contains(name) { + let spots: Vec = names.iter().map(|n| self.colorant_name(n)).collect(); + for (i, name) in spots.iter().enumerate() { + if PROCESS.contains(&name.as_str()) || name == "All" || name == "None" || spots[..i].contains(name) { return None; } } for name in names { - colorants.push(name); let i = self.spot_space(name)?; - weights.push(self.spots.get(i)?.1); + let (_, colorant, cmyk) = self.spots.get(i)?; + colorants.push(colorant.clone()); + weights.push(*cmyk); } let mut def = String::from("[/DeviceN ["); for (i, c) in colorants.iter().enumerate() { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 5b89922d58..2067a7d9c2 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -381,8 +381,50 @@ fn a_gradient_mixing_a_spot_ink_with_rgb_is_written_without_the_ink() { } #[test] -fn spot_inks_named_like_process_inks_all_or_none_are_not_device_n_colorants() { - for name in ["Cyan", "Black", "All", "None"] { +fn spot_inks_named_all_or_none_are_written_under_names_of_their_own() { + let rect = |d: &mut Document, fill: &str, stroke: &str| { + let solid = |name: &str| Paint::Solid { color: GOLD, swatch: Some(name.into()), tint: 1.0 }; + path(d, shapes::rectangle(Rect::new(50.0, 60.0, 150.0, 100.0)), solid(fill), solid(stroke), 2.0) + }; + for (name, colorant) in [("All", "All Spot"), ("None", "None Spot")] { + // A fill of the spot ink and a Registration stroke. + let mut d = doc_with(|_| vec![]); + d.swatches.push(Swatch { name: name.into(), paint: Paint::solid(GOLD), global: true, spot: true }); + let n = rect(&mut d, name, vectorcraft_color::swatch::REGISTRATION); + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let ps = text(&export(&d, &opts(&d), None, None).unwrap()); + assert_eq!(dsc(&ps, "DocumentCustomColors"), Some(format!("({colorant})")), "{ps}"); + assert_eq!(dsc(&ps, "CMYKCustomColor"), Some(format!("0 0.2 0.8 0.1 ({colorant})")), "{ps}"); + assert!(ps.contains(&format!("[/Separation ({colorant}) cvn /DeviceCMYK {{dup 0 mul")), "{name}: {ps}"); + assert!(ps.contains("[/Separation /All /DeviceCMYK {dup dup dup}]"), "Registration prints on every plate: {ps}"); + assert!(!ps.contains(&format!("({name}) cvn")), "{name}: {ps}"); + checked_page(&ps); + + // In a gradient with another spot ink, the DeviceN space has the same colorant. + let mut d = spot_gradient_doc(vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), spot_stop(1.0, name, LEAF, 1.0)]); + d.swatches.push(Swatch { name: name.into(), paint: Paint::solid(LEAF), global: true, spot: true }); + let out = export(&d, &opts(&d), None, None).unwrap(); + let ps = text(&out); + assert!(ps.contains(&format!("/VCdn0 [/DeviceN [(Gold Ink) cvn ({colorant}) cvn ] /DeviceCMYK")), "{name}: {ps}"); + assert!(ps.contains(&format!("%%DocumentCustomColors: (Gold Ink)\n%%+ ({colorant})\n")), "{name}: {ps}"); + assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + } + + // A spot swatch already named All Spot keeps its name, and All is numbered past it. + let mut d = doc_with(|_| vec![]); + for name in ["All", "All Spot"] { + d.swatches.push(Swatch { name: name.into(), paint: Paint::solid(GOLD), global: true, spot: true }); + } + let n = rect(&mut d, "All", "All Spot"); + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let ps = text(&export(&d, &opts(&d), None, None).unwrap()); + assert!(ps.contains("[/Separation (All Spot 2) cvn ") && ps.contains("[/Separation (All Spot) cvn "), "{ps}"); + assert!(ps.contains("%%DocumentCustomColors: (All Spot 2)\n%%+ (All Spot)\n"), "{ps}"); +} + +#[test] +fn spot_inks_named_like_process_inks_are_not_device_n_colorants() { + for name in ["Cyan", "Black"] { // Gold Ink to the spot ink, with no process ink in the stops. let mut d = spot_gradient_doc(vec![spot_stop(0.0, "Gold Ink", GOLD, 1.0), spot_stop(1.0, name, LEAF, 1.0)]); d.swatches.retain(|s| s.name != name); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..63a9afd175 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,7 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). `document.pdfInfo` reads an EPS, a `.ps` file or a `.ai` in PostScript form as one page the size of its bounding box (a US Letter page without one), and its `thumbnail: 1` is a PNG of what that page prints (`crates/engine/src/cmd/fileio/tests_pdfimport.rs`). - EPS export with Use Artboards writes a central EPS file of the whole document, bounded by its visible art, beside the file of each artboard when it writes two or more artboards; a document with no visible art gets only the artboard files (`crates/engine/src/cmd/fileio/tests_eps.rs`). - EPS export writes a linear or radial gradient of tints of one spot color (and paper white) in that ink's Separation space, at Level 2 and 3, and at Level 3 one that mixes a spot color with process or gray colors, or two spot colors, in a DeviceN space of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. At Level 2, such a mix is written in process colors with a warning. In an RGB export, a gradient that mixes a spot color with RGB or Lab colors is written without the spot ink, with a warning; a CMYK export converts those stops to CMYK first, and the gradient follows the rules above. A Perceptual gradient of spot colors, and a mix whose DeviceN space would need more than 32 inks or a spot color named Cyan, Magenta, Yellow, Black, All or None, are also written in process colors with a warning (`crates/eps/src/tests.rs`). + EPS export writes a linear or radial gradient of tints of one spot color (and paper white) in that ink's Separation space, at Level 2 and 3, and at Level 3 one that mixes a spot color with process or gray colors, or two spot colors, in a DeviceN space of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. At Level 2, such a mix is written in process colors with a warning. In an RGB export, a gradient that mixes a spot color with RGB or Lab colors is written without the spot ink, with a warning; a CMYK export converts those stops to CMYK first, and the gradient follows the rules above. A Perceptual gradient of spot colors, and a mix whose DeviceN space would need more than 32 inks or a spot color named Cyan, Magenta, Yellow or Black, are also written in process colors with a warning (`crates/eps/src/tests.rs`). A spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4), is written as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients and DSC comments; Registration still prints on every plate (`tests::spot_inks_named_all_or_none_are_written_under_names_of_their_own`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. The last valid `resc` or `resd` resolution value wins on each axis; an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`). From 880a07805365add3b91d36db532b19f7127bcef3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:27:59 -0800 Subject: [PATCH 052/674] Legacy .ai: type with rotated characters is written as outlines that keep the rotation A version 7 text object has no arbitrary-angle character rotation: its character attributes include baseline shift (Ts), scaling (Tz) and tracking (Tt), Tv only turns Roman characters 90 degrees in vertical text, and the positioning operators such as Tm are ignored on reading. Type with Character Rotation was written as editable text with the rotation left out, so rotated characters opened upright. Such type is now written as its glyphs' outlines, the way type 8-bit text can't hold already is, with the warning "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text". The outlines keep each character's rotation, baseline shift and scale. Type without rotated characters, and type turned a whole number of times, is still written as text. Docs: docs/file-format-parity.md, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/legacy_ai.rs | 2 +- crates/engine/src/cmd/fileio/native.rs | 2 +- crates/eps/src/legacy_ai.rs | 10 ++-- crates/eps/src/legacy_ai/encoding.rs | 20 +++++-- crates/eps/src/legacy_ai/tests.rs | 66 +++++++++++++++++++++++ crates/eps/src/legacy_ai/writer.rs | 17 ++++-- docs/file-format-parity.md | 4 +- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 9 files changed, 111 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 7cbbda2fed..1d9d23590f 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -28,7 +28,7 @@ //! layer's hidden objects go to a hidden layer of their own just above it, with `omit` they are //! left out, with `visible` they show where they are. Type is written as text the format's reader //! lays out again, in the fonts it names; `outlineText` writes its outlines instead (as type that -//! 8-bit text can't hold always is). +//! 8-bit text can't hold and type with rotated characters always are). use std::sync::Arc; diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index d7dbbe5a69..948556c7a6 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -121,7 +121,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "outlineText", ty: "boolean", default: "false", - description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is always outlines", + description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) and type with rotated characters are always outlines", }, ]; diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index fc7d6e9d9c..2e8f5e03ee 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -50,7 +50,8 @@ //! their own above their layer, are left out or show, as [`HiddenObjects`] says (in a hidden //! layer they stay where they are). Type that 8-bit text can't hold (characters outside //! Windows-1252, vertical type, ruby, inline graphics, gradient or pattern fills) is written as its -//! outlines, and all type with [`LegacyAiOptions::outline_text`]. Layer, spot color and gradient +//! outlines, and so is type with rotated characters (a text object has no character rotation), and +//! all type with [`LegacyAiOptions::outline_text`]. Layer, spot color and gradient //! names and the title are written in Windows-1252 too, and a character outside it is written as //! `?`. Two spot colors or two gradients whose names become the same that way are numbered (`? 2`). //! @@ -76,9 +77,9 @@ mod encoding; mod prolog; mod writer; -#[cfg(test)] -use encoding::writable; use encoding::{gradient_def, latin_string}; +#[cfg(test)] +use encoding::{rotated, writable}; pub(crate) use prolog::PROCSET; use prolog::{PROLOG, PS_HEADER, fonts}; use writer::Writer; @@ -94,7 +95,8 @@ const HEX_LINE: usize = 60; pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)"; pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines"; -pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, small caps, superscript and subscript, character rotation, OpenType features, Variable Font settings, area type options, type on a path effects, space after paragraphs, tabs, bulleted and numbered lists) are left out"; +pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)"; +pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, small caps, superscript and subscript, OpenType features, Variable Font settings, area type options, type on a path effects, space after paragraphs, tabs, bulleted and numbered lists) are left out"; pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)"; pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)"; pub const HIDDEN_SHOWN: &str = "hidden objects are written visible (legacy .ai files can hide only layers)"; diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index afa6a9b353..b8055c32f9 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -80,10 +80,25 @@ pub(super) fn latin_string(name: &str) -> String { ps::bytes(&bytes) } -/// Can type `t` be written as text: horizontal, without ruby (which a text object can't hold), its +/// Can type `t` be written as text: 8-bit text can hold it ([`holds_as_text`]) and no character +/// is rotated ([`rotated`])? +pub(super) fn writable(t: &TextObject) -> bool { + holds_as_text(t) && !rotated(t) +} + +/// Has type `t` visible characters with Character Rotation? A legacy `.ai` text object's character +/// attributes have none that turns a character (§15), so such type is written as its outlines. +pub(super) fn rotated(t: &TextObject) -> bool { + t.runs.iter().any(|r| { + let turn = r.style.rotation; + turn.is_finite() && turn.rem_euclid(360.0) != 0.0 && r.text.chars().any(|c| !c.is_whitespace()) + }) +} + +/// Can 8-bit text hold type `t`: horizontal, without ruby (which a text object can't hold), its /// runs plain characters (no inline graphics) that 8-bit text can hold, filled and stroked with /// colours? -pub(super) fn writable(t: &TextObject) -> bool { +pub(super) fn holds_as_text(t: &TextObject) -> bool { let solid = |p: &Paint| matches!(p, Paint::Solid { .. } | Paint::None); !t.vertical && t.ruby.is_empty() @@ -103,7 +118,6 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool { || s.strikethrough || s.small_caps.is_some() || s.position != CharPosition::Normal - || s.rotation != 0.0 || !s.features.is_empty() || !s.font_axes.is_empty() }; diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 1c750d983c..2af528a98d 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1150,6 +1150,72 @@ fn type_8_bit_text_cant_hold_and_type_asked_for_as_outlines_are_outlines() { assert!(!out.warnings.iter().any(|w| w == TYPE), "{:?}", out.warnings); } +/// A legacy `.ai` text object has no character rotation: point type and area type with a rotated +/// character between ordinary ones (turned either way, shifted off the baseline and scaled) are +/// written as their outlines, with the warning, and read back as paths where the laid-out glyphs +/// are, the rotated character turned. A full turn writes text. +#[test] +fn type_with_rotated_characters_is_outlines_that_keep_the_rotation() { + use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; + let typed = |turn: f64, area: bool| { + let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "HE", style(30.0, red())); + let turned = CharStyle { rotation: turn, baseline_shift: 4.0, h_scale: 120.0, v_scale: 80.0, ..style(30.0, red()) }; + t.runs.push(TextRun::new("L", turned)); + t.runs.push(TextRun::new("TH", style(30.0, red()))); + if area { + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)) }; + t.xf = Affine::translate((20.0, 40.0)); + } + t + }; + // Each run's laid-out glyphs' box, in the document. + let boxes = |t: &TextObject| -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + (0..t.runs.len()) + .map(|i| { + let mut bp = kurbo::BezPath::new(); + for g in lay.glyphs.iter().filter(|g| g.run == i) { + bp.extend(g.outline.iter()); + } + bp.apply_affine(t.xf); + bp.bounding_box() + }) + .collect() + }; + let near = |a: kurbo::Rect, b: kurbo::Rect| (a.x0 - b.x0).abs().max((a.y0 - b.y0).abs()).max((a.x1 - b.x1).abs()).max((a.y1 - b.y1).abs()); + for (turn, area) in [(30.0, false), (-45.0, true)] { + let t = typed(turn, area); + assert!(rotated(&t)); + let want = boxes(&t); + let unturned = boxes(&typed(0.0, area)); + assert!(near(want[1], unturned[1]) > 1.0, "the turn moves the glyph: {:?} {:?}", want[1], unturned[1]); + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == ROTATED_TYPE), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings); + assert!(!String::from_utf8_lossy(&out.bytes).contains(" To\n"), "not a text object"); + let back = crate::import(&out.bytes).unwrap().document; + assert!(texts(&back).is_empty(), "no type reads back"); + let parts = children(&children(&back.layers[0])[0]); + assert_eq!(parts.len(), 3, "one compound path for each run"); + for (i, part) in parts.iter().enumerate() { + let b = part.visual_bounds().unwrap(); + assert!(near(b, want[i]) < 0.05, "run {i} at {turn}°: {b:?}, laid out at {:?}", want[i]); + } + } + // A full turn draws the character upright: text. + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(typed(360.0, false)))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = write(&doc); + assert!(String::from_utf8_lossy(&out.bytes).contains(" To\n"), "a text object"); + assert!(!out.warnings.iter().any(|w| w == ROTATED_TYPE), "{:?}", out.warnings); +} + /// Ruby (furigana), which a text object can't hold, makes type 8-bit text could hold outlines, /// with the reading's glyphs among them, where the canvas draws them (the file prints as the /// document draws). diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 9879a51abb..981ab610af 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -1,12 +1,13 @@ use super::encoding::{ - Ink, average, direct_fill, direct_stroke, finite, font_of, invertible, latin_string, lost_attributes, segment_point, unit, writable, + Ink, average, direct_fill, direct_stroke, finite, font_of, holds_as_text, invertible, latin_string, lost_attributes, rotated, segment_point, + unit, writable, }; use super::{ Affine, AnchorKind, AppearanceItem, Arc, BezPath, BlendMode, CharStyle, Cms, Color, Document, ELLIPTICAL, FREEFORM, FillLayer, FillRule, Gradient, GradientKind, GradientPaint, HEX_LINE, HIDDEN, HIDDEN_LAYER, HIDDEN_SHOWN, HiddenObjects, IMAGE_ALPHA, ImageBlob, Justify, LARGE_IMAGE, LAYER_COLORS, LAYER_NAME, LIVE, LayerColor, LegacyAiOptions, LineCap, LineJoin, MAX_IMAGE_PIXELS, MAX_NEST, NAMES, Node, NodeKind, PATTERNS, - Paint, ParaDirection, ParaStyle, PathData, Point, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, - TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, latin, ps, stroke, + Paint, ParaDirection, ParaStyle, PathData, Point, ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, + TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, latin, ps, stroke, }; pub(super) struct Writer<'a> { @@ -719,7 +720,8 @@ impl<'a> Writer<'a> { // ---------- type ---------- - /// Type: a text object when the format can hold it as text, else its outlines. A run whose + /// Type: a text object when the format can hold it as text, else its outlines (type with + /// rotated characters among them, which keeps their rotation). A run whose /// font size measures a height other than the em box is written at the em size it is drawn /// at ([`vectorcraft_text::FontDb::font_heights_resolved`]). fn text(&mut self, t: &TextObject) { @@ -732,7 +734,12 @@ impl<'a> Writer<'a> { if writable(t) { return self.text_object(t); } - self.warn(TYPE); + if !holds_as_text(t) { + self.warn(TYPE); + } + if rotated(t) { + self.warn(ROTATED_TYPE); + } } self.outlines(t); } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c868252dd1..11440516d7 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -65,7 +65,9 @@ private editing data. VectorCraft: `transparentImages: "flatten"|"omit"`). Type is written as editable text objects (point type, area type and type on a path, with their fonts' PostScript names, sizes, colours, alignment, indents, leading, tracking and scaling), which the reading app sets in those fonts; characters outside Windows-1252, vertical type, ruby, inline - graphics and gradient or pattern fills make that type outlines, and Text: Outlines (`outlineText: true`) writes + graphics and gradient or pattern fills make that type outlines, and so do rotated characters (Character Rotation, + which a version 7 text object can't hold: the outlines keep the rotation, and the type is no longer editable text + in the file), and Text: Outlines (`outlineText: true`) writes all type as outlines. The format can hide only layers: hidden objects go to a hidden layer of their own above their layer, are omitted, or are made visible (Hidden Objects, `hiddenObjects: "layer"|"omit"|"visible"`). Sublayers become groups; appearances, effects and brushes are expanded; object names are left out; layer diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..57f990dfe8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -843,7 +843,10 @@ PostScript form, which keeps layers, groups, compound paths and clipping groups of `range` (default all; `{name}-{artboard}.ai` when several, listed in the result's `files`), with `transparentImages: "flatten"` (default) or `"omit"` for images with see-through pixels, opacity or a blending mode, `hiddenObjects: "layer"` (default: a hidden layer of each layer's hidden objects), `"omit"` or `"visible"`, and -`outlineText: true` to write type as outlines instead of text objects. An image that can't be decoded is left out of +`outlineText: true` to write type as outlines instead of text objects. Type with rotated characters (Character +Rotation) is always written as outlines, which keep the rotation, with the warning "type with rotated characters is +written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate +characters)". An image that can't be decoded is left out of the file and does not show in art that is flattened or whose raster effects are expanded; `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such images. From the CLI: `vectorcraft-cli convert in.svg out.ai --ai-version 7 [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] [--outline-text] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..44d7b56c0c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1064,6 +1064,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` or EPS opened from its editing data whose text document makes the type of every text object that shows takes all its type from the text document: each text object stays in its own group, frame and layer, the page's type isn't matched with them, a file of more than 5,000 text objects still opens with its layers, and type the page draws differently (in another font) keeps the layers, with a warning. A line break inside a paragraph stays a line break in it (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ate.rs`). In SVG export without Fewer `` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned ``, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. + Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text: a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304). In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). From d5849d6553e7dc801ac84dcf6cecf9b79102a528 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:41:20 -0800 Subject: [PATCH 053/674] Fix #2181: PDF layer forms get real boxes and lose their off-page marks With Create PDF layers on, every layer's form XObject had /BBox [-32767 -32767 32767 32767] and started with an empty clip at x = -32000 that only marked the form while the file was written. Other apps read that as art about 23 m across, and the reporters could not move or place the imported layers. - The marks of layer, overprint and invisible-text forms are removed when the file is finished. - A layer's form gets a box round its art and the page's paper, in whole units. Since the box still covers the page, PDF import skips it as a clip, so sublayers still import as sublayers. --- crates/pdf/src/export.rs | 3 + crates/pdf/src/export/exporter.rs | 1 + crates/pdf/src/export/nodes.rs | 3 +- crates/pdf/src/export/writer.rs | 2 + crates/pdf/src/forms.rs | 121 +++++++++++++++++++++++------- crates/pdf/src/tests/layers.rs | 39 ++++++++++ 6 files changed, 142 insertions(+), 27 deletions(-) diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 529396fce6..71c9ab25de 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -94,6 +94,9 @@ pub(crate) struct Exporter<'a> { layer_index: HashMap, /// The address of the layer whose form is being drawn. in_layer: usize, + /// The paper of the page being drawn, in its drawing space: the box of each layer's form + /// covers it ([`crate::forms::layer_form`]). + paper: Rect, /// Overprinting fills and strokes are drawn as forms marked to overprint. pub overprint: bool, /// An overprinting fill or stroke was drawn so. diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index ac53090f56..a40e272b01 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -45,6 +45,7 @@ impl<'a> Exporter<'a> { layers: false, layer_index: crate::forms::pdf_layers(doc).iter().enumerate().map(|(i, l)| (address(l.node), i)).collect(), in_layer: 0, + paper: Rect::ZERO, symbol_nodes: 0, overprint: false, overprinted: false, diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 8367bef11d..7d063046cb 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -102,7 +102,8 @@ impl Exporter<'_> { { // A PDF layer: hidden layers and sublayers are written too (their group is off). let enclosing = std::mem::replace(&mut self.in_layer, address(n)); - crate::forms::form(s, Mark::Layer(i), |s| self.node(s, n, page, true)); + let paper = self.paper; + crate::forms::layer_form(s, i, paper, |s| self.node(s, n, page, true)); self.in_layer = enclosing; return; } diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index b2ca788eb1..5e7c7e77ab 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -156,6 +156,8 @@ impl Writer { s.push_mask(all); } if fits { + let shown = (sheet.view * sheet.place).inverse().transform_rect_bbox(paper); + ex.paper = if [shown.x0, shown.y0, shown.x1, shown.y1].iter().all(|v| v.is_finite()) { shown.union(r) } else { r }; ex.children(&mut s, &doc.layers, r); } if page_group || cmyk_page_group { diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index e382ccb0fe..4a1d061473 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -4,9 +4,10 @@ //! form is. Marked forms also stay apart (the writer shares identical forms). [`finish`] completes //! them in the written file: a layer's form is drawn as the layer's optional content (`/OC … //! BDC`), an overprinting form sets a graphics state that overprints first, and the text of an -//! invisible form is drawn in rendering mode 3 (neither filled nor stroked). +//! invisible form is drawn in rendering mode 3 (neither filled nor stroked). It also removes the +//! marks, so no form keeps an empty clip far off the page (#2181). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::io::Read; use craft_pdf::write::backend as krilla; @@ -77,13 +78,30 @@ impl Mark { /// Draw `draw` as a form of its own, marked `mark`. pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface)) { + let (x, y) = mark.at(); + marked(s, mark, [(x + 1.0, y), (x + 1.0, y + 1.0)], draw); +} + +/// Draw `draw` (the art of layer `i` of [`pdf_layers`]) as a form of its own, marked as the +/// layer's. The mark's other two points are the corners of `paper` (the page's paper in the +/// form's drawing space), rounded outwards to whole units: [`finish`] gives the form a box that +/// covers the paper and the art. +pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rect, draw: impl FnOnce(&mut Surface)) { + let corner = |x: f64, y: f64| (x as f32, y as f32); + marked(s, Mark::Layer(i), [corner(paper.x0.floor(), paper.y0.floor()), corner(paper.x1.ceil(), paper.y1.ceil())], draw); +} + +/// Draw `draw` as a form of its own, marked `mark`: an empty clip from the mark's first point +/// through `rest`. +fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(&mut Surface)) { let mut sb = s.stream_builder(); let mut fs = sb.surface(); let (x, y) = mark.at(); let mut pb = PathBuilder::new(); pb.move_to(x, y); - pb.line_to(x + 1.0, y); - pb.line_to(x + 1.0, y + 1.0); + for (x, y) in rest { + pb.line_to(x, y); + } pb.close(); // A form's drawing space is its own: the mark's points are written as they are. if let Some(p) = pb.finish() { @@ -102,8 +120,9 @@ pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface)) const OVERPRINT_GS: &str = "VCop"; /// The prefix of the resource names of the layers' optional content groups (then the index). const LAYER_OC: &str = "VCoc"; -/// The most bytes of a form's content read to find its mark. -const HEAD: u64 = 64; +/// The most bytes of a form's content read to find its mark (a layer's mark holds four more +/// numbers of up to 11 characters each). +const HEAD: u64 = 128; fn bad(why: &str) -> PdfError { PdfError::Write(format!("can't write PDF layers, overprint or invisible text: {why}")) @@ -159,6 +178,31 @@ impl Object<'_> { _ => None, } } + + /// The paper a layer's form's mark gives ([`layer_form`]): its left, top, right and bottom. + fn paper(&self, pdf: &[u8]) -> Option<[i64; 4]> { + let head = self.data(pdf, HEAD)?; + let mut lx = Lexer::at(&head, 0); + let mut word = || match lx.next() { + Some((Tok::Word(w), ..)) => Some(w), + _ => None, + }; + let words = [(); 10].map(|_| word()); + let [Some(b"q"), _, _, Some(b"m"), x0, y0, Some(b"l"), x1, y1, Some(b"l")] = words else { return None }; + Some([x0.and_then(int)?, y0.and_then(int)?, x1.and_then(int)?, y1.and_then(int)?]) + } +} + +/// `content` (a marked form's) without its mark: what follows the mark's `Q`. +fn unmarked(content: &[u8]) -> Option<&[u8]> { + let mut lx = Lexer::at(content, 0); + while let Some((tok, _, end)) = lx.next() { + if let Tok::Word(b"Q") = tok { + let rest = content.get(end..)?; + return rest.get(rest.iter().take_while(|c| c.is_ascii_whitespace()).count()..); + } + } + None } /// The objects of the written file that have a dictionary, by number. @@ -293,7 +337,7 @@ pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bo return Err(bad("an overprinting form can't be read")); }; let mut new = format!("/{OVERPRINT_GS} gs\n").into_bytes(); - new.extend_from_slice(&content); + new.extend_from_slice(unmarked(&content).ok_or_else(|| bad("an overprinting form can't be read"))?); o.rewrite(&mut patch, &new)?; add_resources(&mut patch, res, "ExtGState", &format!("/{OVERPRINT_GS} {gs} 0 R"))?; } @@ -302,15 +346,19 @@ pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bo for (n, _) in marks.iter().filter(|(_, m)| **m == Mark::Invisible) { let Some(o) = objects.get(n) else { continue }; let content = o.data(&pdf, u64::MAX).ok_or_else(|| bad("an invisible text form can't be read"))?; - o.rewrite(&mut patch, &invisible_text(&content).ok_or_else(|| bad("an invisible text form can't be read"))?)?; + let text = unmarked(&content).and_then(invisible_text).ok_or_else(|| bad("an invisible text form can't be read"))?; + o.rewrite(&mut patch, &text)?; } } if layers { - write_layers(&pdf, &xref, &objects, &marks, &mut patch, doc, set)?; + let rewritten = write_layers(&pdf, &xref, &objects, &marks, &mut patch, doc, set)?; for (n, _) in marks.iter().filter(|(_, m)| matches!(m, Mark::Layer(_))) { - if let Some(o) = objects.get(n) { - unbox(&pdf, o, &mut patch)?; + let Some(o) = objects.get(n) else { continue }; + if !rewritten.contains(n) { + let content = o.data(&pdf, u64::MAX).ok_or_else(|| bad("a layer's form can't be read"))?; + o.rewrite(&mut patch, unmarked(&content).ok_or_else(|| bad("a layer's form can't be read"))?)?; } + rebox(&pdf, o, &mut patch)?; } } let pdf = patch.apply(&pdf, &xref)?; @@ -321,7 +369,7 @@ pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bo /// The optional content groups of `doc`'s layers and sublayers ([`pdf_layers`]), the uses of their /// forms marked as their content, and the catalog's `/OCProperties`, listing sublayers under their -/// layers. +/// layers. Returns the content streams it rewrote (a layer's form among them without its mark). fn write_layers( pdf: &[u8], xref: &Xref, @@ -330,7 +378,7 @@ fn write_layers( patch: &mut Patch, doc: &Document, set: &PdfSettings, -) -> Result<(), PdfError> { +) -> Result, PdfError> { // One group per layer, in paint order (bottom first). let layers = pdf_layers(doc); let mut groups: HashMap = HashMap::new(); @@ -357,13 +405,14 @@ fn write_layers( } } // Every content stream drawing layers' forms: the pages' and the forms'. - for o in objects.values() { + let mut rewritten = HashSet::new(); + for (n, o) in objects { let content = match o.dict.get(b"Contents") { - Some(Obj::Ref(c, _)) if o.dict.name(b"Type") == Some(b"Page") => objects.get(c), - _ if o.dict.name(b"Subtype") == Some(b"Form") => Some(o), + Some(Obj::Ref(c, _)) if o.dict.name(b"Type") == Some(b"Page") => objects.get(c).map(|o| (*c, o)), + _ if o.dict.name(b"Subtype") == Some(b"Form") => Some((*n, o)), _ => None, }; - let (Some(content), Some(res)) = (content, resources(objects, o)) else { continue }; + let (Some((number, content)), Some(res)) = (content, resources(objects, o)) else { continue }; let Some(Obj::Dict { entries, .. }) = res.get(b"XObject") else { continue }; let forms: HashMap<&[u8], usize> = entries .iter() @@ -379,8 +428,11 @@ fn write_layers( continue; } let data = content.data(pdf, u64::MAX).ok_or_else(|| bad("a content stream can't be read"))?; - let Some((new, marked)) = mark_layers(&data, &forms) else { continue }; + // A layer's form drawing its sublayers' forms loses its own mark here too. + let data = if marks.contains_key(&number) { unmarked(&data).ok_or_else(|| bad("a layer's form can't be read"))? } else { &data[..] }; + let Some((new, marked)) = mark_layers(data, &forms) else { continue }; content.rewrite(patch, &new)?; + rewritten.insert(number); let entries: String = marked.iter().filter_map(|i| Some(format!("/{LAYER_OC}{i} {} 0 R", groups.get(i)?))).collect(); add_resources(patch, res, "Properties", &entries)?; } @@ -399,24 +451,41 @@ fn write_layers( let root = xref.trailer_ref(pdf, b"/Root").and_then(|n| objects.get(&n)); let Some(Object { dict: Obj::Dict { start, .. }, .. }) = root else { return Err(bad("the written PDF has no catalog")) }; patch.replace(start + 2, start + 2, format!("/OCProperties<>>>", refs(&all)).into_bytes()); - Ok(()) + Ok(rewritten) } -/// A form's box as large as a page can be: the box of a layer's form is only the bounds of its -/// art, and a reader that makes a clipping group of a form's box (as importers do) would gather a -/// layer's art and its sublayers' in one group, which no layer can hold. A box round the whole -/// page clips nothing. +/// A form's box as large as a page can be, for a layer's form whose mark gives no paper. const UNBOXED: &[u8] = b"[-32767 -32767 32767 32767]"; -/// Give the layer's form `o` the [`UNBOXED`] box. -fn unbox(pdf: &[u8], o: &Object<'_>, patch: &mut Patch) -> Result<(), PdfError> { +/// Give the layer's form `o` a box round its art and the paper its mark gives ([`layer_form`]): +/// the box of a layer's form is only the bounds of its art, and a reader that makes a clipping +/// group of a form's box (as importers do) would gather a layer's art and its sublayers' in one +/// group, which no layer can hold. A box round the whole paper clips nothing, and its bounds stay +/// those of the page and the art (#2181). +fn rebox(pdf: &[u8], o: &Object<'_>, patch: &mut Patch) -> Result<(), PdfError> { let Obj::Dict { start, end, .. } = o.dict else { return Err(bad("a layer's form has no dictionary")) }; let dict = pdf.get(start..end).ok_or_else(|| bad("a layer's form can't be read"))?; // The writer writes the box as an array of numbers. let at = dict.windows(5).position(|w| w == b"/BBox").ok_or_else(|| bad("a layer's form has no box"))? + 5; let open = at + dict.get(at..).and_then(|d| d.iter().position(|&c| c == b'[')).ok_or_else(|| bad("a layer's form box isn't an array"))?; let close = open + dict.get(open..).and_then(|d| d.iter().position(|&c| c == b']')).ok_or_else(|| bad("a layer's form box isn't an array"))? + 1; - patch.replace(start + open, start + close, UNBOXED.to_vec()); + let art: Vec = std::str::from_utf8(dict.get(open + 1..close - 1).unwrap_or_default()) + .unwrap_or_default() + .split_ascii_whitespace() + .filter_map(|v| v.parse().ok()) + .collect(); + let new = match (o.paper(pdf), art.as_slice()) { + (Some([x0, y0, x1, y1]), &[a0, b0, a1, b1]) if [a0, b0, a1, b1].iter().all(|v| v.is_finite()) => { + let (a0, a1, b0, b1) = (a0.min(a1), a0.max(a1), b0.min(b1), b0.max(b1)); + // Whole units, outwards (the art's box is written to a few decimals). + let lo = |v: i64, a: f64| (v as f64).min(a.floor()); + let hi = |v: i64, a: f64| (v as f64).max(a.ceil()); + format!("[{} {} {} {}]", lo(x0, a0), lo(y0, b0), hi(x1, a1), hi(y1, b1)).into_bytes() + } + (Some([x0, y0, x1, y1]), _) => format!("[{x0} {y0} {x1} {y1}]").into_bytes(), + _ => UNBOXED.to_vec(), + }; + patch.replace(start + open, start + close, new); Ok(()) } diff --git a/crates/pdf/src/tests/layers.rs b/crates/pdf/src/tests/layers.rs index 05ad63106b..cb5bf9a12e 100644 --- a/crates/pdf/src/tests/layers.rs +++ b/crates/pdf/src/tests/layers.rs @@ -339,6 +339,45 @@ fn overprinting_art_imports_as_it_was_drawn() { } } +/// The `/BBox` of each form of the uncompressed `bytes`, in the order written. +fn form_boxes(bytes: &[u8]) -> Vec { + let text = String::from_utf8_lossy(bytes); + text.split("/Subtype/Form").skip(1).filter_map(|d| Some(d.split("/BBox[").nth(1)?.split(']').next()?.to_string())).collect() +} + +/// #2181: a layer's form has a box round the paper and its art, not one 23 m across, and no +/// form (a layer's, an overprinting one or invisible text's) keeps the empty clip far off the +/// page that marked it while the file was written. +#[test] +fn layer_forms_have_real_boxes_and_no_marks() { + let mut d = overprinting(RED); + // Invisible text (neither fill nor stroke) and art across the paper's left edge. + let l = d.layers[0].id; + let style = CharStyle { size: 24.0, fill: Paint::None, ..Default::default() }; + let t = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(200.0, 40.0), "Hid", style)))); + let past = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-50.0, 10.0, 5.0, 40.0)), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.insert(Some(l), 0, t).unwrap(); + d.insert(Some(l), 0, past).unwrap(); + let mut sub = Node::layer(d.alloc_id(), "Sub", LayerColor::Preset(1)); + if let NodeKind::Layer { children, .. } = &mut sub.kind { + children.push(rect(&mut d, 250.0, BLUE).into()); + } + d.insert(Some(l), 0, sub).unwrap(); + let r = export(&d, json!({"createLayers": true, "compression": {"compressText": false}})); + let text = String::from_utf8_lossy(&r.bytes); + for mark in ["-32000 ", "-32001 ", "-32002 ", "32767"] { + assert!(!text.contains(mark), "{mark} is in the file: {text}"); + } + assert!(text.contains("3 Tr") && text.contains("/VCop gs"), "invisible text and overprint are still written: {text}"); + // The layer's form reaches the art across the left edge; its sublayer's covers the paper. + let boxes = form_boxes(&r.bytes); + assert!(boxes.contains(&"-50 0 300 100".to_string()) && boxes.contains(&"0 0 300 100".to_string()), "{boxes:?}"); + // It still imports as it was drawn: a layer holding its sublayer, no clipping group. + let mut got = vec![]; + tree(&import(&r.bytes).unwrap().layers, 0, &mut got); + assert!(got.contains(&"1 Sub true".to_string()) && got.contains(&format!("2 {:?}", Some(BLUE))), "{got:?}"); +} + #[test] fn pdf_x1a_keeps_overprint() { let r = export(&overprinting(RED), json!({"standard": "pdfX1a", "compatibility": "1.4", "compression": {"compressText": false}})); From ac298b683b22b87f3b354f5df391ba5a21961add Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 17:00:36 -0800 Subject: [PATCH 054/674] Canvas: a drag ends where its button went up When a frame brought pointer moves after the button-up, the canvas ended the drag at the frame's last pointer position. A Rectangle drag stretched to it, a Pencil stroke ran on to it, and dragged art moved there. The release now uses the position the button went up at; the moves after it are hover. --- crates/ui-egui/src/canvas/input.rs | 16 +++++++- crates/ui-egui/src/canvas/tests.rs | 63 ++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 728a38b090..5b45fbe29d 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -117,11 +117,13 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo } else if let Some(d) = drag { // The pointer gone (a pen lifted with its press), the drag ends where it was last seen. let p = pointer.interact_pos().or_else(|| ui.data(|dd| dd.get_temp(drag_pos_id()))).unwrap_or(rect.center()); - let held = if middle_pan { pointer.button_down(egui::PointerButton::Middle) } else { pointer.primary_down() }; + let button = if middle_pan { egui::PointerButton::Middle } else { egui::PointerButton::Primary }; + let held = pointer.button_down(button); if held { drag_held(app, ui, &f, d, p); } else { - drag_released(app, ui, &f, d, p); + // The drag ends where its button went up: the moves after the release in this frame are hover. + drag_released(app, ui, &f, d, release_pos(ui, button).unwrap_or(p)); } } else if let Some(p) = hover_tool && (pointer.is_moving() || mods_changed || !was_over || tool_switched || (context_changed && app.session.tool_wants_rehover())) @@ -550,6 +552,16 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { } } +/// Where `button` went up in this frame, if it did. +fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option { + ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { pos, button: b, pressed: false, .. } if *b == button => Some(*pos), + _ => None, + }) + }) +} + /// Whether Space moves the Zoom tool's marquee in the drag under way ([`zoom_marquee_start`]). fn zoom_space_free_id() -> egui::Id { egui::Id::unique("canvas-zoom-space-free") diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4b59bdb8f6..c5d5327523 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6321,6 +6321,69 @@ fn a_bezier_drag_preview_follows_the_pointer_back_into_the_window_and_to_the_rel assert!(app.session.active().unwrap().interaction.is_none(), "committed"); } +/// A drag ends where its button went up. Pointer moves that come after the release in the same +/// frame are hover: they do not stretch a Rectangle drag, add to a Pencil stroke or move dragged +/// art. +#[test] +fn a_drag_ends_where_the_button_went_up_in_its_frame() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let last_bounds = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap() + }; + let center = app.canvas_rect.unwrap().center(); + let far = center + vec2(150.0, 100.0); + + app.select_tool("rectangle"); + let a = center - vec2(100.0, 60.0); + let end = a + vec2(80.0, 50.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(a)]); + frame(&mut app, &ctx, vec![button(a, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(40.0, 20.0))]); + frame(&mut app, &ctx, vec![Event::PointerMoved(end), button(end, false), Event::PointerMoved(far)]); + let r = last_bounds(&app); + let want = xf.to_doc(end); + assert!((r.x1 - want.x).abs() < 1e-3 && (r.y1 - want.y).abs() < 1e-3, "the rectangle ends at the release: {r:?}, {want:?}"); + + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pencil"); + let a = center - vec2(100.0, 0.0); + let end = a + vec2(120.0, 0.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(a)]); + frame(&mut app, &ctx, vec![button(a, true)]); + for x in [20.0, 40.0, 60.0] { + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(x, 0.0))]); + } + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(90.0, 0.0)), Event::PointerMoved(end), button(end, false), Event::PointerMoved(far)]); + let r = last_bounds(&app); + let (left, right) = (xf.to_doc(a), xf.to_doc(end)); + assert!((r.x0 - left.x).abs() < 1.0 && (r.x1 - right.x).abs() < 1.0 && r.height() < 1.0, "the stroke ends at the release: {r:?}"); + + app.session.execute("shape.rectangle", &json!({"x": 250, "y": 40, "width": 60, "height": 40})).unwrap(); + app.session.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("selection"); + let before = Rect::new(250.0, 40.0, 310.0, 80.0); + let grab = xf.to_screen(Point::new(280.0, 60.0)); + let to = grab + vec2(30.0, 40.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(grab)]); + frame(&mut app, &ctx, vec![button(grab, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(grab + vec2(10.0, 10.0))]); + frame(&mut app, &ctx, vec![Event::PointerMoved(to), button(to, false), Event::PointerMoved(far)]); + let moved = last_bounds(&app); + let d = xf.to_doc(to) - xf.to_doc(grab); + assert!((moved.x0 - before.x0 - d.x).abs() < 1e-3 && (moved.y0 - before.y0 - d.y).abs() < 1e-3, "the art moves to the release: {moved:?}, {d:?}"); + assert!(app.session.active().unwrap().interaction.is_none(), "committed"); +} + #[test] fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { let ctx = egui::Context::default(); From 0567eaffbf15bb7054d754fa4674954c628c4c02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 17:20:56 -0800 Subject: [PATCH 055/674] Recolor: the Global Adjust sliders change every color at once The Edit tab's color mode menu offers Global Adjust, with Saturation, Brightness, Temperature and Luminosity sliders from -100% to 100% that open at 0%, which changes nothing. One slider changes every recolored color, each one separately, in its own model; the rows keep their new colors and the art previews the change. The Edit tab also shows the color sliders of the selected new color in the other modes. recolor.apply takes globalAdjust {saturation, brightness, temperature, luminosity}. Excluded rows and colors no row holds stay as they are, a rewritten color group takes the same change, and with Limit to Library each row's new color takes it before it snaps to the library. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/color/src/recolor.rs | 142 ++++++++++++++++++++++ crates/engine/src/cmd/recolor.rs | 64 ++++++++-- crates/engine/src/tests/recolor.rs | 115 ++++++++++++++++++ crates/ui-egui/src/dialogs/recolor.rs | 167 ++++++++++++++++++++++---- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/tests/recolor.rs | 67 ++++++++++- docs/control-protocol.md | 7 +- docs/mcp.md | 19 ++- docs/target-app-parity.md | 2 +- 34 files changed, 590 insertions(+), 41 deletions(-) diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index e88f767a5e..53cb12478d 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -255,6 +255,77 @@ pub fn shaded(c: Color, f: f32) -> Color { } } +/// Recolor Artwork's Global Adjust: the same change to every color, by four amounts from -1 to 1 +/// (-100% to +100%), where 0 leaves a color as it is. The steps run in this order: +/// +/// 1. Saturation multiplies HSB saturation by 1 + `saturation` (-1 gives a gray, 1 doubles it). +/// 2. Brightness moves HSB brightness that share of the way to its top (above 0) or to black +/// (below 0). +/// 3. Temperature adds 0.2 × `temperature` to display red and takes as much from blue (warmer +/// above 0, cooler below). +/// 4. Luminosity moves Lab lightness that share of the way to 100 (above 0) or to 0 (below 0), +/// with Lab a and b, and so the Lab hue, kept. +/// +/// The result is in the model of the color it changes, with its components clamped to their +/// ranges. An amount that is not finite counts as 0. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct GlobalAdjust { + pub saturation: f32, + pub brightness: f32, + pub temperature: f32, + pub luminosity: f32, +} + +impl GlobalAdjust { + /// The four amounts, in order, each finite and within -1..=1. + fn amounts(&self) -> [f32; 4] { + [self.saturation, self.brightness, self.temperature, self.luminosity].map(|v| if v.is_finite() { v.clamp(-1.0, 1.0) } else { 0.0 }) + } + + /// Whether every color stays as it is (all four amounts 0). + pub fn is_identity(&self) -> bool { + self.amounts().iter().all(|v| *v == 0.0) + } + + /// `c` with the adjustment, in `c`'s model; `c` itself when [`GlobalAdjust::is_identity`]. + pub fn apply(&self, c: Color) -> Color { + let [sat, bri, temp, lum] = self.amounts(); + if [sat, bri, temp, lum].iter().all(|v| *v == 0.0) { + return c; + } + // `v` moved the share `a` of the way to `top` (a > 0) or to 0 (a < 0). + let toward = |v: f32, a: f32, top: f32| if a >= 0.0 { v + (top - v) * a } else { v * (1.0 + a) }; + let mut out = c; + if sat != 0.0 || bri != 0.0 { + let [h, s, v] = out.to_hsb(); + out = Color::from_hsb(h, (s * (1.0 + sat)).clamp(0.0, 1.0), toward(v.clamp(0.0, 1.0), bri, 1.0)); + } + if temp != 0.0 { + let [r, g, b] = out.to_rgb(); + out = Color::rgb((r + 0.2 * temp).clamp(0.0, 1.0), g.clamp(0.0, 1.0), (b - 0.2 * temp).clamp(0.0, 1.0)); + } + if lum != 0.0 { + let Lab { l, a, b } = match out { + Color::Lab { l, a, b } => Lab::new(l, a, b), + _ => out.to_lab(), + }; + out = Color::lab(toward(l.clamp(0.0, 100.0), lum, 100.0), a, b); + } + clamped(keep_model(c, out)) + } +} + +/// `c` with its components in their ranges: RGB, CMYK and Gray 0..1, Lab lightness 0..100. +fn clamped(c: Color) -> Color { + let u = |v: f32| v.clamp(0.0, 1.0); + match c { + Color::Rgb { r, g, b } => Color::rgb(u(r), u(g), u(b)), + Color::Cmyk { c, m, y, k } => Color::cmyk(u(c), u(m), u(y), u(k)), + Color::Gray { k } => Color::gray(u(k)), + Color::Lab { l, a, b } => Color::lab(l.clamp(0.0, 100.0), a, b), + } +} + /// One row of Recolor Artwork prepared for mapping: its current colours take `to` by `method`. #[derive(Clone, Copy, Debug)] pub struct RowMap { @@ -615,6 +686,77 @@ mod tests { assert!(row.iter().all(|c| kept.map(*c).model() == c.model())); } + fn adjust(saturation: f32, brightness: f32, temperature: f32, luminosity: f32) -> GlobalAdjust { + GlobalAdjust { saturation, brightness, temperature, luminosity } + } + + #[test] + fn global_adjust_at_zero_leaves_every_color_as_it_is() { + let zero = GlobalAdjust::default(); + assert!(zero.is_identity()); + assert!(adjust(f32::NAN, 0.0, f32::INFINITY, 0.0).is_identity(), "amounts that aren't finite count as 0"); + for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.1234, 0.5, 0.0, 0.07), Color::gray(0.4), Color::lab(55.0, 60.5, -40.25)] { + assert_eq!(zero.apply(c), c); + } + assert!(!adjust(0.0, 0.0, 0.0, 0.01).is_identity()); + } + + #[test] + fn global_adjust_saturation_and_brightness_reach_their_ends() { + let c = Color::rgb(0.8, 0.4, 0.2); + let [h, s, v] = c.to_hsb(); + let gray = adjust(-1.0, 0.0, 0.0, 0.0).apply(c).to_hsb(); + assert!(gray[1].abs() < 1e-4 && (gray[2] - v).abs() < 1e-4, "-100% saturation gives a gray as bright: {gray:?}"); + let more = adjust(0.5, 0.0, 0.0, 0.0).apply(c).to_hsb(); + assert!((more[0] - h).abs() < 0.5 && more[1] > s && (more[1] - (s * 1.5).min(1.0)).abs() < 1e-3, "{more:?}"); + assert!(adjust(-1.0, 0.0, 0.0, 0.0).apply(Color::rgb(0.5, 0.5, 0.5)) == Color::rgb(0.5, 0.5, 0.5), "a gray stays gray"); + assert!(adjust(0.0, -1.0, 0.0, 0.0).apply(c).to_hsb()[2] < 1e-4, "-100% brightness is black"); + assert!((adjust(0.0, 1.0, 0.0, 0.0).apply(c).to_hsb()[2] - 1.0).abs() < 1e-4, "+100% brightness is full brightness"); + let half = adjust(0.0, 0.5, 0.0, 0.0).apply(c).to_hsb(); + assert!((half[2] - (v + (1.0 - v) * 0.5)).abs() < 1e-3 && (half[1] - s).abs() < 1e-3, "{half:?}"); + } + + #[test] + fn global_adjust_temperature_warms_and_cools() { + let c = Color::rgb(0.5, 0.5, 0.5); + let warm = adjust(0.0, 0.0, 1.0, 0.0).apply(c).to_rgb(); + let cool = adjust(0.0, 0.0, -1.0, 0.0).apply(c).to_rgb(); + assert!(warm[0] > warm[1] && warm[1] > warm[2], "warmer: more red, less blue {warm:?}"); + assert!(cool[2] > cool[1] && cool[1] > cool[0], "cooler: more blue, less red {cool:?}"); + let edge = adjust(0.0, 0.0, 1.0, 0.0).apply(Color::rgb(1.0, 0.0, 0.0)); + assert_eq!(edge, Color::rgb(1.0, 0.0, 0.0), "clamped at the ends of the channels"); + } + + #[test] + fn global_adjust_luminosity_keeps_the_hue() { + let lab = Color::lab(50.0, 30.0, -20.0); + assert_eq!(adjust(0.0, 0.0, 0.0, 0.5).apply(lab), Color::lab(75.0, 30.0, -20.0), "a Lab color keeps a and b exactly"); + assert_eq!(adjust(0.0, 0.0, 0.0, -0.5).apply(lab), Color::lab(25.0, 30.0, -20.0)); + let c = Color::rgb(0.6, 0.35, 0.3); + let (before, after) = (c.to_lab(), adjust(0.0, 0.0, 0.0, 0.2).apply(c).to_lab()); + assert!(after.l > before.l, "lighter: {after:?}"); + assert!((after.hue() - before.hue()).abs() < 2.0, "hue kept: {} vs {}", after.hue(), before.hue()); + let darkest = adjust(0.0, 0.0, 0.0, -1.0).apply(c).to_lab(); + assert!(darkest.l < before.l * 0.5, "-100% is far darker: {darkest:?}"); + assert_eq!(adjust(0.0, 0.0, 0.0, -1.0).apply(Color::gray(0.4)), Color::gray(1.0), "-100% makes a gray black"); + } + + #[test] + fn global_adjust_keeps_the_model_and_the_ranges() { + let all = adjust(1.0, 1.0, 1.0, 1.0); + for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.2, 0.9, 0.1, 0.3), Color::gray(0.4), Color::lab(55.0, 60.0, -40.0)] { + let out = all.apply(c); + assert_eq!(out.model(), c.model(), "{c:?} → {out:?}"); + let comps: Vec = match out { + Color::Rgb { r, g, b } => vec![r, g, b], + Color::Cmyk { c, m, y, k } => vec![c, m, y, k], + Color::Gray { k } => vec![k], + Color::Lab { l, .. } => vec![l / 100.0], + }; + assert!(comps.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}"); + } + } + #[test] fn palette_snaps_to_the_nearest_colour() { let p = Palette::new([Color::rgb(1.0, 0.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::gray(0.5)]); diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index b1fd2489e9..75b2cc73b6 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeSet, HashMap}; use serde_json::{Value, json}; -use vectorcraft_color::recolor::{ColorKey, Method, Preserve, Rng, RowMap, cluster}; +use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster}; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::swatches::{node_colors, node_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", has_doc, apply ), @@ -224,6 +224,30 @@ fn reduce(s: &mut Session, p: &Value) -> Result { Ok(json!({"map": map, "preserved": kept.iter().map(|u| key_str(&u.color)).collect::>(), "method": method.id()})) } +/// The `globalAdjust` parameter: `{saturation?, brightness?, temperature?, luminosity?}`, each a +/// percentage from -100 to 100 (0 when left out or null), as amounts from -1 to 1. +fn adjust_param(p: &Value, cmd: &str) -> Result { + let given = match p.get("globalAdjust") { + None | Some(Value::Null) => return Ok(GlobalAdjust::default()), + Some(v @ Value::Object(_)) => v, + Some(_) => return Err(bad(cmd, "`globalAdjust` must be an object")), + }; + let amount = |key: &str| -> Result { + let x = super::number_or(given, key, 0.0, cmd)?; + let (min, max) = (-100, 100); + if !(f64::from(min)..=f64::from(max)).contains(&x) { + return Err(bad(cmd, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + Ok((x / 100.0) as f32) + }; + Ok(GlobalAdjust { + saturation: amount("saturation")?, + brightness: amount("brightness")?, + temperature: amount("temperature")?, + luminosity: amount("luminosity")?, + }) +} + /// A current colour of a row: an exact colour, or every colour shown as a hex. enum Match { Key(ColorKey), @@ -370,15 +394,25 @@ struct ColorMap { hexes: HashMap, /// Set when a colour took a new colour of another model in its own model. converted: std::cell::Cell, + /// The Global Adjust every mapped colour takes after its row's new colour. + adjust: GlobalAdjust, } impl ColorMap { /// `links`: the swatch of each of `rows`' new colours (as many as `rows`, or none); `group`: the /// global swatches of the color group being rewritten; `model`: the model rule of a row without - /// its own. - fn new(rows: &[Row], method: Method, model: ModelRule, links: &[Option], group: Vec) -> Self { - let mut out = - Self { rows: vec![], links: vec![], tos: vec![], group, keys: HashMap::new(), hexes: HashMap::new(), converted: Default::default() }; + /// its own; `adjust`: the Global Adjust of each mapped colour. + fn new(rows: &[Row], method: Method, model: ModelRule, links: &[Option], group: Vec, adjust: GlobalAdjust) -> Self { + let mut out = Self { + rows: vec![], + links: vec![], + tos: vec![], + group, + keys: HashMap::new(), + hexes: HashMap::new(), + converted: Default::default(), + adjust, + }; for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) { let Some(to) = r.new_color() else { continue }; let i = out.rows.len(); @@ -387,7 +421,8 @@ impl ColorMap { // Colors that can't link to the swatch take the row's tint of it too. let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint)); out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(r.model.unwrap_or(model) != ModelRule::Keep)); - out.tos.push(to); + // Compared with the group's new colours, which take the adjustment too. + out.tos.push(adjust.apply(to)); out.links.push(link); for m in &r.from { match m { @@ -409,7 +444,7 @@ impl ColorMap { if r.converts(c) { self.converted.set(true); } - r.map(c) + self.adjust.apply(r.map(c)) } /// Recolour a colour that can link to a swatch: a row whose new colour is a global or spot @@ -448,7 +483,7 @@ impl ColorMap { if row.converts(*c) { self.converted.set(true); } - row.map(*c) + self.adjust.apply(row.map(*c)) } }; // A color its row leaves as it is still loses its link to a swatch of the rewritten group @@ -468,9 +503,13 @@ fn apply(s: &mut Session, p: &Value) -> Result { let method = method_param(p, C, Method::Exact)?; let palette = super::swatchlib::limit_param(s, p, C)?; let mut rows = parse_rows(p, C)?; + let adjust = adjust_param(p, C)?; + // With Limit to Library a row's new colour takes the Global Adjust before it snaps, so the art + // still takes the library's colours; otherwise every colour the rows map takes it. + let mapped_adjust = if palette.is_some() { GlobalAdjust::default() } else { adjust }; if let Some(pl) = &palette { for r in &mut rows { - r.to = r.to.map(|c| pl.nearest(c)); + r.to = r.to.map(|c| pl.nearest(adjust.apply(c))); } } // With Limit to Library, a row's new colour is a swatch of the library: the art takes that @@ -510,11 +549,12 @@ fn apply(s: &mut Session, p: &Value) -> Result { .iter() .map(|v| { color_value(v) + .map(|c| adjust.apply(c)) .map(|c| in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))) .ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))) }) .collect::>()?, - None => rows.iter().filter_map(Row::new_color).collect(), + None => rows.iter().filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(), }; let rename = text_param(p, "rename", C)?; let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); @@ -553,7 +593,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .collect() }) .unwrap_or_default(); - let map = ColorMap::new(&rows, method, model, &links, kept); + let map = ColorMap::new(&rows, method, model, &links, kept, mapped_adjust); let f = |c: Color| map.map(c); let lf = |c: &mut Color, link: &mut Option, tint: &mut f32| map.map_link(c, link, tint); let changed = Recolor::with_links(scope, &f, &lf).run(d, &ids); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 565405d58e..cadf9314a9 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -721,3 +721,118 @@ fn document_model_converts_the_colours_of_a_group_too() { run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#00ff00"], "model": "document"})); assert!(group(&s).iter().all(|c| c.model() == vectorcraft_color::cms::Model::Cmyk), "{:?}", group(&s)); } + +fn stroke(s: &Session, id: NodeId) -> Color { + s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_paint().color().unwrap() +} + +/// Global Adjust changes every colour the rows recolour, each one separately (the colours of a +/// row of several, fills and strokes alike), in its own model, as one undo step; an excluded +/// row's colours and preserved colours stay. +#[test] +fn global_adjust_changes_every_recolored_color() { + let mut s = session(); + let red = rect(&mut s, json!("#ff0000")); + let pink = rect(&mut s, json!("#ff8080")); + let cmyk = rect(&mut s, json!({"c": 100, "m": 0, "y": 0, "k": 0})); + let kept = rect(&mut s, json!("#00ff00")); + run(&mut s, "paint.setStroke", json!({"ids": [red.0], "color": "#0000ff", "width": 2})); + select_all(&mut s); + let map = json!([ + {"from": ["rgb 255 0 0", "rgb 255 128 128"], "to": "rgb 255 0 0"}, + {"from": ["cmyk 100 0 0 0"], "to": "cmyk 100 0 0 0"}, + {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"}, + {"from": ["rgb 0 255 0"], "to": "rgb 0 255 0", "exclude": true}, + ]); + let undo = s.doc().unwrap().history.undo.len(); + let sat = |c: Color| c.to_hsb()[1]; + let saturations = [fill(&s, red), fill(&s, pink), fill(&s, cmyk), stroke(&s, red)].map(sat); + let r = run(&mut s, "recolor.apply", json!({"map": map, "method": "scaleTints", "globalAdjust": {"saturation": -50}})); + assert_eq!(r["changed"], 4, "three fills and a stroke: {r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let after = [fill(&s, red), fill(&s, pink), fill(&s, cmyk), stroke(&s, red)].map(sat); + for (n, what) in ["red", "pink", "cyan", "the stroke"].iter().enumerate() { + // CMYK reads back through the profile-free conversion, so its saturation is near half, not exact. + assert!((after[n] - saturations[n] * 0.5).abs() < 0.05, "{what} has about half its saturation: {} → {}", saturations[n], after[n]); + } + assert!(close(fill(&s, red), Color::rgb(1.0, 0.5, 0.5)), "{:?}", fill(&s, red)); + assert!(close(fill(&s, pink), Color::rgb(1.0, 0.75, 0.75)), "each colour of a row changes on its own: {:?}", fill(&s, pink)); + assert!(matches!(fill(&s, cmyk), Color::Cmyk { .. }), "a CMYK colour stays CMYK: {:?}", fill(&s, cmyk)); + assert_eq!(fill(&s, kept).to_hex(), "#00ff00", "an excluded row keeps its colours"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(fill(&s, red).to_hex(), "#ff0000"); + assert_eq!(fill(&s, pink).to_hex(), "#ff8080"); + assert_eq!(stroke(&s, red).to_hex(), "#0000ff"); + // Brightness -100 makes every recolored color black; the rows' new colors are taken first. + run(&mut s, "recolor.apply", json!({"map": [{"from": ["#ff0000"], "to": "#00ff00"}], "globalAdjust": {"brightness": -100}})); + assert_eq!(fill(&s, red).to_hex(), "#000000"); + assert_eq!(fill(&s, pink).to_hex(), "#ff8080", "a colour no row holds stays"); +} + +/// Global Adjust at 0 changes nothing, a global swatch's link included, and a non-zero adjustment +/// gives the art the adjusted colour without the link. +#[test] +fn global_adjust_at_zero_keeps_colors_and_links() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Brand", "color": "#2878f0", "global": true})); + let art = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [art.0], "swatch": "Brand"})); + select_all(&mut s); + let link = |s: &Session| match s.doc().unwrap().doc.node(art).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { swatch, .. } => swatch, + p => panic!("a solid fill: {p:?}"), + }; + let before = fill(&s, art); + let zero = json!({"saturation": 0, "brightness": 0, "temperature": 0, "luminosity": 0}); + run(&mut s, "recolor.apply", json!({"map": {"rgb 40 120 240": "rgb 40 120 240"}, "globalAdjust": zero})); + assert_eq!(fill(&s, art), before); + assert_eq!(link(&s).as_deref(), Some("Brand"), "the link stays"); + run(&mut s, "recolor.apply", json!({"map": {"rgb 40 120 240": "rgb 40 120 240"}, "globalAdjust": {"temperature": 50}})); + let [r, _, b] = fill(&s, art).to_rgb(); + let [r0, _, b0] = before.to_rgb(); + assert!(r > r0 && b < b0, "warmer: {:?}", fill(&s, art)); + assert_eq!(link(&s), None, "the adjusted colour is no longer the swatch's"); +} + +/// With Limit to Library each row's new colour takes the Global Adjust and then snaps to the +/// library; a colour group rewritten with the rows' new colours takes the adjustment too. +#[test] +fn global_adjust_with_a_library_and_a_group() { + let mut s = session(); + let art = rect(&mut s, json!("#f01020")); + select_all(&mut s); + run(&mut s, "recolor.apply", json!({"map": {"#f01020": "#f01020"}, "limitTo": "Web Safe 216", "globalAdjust": {"brightness": -100}})); + assert_eq!(fill(&s, art).to_hex(), "#000000", "black, a colour of the library"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "swatch.newGroup", json!({"name": "Theme", "colors": ["#f01020"]})); + run(&mut s, "recolor.apply", json!({"map": [{"from": ["#f01020"], "to": "#f01020"}], "group": "Theme", "globalAdjust": {"saturation": -100}})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + let c = g.swatches[0].paint.color().unwrap(); + assert!(c.to_hsb()[1] < 1e-3, "the group's colour is adjusted: {c:?}"); + assert_eq!(c, fill(&s, art), "as the art is"); +} + +/// `globalAdjust` must be an object of numbers from -100 to 100; a refusal changes nothing and +/// records no undo step. A null counts as left out. +#[test] +fn global_adjust_refuses_params_of_the_wrong_form() { + let mut s = session(); + let art = rect(&mut s, json!("#ff0000")); + select_all(&mut s); + let undo = s.doc().unwrap().history.undo.len(); + let map = json!({"#ff0000": "#ff0000"}); + for (adjust, msg) in [ + (json!(5), "`globalAdjust` must be an object"), + (json!({"saturation": "50"}), "`saturation` must be a number"), + (json!({"brightness": 101}), "`brightness` must be between -100 and 100 (got 101)"), + (json!({"luminosity": -100.5}), "`luminosity` must be between -100 and 100 (got -100.5)"), + ] { + let e = s.execute("recolor.apply", &json!({"map": map, "globalAdjust": adjust})).unwrap_err().to_string(); + assert!(e.contains(msg), "{adjust}: {e}"); + } + assert_eq!(fill(&s, art).to_hex(), "#ff0000", "nothing changed"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + run(&mut s, "recolor.apply", json!({"map": map, "globalAdjust": null})); + run(&mut s, "recolor.apply", json!({"map": map, "globalAdjust": {"saturation": null, "temperature": -100}})); + assert_ne!(fill(&s, art).to_hex(), "#ff0000", "an amount at the end of the range applies"); +} diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 76f3a15e87..1f319ca96e 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -13,7 +13,9 @@ //! library file and limits to it; a library's colours apply as its swatches: a spot colour stays a //! spot colour, and joins the document's swatches). Edit tab: a hue and //! saturation wheel with a marker per new colour (drag one; with linked handles they all turn and -//! scale together), a brightness slider and the harmony rules. The preset menu sets up a 1, 2 or 3 +//! scale together), a brightness slider, the harmony rules, and the color sliders with their mode +//! menu, whose Global Adjust shows Saturation, Brightness, Temperature and Luminosity (-100% to +//! 100%, 0% changes nothing), which change every new color at once. The preset menu sets up a 1, 2 or 3 //! colour job or a library. Opened on a colour group (Edit or Apply Color Group), OK also rewrites //! the group with the new colours (renamed by `groupName`); without art only the group changes. //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new @@ -24,13 +26,15 @@ //! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none), //! `group`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, //! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for -//! a gray and Tint for a spot color). Changing `colors`, a preserve flag or `limitTo` reduces the -//! rows again. +//! a gray and Tint for a spot color; `global`: Global Adjust, on the Edit tab), `globalAdjust` +//! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s +//! `globalAdjust` in every slider mode). Changing `colors`, a preserve flag or `limitTo` reduces +//! the rows again. use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; use vectorcraft_color::harmony::{Harmony, move_on_wheel}; -use vectorcraft_color::recolor::{ColorKey, Method}; +use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method}; use vectorcraft_color::{Color, keep_model}; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; @@ -70,9 +74,18 @@ const NEW_CHIP: &str = "recolor-new"; /// The color modes of the sliders under the rows; a row whose new color is a spot color of the /// library also has Tint. const SLIDER_MODES: [Mode; 4] = [Mode::Hsb, Mode::Rgb, Mode::Cmyk, Mode::Lab]; -/// Widths of a color slider and of its number field. +/// Widths of a color slider's label, of the slider and of its number field. +const SLIDER_LABEL_W: f32 = 12.0; const SLIDER_W: f32 = 170.0; const SLIDER_FIELD_W: f32 = 48.0; +/// The `sliderMode` of the Edit tab's Global Adjust sliders, and the menu's name for it. +const GLOBAL: &str = "global"; +const GLOBAL_ADJUST: &str = "Global Adjust"; +/// The `globalAdjust` field's keys (and `recolor.apply`'s), in the order of the sliders. +const ADJUSTS: [&str; 4] = ["saturation", "brightness", "temperature", "luminosity"]; +/// Widths of a Global Adjust slider's label and of the slider. +const GLOBAL_LABEL_W: f32 = 76.0; +const GLOBAL_SLIDER_W: f32 = 110.0; /// The slider values last shown: `{row, key, mode, v}` (HSB keeps its hue at no saturation). const COMPS: &str = "__comps"; @@ -260,6 +273,11 @@ fn apply_params(d: &Dialog) -> Value { }); // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); + // The Global Adjust amounts, kept while the sliders show another mode; at 0% they are left out. + let values = adjust_values(d); + if values.iter().any(|v| *v != 0.0) { + p["globalAdjust"] = Value::Object(ADJUSTS.iter().zip(values).map(|(k, v)| (k.to_string(), json!(v))).collect()); + } if let (Some(Value::Object(g)), Some(p)) = (group, p.as_object_mut()) { p.extend(g.into_iter().filter(|(_, v)| !v.is_null())); } @@ -288,7 +306,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { ui.add_space(4.0); let mut rs = rows(d); let top = ui.cursor().top(); - let (changed, pick) = if d.str("tab") == "edit" { (edit_tab(ui, d, &mut rs), None) } else { assign_tab(app, ui, d, &mut rs) }; + let (changed, pick) = if d.str("tab") == "edit" { (edit_tab(app, ui, d, &mut rs), None) } else { assign_tab(app, ui, d, &mut rs) }; if d.str("tab") != "edit" { ui.add_space((TAB_H - (ui.cursor().top() - top)).max(0.0)); } @@ -335,7 +353,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); sync(app, &mut d); if d.bool("__newGroup") { - let colors: Vec = rows(&d).into_iter().filter(|r| !excluded(r)).map(|r| r["to"].clone()).collect(); + // The new colors with the Global Adjust, as `recolor.apply` gives them to a group. + let adjust = global_adjust(adjust_values(&d)); + let colors: Vec = rows(&d) + .into_iter() + .filter(|r| !excluded(r)) + .map(|r| to_color(&r).filter(|_| !adjust.is_identity()).map_or_else(|| r["to"].clone(), |c| key(&adjust.apply(c)))) + .collect(); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); } let r = form::commit_preview(app, CMD, apply_params(&d))?; @@ -529,7 +553,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } } let target = SliderTarget::of(app, d, rows); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target, false)); }); ui.add_space(6.0); changed |= sliders(app, ui, d, rows); @@ -686,30 +710,84 @@ impl SliderTarget { } } -/// The color mode menu of the sliders (HSB, RGB, CMYK, Lab, and Tint for a spot color), drawn -/// right to left: the menu, then its label. -fn mode_menu(ui: &mut Ui, d: &mut Dialog, target: &SliderTarget) { +/// The color mode menu of the sliders (HSB, RGB, CMYK, Lab, Tint for a spot color, and with +/// `global` Global Adjust), drawn right to left: the menu, then its label. +fn mode_menu(ui: &mut Ui, d: &mut Dialog, target: &SliderTarget, global: bool) { let t = Tokens::get(ui.ctx()); let mut labels: Vec<&str> = SLIDER_MODES.iter().map(|m| m.label()).collect(); if target.spot.is_some() { labels.push("Tint"); } - let current = target.mode(d).map_or("Tint", Mode::label); + if global { + labels.push(GLOBAL_ADJUST); + } + let adjusting = global && d.str("sliderMode") == GLOBAL; + let current = if adjusting { GLOBAL_ADJUST } else { target.mode(d).map_or("Tint", Mode::label) }; // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. let chosen = ui - .add_enabled_ui(target.color.is_some(), |ui| { - widgets::dropdown_named(ui, "recolor-slider-mode", Some(tl!("Color Mode:")), current, &labels, 90.0) + .add_enabled_ui(target.color.is_some() || global, |ui| { + widgets::dropdown_named(ui, "recolor-slider-mode", Some(tl!("Color Mode:")), current, &labels, if global { 110.0 } else { 90.0 }) }) .inner; if let Some(i) = chosen { - d.fields.insert("sliderMode".into(), json!(SLIDER_MODES.get(i).map_or_else(|| "tint".to_string(), |m| mode_id(*m)))); + let id = match SLIDER_MODES.get(i) { + Some(m) => mode_id(*m), + None if labels.get(i) == Some(&GLOBAL_ADJUST) => GLOBAL.to_string(), + None => "tint".to_string(), + }; + d.fields.insert("sliderMode".into(), json!(id)); } ui.label(egui::RichText::new(tl!("Color Mode:")).color(t.text_dim)); } -/// One color slider in the grid: its label, its rail with `track` and its number field, showing -/// `shown` with `suffix`. Returns the whole number in `shown`'s range that a drag, a key or the -/// field sets. +/// The Global Adjust amounts, in percent from -100 to 100, of `ADJUSTS`' keys in the +/// `globalAdjust` field (0 for one it lacks). +fn adjust_values(d: &Dialog) -> [f64; 4] { + let given = d.fields.get("globalAdjust"); + ADJUSTS.map(|k| given.and_then(|g| g.get(k)).and_then(Value::as_f64).unwrap_or(0.0).clamp(-100.0, 100.0)) +} + +/// The Global Adjust of `values` (percent, in the order of `ADJUSTS`). +fn global_adjust(values: [f64; 4]) -> GlobalAdjust { + let [saturation, brightness, temperature, luminosity] = values.map(|v| (v / 100.0) as f32); + GlobalAdjust { saturation, brightness, temperature, luminosity } +} + +/// The Global Adjust sliders, two to a line: Saturation, Brightness, Temperature and Luminosity, +/// each from -100% to 100% (0% changes nothing). They change every new color at once, so they +/// edit no row; each rail shows its amounts on `sample`. +fn global_sliders(ui: &mut Ui, d: &mut Dialog, sample: Color) { + let labels = [tl!("Saturation"), tl!("Brightness"), tl!("Temperature"), tl!("Luminosity")]; + let values = adjust_values(d); + let mut set: Option<(usize, f64)> = None; + egui::Grid::new("recolor-global-adjust").num_columns(6).spacing([6.0, 4.0]).show(ui, |ui| { + for (n, lbl) in labels.iter().enumerate() { + let shown = widgets::SliderValue::field(values[n], -100.0..=100.0, "%", 0); + // The rail: `sample` with this slider's amount alone. + let track = |x: f32| { + let mut one = [0.0; 4]; + one[n] = f64::from(x) * 200.0 - 100.0; + c32(&global_adjust(one).apply(sample)) + }; + if let Some(v) = slider_cell(ui, ("global", n), lbl, shown, "%", &track, GLOBAL_LABEL_W, GLOBAL_SLIDER_W) { + set = Some((n, v)); + } + if n % 2 == 1 { + ui.end_row(); + } + } + }); + if let Some((n, v)) = set { + let mut values = values; + values[n] = v; + d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().zip(values).map(|(k, v)| (k.to_string(), json!(v))).collect())); + } +} + +/// One color slider in the grid: its label `label_w` wide, its rail with `track` `slider_w` wide +/// and its number field, showing `shown` with `suffix`. Returns the whole number in `shown`'s +/// range that a drag, a key or the field sets. +#[allow(clippy::too_many_arguments)] fn slider_cell( ui: &mut Ui, id: impl std::hash::Hash + Copy, @@ -717,13 +795,15 @@ fn slider_cell( shown: widgets::SliderValue, suffix: &str, track: &dyn Fn(f32) -> egui::Color32, + label_w: f32, + slider_w: f32, ) -> Option { let t = Tokens::get(ui.ctx()); let (lo, hi) = (*shown.range.start(), *shown.range.end()); let value = shown.value; - ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(label).size(12.5).color(t.text))); + ui.add_sized(vec2(label_w, 22.0), egui::Label::new(egui::RichText::new(label).size(12.5).color(t.text))); let unit = ((value - lo) / (hi - lo)) as f32; - let (dragged, _, keyed) = widgets::color_slider_stepped(ui, ("recolor-slider", id), label, Some(shown), unit, SLIDER_W, track); + let (dragged, _, keyed) = widgets::color_slider_stepped(ui, ("recolor-slider", id), label, Some(shown), unit, slider_w, track); let typed = widgets::plain_field_named(ui, ("recolor-slider-field", id), Some(label), value, suffix, 0, SLIDER_FIELD_W); dragged.map(|x| (lo + f64::from(x) * (hi - lo)).round()).or(keyed).or(typed).map(|v| v.clamp(lo, hi)).filter(|v| (v - value).abs() > 1e-6) } @@ -746,7 +826,7 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] let gray = move |_: f32| input; for (n, lbl) in mode.labels().iter().enumerate() { let shown = widgets::SliderValue::field(0.0, f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); - slider_cell(ui, n, lbl, shown, mode.suffix(n), &gray); + slider_cell(ui, n, lbl, shown, mode.suffix(n), &gray, SLIDER_LABEL_W, SLIDER_W); if n % 2 == 1 { ui.end_row(); } @@ -757,7 +837,7 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] // Tint of the spot color, and its name. let tint = f64::from(row_tint(&rows[i])) * 100.0; let shown = widgets::SliderValue::field(tint, 0.0..=100.0, "%", 0); - if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&spot_tinted(app, c, x))) { + if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&spot_tinted(app, c, x)), SLIDER_LABEL_W, SLIDER_W) { rows[i]["tint"] = json!(v); changed = true; } @@ -769,7 +849,8 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] for (n, lbl) in mode.labels().iter().enumerate() { let v = comps.get(n).copied().unwrap_or(0.0); let shown = widgets::SliderValue::field(f64::from(v), f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); - if let Some(nv) = slider_cell(ui, n, lbl, shown, mode.suffix(n), &|x| c32(&track_color(mode, &comps, n, x))) { + if let Some(nv) = slider_cell(ui, n, lbl, shown, mode.suffix(n), &|x| c32(&track_color(mode, &comps, n, x)), SLIDER_LABEL_W, SLIDER_W) + { let mut c2 = comps.clone(); c2[n] = nv as f32; set = Some(c2); @@ -845,13 +926,14 @@ fn move_color(rows: &mut [Value], i: usize, hsb: [f32; 3], linked: bool) { const DRAG: &str = "__drag"; /// The Edit tab. Returns true when the rows changed. -fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { +fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { let top = ui.cursor().top(); let t = Tokens::get(ui.ctx()); let mut changed = false; let linked = d.bool("linked"); let active = active_rows(rows); let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied()); + let target = SliderTarget::of(app, d, rows); ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Harmony Rules:")).color(t.text_dim)); let rule = Harmony::parse(&d.str("rule")).unwrap_or(Harmony::Complementary); @@ -870,6 +952,10 @@ fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { if widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tip, linked, 24.0).clicked() { d.fields.insert("linked".into(), json!(!linked)); } + ui.add_space(8.0); + // The mode of the color sliders under the wheel: the selected new color in a color + // mode, or Global Adjust for all of them. + mode_menu(ui, d, &target, true); }); }); ui.add_space(8.0); @@ -899,6 +985,12 @@ fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { d.fields.remove(DRAG); } ui.add_space(6.0); + if d.str("sliderMode") == GLOBAL { + let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25)); + global_sliders(ui, d, sample); + } else { + changed |= sliders(app, ui, d, rows); + } // The new colours: click one to make it the base colour. let min_height = (TAB_H - (ui.cursor().top() - top)).max(0.0); super::modal::scrolled_rows(ui, "recolor-edit-colors", |ui| { @@ -957,6 +1049,33 @@ mod tests { assert!(apply_params(d).get("model").is_none()); } + /// `recolor.apply` gets the Global Adjust amounts only when one of them is not 0%, whatever + /// mode the sliders show. + #[test] + fn apply_params_send_global_adjust_only_when_it_changes_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("ui.recolorDialog", json!({"colors": ["#ff8000"]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert!(apply_params(d).get("globalAdjust").is_none(), "no field"); + d.fields.insert("globalAdjust".into(), json!({"saturation": 0, "brightness": 0})); + assert!(apply_params(d).get("globalAdjust").is_none(), "all 0%"); + d.fields.insert("globalAdjust".into(), json!({"temperature": 25, "luminosity": 500})); + d.fields.insert("sliderMode".into(), json!("hsb")); + assert_eq!( + apply_params(d)["globalAdjust"], + json!({"saturation": 0.0, "brightness": 0.0, "temperature": 25.0, "luminosity": 100.0}), + "every amount, clamped to 100%" + ); + // Colors opened alone become a new color group with the adjustment. + d.fields.insert("globalAdjust".into(), json!({"saturation": -100})); + let d = d.clone(); + confirm(&mut app, &d).unwrap(); + let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); + let c = g.swatches[0].paint.color().unwrap(); + assert!(c.to_hsb()[1] < 1e-3, "{c:?}"); + } + #[test] fn merge_and_separate_rows() { let mut r = rows(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f3f6cbfbb6..9d353951bd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1244,6 +1244,7 @@ font-technology Variable Променливи Get Preferences Извличане на предпочитания Get Text Range Вземане на текстов диапазон Global Глобален + Global Adjust Глобална корекция Global Brush Dimensions Глобални размери на четката Global Process Color Глобален процесен цвят Global Process Color, CMYK Глобален процесен цвят, CMYK diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7efa9c0e7..8951eb2262 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2138,6 +2138,7 @@ digits Malayalam Malajalam Color Mode: Način boja: Convert Pretvori Global Globalno + Global Adjust Globalno podešavanje Green Zelena Shifts the tints of global and spot colors; other colors stay. Pomjera nijanse globalnih i spot boja; ostale boje ostaju. Tint Preliv @@ -4260,6 +4261,7 @@ imageTrace Outline Obris @msg `library` is a library id or name (see {list}) `library` je ID ili naziv biblioteke (vidi {list}) @msg `mode` applies to freeform gradients `mode` se primjenjuje na gradijente slobodnog oblika @msg `preserve` must be an object `preserve` mora biti objekat +@msg `globalAdjust` must be an object `globalAdjust` mora biti objekat @msg `sampleSize` must be 1, 3 or 5 `sampleSize` mora biti 1, 3 ili 5 @msg `stops` must be an array `stops` mora biti niz @msg `svg` must be an object of SVG options (see document.formats) `svg` mora biti objekat SVG opcija (vidi document.formats) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd6172d6a6..08bf73630e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1699,6 +1699,7 @@ digits Malayalam Malaiàlam Glass Vidre Glass… Vidre… Global Global + Global Adjust Ajust global Global Brush Dimensions Dimensions globals del pinzell Global Edit Options Opcions globals d’edició Global Process Color Color de procés global @@ -4776,6 +4777,7 @@ digits Malayalam Malaiàlam @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte @msg `preserve` must be an object `preserve` ha de ser un objecte +@msg `globalAdjust` must be an object `globalAdjust` ha de ser un objecte @msg `sampleSize` must be 1, 3 or 5 `sampleSize` ha de ser 1, 3 o 5 @msg `select` must be true or false `select` ha de ser cert o fals @msg `stops` must be an array `stops` ha de ser una matriu diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 34c7f4e035..55f2c26ecc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2166,6 +2166,7 @@ digits Malayalam Malajálamské Color Mode: Barevný režim: Convert Převést Global Globální + Global Adjust Globální úprava Green Zelená Shifts the tints of global and spot colors; other colors stay. Posune tóny globálních a přímých barev; ostatní barvy zůstanou. Tint Tón @@ -4299,6 +4300,7 @@ imageTrace Outline Obrys @msg `library` is a library id or name (see {list}) `library` je ID nebo název knihovny (viz {list}) @msg `mode` applies to freeform gradients `mode` platí pro volné přechody @msg `preserve` must be an object `preserve` musí být objekt +@msg `globalAdjust` must be an object `globalAdjust` musí být objekt @msg `sampleSize` must be 1, 3 or 5 `sampleSize` musí být 1, 3 nebo 5 @msg `stops` must be an array `stops` musí být pole @msg `svg` must be an object of SVG options (see document.formats) `svg` musí být objekt s možnostmi SVG (viz document.formats) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5a23913424..f5f717ed56 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1969,6 +1969,7 @@ digits Malayalam Malayalam Color Mode: Farvetilstand: Convert Konvertér Global Global + Global Adjust Global justering Green Grøn Shifts the tints of global and spot colors; other colors stay. Flytter nuancerne af globale farver og spotfarver; andre farver forbliver uændrede. Tint Nuance diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 101bbefac6..831a355b22 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1268,6 +1268,7 @@ file-filter Templates Vorlagen Get Preferences Voreinstellungen abrufen Get Text Range Textbereich abrufen Global Global + Global Adjust Globale Anpassung Global Brush Dimensions Globale Pinselabmessungen Global Process Color Globale Prozessfarbe Global Process Color, CMYK Globale Prozessfarbe, CMYK @@ -3906,6 +3907,7 @@ theme Appearance Erscheinungsbild @msg `library` is a library id or name (see {list}) `library` ist die ID oder der Name einer Bibliothek (siehe {list}) @msg `mode` applies to freeform gradients `mode` gilt für Freiformverläufe @msg `preserve` must be an object `preserve` muss ein Objekt sein +@msg `globalAdjust` must be an object `globalAdjust` muss ein Objekt sein @msg `sampleSize` must be 1, 3 or 5 `sampleSize` muss 1, 3 oder 5 sein @msg `stops` must be an array `stops` muss ein Array sein @msg `svg` must be an object of SVG options (see document.formats) `svg` muss ein Objekt mit SVG-Optionen sein (siehe document.formats) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e704faade5..0c1adf7cff 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1208,6 +1208,7 @@ font-technology Variable Μεταβλητές Get Preferences Λήψη προτιμήσεων Get Text Range Λήψη περιοχής κειμένου Global Καθολικό + Global Adjust Καθολική ρύθμιση Global Brush Dimensions Καθολικές διαστάσεις πινέλου Global Process Color Καθολικό χρώμα τετραχρωμίας Global Process Color, CMYK Καθολικό χρώμα τετραχρωμίας, CMYK @@ -2208,6 +2209,7 @@ axis Both Και τα δύο @msg `library` is a library id or name (see {list}) Το `library` είναι αναγνωριστικό ή όνομα βιβλιοθήκης (δείτε {list}) @msg `mode` applies to freeform gradients Το `mode` ισχύει για ντεγκραντέ ελεύθερης μορφής @msg `preserve` must be an object Το `preserve` πρέπει να είναι αντικείμενο +@msg `globalAdjust` must be an object Το `globalAdjust` πρέπει να είναι αντικείμενο @msg `sampleSize` must be 1, 3 or 5 Το `sampleSize` πρέπει να είναι 1, 3 ή 5 @msg `stops` must be an array Το `stops` πρέπει να είναι πίνακας @msg `svg` must be an object of SVG options (see document.formats) Το `svg` πρέπει να είναι αντικείμενο επιλογών SVG (δείτε document.formats) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4ebddbe9a9..a93fd5d223 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1287,6 +1287,7 @@ font-technology Variable Variables Get Preferences Obtener preferencias Get Text Range Obtener rango de texto Global Global + Global Adjust Ajuste global Global Brush Dimensions Dimensiones globales de pincel Global Process Color Color de cuatricromía global Global Process Color, CMYK Color de cuatricromía global, CMYK @@ -3992,6 +3993,7 @@ axis Both Ambos @msg `library` is a library id or name (see {list}) `library` es el id o el nombre de una biblioteca (consulta {list}) @msg `mode` applies to freeform gradients `mode` se aplica a los degradados de forma libre @msg `preserve` must be an object `preserve` debe ser un objeto +@msg `globalAdjust` must be an object `globalAdjust` debe ser un objeto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` debe ser 1, 3 o 5 @msg `stops` must be an array `stops` debe ser una lista @msg `svg` must be an object of SVG options (see document.formats) `svg` debe ser un objeto con opciones de SVG (consulta document.formats) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7042b21f22..f5c9167093 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2125,6 +2125,7 @@ digits Malayalam Malajalam Color Mode: Väritila: Convert Muunna Global Globaali + Global Adjust Yleissäätö Green Vihreä Shifts the tints of global and spot colors; other colors stay. Siirtää globaalien värien ja spottivärien sävyjä; muut värit säilyvät. Tint Sävy @@ -4213,6 +4214,7 @@ imageTrace Outline Ääriviiva @msg `library` is a library id or name (see {list}) `library` on kirjaston tunnus tai nimi (ks. {list}) @msg `mode` applies to freeform gradients `mode` koskee vapaamuotoisia liukuvärejä @msg `preserve` must be an object `preserve` on oltava objekti +@msg `globalAdjust` must be an object `globalAdjust` on oltava objekti @msg `sampleSize` must be 1, 3 or 5 `sampleSize` on oltava 1, 3 tai 5 @msg `stops` must be an array `stops` on oltava taulukko @msg `svg` must be an object of SVG options (see document.formats) `svg` on oltava SVG-asetusten objekti (ks. document.formats) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 48eb621eb9..d590de2586 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1281,6 +1281,7 @@ font-technology Variable Variables Get Preferences Obtenir les préférences Get Text Range Obtenir une plage de texte Global Globale + Global Adjust Réglage global Global Brush Dimensions Dimensions globales des formes Global Process Color Couleur quadrichromique globale Global Process Color, CMYK Couleur quadrichromique globale, CMJN @@ -3982,6 +3983,7 @@ axis Both Les deux @msg `library` is a library id or name (see {list}) `library` est l’identifiant ou le nom d’une bibliothèque (voir {list}) @msg `mode` applies to freeform gradients `mode` s’applique aux dégradés de forme libre @msg `preserve` must be an object `preserve` doit être un objet +@msg `globalAdjust` must be an object `globalAdjust` doit être un objet @msg `sampleSize` must be 1, 3 or 5 `sampleSize` doit valoir 1, 3 ou 5 @msg `stops` must be an array `stops` doit être un tableau @msg `svg` must be an object of SVG options (see document.formats) `svg` doit être un objet d’options SVG (voir document.formats) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 81f9482631..23d51e8ea3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1602,6 +1602,7 @@ file-filter Templates Sablonok Glass Üveg Glass… Üveg… Global Globális + Global Adjust Globális beállítás Global Brush Dimensions Globális ecsetméretek Global Process Color Globális skálaszín Global Process Color, CMYK Globális skálaszín, CMYK @@ -4521,6 +4522,7 @@ imageTrace Outline Körvonal @msg `library` is a library id or name (see {list}) a `library` könyvtárazonosító vagy -név lehet (lásd: {list}) @msg `mode` applies to freeform gradients a `mode` a szabad formájú színátmenetekre vonatkozik @msg `preserve` must be an object `preserve`: objektum kell +@msg `globalAdjust` must be an object `globalAdjust`: objektum kell @msg `sampleSize` must be 1, 3 or 5 `sampleSize`: 1, 3 vagy 5 kell @msg `stops` must be an array `stops`: tömb kell @msg `svg` must be an object of SVG options (see document.formats) `svg`: SVG-beállításokat tartalmazó objektum kell (lásd: document.formats) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 89633ae991..ce1ce4436e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1969,6 +1969,7 @@ digits Malayalam Malayalam Color Mode: Mode warna: Convert Konversi Global Global + Global Adjust Penyesuaian global Green Hijau Shifts the tints of global and spot colors; other colors stay. Menggeser tint warna global dan warna spot; warna lainnya tetap. Tint Tint diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6acfaf3c9a..33b2c97797 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1298,6 +1298,7 @@ file-filter Templates Modelli Get Preferences Ottieni preferenze Get Text Range Ottieni intervallo di testo Global Globale + Global Adjust Regolazione globale Global Brush Dimensions Dimensioni pennello globali Global Process Color Colore quadricromia globale Global Process Color, CMYK Colore quadricromia globale, CMYK @@ -4033,6 +4034,7 @@ axis Both Entrambi @msg `library` is a library id or name (see {list}) `library` è l'id o il nome di una libreria (vedi {list}) @msg `mode` applies to freeform gradients `mode` si applica alle sfumature a forma libera @msg `preserve` must be an object `preserve` deve essere un oggetto +@msg `globalAdjust` must be an object `globalAdjust` deve essere un oggetto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` deve essere 1, 3 o 5 @msg `stops` must be an array `stops` deve essere un array @msg `svg` must be an object of SVG options (see document.formats) `svg` deve essere un oggetto di opzioni SVG (vedi document.formats) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bf3cd6bd1..18b45acef2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1662,6 +1662,7 @@ digits Malayalam マラヤーラム数字 Get Preferences 環境設定を取得 Get Text Range テキスト範囲を取得 Global グローバル + Global Adjust グローバル調整 Global Brush Dimensions ブラシサイズ (共通) Global Process Color グローバルプロセスカラー Go To Link リンク元へ移動 @@ -4149,6 +4150,7 @@ swatch Bright Violet ビビッドバイオレット @msg `groupColors` must be an array `groupColors` には配列を指定してください @msg `mode` applies to freeform gradients `mode` はフリーフォームグラデーションにのみ適用されます @msg `preserve` must be an object `preserve` にはオブジェクトを指定してください +@msg `globalAdjust` must be an object `globalAdjust` にはオブジェクトを指定してください @msg `stops` must be an array `stops` には配列を指定してください @msg `{k}` must be [x, y] `{k}` は [x, y] の形式で指定してください @msg a gradient needs at least two stops グラデーションには 2 つ以上の分岐点が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cf411b072c..437a7f1325 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1870,6 +1870,7 @@ digits Malayalam მალაიალამური Color Mode: ფერის რეჟიმი: Convert გარდაქმნა Global გლობალური + Global Adjust გლობალური კორექცია Green მწვანე Shifts the tints of global and spot colors; other colors stay. ცვლის გლობალური და სპოტ-ფერების ტონირებებს; სხვა ფერები უცვლელი რჩება. Tint ტონირება @@ -3778,6 +3779,7 @@ font-technology Variable ცვლადი @msg `library` is a library id or name (see {list}) `library` არის ბიბლიოთეკის id ან სახელი (იხ. {list}) @msg `mode` applies to freeform gradients `mode` ეხება თავისუფალი ფორმის გრადიენტებს @msg `preserve` must be an object `preserve` უნდა იყოს ობიექტი +@msg `globalAdjust` must be an object `globalAdjust` უნდა იყოს ობიექტი @msg `sampleSize` must be 1, 3 or 5 `sampleSize` უნდა იყოს 1, 3 ან 5 @msg `stops` must be an array `stops` უნდა იყოს მასივი @msg `svg` must be an object of SVG options (see document.formats) `svg` უნდა იყოს SVG-ის პარამეტრების ობიექტი (იხ. document.formats) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81f6c600c6..ac3d41d183 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1652,6 +1652,7 @@ digits Malayalam 말라얄람어 Get Preferences 환경 설정 가져오기 Get Text Range 텍스트 범위 가져오기 Global 전역 + Global Adjust 전체 조정 Global Brush Dimensions 전역 브러시 치수 Global Process Color 전역 프로세스 색상 Go To Link 링크로 이동 @@ -4076,6 +4077,7 @@ theme Appearance 외관 @msg `groupColors` must be an array `groupColors`는 배열이어야 합니다 @msg `mode` applies to freeform gradients `mode`는 자유형 그레이디언트에 적용됩니다 @msg `preserve` must be an object `preserve`는 개체여야 합니다 +@msg `globalAdjust` must be an object `globalAdjust`는 개체여야 합니다 @msg `stops` must be an array `stops`는 배열이어야 합니다 @msg `{k}` must be [x, y] `{k}`은(는) [x, y]여야 합니다 @msg a gradient needs at least two stops 그레이디언트에는 정지점이 두 개 이상 필요합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3448536832..8bdbcaa5f7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1983,6 +1983,7 @@ digits Malayalam Malayalam Color Mode: Kleurmodus: Convert Converteren Global Globaal + Global Adjust Globale aanpassing Green Groen Shifts the tints of global and spot colors; other colors stay. Verschuift de tinten van globale kleuren en spotkleuren; andere kleuren blijven ongewijzigd. Tint Tint diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14825f83cf..c5530da3f1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2083,6 +2083,7 @@ digits Malayalam Malajalam Color Mode: Tryb koloru: Convert Konwertuj Global Globalny + Global Adjust Dopasowanie globalne Green Zielony Shifts the tints of global and spot colors; other colors stay. Przesuwa tinty kolorów globalnych i dodatkowych; pozostałe kolory bez zmian. Tint Tinta @@ -4122,6 +4123,7 @@ imageTrace Outline Kontur @msg `library` is a library id or name (see {list}) `library` to identyfikator lub nazwa biblioteki (patrz {list}) @msg `mode` applies to freeform gradients `mode` dotyczy gradientów dowolnych @msg `preserve` must be an object `preserve` musi być obiektem +@msg `globalAdjust` must be an object `globalAdjust` musi być obiektem @msg `sampleSize` must be 1, 3 or 5 `sampleSize` musi wynosić 1, 3 lub 5 @msg `stops` must be an array `stops` musi być tablicą @msg `svg` must be an object of SVG options (see document.formats) `svg` musi być obiektem opcji SVG (patrz document.formats) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 96a31c3e57..d134a0be74 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1134,6 +1134,7 @@ Get Preferences Obter Preferências Get Text Range Obter Intervalo de Texto Global Global + Global Adjust Ajuste Global Global Brush Dimensions Dimensões Globais do Pincel Global Process Color Cor Global de Processo Glyphs Glifos @@ -3574,6 +3575,7 @@ axis Both Ambos @msg `library` is a library id or name (see {list}) `library` é o id ou o nome de uma biblioteca (veja {list}) @msg `mode` applies to freeform gradients `mode` se aplica a gradientes de forma livre @msg `preserve` must be an object `preserve` deve ser um objeto +@msg `globalAdjust` must be an object `globalAdjust` deve ser um objeto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` deve ser 1, 3 ou 5 @msg `stops` must be an array `stops` deve ser uma matriz @msg `svg` must be an object of SVG options (see document.formats) `svg` deve ser um objeto com opções de SVG (veja document.formats) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fdb51b80df..9162379d9a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1295,6 +1295,7 @@ file-filter Templates Шаблоны Get Preferences Получить настройки Get Text Range Получить диапазон текста Global Глобальный + Global Adjust Глобальная настройка Global Brush Dimensions Глобальные размеры кисти Global Process Color Глобальный составной цвет Global Process Color, CMYK Глобальный составной цвет, CMYK @@ -4028,6 +4029,7 @@ axis Both Оба @msg `library` is a library id or name (see {list}) `library` — это идентификатор или имя библиотеки (см. {list}) @msg `mode` applies to freeform gradients `mode` применяется к произвольным градиентам @msg `preserve` must be an object `preserve` должно быть объектом +@msg `globalAdjust` must be an object `globalAdjust` должно быть объектом @msg `sampleSize` must be 1, 3 or 5 `sampleSize` должно быть 1, 3 или 5 @msg `stops` must be an array `stops` должно быть массивом @msg `svg` must be an object of SVG options (see document.formats) `svg` должно быть объектом параметров SVG (см. document.formats) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e2dddf022b..3d57ae9adb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1246,6 +1246,7 @@ font-technology Variable Variabla Get Preferences Hämta inställningar Get Text Range Hämta textintervall Global Global + Global Adjust Global justering Global Brush Dimensions Globala penseldimensioner Global Process Color Global processfärg Global Process Color, CMYK Global processfärg, CMYK @@ -3903,6 +3904,7 @@ axis Both Båda @msg `library` is a library id or name (see {list}) `library` är ett biblioteks-id eller biblioteksnamn (se {list}) @msg `mode` applies to freeform gradients `mode` gäller för fria gradienter @msg `preserve` must be an object `preserve` måste vara ett objekt +@msg `globalAdjust` must be an object `globalAdjust` måste vara ett objekt @msg `sampleSize` must be 1, 3 or 5 `sampleSize` måste vara 1, 3 eller 5 @msg `stops` must be an array `stops` måste vara en array @msg `svg` must be an object of SVG options (see document.formats) `svg` måste vara ett objekt med SVG-alternativ (se document.formats) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9ecf2ccf93..d547b2b351 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1224,6 +1224,7 @@ font-technology Variable Değişken Get Preferences Tercihleri Al Get Text Range Metin Aralığını Al Global Küresel + Global Adjust Genel Ayarlama Global Brush Dimensions Küresel Fırça Boyutları Global Process Color Global Proses Rengi Global Process Color, CMYK Küresel Proses Rengi, CMYK @@ -3786,6 +3787,7 @@ axis Both Her İkisi @msg `library` is a library id or name (see {list}) 'kitaplık' bir kitaplık kimliği veya adıdır (bkz. {list}) @msg `mode` applies to freeform gradients "mod" serbest biçimli degradeler için geçerlidir @msg `preserve` must be an object `preserve` bir nesne olmalıdır +@msg `globalAdjust` must be an object `globalAdjust` bir nesne olmalıdır @msg `sampleSize` must be 1, 3 or 5 "sampleSize" 1, 3 veya 5 olmalıdır @msg `stops` must be an array "duraklar" bir dizi olmalıdır @msg `svg` must be an object of SVG options (see document.formats) `svg`, SVG seçeneklerinin bir nesnesi olmalıdır (bkz. document.formats) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d348440a2c..18247cb531 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1292,6 +1292,7 @@ file-filter Templates Шаблони Get Preferences Отримати налаштування Get Text Range Отримати діапазон тексту Global Глобальний + Global Adjust Глобальне налаштування Global Brush Dimensions Глобальні розміри пензля Global Process Color Глобальний складовий колір Global Process Color, CMYK Глобальний складовий колір, CMYK @@ -4017,6 +4018,7 @@ axis Both Обидві @msg `library` is a library id or name (see {list}) `library` — це ідентифікатор або ім’я бібліотеки (див. {list}) @msg `mode` applies to freeform gradients `mode` застосовується до довільних градієнтів @msg `preserve` must be an object `preserve` має бути об’єктом +@msg `globalAdjust` must be an object `globalAdjust` має бути об’єктом @msg `sampleSize` must be 1, 3 or 5 `sampleSize` має бути 1, 3 або 5 @msg `stops` must be an array `stops` має бути масивом @msg `svg` must be an object of SVG options (see document.formats) `svg` має бути об’єктом параметрів SVG (див. document.formats) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 09652ede2b..9ee468d56c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1503,6 +1503,7 @@ file-filter Templates Mẫu Glass Kính Glass… Kính… Global Toàn cục + Global Adjust Điều chỉnh toàn cục Global Brush Dimensions Kích thước cọ toàn cục Global Process Color Màu xử lý toàn cục Global Process Color, CMYK Màu xử lý toàn cục, CMYK @@ -4173,6 +4174,7 @@ theme Appearance Giao diện @msg `library` is a library id or name (see {list}) `library` là id hoặc tên thư viện (xem {list}) @msg `mode` applies to freeform gradients `mode` áp dụng cho chuyển sắc tự do @msg `preserve` must be an object `preserve` phải là một đối tượng +@msg `globalAdjust` must be an object `globalAdjust` phải là một đối tượng @msg `sampleSize` must be 1, 3 or 5 `sampleSize` phải là 1, 3 hoặc 5 @msg `stops` must be an array `stops` phải là một mảng @msg `svg` must be an object of SVG options (see document.formats) `svg` phải là đối tượng tùy chọn SVG (xem document.formats) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 841bd4528a..2e6b58886c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1236,6 +1236,7 @@ file-filter Templates 模板 Get Preferences 获取首选项 Get Text Range 获取文本范围 Global 全局 + Global Adjust 全局调整 Global Brush Dimensions 全局画笔尺寸 Global Process Color 全局印刷色 Global Process Color, CMYK 全局印刷色,CMYK @@ -3878,6 +3879,7 @@ imageTrace Outline 轮廓 @msg `groupColors` must be an array `groupColors` 必须是数组 @msg `mode` applies to freeform gradients `mode` 仅适用于任意形状渐变 @msg `preserve` must be an object `preserve` 必须是对象 +@msg `globalAdjust` must be an object `globalAdjust` 必须是对象 @msg `stops` must be an array `stops` 必须是数组 @msg `{k}` must be [x, y] `{k}` 必须是 [x, y] @msg a gradient needs at least two stops 渐变至少需要两个色标 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a515d59a74..9f2adef1c2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1262,6 +1262,7 @@ file-filter Templates 範本 Get Preferences 取得偏好設定 Get Text Range 取得文字範圍 Global 全域 + Global Adjust 整體調整 Global Brush Dimensions 整體筆刷尺寸 Global Process Color 整體印刷色 Global Process Color, CMYK 整體印刷色,CMYK @@ -1801,6 +1802,7 @@ file-filter Templates 範本 @msg `groupColors` must be an array `groupColors` 必須是陣列 @msg `mode` applies to freeform gradients `mode` 只適用於任意形狀漸層 @msg `preserve` must be an object `preserve` 必須是物件 +@msg `globalAdjust` must be an object `globalAdjust` 必須是物件 @msg `stops` must be an array `stops` 必須是陣列 @msg `{k}` must be [x, y] `{k}` 必須是 [x, y] @msg a gradient needs at least two stops 漸層至少需要兩個色標 diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 7c20467185..1786b7a614 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -572,11 +572,76 @@ fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", "recolor")))).unwrap().height() }; let assign = height(&mut h, "sliderMode", json!("cmyk")); - for (k, v) in [("sliderMode", json!("hsb")), ("sliderMode", json!("lab")), ("tab", json!("edit")), ("tab", json!("assign"))] { + for (k, v) in [ + ("sliderMode", json!("hsb")), + ("sliderMode", json!("lab")), + ("tab", json!("edit")), + ("sliderMode", json!("global")), + ("sliderMode", json!("rgb")), + ("tab", json!("assign")), + ] { assert_eq!(height(&mut h, k, v.clone()), assign, "{k} {v}"); } } +/// The fills of the document's objects, in order. +fn fills(app: &VectorcraftApp) -> Vec> { + let d = &app.session.doc().unwrap().doc; + d.layers[0].children().unwrap().iter().map(|n| d.node(n.id).unwrap().appearance.fill_paint().color()).collect() +} + +/// The Edit tab's color mode menu offers Global Adjust: Saturation, Brightness, Temperature and +/// Luminosity open at 0%, which changes nothing; one slider changes every recolored color at once +/// (the rows keep their new colors) and the art previews it; back at 0% the art has its own colors +/// again; the amounts stay while the tab or the mode changes; OK keeps the change as one undo step +/// and Cancel leaves the art as it was. +#[test] +fn global_adjust_changes_every_color_at_once() { + for confirm in [true, false] { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]); + let before = fills(h.state()); + let undo = h.state().session.doc().unwrap().history.undo.len(); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Color Mode:").click(); + h.run_steps(2); + h.get_by_label("Global Adjust").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "sliderMode"), json!("global")); + for name in ["Saturation", "Temperature", "Luminosity"] { + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, name).is_some(), "{name}"); + } + // Global Adjust's Brightness and the wheel's. + assert_eq!(h.get_all_by_role_and_label(egui::accesskit::Role::Slider, "Brightness").count(), 2); + assert_eq!(fills(h.state()), before, "at 0% the art keeps its colors"); + let rows = field(h.state(), "rows"); + click_slider(&mut h, "Saturation", 0.0); + assert_eq!(field(h.state(), "globalAdjust")["saturation"], json!(-100.0)); + assert_eq!(field(h.state(), "rows"), rows, "the rows keep their new colors"); + let gray = |app: &VectorcraftApp| fills(app).iter().all(|c| c.is_some_and(|c| c.to_hsb()[1] < 1e-3)); + assert!(gray(h.state()), "every color previews gray: {:?}", fills(h.state())); + click_slider(&mut h, "Saturation", 0.5); + assert_eq!(field(h.state(), "globalAdjust")["saturation"], json!(0.0)); + assert_eq!(fills(h.state()), before, "back at 0% the art has its own colors"); + click_slider(&mut h, "Saturation", 0.0); + for (k, v) in [("tab", json!("assign")), ("tab", json!("edit")), ("sliderMode", json!("hsb")), ("sliderMode", json!("global"))] { + set(h.state_mut(), k, v); + h.run_steps(3); + } + assert_eq!(field(h.state(), "globalAdjust")["saturation"], json!(-100.0), "the amount stays"); + assert!(gray(h.state()), "and still applies"); + h.get_by_label(if confirm { "OK" } else { "Cancel" }).click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + let app = h.state(); + if confirm { + assert!(gray(app), "OK keeps the change: {:?}", fills(app)); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + } else { + assert_eq!(fills(app), before, "Cancel leaves the art unchanged"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + } + } +} + /// The Assign tab's per-row hex fields are named by their row, not all "Color": a screen reader can /// tell the second from the first. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8f09432303..ad3a44d500 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -259,7 +259,12 @@ as `recolor.reduce` returns them), `colors` (null for Auto), `method`, `preserve `sliderMode` (the mode of the color sliders under the rows: `hsb`, `rgb`, `cmyk`, `lab`, or `tint` for a row whose new color is a spot color of the library; unset, they show the new color's own model). The sliders edit the first selected row's new color and give that row `model: "new"`, so the preview and confirm give only that row's art the color in -the sliders' mode; another edit of the row's new color, Reset and rows reduced again remove it. Setting +the sliders' mode; another edit of the row's new color, Reset and rows reduced again remove it. The Edit tab shows the +same sliders under the wheel, and its mode menu also has Global Adjust (`sliderMode: "global"`): Saturation, +Brightness, Temperature and Luminosity sliders that set `globalAdjust` (`{saturation, brightness, temperature, +luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-zero `globalAdjust` as `recolor.apply`'s +`globalAdjust` in every slider mode, so one slider changes every recolored color at once and the rows keep their new +colors; colors opened alone are saved as a group with the change. Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..92d031ba53 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1929,7 +1929,7 @@ the objects `select.all` takes, which leaves out hidden and locked art, and the and locked objects inside a group are left out too, also in isolation mode. `recolor.reduce {colors?, method?, preserve?, limitTo?, ids?}` groups those colours into rows of similar colours (k-means in Lab, weighted by use; tints of a global swatch share its row; White and Black are preserved by default) and returns a map of rows -`[{from: [keys], to: key}]` to edit and pass to `recolor.apply {map, method?, model?, limitTo?, group?, groupColors?, rename?}`. +`[{from: [keys], to: key}]` to edit and pass to `recolor.apply {map, method?, model?, limitTo?, group?, groupColors?, rename?, globalAdjust?}`. For scripts and MCP, `model` selects the replacement color model: `keep` (default) retains each original color's model, `new` takes the replacement's model, and `document` converts replacements and edited color groups to the document's model. A row's own `model` (the same values) takes the @@ -1953,11 +1953,26 @@ is linked to a swatch rewritten with another color keeps its row's new color, ev linked to the swatch, as does art whose color the row converts into the art's own color model. Without `group`, the swatch keeps its color and the recolored art is no longer linked to it. +`globalAdjust: {saturation?, brightness?, temperature?, luminosity?}` is the dialog's Global Adjust: each amount is a +percentage from -100 to 100 (0 when left out), and all four at 0 change nothing. Every color that a row which is not +excluded recolors takes the same change after its row's new color, in this order: saturation multiplies HSB +saturation by 1 + saturation/100; brightness moves HSB brightness that share of the way to full brightness (above 0) +or to black (below 0); temperature adds 0.2 × temperature/100 to red and subtracts it from blue; luminosity moves Lab +lightness that share of the way to 100 or to 0 and keeps Lab a and b, so the hue stays. Each color keeps its own +model, and a changed color is no longer linked to its swatch. The colors a `group` is rewritten with take the same +change. With `limitTo`, each row's new color takes the change before it snaps to the library, so the art still takes +the library's colors. Colors that no row holds, such as preserved White and Black, and excluded rows stay as they are. + +```json +{"name":"run_command","arguments":{"command":"recolor.apply","params":{"map":{"#ff0000":"#ff0000","#0000ff":"#0000ff"},"globalAdjust":{"saturation":-40,"temperature":25}}}} +``` + The `recolor.*` commands refuse parameters of the wrong form. A `limitTo` or `method` that is not a string gets the error for an unknown library or method. Other wrong-form parameters get an error that names them. `includeImages`, `includePatterns`, a row's `exclude`, `order`, `saturationBrightness` and the `white`, `black` and `grays` switches of `preserve` must be true or false; `colors` and `seed` must be whole numbers; `group` and `rename` -must be strings, `groupColors` must be an array and `preserve` must be an object. Each refusal leaves the document unchanged and records no undo step. A `null` +must be strings, `groupColors` must be an array, `preserve` must be an object, and `globalAdjust` must be an object +whose amounts are numbers from -100 to 100. Each refusal leaves the document unchanged and records no undo step. A `null` counts as a value left out except for `recolor.apply`'s `model` and a `map` row's `model`, which must be strings when given. ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..3a9260f931 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -123,7 +123,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 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`) | | 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 | +| 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, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (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 | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | From 1ef52dd50e8b2006f02b9b88ca985c25b3c75478 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 10:25:50 -0800 Subject: [PATCH 056/674] Artwork Cleanup: Simplify Anchors and Deep Ungroup leave hidden and locked art alone Simplify Anchors (Keep Shape) simplified every path under the selection, locked and hidden paths and paths in locked or hidden groups included. It now takes only the paths Document::editable allows, as the health check and Rejoin Path Pieces already do. Deep Ungroup took apart hidden and locked groups inside the selection, so their members became visible or unlocked. A hidden or locked group now stays whole, a locked or hidden object named in ids is left alone, and members that are locked or hidden themselves keep that and are not selected. With no group to take apart, the reply's ids list the selection, which stays as it was. --- crates/engine/src/cmd/addons/cleanup.rs | 35 ++++++--- crates/engine/src/cmd/addons/cleanup/tests.rs | 78 +++++++++++++++++++ docs/mcp.md | 8 +- 3 files changed, 107 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index b65fc75ac3..cba512cd18 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Simplify Anchors (Keep Shape)…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay → {ids, before, after} anchor counts", + "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts", has_selection, simplify ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Deep Ungroup…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in → {ids (the objects left, selected), ungrouped (groups)}", + "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}", has_selection, deep_ungroup ), @@ -91,7 +91,8 @@ pub fn specs() -> Vec { v } -/// The paths (not guides) under `roots`, compound path members included. +/// The paths (not guides) under `roots`, compound path members included; locked and hidden +/// paths, and those in locked or hidden groups, stay out. fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { let mut out = vec![]; for n in roots.iter().filter_map(|id| d.node(*id)) { @@ -101,6 +102,8 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { } }); } + let editable = d.editable(); + out.retain(|id| editable(*id)); out } @@ -256,9 +259,9 @@ fn ungroupable(n: &Node, clips: bool) -> bool { /// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts /// the groups. Members take on the opacity of the groups they were in, and a clipping path -/// becomes a plain path. +/// becomes a plain path. A locked or hidden group stays whole. fn flatten(n: Node, clips: bool, out: &mut Vec, count: &mut usize) { - if !ungroupable(&n, clips) { + if !ungroupable(&n, clips) || n.locked || !n.visible { out.push(n); return; } @@ -282,6 +285,11 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result { let clips = switch_or(p, "includeClipGroups", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; + // Locked and hidden objects, and those in locked or hidden groups, stay as they are. + let roots: Vec = { + let editable = d.editable(); + roots.into_iter().filter(|id| editable(*id)).collect() + }; let (mut items, mut selected, mut count) = (vec![], vec![], 0); for id in &roots { match d.node(*id).filter(|n| ungroupable(n, clips)) { @@ -294,13 +302,18 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result { None => selected.push(*id), } } - // With no group to take apart, the document and its undo history stay as they are. - if !items.is_empty() { - let ids = selected.clone(); - s.edit("Deep Ungroup", |d, sel| { + // With no group to take apart, the document, the selection and the undo history stay as they + // are, and the reply lists the selection. + if items.is_empty() { + selected = s.doc()?.selection.objects.to_vec(); + } else { + selected = s.edit("Deep Ungroup", move |d, sel| { d.insert_beside(items, true)?; - sel.set(ids); - Ok(()) + // Members that are locked or hidden themselves keep that, and are not selected. + let editable = d.editable(); + selected.retain(|id| editable(*id)); + sel.set(selected.iter().copied()); + Ok(selected) })?; } Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::>(), "ungrouped": count })) diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index d02e1e4c09..83b67c6b16 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -104,6 +104,39 @@ fn simplify_keeps_the_shape_with_fewer_anchors_in_one_step() { } } +#[test] +fn simplify_leaves_locked_and_hidden_paths_alone() { + let mut s = session(); + let mut ids = vec![]; + for x in [20.0, 140.0, 260.0] { + ids.push(id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": 50, "width": 100, "height": 100})).unwrap())); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + } + select(&mut s, &ids); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, ids[1], |n| n.locked = true); + change(&mut s, ids[2], |n| n.visible = false); + select(&mut s, &[g]); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([ids[0].0])); + assert_eq!(r["before"], 16); + assert!(anchors(&s, ids[0]) < 16); + assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); + // Named by `ids`, or in a locked group, a path stays too, with no undo step. + let steps = undo_steps(&s); + s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap(); + assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); + assert_eq!(undo_steps(&s), steps); + change(&mut s, ids[1], |n| n.locked = false); + change(&mut s, g, |n| n.locked = true); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap(); + assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0))); + assert_eq!(anchors(&s, ids[1]), 16); + assert_eq!(undo_steps(&s), steps); +} + /// Each kind: what makes the issue in a fresh document (beside a clean rectangle). fn make_issue(s: &mut Session, kind: &str) { match kind { @@ -333,6 +366,51 @@ fn deep_ungroup_takes_apart_every_level_but_clipping_groups() { assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Path { clipping: false, .. })); } +#[test] +fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0); + select(&mut s, &[b]); + let hidden = id_of(&s.execute("object.group", &json!({})).unwrap()); + select(&mut s, &[c]); + let locked = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, hidden, |n| n.visible = false); + change(&mut s, locked, |n| n.locked = true); + change(&mut s, e, |n| n.locked = true); + s.edit("t", |d, _| { + let w = d.alloc_id(); + Ok(d.wrap(&[a, hidden, locked, e], |ch| Node::group(w, ch))?) + }) + .unwrap(); + let outer = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + select(&mut s, &[outer]); + let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap(); + assert_eq!(r["ungrouped"], 1); + assert_eq!(r["ids"], json!([a.0])); + let d = &s.doc().unwrap().doc; + let layer: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [a, hidden, locked, e], "the hidden and locked groups stay whole"); + assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible); + assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked); + assert_eq!(s.doc().unwrap().selection.objects, [a]); + // Named by `ids`, a locked group stays as it is, with no undo step. + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap(); + assert_eq!(r["ungrouped"], 0); + assert!(node(&s, locked).is_some()); + assert_eq!(undo_steps(&s), steps); + // With nothing ungrouped, the selection stays and the reply lists it. + assert_eq!(r["ids"], json!([a.0])); + let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0); + select(&mut s, &[a]); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap(); + assert_eq!((r["ids"].clone(), r["ungrouped"].clone()), (json!([a.0]), json!(0))); + assert_eq!(s.doc().unwrap().selection.objects, [a]); +} + #[test] fn rejoin_joins_pieces_within_the_gap_only() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index fa8e05fab3..97fd9dc64f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5910,8 +5910,9 @@ Plug-ins › Artwork Cleanup and in its panel (`window.panel {panel: "artworkCle `addon.cleanup.simplify {tolerance?, protectCorners?, ids?}` removes the anchors each selected path can do without and refits the handles beside each one, so the outline keeps its shape. `tolerance` runs from 1 to 100 (20 by default); the outline stays within tolerance × 0.02 pt of where it was, measured against the original outline, so removals don't add -up. With `protectCorners`, anchors where the path turns by more than 30° stay. Open ends always stay. It reports the -anchor counts `before` and `after`, as one undo step. +up. With `protectCorners`, anchors where the path turns by more than 30° stay. Open ends always stay. Locked and hidden +paths, and paths in locked or hidden groups, are left out. It reports the anchor counts `before` and `after`, as one +undo step. The health check looks for issues in the selection, or in the whole document while nothing is selected (`scope: "selection"|"document"` picks one). Locked and hidden objects, and the insides of live or generated art (blends, @@ -5945,7 +5946,8 @@ envelopes, graphs, symbols), are left out. `addon.cleanup.deepUngroup {includeClipGroups?, ids?}` takes apart every level of grouping in the selection. Clipping groups stay whole unless `includeClipGroups` is true; their clipping paths then become plain paths. Objects keep the -opacity of the groups they were in. +opacity of the groups they were in. Locked and hidden groups stay whole, and locked and hidden objects stay locked or +hidden and are left out of the selection. `addon.cleanup.rejoin {gap?, ids?}` welds the selected open paths whose ends lie within `gap` (0 to 6 pt, 0.1 by default) back into paths. Each end joins one other end: where several are in reach, the one the path turns least to go From 1186d1f7127e5dfbf4184df86ff89b08f6a66d1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 18:09:53 -0800 Subject: [PATCH 057/674] Affinity: pressure curves that can't be read count against the document's limit A curve rejected for having more than 256 segments now counts the most points a curve may have against the document's pressure points, so linking it from many strokes reads it a bounded number of times. Once the points are used up, later strokes import as plain strokes with a warning. --- crates/affinity/src/geometry.rs | 4 ++++ crates/affinity/src/paint.rs | 6 ++++-- crates/engine/src/cmd/fileio/tests_affinity.rs | 6 ++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index 945c3040f9..bb1c45746b 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -178,6 +178,10 @@ const MAX_PRESSURE_SEGMENTS: usize = 256; /// points; the document's limit counts all of them. const PRESSURE_POINTS: usize = 512; +/// Most points one pressure curve can have (see [`PRESSURE_POINTS`]). A curve that can't be read +/// counts this many against the document's limit. +pub(crate) const MAX_PRESSURE_CURVE_POINTS: usize = 1 + 4 * MAX_PRESSURE_SEGMENTS; + /// A stroke's pressure curve (`LDsc.LDeP`, a `CrvD` whose positional `Data` holds an array of /// 18-byte records as in [`curves`]): x is the position along the path (0 to 1) and y the width as /// a fraction of the stroke's weight. Each segment is sampled at 2 to 8 points, at most diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs index cfc95b8dda..12102581e1 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -357,8 +357,9 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh r.warn("brush strokes (imported as plain strokes)"); } // The pressure curve sets the width along the path; one at full width all along is a plain - // stroke. Every curve read, full width or not, counts against the document's points, and once - // they are used up the rest are not read. + // stroke. Every curve read counts against the document's points: one at full width counts its + // points, and one that can't be read counts the most a curve may have. Once the points are + // used up the rest are not read. const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)"; let ldep = s.obj(ldsc, b"LDeP"); if ldep.is_some() && r.budget.pressure == 0 { @@ -377,6 +378,7 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh } }, Some(None) => { + r.budget.pressure = r.budget.pressure.saturating_sub(crate::geometry::MAX_PRESSURE_CURVE_POINTS); r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)"); None } diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rs index a57da79fcb..70b9b992af 100644 --- a/crates/engine/src/cmd/fileio/tests_affinity.rs +++ b/crates/engine/src/cmd/fileio/tests_affinity.rs @@ -462,6 +462,12 @@ mod native { let flat: Vec> = (0..=768).map(|i| node(f64::from(i) / 768.0, 1.0, if i % 3 == 0 { 4 } else { 0 }, (i % 3) as u8)).collect(); let r = load("flat-many.af", &pressure_documents(flat, 2100)).unwrap(); assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings); + + // So do curves that can't be read: 768 segments, more than a curve may have. + let long: Vec> = (0..=768).map(|i| node(f64::from(i) / 768.0, f64::from(i % 2), 4, 0)).collect(); + let r = load("long-many.af", &pressure_documents(long, 2100)).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("pressure curve can't be read")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings); } #[test] From d46284c52c389bccfa3ac497b01f6f248c5dc5ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 18:10:13 -0800 Subject: [PATCH 058/674] Recolor: Global Adjust gives linked tints of a rewritten group their adjusted color A tint linked to a global swatch of the color group that recolor.apply rewrites kept its link and showed the swatch's adjusted color at its tint, which differs from the same color adjusted on its own. It now keeps the link only when the two match, and otherwise takes the adjusted color, unlinked. --- crates/color/src/recolor.rs | 6 ++++++ crates/engine/src/cmd/recolor.rs | 9 +++++---- crates/engine/src/tests/recolor.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 53cb12478d..e7cf22c41f 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -244,6 +244,12 @@ pub fn is_tint(c: Color, base: Color) -> bool { a.iter().zip(b).all(|(x, y)| (x - y * t).abs() <= 0.01) } +/// Whether `a` and `b` carry the same ink in `a`'s model, within [`is_tint`]'s tolerance. +pub fn same_ink(a: Color, b: Color) -> bool { + let (x, y) = (ink(a, a.model()), ink(b, a.model())); + x.iter().zip(y).all(|(p, q)| (p - q).abs() <= 0.01) +} + /// `c` darkened by `f` (0..1) toward black: more K for CMYK and Gray, scaled RGB and Lab. pub fn shaded(c: Color, f: f32) -> Color { let f = f.clamp(0.0, 1.0); diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 75b2cc73b6..1759372d0a 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeSet, HashMap}; use serde_json::{Value, json}; -use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster}; +use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink}; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::swatches::{node_colors, node_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; @@ -452,7 +452,8 @@ impl ColorMap { /// stay unlinked), a /// process swatch gives its colour in its own model; a color linked to a global swatch of the /// rewritten group that takes the row's new color keeps its link (at its tint in the row) when - /// the row gives it the new color in that color's model; + /// the row gives it the new color in that color's model and the Global Adjust gives it the + /// swatch's new color at that tint; /// other rows map the colour, which loses its link when it changes or when the group's rewrite /// would change it. True when anything changed. fn map_link(&self, c: &mut Color, link: &mut Option, tint: &mut f32) -> bool { @@ -462,9 +463,9 @@ impl ColorMap { && let Some(g) = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)) && self.tos.get(i) == Some(&g.color) && !row.converts(*c) - && let Some(t) = row.tint(*c) + && let Some(t) = row.tint(*c).map(|t| t.clamp(0.0, 1.0)) + && (self.adjust.is_identity() || same_ink(self.adjust.apply(row.map(*c)), g.shown.tinted(t))) { - let t = t.clamp(0.0, 1.0); let shown = g.shown.tinted(t); let changed = *tint != t || *c != shown; (*c, *tint) = (shown, t); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index cadf9314a9..cff302503d 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -812,6 +812,34 @@ fn global_adjust_with_a_library_and_a_group() { assert_eq!(c, fill(&s, art), "as the art is"); } +/// Art linked to a global swatch of the rewritten group takes the same Global Adjust as unlinked +/// art of its color: at 100% it keeps the link, and a tint whose adjusted color is not the +/// swatch's new color at that tint takes the adjusted color and loses the link. +#[test] +fn global_adjust_gives_linked_tints_of_a_group_the_adjusted_color() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Theme", "colors": ["#ff0000"]})); + let name = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().swatches[0].name.clone(); + run(&mut s, "swatch.edit", json!({"name": name, "global": true})); + let full = rect(&mut s, json!("#000000")); + let tint = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [full.0], "swatch": name})); + run(&mut s, "paint.setFill", json!({"ids": [tint.0], "swatch": name, "tint": 50})); + let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, tint } => (color, swatch, tint), + p => panic!("{p:?}"), + }; + select_all(&mut s); + let tint_key = vectorcraft_color::recolor::ColorKey::of(&fill(&s, tint)).to_string(); + let rows = json!([{"from": ["rgb 255 0 0", tint_key], "to": "#ff0000"}]); + run(&mut s, "recolor.apply", json!({"map": rows, "method": "scaleTints", "group": "Theme", "globalAdjust": {"brightness": -50}})); + let (c, w, t) = link(&s, full); + assert!(close(c, Color::rgb(0.5, 0.0, 0.0)) && w.as_deref() == Some(name.as_str()) && t == 1.0, "{c:?} {w:?} {t}"); + let (c, w, _) = link(&s, tint); + assert!(close(c, Color::rgb(0.5, 0.25, 0.25)), "the tint's own color, adjusted: {c:?}"); + assert_eq!(w, None, "the adjusted tint is not a tint of the swatch's new color"); +} + /// `globalAdjust` must be an object of numbers from -100 to 100; a refusal changes nothing and /// records no undo step. A null counts as left out. #[test] From 7389cc22d6af82de9311193eb8cb6e30cb423d14 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 18:18:19 -0800 Subject: [PATCH 059/674] Document Info: Save writes the category the panel shows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Save… in the Document Info panel menu now writes only the category the panel shows, with Selection Only applied. With All Categories shown it writes every category, as before. docInfo.save takes an optional category (a document.info category id) and passes it to document.info. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/doc_info.rs | 71 +++++++++++++++++++++++-- docs/control-protocol.md | 3 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 5 files changed, 73 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 11f3424200..48a1d2ecc8 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1130,7 +1130,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "docInfo.save", "Save Document Info…", "", - "{path?, selectionOnly?} write Document Info's text report (document.info {format: \"text\"}) to path, else a picked file (the web downloads it) → {path}", + "{path?, selectionOnly?, category?} write Document Info's text report (document.info {format: \"text\"}) to path, else a picked file (the web downloads it); with category (a document.info category id) only that category, else every category. The panel menu's Save… passes the category the panel shows and its Selection Only → {path}", ), ( "ui.epsOptionsDialog", diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 87f08f7f3f..f6becb3911 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -101,11 +101,15 @@ fn named_rows(id: &str, rows: &[Value]) -> std::ops::Range { } } -/// `docInfo.save {path?, selectionOnly?}`: write the text report to `path`, else a picked file -/// (the web downloads it) → `{path}`. +/// `docInfo.save {path?, selectionOnly?, category?}`: write the text report (only `category` when given, +/// else every category) to `path`, else a picked file (the web downloads it) → `{path}`. pub(crate) fn save_report(app: &mut VectorcraftApp, p: &Value) -> Result { let sel_only = p.get("selectionOnly").and_then(Value::as_bool).unwrap_or(false); - let r = app.session.execute("document.info", &json!({ "format": "text", "selectionOnly": sel_only })).map_err(|e| e.to_string())?; + let mut q = json!({ "format": "text", "selectionOnly": sel_only }); + if let Some(c) = p.get("category").and_then(Value::as_str).filter(|c| !c.is_empty()) { + q["category"] = c.into(); + } + let r = app.session.execute("document.info", &q).map_err(|e| e.to_string())?; let text = r["text"].as_str().unwrap_or_default(); let title = app.session.active().map(|d| d.title()).unwrap_or_default(); let stem = std::path::Path::new(&title).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); @@ -134,7 +138,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); if menu_item(ui, tl!("Save…"), app.session.active().is_some(), false) { - crate::menus::invoke(app, "docInfo.save", json!({ "selectionOnly": sel })); + crate::menus::invoke(app, "docInfo.save", json!({ "selectionOnly": sel, "category": category })); } } @@ -207,4 +211,63 @@ mod tests { let report = String::from_utf8(written.borrow().clone()).unwrap(); assert!(report.starts_with("Document Info: ") && report.contains("\nFONT DETAILS\n") && report.contains("\nREPEAT OBJECTS\n"), "{report}"); } + + /// The report the panel menu's Save… writes with category `category` shown ("" for All + /// Categories) and Selection Only set to `sel_only`. + fn saved_from_menu(app: &mut VectorcraftApp, category: &str, sel_only: bool) -> String { + let written: std::rc::Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |_: &str, b: &[u8]| { + w.borrow_mut().extend_from_slice(b); + Ok(()) + })); + app.services.pick_save = Some(Box::new(|pick: &crate::FilePick| Some(format!("/tmp/{}", pick.name)))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "docinfo-category", category.to_string()); + set_pstate(&ctx, "docinfo-sel", sel_only); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(236.0, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| menu(app, ui)); + out.textures_delta.clear(); + crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()) + }; + let labels = frame(app, vec![]); + let at = labels.iter().find(|(t, _)| t.trim() == "Save…").map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no Save… in {labels:?}")); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(at), button(true)]); + frame(app, vec![button(false)]); + let report = String::from_utf8(written.borrow().clone()).unwrap(); + assert!(report.starts_with("Document Info: "), "nothing saved: {report:?}"); + report + } + + /// Save… writes the category the panel shows, with Selection Only applied; All Categories + /// writes every category. + #[test] + fn save_writes_the_category_the_panel_shows() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let text = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone(); + let objects = saved_from_menu(&mut app, "objects", false); + assert!(objects.contains("\nOBJECTS\n") && objects.contains("Paths: 1") && objects.contains("Text Objects: 1"), "{objects}"); + assert!(!objects.contains("\nDOCUMENT\n") && !objects.contains("\nFONTS\n"), "only Objects: {objects}"); + let fonts = saved_from_menu(&mut app, "fonts", false); + assert!(fonts.contains("\nFONTS\n") && fonts.contains("Source Sans 3"), "{fonts}"); + assert!(!fonts.contains("\nOBJECTS\n") && !fonts.contains("\nFONT DETAILS\n"), "only Fonts: {fonts}"); + let all = saved_from_menu(&mut app, "", false); + assert!( + all.contains("\nDOCUMENT\n") && all.contains("\nOBJECTS\n") && all.contains("\nFONTS\n") && all.contains("\nREPEAT OBJECTS\n"), + "{all}" + ); + app.session.execute("select.set", &json!({"ids": [text]})).unwrap(); + let selected = saved_from_menu(&mut app, "objects", true); + assert!(selected.contains("(the selection only)") && selected.contains("Text Objects: 1"), "{selected}"); + assert!(!selected.contains("Paths: 1") && !selected.contains("\nFONTS\n"), "the selection's objects only: {selected}"); + // The command takes the category too; an unknown one is an error and writes nothing. + let err = app.run("docInfo.save", json!({"path": "/tmp/info.txt", "category": "colors"})).unwrap_err(); + assert!(err.contains("category `colors`"), "{err}"); + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8f09432303..379c4b37b5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -646,7 +646,8 @@ Package: File → Package… (`ui.packageDialog`) opens the `package` dialog for gets a `confirm` dialog whose OK runs `file.saveAs`). Fields: `folder` (the location), `name` (the package folder), `copyLinks`, `linksFolder`, `relink`, `copyFonts`, `report`. `ui.dialog.confirm` saves unsaved changes, runs `file.package` and then opens a `confirm` dialog whose OK runs `file.showPackage {folder}`; the web downloads the zip -instead. Document Info's flyout picks a category and Save… runs `docInfo.save {path?, selectionOnly?}`. +instead. Document Info's flyout picks a category and Save… runs `docInfo.save {path?, selectionOnly?, category?}` with the +category the panel shows (none for All Categories, which writes every category). Slices: through the app, `object.slice.options` and `object.slice.divide` with no params open their dialogs on the selected slices. `sliceOptions` (fields `kind`: `image`/`noImage`/`htmlText`, `name`, `url`, `target`, `message`, diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..ac1eef8518 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4052,8 +4052,8 @@ groups and in other repeats included, with its type `radial`, `grid` or `mirror` and a grid's `rows` and `cols`; with `selectionOnly`, the Repeat objects in the selection) and `pathLength` (pt: the total length of the paths, compound paths' pieces included and guides left out, which objects lists as Path Length in the document's units, say for a cut line or an LED strip along the letters); -`format: "text"` returns the plain-text report Document Info › Save… (`docInfo.save {path?}`) and the package report -write. +`format: "text"` returns the plain-text report Document Info › Save… (`docInfo.save {path?, selectionOnly?, category?}`: +only `category` when given, else every category) and the package report write. ```json {"name":"run_command","arguments":{"command":"file.package","params":{"folder":"/tmp/handoff","copyFonts":false}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..e0eacde1e4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -986,6 +986,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Brushes panel's Delete Brush button and panel menu item ask "Delete the selected brushes?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page (archived copy) lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). + Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step. In Pattern Brush Options, a menu below the Outer Corner Tile and the Inner Corner Tile sets each to the brush's own corner art (Original), None, or a tile made from the side tile: Auto-Centered stretches one side tile around the corner, Auto-Between bends a side tile on each side into the corner's diagonal, Auto-Sliced cuts a side tile on each side along the diagonal, and Auto-Overlap runs a side tile on each side past the corner. Auto-Sliced masks the tiles at the diagonal, so their outlines stay as drawn. Brushes saved without these choices draw their corners as before (`brush.options` `outer_source`, `inner_source`). Evidence: `tests::pattern_auto_corners_fill_each_corner_of_a_square`, `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), `dialogs::brush_options::tests::pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile` (vectorcraft-ui-egui). From 1c6720a85c43d1297aaff0fa47ddd3929002d336 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 18:33:20 -0800 Subject: [PATCH 060/674] Recolor: a new color group keeps Global Adjust colors in Limit to Library OK on colors opened alone snaps each color the Global Adjust changed to the library's nearest color before saving the new group, as recolor.apply does for a group's colors. --- crates/ui-egui/src/dialogs/recolor.rs | 15 +++++++++++++-- crates/ui-egui/src/tests/recolor.rs | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1f319ca96e..70e69a78c5 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -353,12 +353,23 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); sync(app, &mut d); if d.bool("__newGroup") { - // The new colors with the Global Adjust, as `recolor.apply` gives them to a group. + // The new colors with the Global Adjust, snapped to Limit to Library, as `recolor.apply` + // gives them to a group. let adjust = global_adjust(adjust_values(&d)); + let limit = d.str("limitTo"); + let palette = Some(limit).filter(|l| !l.is_empty()).and_then(|l| swatchlib::limit_palette(&app.session, &l)); let colors: Vec = rows(&d) .into_iter() .filter(|r| !excluded(r)) - .map(|r| to_color(&r).filter(|_| !adjust.is_identity()).map_or_else(|| r["to"].clone(), |c| key(&adjust.apply(c)))) + .map(|r| { + to_color(&r).filter(|_| !adjust.is_identity()).map_or_else( + || r["to"].clone(), + |c| { + let c = adjust.apply(c); + key(&palette.as_ref().map_or(c, |p| p.nearest(c))) + }, + ) + }) .collect(); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 1786b7a614..0e7fe849b2 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -642,6 +642,24 @@ fn global_adjust_changes_every_color_at_once() { } } +/// Colors opened alone with Limit to Library: OK saves the new colors with the Global Adjust as a +/// new color group, each snapped to the library again, as `recolor.apply` gives them to a group. +#[test] +fn global_adjust_on_a_new_group_keeps_its_colors_in_the_library() { + let mut app = app(); + app.run("ui.recolorDialog", json!({"colors": ["#123456", "#abcdef"], "library": ""})).unwrap(); + assert_eq!(field(&app, "limitTo"), "web-safe-216"); + let web = |k: &Value| vectorcraft_engine::cmd::color_value(k).unwrap().to_rgb().iter().all(|v| ((v * 5.0).round() - v * 5.0).abs() < 1e-3); + let rows: Vec = field(&app, "rows").as_array().unwrap().iter().map(|r| r["to"].clone()).collect(); + assert!(rows.iter().all(web), "the rows open snapped: {rows:?}"); + set(&mut app, "globalAdjust", json!({"brightness": -60})); + dialogs::confirm(&mut app).unwrap(); + let keys = group_keys(&app, "Color Group"); + assert_eq!(keys.len(), 2); + assert_ne!(keys, rows, "the Global Adjust changed the colors"); + assert!(keys.iter().all(web), "every group color is a library color: {keys:?}"); +} + /// The Assign tab's per-row hex fields are named by their row, not all "Color": a screen reader can /// tell the second from the first. #[test] From bce3de36ca6b5b98d156004a7417f54e083c9e46 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 1 Nov 2026 23:27:52 -0500 Subject: [PATCH 061/674] Legacy .ai: docs say when the rotated-type warning shows, and record the change Co-Authored-By: Claude Opus 5.5 --- docs/mcp.md | 2 +- docs/target-app-parity.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 57f990dfe8..4a47d0dbc5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -844,7 +844,7 @@ of `range` (default all; `{name}-{artboard}.ai` when several, listed in the resu `transparentImages: "flatten"` (default) or `"omit"` for images with see-through pixels, opacity or a blending mode, `hiddenObjects: "layer"` (default: a hidden layer of each layer's hidden objects), `"omit"` or `"visible"`, and `outlineText: true` to write type as outlines instead of text objects. Type with rotated characters (Character -Rotation) is always written as outlines, which keep the rotation, with the warning "type with rotated characters is +Rotation) is always written as outlines, which keep the rotation; without `outlineText: true` this gives the warning "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)". An image that can't be decoded is left out of the file and does not show in art that is flattened or whose raster effects are expanded; `warnings` carries "an image diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 44d7b56c0c..31e65d51dd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Legacy `.ai` saves (version 7) write type with rotated characters as outlines that keep each character's rotation, with a warning unless `outlineText` is on (#5186); scores unchanged. | | 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | | 2026-10-31 | minor | New Document: More Settings has the Save Preset button beside the name too, saving its settings (artboard layout included) as a preset (#4893); scores unchanged. | | 2026-10-31 | minor | Object › Rasterize in a CMYK document with its CMYK colour model makes a CMYK image of the art's ink amounts (as CMYK exports draw them), so the Properties panel says CMYK and CMYK exports keep its inks; a transparent background becomes the image's opacity mask (#4882); scores unchanged. | @@ -1064,7 +1065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` or EPS opened from its editing data whose text document makes the type of every text object that shows takes all its type from the text document: each text object stays in its own group, frame and layer, the page's type isn't matched with them, a file of more than 5,000 text objects still opens with its layers, and type the page draws differently (in another font) keeps the layers, with a warning. A line break inside a paragraph stays a line break in it (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ate.rs`). In SVG export without Fewer `` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned ``, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. - Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text: a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). + Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304). In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). From 890c27ccb212fc020f7f94da8533d4aadb773571 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Sun, 1 Nov 2026 20:30:54 -0800 Subject: [PATCH 062/674] Native format: take the .vectorcraft envelope from craft-vectorcraft-format (#5146) * Native format: the .vectorcraft envelope comes from craft-vectorcraft-format vectorcraft-format reads and writes the file's envelope through the craft-vectorcraft-format crate in craft-libs: Head and Image, the version and size constants, the format and version check, Tail for the data after the JSON, split_tail and entry, and base64. The constants, is_compressed, json_part, base64_encode and base64_decode are re-exported from vectorcraft_format, so callers do not change. load_file reads the members it uses with Image entries and skips the preview and PDF data. The document, its migrations, the version 1 writer, gzip writing, sniff and the limits on decompression stay here. A preview or pdf member of the wrong shape now reads as missing on its own, so pdf_content still returns a file's PDF when its preview is damaged. A new test saves a document in every version, compressed and pretty, with a preview, profiles and a PDF, reads it back, saves it again and compares the bytes; it also reads each uncompressed file as the crate's File. Another reads the PDF of a file whose preview is damaged. * Native format: sniff from craft-vectorcraft-format, pinned at #408's head - craft-vectorcraft-format moves to craft-libs 0fd7e75fe6, the head of storytold/craft-libs#408. - `sniff` is the crate's: a file is native when its top-level `format` member, within the first 256 bytes after decompression, is `vectorcraft` or `drawcraft`, read with JSON escapes decoded. The word elsewhere in the head no longer counts. All 192 corpus files and their resaved copies get the same answer as before. - Envelope errors other than the format and the version keep the crate's message instead of reading as a compressed file that unpacks to too much. - A test checks that a repeated `generator`, `preview` or `pdf` opens and any other repeated member is refused, by `load_file` and by the crate's `Contents` alike. * Native format: read through the crate's Contents and Entries Pins craft-vectorcraft-format at 420a27f18f, the current head of craft-libs#408, and replaces VectorCraft's own copies with the crate's: - load_file reads the JSON through Contents::read, which also refuses another format or a newer version. Opened is removed. Messages are those of main: serde names the struct File, as main's reader did. - In-memory data after the JSON (uncompressed files, and compressed files unpacked whole) is read through the crate's Entries. entries_within keeps its streaming reader for compressed files, whose data is unpacked entry by entry and is never one slice in memory. - The streaming reader finds the marker through the crate's marker_at. - MAX_BLOB is the crate's MAX_ENTRY (1 GiB). save_to still writes the envelope member by member: it streams the document into the output and looks for the images it uses as it writes, and File would need the images before the document. A new test checks that its output, compact, pretty and compressed, for versions 1 to 4, equals serde_json::to_vec or to_vec_pretty of the crate's File holding the same members followed by the crate's Tail, so a change to either side fails. * Native format: pin craft-vectorcraft-format at craft-libs main craft-libs#408 merged as 14d5dbb50c; the crate is unchanged from 420a27f18f. A test checks that the crate's sniff takes every layout VectorCraft has written: the version 1 and 2 files from before the rename, compact and pretty, and each version save_with writes. --- Cargo.lock | 12 + Cargo.toml | 2 + crates/format/Cargo.toml | 3 +- crates/format/src/lib.rs | 410 +++++++++++++--------------- crates/format/src/unpack.rs | 50 ++-- crates/format/tests/it/native_v4.rs | 79 ++++++ 6 files changed, 311 insertions(+), 245 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 692dd5a91a..01b2e0e815 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1081,6 +1081,17 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-vectorcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=14d5dbb50c317b8747a9cf9eb35ab8a22515f137#14d5dbb50c317b8747a9cf9eb35ab8a22515f137" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-window" version = "0.1.0" @@ -6281,6 +6292,7 @@ dependencies = [ name = "vectorcraft-format" version = "0.20.0" dependencies = [ + "craft-vectorcraft-format", "flate2", "proptest", "rustix 1.1.6", diff --git a/Cargo.toml b/Cargo.toml index 3088b469b3..1876edbf7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,8 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # internal diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 55fbe7056a..fc6a060a5a 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -10,7 +10,8 @@ workspace = true [dependencies] vectorcraft-doc = { workspace = true } -serde = { workspace = true } +craft-vectorcraft-format = { workspace = true } +serde ={ workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } flate2 = { workspace = true } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index ad9df39ffd..6eb2e2bd35 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,33 +37,23 @@ mod legacy; mod stream; mod unpack; -use std::borrow::Cow; use std::collections::{BTreeMap, HashSet}; -use std::io::{Read as _, Write}; +use std::io::Write; use std::sync::Arc; -use serde::{Deserialize, Serialize}; +use craft_vectorcraft_format::{Contents, Head, Image, ReadError, Tail}; +use serde::Serialize; use vectorcraft_doc::{Document, ImageBlob}; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use craft_vectorcraft_format::base64::{decode as base64_decode, encode as base64_encode}; +pub use craft_vectorcraft_format::{ + BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part, + sniff, +}; use stream::{Gz, Indent, KeyScan, Out}; -/// v4: large data after the JSON (v1 to v3 files still load). -pub const VERSION: u32 = 4; -/// Data this large or larger goes after the JSON (v4), not into it as base64. -pub const INLINE_MAX: usize = 8 << 10; -/// What separates the JSON from the data after it (v4). -pub const BLOB_MAGIC: &[u8] = b"\n\0VCBLOBS\0"; -/// The oldest version [`save_with`] writes. -pub const MIN_VERSION: u32 = 1; -/// The first version whose readers open compressed files. -pub const COMPRESSED_SINCE: u32 = 3; -/// Most pixels on the longer side of an embedded preview. -pub const PREVIEW_MAX: u32 = 256; -pub const EXTENSION: &str = "vectorcraft"; -/// Extension and format name from before the project was renamed (DrawCraft): still opened. -pub const LEGACY_EXTENSION: &str = "drawcraft"; /// Most bytes the JSON of a compressed file may unpack to (a guard against decompression bombs, /// as are [`MAX_BLOB`] and [`MAX_BLOBS`]). A compressed save refuses a document past any of them, /// so every file VectorCraft writes reads back. On wasm32 the cap is a quarter of the native @@ -72,7 +62,7 @@ pub const LEGACY_EXTENSION: &str = "drawcraft"; pub const MAX_JSON: u64 = if cfg!(target_arch = "wasm32") { 256 << 20 } else { 1 << 30 }; /// Most bytes one entry of the data after the JSON (an image, a placed document, the PDF, a /// profile) may have in a compressed file. -pub const MAX_BLOB: u64 = 1 << 30; +pub const MAX_BLOB: u64 = craft_vectorcraft_format::MAX_ENTRY; /// Most bytes the entries after the JSON may have together in a compressed file: 1 GiB in the web /// build, whose 4 GiB address space also holds the JSON, the document and the app, so 4 GiB of /// entries failed to allocate rather than being refused. @@ -111,53 +101,17 @@ pub enum FormatError { Encode(String), } -#[derive(Serialize, Deserialize)] -struct Image { - mime: String, - /// The bytes as base64, unless they come after the JSON (`blob`). - #[serde(default, skip_serializing_if = "String::is_empty")] - data: String, - /// Where the bytes are in the data after the JSON (v4): `[offset, length]`. - #[serde(default, skip_serializing_if = "Option::is_none")] - blob: Option<[u64; 2]>, - /// `data` is a linked image's preview ([`ImageBlob::proxy`]), not the file's bytes. - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - proxy: bool, -} - -impl Image { - /// Its bytes when they are in the JSON (base64 `data`); `None` when they come after it - /// ([`Image::blob`]) or don't decode. - fn inline(&self) -> Option> { - match self.blob { - Some(_) => None, - None => base64_decode(&self.data), +impl From for FormatError { + fn from(e: craft_vectorcraft_format::Error) -> Self { + match e { + craft_vectorcraft_format::Error::Format(format) => FormatError::NotVectorcraft(format!("format is `{format}`")), + craft_vectorcraft_format::Error::TooNew(version) => FormatError::TooNew(version), + // The crate's other errors (`TooBig`: entries past the data after the JSON) keep their message. + e => FormatError::NotVectorcraft(e.to_string()), } } } -/// Entries written for one file: large bytes go to the data after the JSON when the version keeps -/// them there (in the order they are added, each at the offset it is given). -struct Blobs<'a> { - /// The bytes, and whether they are compressed already ([`is_packed`]). - tail: Vec<(&'a [u8], bool)>, - at: u64, - outside: bool, -} - -impl<'a> Blobs<'a> { - fn image(&mut self, mime: &str, bytes: &'a [u8], proxy: bool) -> Image { - if self.outside && bytes.len() >= INLINE_MAX { - let len = bytes.len() as u64; - let at = self.at; - self.at += len; - self.tail.push((bytes, is_packed(mime))); - return Image { mime: mime.into(), data: String::new(), blob: Some([at, len]), proxy }; - } - Image { mime: mime.into(), data: base64_encode(bytes), blob: None, proxy } - } -} - /// Is data of this MIME type compressed already (no use compressing it again)? fn is_packed(mime: &str) -> bool { matches!(mime, "image/jpeg" | "image/png" | "image/gif" | "image/webp") @@ -168,52 +122,6 @@ fn preview_mime(bytes: &[u8]) -> &'static str { if bytes.starts_with(&[0xff, 0xd8]) { "image/jpeg" } else { vectorcraft_doc::links::PROXY_MIME } } -/// The JSON of a native file without the data after it (version 4 keeps images there): a -/// complete JSON value whose `images` give each image's MIME type and where its data was, without -/// the data. -pub fn json_part(file: &[u8]) -> &[u8] { - split_tail(file).0 -} - -/// The JSON of a file and the data after it (v4), split at [`BLOB_MAGIC`] after the first JSON -/// value. -fn split_tail(text: &[u8]) -> (&[u8], &[u8]) { - // JSON holds no raw NUL, so the marker (which has one) starts at the first NUL, if the file - // has one. The writer puts it right after the JSON's last byte; found there, it is where the - // first JSON value ends, without parsing the JSON twice. Anything else takes the parse. - let Some(nul) = text.iter().position(|&b| b == 0) else { - // No NUL, so no marker: the parse below would find none either. - return (text, &[]); - }; - if let Some(at) = nul.checked_sub(1) - && text.get(at..).is_some_and(|r| r.starts_with(BLOB_MAGIC)) - && at.checked_sub(1).and_then(|k| text.get(k)).is_some_and(|b| matches!(b, b'}' | b']' | b'"')) - { - return (text.get(..at).unwrap_or(text), text.get(at + BLOB_MAGIC.len()..).unwrap_or_default()); - } - let mut values = serde_json::Deserializer::from_slice(text).into_iter::(); - if values.next().is_some_and(|v| v.is_ok()) { - let end = values.byte_offset(); - if let Some(rest) = text.get(end..) - && rest.starts_with(BLOB_MAGIC) - { - return (text.get(..end).unwrap_or(text), rest.get(BLOB_MAGIC.len()..).unwrap_or_default()); - } - } - (text, &[]) -} - -#[derive(Deserialize)] -struct File { - format: String, - version: u32, - document: Document, - #[serde(default)] - images: BTreeMap, - #[serde(default)] - profiles: BTreeMap, -} - /// How [`save_with`] writes a document. #[derive(Clone, Debug)] pub struct SaveOptions { @@ -239,9 +147,6 @@ impl Default for SaveOptions { } } -/// The MIME type of embedded ICC profiles. -pub const ICC_MIME: &str = "application/vnd.iccprofile"; - impl SaveOptions { /// Can a file be written this way (a version [`save_with`] writes, compressed only for readers /// that open compressed files)? @@ -369,7 +274,7 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For let pretty = o.pretty && !o.compress; let Body { d, v1, blobs, linked } = body(doc, o)?; let entries = Entries { blobs: &blobs, linked: &linked, include_linked: o.include_linked }; - let mut out_blobs = Blobs { tail: vec![], at: 0, outside: o.version >= 4 }; + let mut out_blobs = Tail::new(o.version); // Images are only referenced by image objects' `key` (wherever the objects are: layers, // symbols, patterns, masks, or foreign data). The data after the JSON has the images first, // then the profiles and the PDF, which the file lists before the document: with those, the @@ -382,7 +287,6 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For } let profiles: BTreeMap<&str, Image> = o.profiles.iter().map(|(name, icc)| (name.as_str(), out_blobs.image(ICC_MIME, icc, false))).collect(); let pdf = o.pdf.as_deref().map(|p| out_blobs.image("application/pdf", p, false)); - let blob = |mime: &str, bytes: &[u8]| Image { mime: mime.into(), data: base64_encode(bytes), blob: None, proxy: false }; let mut out = if o.compress { Out::Gz(Box::new(Gz::new(w).map_err(encode_err)?)) } else { Out::Plain(w) }; let mut env = Envelope { pretty, first: true }; // Older apps only know the name from before the rename. @@ -390,7 +294,7 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For env.field(&mut out, "version", &o.version)?; env.field(&mut out, "generator", &format!("VectorCraft {}", env!("CARGO_PKG_VERSION")))?; if let Some(png) = &o.preview { - env.field(&mut out, "preview", &blob("image/png", png))?; + env.field(&mut out, "preview", &Image::inline("image/png", png))?; } if !profiles.is_empty() { env.field(&mut out, "profiles", &profiles)?; @@ -412,22 +316,22 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For env.finish(&mut out)?; if o.compress { let json = out.written().unwrap_or(0); - let tail: Vec = out_blobs.tail.iter().map(|(b, _)| b.len() as u64).collect(); + let tail: Vec = out_blobs.parts().iter().map(|p| p.bytes.len() as u64).collect(); if json > MAX_JSON { return Err(FormatError::TooBigToCompress(format!("{} MB of document, at most {} MB", json >> 20, MAX_JSON >> 20))); } if let Some(big) = tail.iter().find(|&&n| n > MAX_BLOB) { return Err(FormatError::TooBigToCompress(format!("an image of {} MB, at most {} MB", big >> 20, MAX_BLOB >> 20))); } - if out_blobs.at > MAX_BLOBS { - return Err(FormatError::TooBigToCompress(format!("{} MB of images, at most {} MB", out_blobs.at >> 20, MAX_BLOBS >> 20))); + if out_blobs.len() > MAX_BLOBS { + return Err(FormatError::TooBigToCompress(format!("{} MB of images, at most {} MB", out_blobs.len() >> 20, MAX_BLOBS >> 20))); } } - if !out_blobs.tail.is_empty() { + if !out_blobs.is_empty() { out.write_all(BLOB_MAGIC).map_err(encode_err)?; - for &(bytes, packed) in &out_blobs.tail { - out.packed(packed).map_err(encode_err)?; - out.write_all(bytes).map_err(encode_err)?; + for part in out_blobs.parts() { + out.packed(is_packed(&part.mime)).map_err(encode_err)?; + out.write_all(part.bytes).map_err(encode_err)?; } } out.finish().map_err(encode_err) @@ -443,7 +347,7 @@ struct Entries<'a> { impl<'a> Entries<'a> { /// The entries of the images named in `used`, in the order of their names. - fn images(&self, used: &HashSet, out: &mut Blobs<'a>) -> BTreeMap<&'a str, Image> { + fn images(&self, used: &HashSet, out: &mut Tail<'a>) -> BTreeMap<&'a str, Image> { self.blobs .iter() .filter(|(k, _)| used.contains(k.as_str())) @@ -508,11 +412,6 @@ impl Envelope { } } -/// Is this gzip data (a compressed file)? -pub fn is_compressed(bytes: &[u8]) -> bool { - bytes.starts_with(&[0x1f, 0x8b]) -} - pub fn load(bytes: &[u8]) -> Result { load_info(bytes).map(|(doc, _)| doc) } @@ -563,22 +462,22 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result let file = unpack::Unpacked::new(bytes)?; // The JSON reader stops at 128 levels (a document's objects use three each), the paths read // at `MAX_READ_ANCHORS` anchors together, the document at `MAX_READ_NODES` objects, and the - // fields read before an object's type at `MAX_BUFFERED_VALUES` values. + // fields read before an object's type at `MAX_BUFFERED_VALUES` values. The preview and the + // PDF are skipped without being kept. let read = || { vectorcraft_doc::node::with_node_budget(max_nodes, || { - vectorcraft_doc::node::with_buffered_value_budget(max_values, || serde_json::from_slice::(file.json())) + vectorcraft_doc::node::with_buffered_value_budget(max_values, || Contents::::read(file.json())) }) }; - let f: File = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| { - let why = if e.to_string().contains("recursion limit") { format!("its objects are nested too deep ({e})") } else { e.to_string() }; - FormatError::NotVectorcraft(why) + let f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { + ReadError::Json(e) => { + let why = if e.to_string().contains("recursion limit") { format!("its objects are nested too deep ({e})") } else { e.to_string() }; + FormatError::NotVectorcraft(why) + } + ReadError::Envelope(e) => e.into(), + e => FormatError::NotVectorcraft(e.to_string()), })?; - if f.format != EXTENSION && f.format != LEGACY_EXTENSION { - return Err(FormatError::NotVectorcraft(format!("format is `{}`", f.format))); - } - if f.version > VERSION { - return Err(FormatError::TooNew(f.version)); - } + let info = FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION }; // The bytes after the JSON, read in one pass: the images' first, then the profiles'. let entries: Vec<[u64; 2]> = f.images.values().chain(f.profiles.values()).filter_map(|i| i.blob).collect(); let tail = file.entries(&entries)?; @@ -589,7 +488,7 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result let mut tail = tail.into_iter(); let mut bytes_of = |img: &Image| match img.blob { Some(_) => tail.next().flatten(), - None => img.inline().map(Arc::new), + None => base64_decode(&img.data).map(Arc::new), }; let mut doc = f.document; for (k, img) in f.images { @@ -652,14 +551,7 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result } }) .collect::>()?; - Ok(NativeFile { doc, depth_notes, info: FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION }, profiles }) -} - -/// The members of a native file besides its document (which is skipped, not decoded). -#[derive(Deserialize)] -struct Head { - preview: Option, - pdf: Option, + Ok(NativeFile { doc, depth_notes, info, profiles }) } /// The bytes of the member of the file's head `pick` picks (only that entry of the data after @@ -670,7 +562,7 @@ fn head_member(bytes: &[u8], pick: impl FnOnce(Head) -> Option) -> Option let img = pick(head)?; match img.blob { Some(at) => file.entries(&[at]).ok()?.pop().flatten().map(Arc::unwrap_or_clone), - None => img.inline(), + None => base64_decode(&img.data), } } @@ -685,71 +577,6 @@ pub fn pdf_content(bytes: &[u8]) -> Option> { head_member(bytes, |h| h.pdf) } -/// Does this look like a `.vectorcraft` file (compressed or not)? -pub fn sniff(bytes: &[u8]) -> bool { - const HEAD: usize = 256; - let head: Cow<'_, [u8]> = if is_compressed(bytes) { - let mut head = Vec::with_capacity(HEAD); - // A damaged stream may still unpack its start: judge what came out. - let _ = flate2::read::GzDecoder::new(bytes).take(HEAD as u64).read_to_end(&mut head); - Cow::Owned(head) - } else { - Cow::Borrowed(bytes.get(..HEAD).unwrap_or(bytes)) - }; - // The cut may split a character. - let s = String::from_utf8_lossy(&head); - s.trim_start().starts_with('{') && (s.contains("\"vectorcraft\"") || s.contains("\"drawcraft\"")) -} - -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -pub fn base64_encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for c in data.chunks(3) { - let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; - out.push(B64[(n >> 18) as usize & 63] as char); - out.push(B64[(n >> 12) as usize & 63] as char); - out.push(if c.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' }); - out.push(if c.len() > 2 { B64[n as usize & 63] as char } else { '=' }); - } - out -} - -pub fn base64_decode(s: &str) -> Option> { - let val = |c: u8| B64.iter().position(|&b| b == c).map(|p| p as u32); - let clean: Vec = s.bytes().filter(|b| !b.is_ascii_whitespace()).collect(); - if !clean.len().is_multiple_of(4) { - return None; - } - let mut out = Vec::with_capacity(clean.len() / 4 * 3); - let groups = clean.len() / 4; - for (i, c) in clean.chunks(4).enumerate() { - let mut n = 0u32; - let mut pad = 0; - for &b in c { - n <<= 6; - if b == b'=' { - pad += 1; - } else if pad > 0 { - return None; - } else { - n |= val(b)?; - } - } - if pad > 2 || (pad > 0 && i + 1 != groups) { - return None; - } - out.push((n >> 16) as u8); - if pad < 2 { - out.push((n >> 8) as u8); - } - if pad < 1 { - out.push(n as u8); - } - } - Some(out) -} - #[cfg(test)] mod tests { use super::*; @@ -778,6 +605,163 @@ mod tests { assert_eq!(load_info(v1.as_bytes()).unwrap().1, FileInfo { version: 1, legacy: false }); assert!(load_info(v1.as_bytes()).unwrap().1.is_old()); } + + /// A file is native when its top-level `format` member names VectorCraft, read as JSON reads + /// it; the word elsewhere in the head does not count. + #[test] + fn sniff_reads_the_format_member() { + // `vectorcraft` with its second `c` written as a JSON escape. + let escaped = [br#"{"format":"vector\"#.as_slice(), br#"u0063raft","version":4,"document":{}}"#].concat(); + assert!(sniff(&escaped)); + assert!(!sniff(br#"{"format":"other","generator":"vectorcraft"}"#)); + assert!(!sniff(br#"{"names":["vectorcraft"],"format":"svg"}"#)); + } + + /// Every layout VectorCraft has written puts `format` first: the version 1 and 2 files from + /// before the rename (a struct of `format`, `version`, `generator`, `document` and `images`, + /// compact or pretty), and each version `save_with` writes, compact, pretty and compressed. + #[test] + fn sniff_takes_every_layout_written() { + let before_rename = [ + r#"{"format":"drawcraft","version":1,"generator":"DrawCraft 0.1.0","document":{},"images":{}}"#, + "{\n \"format\": \"drawcraft\",\n \"version\": 2,\n \"generator\": \"DrawCraft 0.1.0\",\n \"document\": {},\n \"images\": {}\n}", + ]; + for text in before_rename { + assert!(sniff(text.as_bytes()), "{text}"); + } + let d = Document::new(10.0, 10.0); + for version in MIN_VERSION..=VERSION { + for (pretty, compress) in [(false, false), (true, false), (false, true)] { + let o = SaveOptions { pretty, compress, version, ..SaveOptions::default() }; + if o.check().is_err() { + continue; + } + let bytes = save_with(&d, &o).unwrap(); + assert!(sniff(&bytes), "version {version}, pretty {pretty}, compress {compress}"); + } + } + } + + /// An envelope error other than the format and version keeps the crate's message. + #[test] + fn envelope_errors_keep_their_message() { + let e = FormatError::from(craft_vectorcraft_format::Error::TooBig); + assert!(matches!(e, FormatError::NotVectorcraft(_)), "{e}"); + assert!(e.to_string().contains(&craft_vectorcraft_format::Error::TooBig.to_string()), "{e}"); + let e = FormatError::from(craft_vectorcraft_format::Error::Format("x".into())); + assert_eq!(e.to_string(), "not a VectorCraft file: format is `x`"); + assert!(matches!(FormatError::from(craft_vectorcraft_format::Error::TooNew(9)), FormatError::TooNew(9))); + } + + /// `save_to` writes the file member by member and streams the document in. For every version + /// it writes, compact, pretty and compressed, its bytes are those of the crate's `File` + /// holding the same members, serialized with `serde_json::to_vec` or `to_vec_pretty` and + /// followed by the crate's `Tail`. + #[test] + fn save_to_writes_the_bytes_of_the_crates_file() { + use std::io::Read; + + /// The document as `save_to` writes it: its version 1 form, or the document. + struct Written<'a>(&'a Body); + impl Serialize for Written<'_> { + fn serialize(&self, s: S) -> Result { + match &self.0.v1 { + Some(v) => v.serialize(s), + None => self.0.d.serialize(s), + } + } + } + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())).unwrap(); + // An image large enough to go after the JSON from version 4, a small one, and one that + // nothing uses. + let big: Vec = (0..INLINE_MAX as u32 + 5).map(|i| (i % 251) as u8).collect(); + for (key, bytes) in [("big", big), ("small", vec![1, 2, 3, 250]), ("unused", vec![9])] { + d.images.insert(key.into(), ImageBlob::new("image/png", bytes)); + } + for (i, key) in ["big", "small"].into_iter().enumerate() { + let img = d.alloc_id(); + let im = + ImageObject { key: key.into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), i + 1, Node::new(img, NodeKind::Image(Box::new(im)))).unwrap(); + } + let png = vec![0x89, b'P', b'N', b'G']; + let icc = vec![7u8; INLINE_MAX]; + let mut pdf = b"%PDF-1.7\n".to_vec(); + pdf.resize(INLINE_MAX + 1, b' '); + let full = SaveOptions { + preview: Some(png.clone()), + profiles: [("Gray".to_string(), icc.clone())].into(), + pdf: Some(pdf.clone()), + ..SaveOptions::default() + }; + let mut checked = 0; + for version in MIN_VERSION..=VERSION { + for members in [&full, &SaveOptions::default()] { + for pretty in [false, true] { + let o = SaveOptions { version, pretty, ..members.clone() }; + let b = body(&d, &o).unwrap(); + let mut file = craft_vectorcraft_format::File::new(Written(&b)); + file.format = if version < 3 { LEGACY_EXTENSION } else { EXTENSION }.into(); + file.version = version; + file.generator = Some(format!("VectorCraft {}", env!("CARGO_PKG_VERSION"))); + file.preview = o.preview.as_deref().map(|p| Image::inline("image/png", p)); + // The images come first in the data after the JSON, then the profiles and the PDF. + let mut tail = file.tail(); + for key in ["big", "small"] { + file.images.insert(key.into(), tail.image("image/png", b.blobs[key].bytes.as_slice(), false)); + } + for (name, icc) in &o.profiles { + file.profiles.insert(name.clone(), tail.image(ICC_MIME, icc, false)); + } + file.pdf = o.pdf.as_deref().map(|p| tail.image("application/pdf", p, false)); + let mut expected = if pretty { serde_json::to_vec_pretty(&file) } else { serde_json::to_vec(&file) }.unwrap(); + tail.write_to(&mut expected).unwrap(); + assert_eq!(tail.is_empty(), version < 4, "version {version}"); + assert!(save_with(&d, &o).unwrap() == expected, "version {version}, pretty {pretty}, {} profiles", o.profiles.len()); + checked += 1; + if version >= COMPRESSED_SINCE && !pretty { + let gz = save_with(&d, &SaveOptions { compress: true, ..o.clone() }).unwrap(); + let mut unpacked = Vec::new(); + flate2::read::GzDecoder::new(gz.as_slice()).read_to_end(&mut unpacked).unwrap(); + assert!(unpacked == expected, "version {version}, compressed, {} profiles", o.profiles.len()); + checked += 1; + } + } + } + } + assert_eq!(checked, 20); + } + + /// Files are read through the crate's `Contents` with the messages VectorCraft gave before, + /// and a top-level array holds the format, version, document, images and profiles in that + /// order. + #[test] + fn files_read_through_the_crates_contents_as_before() { + let message = |json: &str| load(json.as_bytes()).err().map(|e| e.to_string()); + assert_eq!( + message(r#""x""#).as_deref(), + Some(r#"not a VectorCraft file: invalid type: string "x", expected struct File at line 1 column 3"#) + ); + assert!( + message(r#"{"format":"vectorcraft","version":4}"#).is_some_and(|m| m.starts_with("not a VectorCraft file: missing field `document`")) + ); + let v: serde_json::Value = serde_json::from_slice(&save(&Document::new(10.0, 10.0), false)).unwrap(); + let doc = v["document"].to_string(); + let file = |format: &str, version: u32| format!(r#"{{"format":"{format}","version":{version},"document":{doc}}}"#); + assert_eq!(message(&file("svg", 4)).as_deref(), Some("not a VectorCraft file: format is `svg`")); + assert_eq!(message(&file("vectorcraft", 9)).as_deref(), Some("file version 9 is newer than this VectorCraft supports (4)")); + // A document that does not read is reported first, as before. + assert!( + message(r#"{"format":"vectorcraft","version":9,"document":7}"#).is_some_and(|m| m.starts_with("not a VectorCraft file: invalid type")) + ); + for json in [format!(r#"["vectorcraft",3,{doc},{{}},{{}}]"#), format!(r#"["vectorcraft",3,{doc}]"#)] { + assert_eq!(load(json.as_bytes()).map(|d| d.artboards.len()).ok(), Some(1), "{json}"); + } + assert!(load(format!(r#"["vectorcraft",3,{{}},{doc},{{}}]"#).as_bytes()).is_err()); + } use vectorcraft_doc::{Appearance, ImageObject, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect, shapes}; diff --git a/crates/format/src/unpack.rs b/crates/format/src/unpack.rs index d0833ad0f0..1573fa0bc7 100644 --- a/crates/format/src/unpack.rs +++ b/crates/format/src/unpack.rs @@ -7,9 +7,10 @@ use std::collections::HashMap; use std::io::{self, Read}; use std::sync::Arc; +use craft_vectorcraft_format::{Entries, marker_at, split_tail}; use flate2::read::GzDecoder; -use crate::{BLOB_MAGIC, FormatError, MAX_BLOB, MAX_BLOBS, MAX_JSON, MAX_UNPACKED, is_compressed, split_tail}; +use crate::{BLOB_MAGIC, FormatError, MAX_BLOB, MAX_BLOBS, MAX_JSON, MAX_UNPACKED, is_compressed}; /// Bytes unpacked at a time while looking for the end of the JSON. const CHUNK: u64 = 64 << 10; @@ -87,19 +88,16 @@ impl<'a> Unpacked<'a> { return Err(FormatError::TooBig); } } - let Some(z) = nul else { + if nul.is_none() { // No NUL, so no marker: all of it is JSON. if buf.len() as u64 > max_json { return Err(FormatError::TooBig); } return Ok(Self { json: Json::Owned(buf), tail: Tail::None }); - }; - // JSON holds no raw NUL, so the marker (which has one) starts right before the first NUL; - // the writer puts it right after the JSON's last byte. - if let Some(end) = z.checked_sub(1) - && buf.get(end..).is_some_and(|r| r.starts_with(BLOB_MAGIC)) - && end.checked_sub(1).and_then(|k| buf.get(k)).is_some_and(|b| matches!(b, b'}' | b']' | b'"')) - { + } + // The marker where the writer puts it, right after the JSON's last byte: what is unpacked + // so far reaches past it. + if let Some(end) = marker_at(&buf) { if end as u64 > max_json { return Err(FormatError::TooBig); } @@ -143,24 +141,17 @@ impl<'a> Unpacked<'a> { /// [`Self::entries`], unpacking at most `work` bytes of a streamed file to find them. fn entries_within(self, wanted: &[[u64; 2]], work: u64) -> Result, FormatError> { let mut out: Vec = vec![None; wanted.len()]; - // The entries read so far, by `[offset, length]`, and the bytes copied for them. - let mut done: HashMap<[u64; 2], Entry> = HashMap::new(); - let mut copied = 0u64; - let mut in_memory = |tail: &[u8], out: &mut Vec| { + // Data in memory is read through the crate's `Entries`: entries naming the same bytes + // share them, and the bytes copied stay within the data. + let in_memory = |tail: &[u8], out: &mut Vec| { + let mut entries = Entries::new(tail); for (slot, &w) in out.iter_mut().zip(wanted) { - if let Some(e) = done.get(&w) { - *slot = e.clone(); - continue; - } - let bytes = range(w[0], w[1]).and_then(|(a, b)| tail.get(a..b)); - copied = copied.saturating_add(bytes.map_or(0, |b| b.len() as u64)); - if copied > tail.len() as u64 { - return Err(FormatError::TooBig); - } - *slot = bytes.map(|b| Arc::new(b.to_vec())); - done.insert(w, slot.clone()); + *slot = entries.blob(w).map_err(|e| match e { + craft_vectorcraft_format::Error::TooBig => FormatError::TooBig, + e => e.into(), + })?; } - Ok(()) + Ok::<(), FormatError>(()) }; match self.tail { Tail::Slice(tail) => { @@ -179,6 +170,9 @@ impl<'a> Unpacked<'a> { Tail::Stream { file, at, read, rest } => { within(wanted, MAX_BLOB, MAX_BLOBS)?; drop(self.json); + // The entries read so far, by `[offset, length]`, and the bytes copied for them. + let mut done: HashMap<[u64; 2], Entry> = HashMap::new(); + let mut copied = 0u64; let mut order: Vec = (0..wanted.len()).collect(); order.sort_by_key(|&i| wanted.get(i).map_or(0, |w| w[0])); let mut s = Stream { r: Box::new(io::Cursor::new(read).chain(rest)), pos: 0, file, at, left: work }; @@ -220,12 +214,6 @@ fn within(wanted: &[[u64; 2]], each: u64, all: u64) -> Result<(), FormatError> { if total > all { Err(FormatError::TooBig) } else { Ok(()) } } -/// `offset..offset + len` as indices, when they fit. -fn range(offset: u64, len: u64) -> Option<(usize, usize)> { - let a = usize::try_from(offset).ok()?; - Some((a, a.checked_add(usize::try_from(len).ok()?)?)) -} - /// The data after a compressed file's JSON, being unpacked. struct Stream<'a> { r: Box, diff --git a/crates/format/tests/it/native_v4.rs b/crates/format/tests/it/native_v4.rs index c242316514..0a41b2d9e7 100644 --- a/crates/format/tests/it/native_v4.rs +++ b/crates/format/tests/it/native_v4.rs @@ -1,6 +1,7 @@ //! `.vectorcraft` v4: large data after the JSON (images, the PDF, profiles), small files still plain //! JSON, older versions inline, damaged offsets refused. +use std::collections::BTreeMap; use std::sync::Arc; use serde_json::Value; @@ -87,3 +88,81 @@ fn damaged_offsets_are_refused_not_a_crash() { assert!(load_file(json_only).is_err()); let _ = Arc::new(()); } + +/// A `preview` of the wrong shape reads as missing without hiding the file's PDF. +#[test] +fn a_damaged_preview_leaves_the_pdf_readable() { + let pdf = b"%PDF-1.7 small".to_vec(); + let o = SaveOptions { version: 3, preview: Some(vec![5; 30]), pdf: Some(pdf.clone()), ..SaveOptions::default() }; + let mut v: Value = serde_json::from_slice(&save_with(&doc_with_image("small", 100), &o).unwrap()).unwrap(); + v["preview"] = Value::from(5); + let damaged = serde_json::to_vec(&v).unwrap(); + assert_eq!(vectorcraft_format::preview(&damaged), None); + assert_eq!(pdf_content(&damaged), Some(pdf)); + assert!(load_file(&damaged).is_ok()); +} + +/// A repeated `generator`, `preview` or `pdf` opens, of any shape; any other repeated member is +/// refused. The crate's `Contents` and `File` accept and refuse the same files. +#[test] +fn repeated_members_open_only_when_skipped() { + let o = SaveOptions { version: 3, ..SaveOptions::default() }; + let text = String::from_utf8(save_with(&doc_with_image("small", 100), &o).unwrap()).unwrap(); + let document = serde_json::from_str::(&text).unwrap()["document"].to_string(); + let with = |members: &str| text.replacen('{', &format!("{{{members},"), 1); + let contents_reads = |s: &str| { + let contents = craft_vectorcraft_format::Contents::::read(s.as_bytes()).is_ok(); + assert_eq!(craft_vectorcraft_format::File::::read(s.as_bytes()).is_ok(), contents, "{s}"); + contents + }; + let skipped = with(r#""preview":5,"preview":{"mime":"image/png","data":"AA=="},"generator":[],"generator":"x","pdf":{},"pdf":null"#); + let back = load_file(skipped.as_bytes()).unwrap(); + assert_eq!(back.doc.images["small"].bytes.len(), 100); + assert!(contents_reads(&skipped)); + let document = format!(r#""document":{document}"#); + for member in [document.as_str(), r#""format":"vectorcraft""#, r#""version":3"#, r#""images":{}"#, r#""profiles":{}"#] { + let repeated = with(&format!("{member},{member}")); + let err = load_file(repeated.as_bytes()).err().unwrap_or_else(|| panic!("{member}: a repeated member opened")); + assert!(err.to_string().contains("duplicate field"), "{member}: {err}"); + assert!(!contents_reads(&repeated), "{member}: the crate's Contents read a repeated member"); + } +} + +/// A file read back and saved again with the same options gives the same bytes, in every version, +/// compressed or not, with a preview, profiles and a PDF inline and after the JSON. +#[test] +fn a_file_read_back_saves_to_the_same_bytes() { + let mut d = doc_with_image("big", INLINE_MAX + 10); + d.images.insert("small".into(), ImageBlob::new("image/png", vec![1, 2, 3])); + let l = d.layers[0].id; + let id = d.alloc_id(); + let im = ImageObject { key: "small".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 1, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + let profiles: BTreeMap> = [("Small".to_string(), vec![7; 40]), ("Large".to_string(), vec![9; INLINE_MAX])].into_iter().collect(); + for version in 1..=4 { + for compress in [false, true].into_iter().filter(|&c| !c || version >= 3) { + for pretty in [false, true] { + let o = SaveOptions { + version, + compress, + pretty, + preview: Some(vec![5; 300]), + profiles: profiles.clone(), + pdf: Some(vec![b'%'; INLINE_MAX * 2]), + ..SaveOptions::default() + }; + let first = save_with(&d, &o).unwrap(); + if !compress { + let json = vectorcraft_format::json_part(&first); + let env = craft_vectorcraft_format::File::::read(json).unwrap(); + assert_eq!((env.version, env.images.len(), env.profiles.len()), (version, 2, 2)); + assert!(env.preview.is_some() && env.pdf.is_some()); + } + let back = load_file(&first).unwrap(); + assert_eq!(back.profiles, profiles, "v{version} compress {compress} pretty {pretty}"); + let again = save_with(&back.doc, &SaveOptions { profiles: back.profiles, ..o }).unwrap(); + assert!(first == again, "v{version} compress {compress} pretty {pretty}: the second save differs"); + } + } + } +} From 9dbbe52a3c3d34cd2a0e139780bb94d340c1c908 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:13:31 -0800 Subject: [PATCH 063/674] Variables: Edit Data Set keeps an empty text value when OK changes nothing A row's empty text value fills its field with nothing, the same as a row without a value for that variable, and OK left every empty field out of dataset.set. An untouched OK therefore removed the empty value, and selecting the row afterward left the previous row's text on the art. Edit Data Set now marks the fields that hold the row's empty text value and keeps those values on OK. Typing in such a field, or setting it with ui.dialog.set, removes the mark, so emptying it still unsets the variable. --- crates/ui-egui/src/dialogs.rs | 6 +- crates/ui-egui/src/dialogs/variables.rs | 79 +++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6e86304e21..82cd2b8b00 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -443,11 +443,15 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { } /// Set `field` of `d` to `value` for `ui.dialog.set`, as the dialog's own control for it does: a -/// Pattern Brush Options corner tile set this way is saved by OK, as one chosen from its menu is. +/// Pattern Brush Options corner tile set this way is saved by OK, as one chosen from its menu is, +/// and an Edit Data Set field set this way is no longer the row's empty text value. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); } + if d.kind == variables::KIND { + variables::note_set(d, &field); + } d.fields.insert(field, value); } diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index d63ea55620..58cb18c861 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -86,6 +86,13 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool let Some(current) = vars.dataset(&name) else { return true }; fields.insert("name".into(), json!(name)); value_fields(&vars, Some(¤t.values), &mut fields); + // An empty text value is a value, but its field looks like a field with no value: + // mark it so OK keeps it until the field is edited. + for (var, value) in ¤t.values { + if matches!(value, DataValue::Text(t) if t.is_empty()) { + fields.insert(empty_marker(&value_key(var)), json!(true)); + } + } } "dataset.select" => { fields.insert("name".into(), json!("")); @@ -142,6 +149,12 @@ fn value_key(name: &str) -> String { format!("value:{name}") } +/// The key that marks the field `key` as holding the edited row's empty text value. Editing the +/// field removes the mark. +fn empty_marker(key: &str) -> String { + format!("__empty:{key}") +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { @@ -227,11 +240,23 @@ fn text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> egui::Respo let mut s = d.str(key); let r = ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(width)); if r.changed() { - d.fields.insert(key.into(), json!(s)); + set_text(d, key, s); } r } +/// Write a typed `s` into `key`. +fn set_text(d: &mut Dialog, key: &str, s: String) { + note_set(d, key); + d.fields.insert(key.into(), json!(s)); +} + +/// Records that `field` was typed in or set by `ui.dialog.set`: it no longer holds the row's +/// empty text value, so emptying it unsets the variable. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + d.fields.remove(&empty_marker(field)); +} + /// A checkbox for `key`, written back as it is toggled, which screen readers call `name`. fn checkbox(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str) { let b = d.bool(key); @@ -256,7 +281,8 @@ fn dropdown(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[&str], widt } /// The `values` object the dialog's fields mean: a text, image or graph variable whose field is -/// empty carries no value in this row, and a visibility checkbox is always a value — its false, +/// empty carries no value in this row, except a text variable whose value in the edited row was +/// already the empty text, which keeps it. A visibility checkbox is always a value — its false, /// too. fn values_of(d: &Dialog, vars: &Variables) -> Value { let mut out = serde_json::Map::new(); @@ -265,7 +291,7 @@ fn values_of(d: &Dialog, vars: &Variables) -> Value { match v.kind { VariableKind::Text | VariableKind::Image | VariableKind::Graph => { let text = d.str(&key); - if !text.is_empty() { + if !text.is_empty() || (v.kind == VariableKind::Text && d.bool(&empty_marker(&key))) { out.insert(v.name.clone(), json!(text)); } } @@ -282,7 +308,7 @@ fn text_area(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) { let mut s = d.str(key); let r = ui.add(egui::TextEdit::multiline(&mut s).desired_width(width).desired_rows(4)); if r.changed() { - d.fields.insert(key.into(), json!(s)); + set_text(d, key, s); } } @@ -371,6 +397,51 @@ mod tests { assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true})); } + #[test] + fn an_untouched_edit_keeps_an_empty_text_value() { + let mut app = app_with_variables(); + let id = app.run("text.create", json!({"x": 10, "y": 10, "text": "x"})).unwrap()["id"].as_u64().unwrap(); + app.run("variable.bind", json!({"variable": "Title", "ids": [id]})).unwrap(); + app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "", "Badge": true}})).unwrap(); + app.run("dataset.new", json!({"name": "Row 2", "values": {"Title": "Bob", "Badge": true}})).unwrap(); + app.run("dataset.select", json!({"name": "Row 1"})).unwrap(); + open(&mut app, "dataset.set", None); + assert_eq!(app.ui.dialog.as_ref().unwrap().str(&value_key("Title")), ""); + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"]["Title"], json!({"text": ""}), "OK with nothing changed keeps the empty text"); + app.run("dataset.select", json!({"name": "Row 2"})).unwrap(); + app.run("dataset.select", json!({"name": "Row 1"})).unwrap(); + assert_eq!(app.run("text.getRange", json!({"id": id})).unwrap()["text"], "", "the row still empties the text"); + // A field the user empties on a row that had a value still leaves the variable unset. + app.run("dataset.select", json!({"name": "Row 2"})).unwrap(); + open(&mut app, "dataset.set", None); + app.ui.dialog.as_mut().unwrap().fields.insert(value_key("Title"), json!("")); + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][1]["values"]["Title"], json!(null)); + // Typing into the empty text value's field and emptying it again unsets it too, and so + // does the same edit through `ui.dialog.set`. + for typed in [true, false] { + app.run("dataset.set", json!({"name": "Row 1", "values": {"Title": "", "Badge": true}})).unwrap(); + app.run("dataset.select", json!({"name": "Row 1"})).unwrap(); + open(&mut app, "dataset.set", None); + { + let d = app.ui.dialog.as_mut().unwrap(); + for s in ["a", ""] { + if typed { + set_text(d, &value_key("Title"), s.into()); + } else { + crate::dialogs::set_field(d, value_key("Title"), json!(s)); + } + } + } + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"]["Title"], json!(null), "typed: {typed}"); + } + } + #[test] fn selecting_a_dataset_from_the_dialog_applies_it() { let mut app = app_with_variables(); From 43b2733fc96b865416b0fd25fb05495b4a4dc66e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 12:17:39 -0800 Subject: [PATCH 064/674] Tests: move the empty text value test next to the new data set test --- crates/ui-egui/src/dialogs/variables.rs | 38 ++++++++++++------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index 58cb18c861..7fd8639ab8 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -378,25 +378,6 @@ mod tests { assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": false})); } - #[test] - fn editing_a_dataset_opens_with_the_rows_own_values() { - let mut app = app_with_variables(); - app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Hello", "Badge": false}})).unwrap(); - app.run("dataset.set", json!({"name": "Row 1", "values": {"Badge": true}})).unwrap(); - open(&mut app, "dataset.set", None); - { - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("name"), "Row 1"); - assert_eq!(d.str(&value_key("Title")), "", "the row carries no value for it"); - assert!(d.bool(&value_key("Badge")), "the row's own value"); - } - app.ui.dialog.as_mut().unwrap().fields.insert(value_key("Title"), json!("Changed")); - crate::dialogs::confirm(&mut app).unwrap(); - let sets = app.run("dataset.list", json!({})).unwrap(); - assert_eq!(sets["datasets"][0]["values"]["Title"], json!({"text": "Changed"})); - assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true})); - } - #[test] fn an_untouched_edit_keeps_an_empty_text_value() { let mut app = app_with_variables(); @@ -442,6 +423,25 @@ mod tests { } } + #[test] + fn editing_a_dataset_opens_with_the_rows_own_values() { + let mut app = app_with_variables(); + app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Hello", "Badge": false}})).unwrap(); + app.run("dataset.set", json!({"name": "Row 1", "values": {"Badge": true}})).unwrap(); + open(&mut app, "dataset.set", None); + { + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("name"), "Row 1"); + assert_eq!(d.str(&value_key("Title")), "", "the row carries no value for it"); + assert!(d.bool(&value_key("Badge")), "the row's own value"); + } + app.ui.dialog.as_mut().unwrap().fields.insert(value_key("Title"), json!("Changed")); + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"]["Title"], json!({"text": "Changed"})); + assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true})); + } + #[test] fn selecting_a_dataset_from_the_dialog_applies_it() { let mut app = app_with_variables(); From fa8d3b8de4f5800b4b9864374dc4f64b1c0a6ca9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:05:22 -0800 Subject: [PATCH 065/674] Fix #3797: documents open in Preview, and Outline is a setting of each document View > Outline was one app-wide flag saved in the interface preferences, so after Cmd+Y every later launch drew every opened or new document as outlines, with no fills. The flag is now part of each document's view: a document opens in Preview, each tab shows its own Outline or Preview, and the setting is not saved at launch. An older preferences file that holds the flag still loads, and its value is ignored. The Outline command and ui.set's outline act on the active document and are an error without one. --- crates/ui-egui/src/app/view.rs | 7 +++- crates/ui-egui/src/canvas.rs | 8 ++-- crates/ui-egui/src/canvas/outline.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 62 +++++++++++++++++++++++++++- crates/ui-egui/src/chrome/tabs.rs | 10 ++++- crates/ui-egui/src/chrome/tests.rs | 12 ++++++ crates/ui-egui/src/control.rs | 6 ++- crates/ui-egui/src/control/tests.rs | 18 ++++++++ crates/ui-egui/src/menus/labels.rs | 2 +- crates/ui-egui/src/menus/run.rs | 6 ++- crates/ui-egui/src/menus/state.rs | 3 +- crates/ui-egui/src/state.rs | 9 ++-- docs/control-protocol.md | 2 +- 13 files changed, 129 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 6aac1150e3..fd38968d2d 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -72,6 +72,11 @@ impl VectorcraftApp { self.session.active_index().and_then(|i| self.views.get(i)) } + /// Whether the active document is in Outline view (View › Outline); false without one. + pub fn outline_view(&self) -> bool { + self.view().is_some_and(|v| v.outline) + } + /// The zero point shown by rulers and position fields: the document's with global rulers, the /// active artboard's with artboard rulers. Command coordinates stay absolute. pub(crate) fn ruler_origin(&self) -> vectorcraft_geom::Point { @@ -88,7 +93,7 @@ impl VectorcraftApp { pub fn view_info(&self) -> ViewInfo { ViewInfo { zoom: self.view().map(|v| v.zoom).unwrap_or(1.0), - outline: self.ui.view.outline, + outline: self.outline_view(), smart_guides: self.ui.view.smart_guides, guides: self.ui.view.guides, snap_to_grid: self.ui.view.snap_to_grid, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4850b9e259..c867918bf2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -492,7 +492,7 @@ fn cache_key( cy: v.center.y, w, h, - outline: app.ui.view.outline, + outline: app.outline_view(), trim: app.ui.view.trim_view, templates: app.ui.view.templates, guides: app.ui.view.guides, @@ -560,7 +560,7 @@ fn frame_options( mask_view: Option, smooth_images: bool, ) -> vectorcraft_render::RenderOptions { - let opts = vectorcraft_render::RenderOptions { outline: app.ui.view.outline, background: None, artboards: false, ..Default::default() }; + let opts = vectorcraft_render::RenderOptions { outline: app.outline_view(), background: None, artboards: false, ..Default::default() }; vectorcraft_render::RenderOptions { proof: vectorcraft_render::proof::active_proof(), overprint_preview: vectorcraft_render::proof::overprint_preview_on(), @@ -669,7 +669,7 @@ fn paint_paper(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: &Xf, // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). let setup = &doc.setup; painter.rect_filled(rect, 0.0, if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }); - } else if !app.ui.view.outline { + } else if !app.outline_view() { let setup = &doc.setup; let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent).then(|| checker_texture(ui.ctx(), setup)); let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }; @@ -687,7 +687,7 @@ fn paint_paper(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: &Xf, } } } - } else if app.ui.view.outline { + } else if app.outline_view() { for ab in &doc.artboards { painter.add(Shape::convex_polygon(xf.quad(ab.rect), Color32::WHITE, Stroke::NONE)); } diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index b5d14e1519..9d1794ab7d 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -184,7 +184,7 @@ pub(super) fn hit_with( let prefs = &app.session.prefs; let opt = vectorcraft_doc::hit::HitOptions { tol: prefs.selection_tolerance / zoom, - outline: app.ui.view.outline, + outline: app.outline_view(), path_only: prefs.object_selection_by_path_only, type_path_only: prefs.type_selection_by_path_only, scope: app.session.active().and_then(|st| st.isolation), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4b59bdb8f6..1d1eb43148 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2588,7 +2588,7 @@ fn pan_fills_the_area_the_last_frame_leaves() { assert!(app.canvas.fill_worker.as_ref().unwrap().pending.is_none(), "the late fill was taken"); // A pan with Outline turned on: the frame shown's options are not the ones asked for, and // no fill is asked for. - app.ui.view.outline = true; + app.view_mut().unwrap().outline = true; app.view_mut().unwrap().center = Point::new(400.0, 150.0); frame(&mut app); assert!(jobs.try_iter().last().is_some_and(|j| j.key.outline), "the outline frame is on the worker"); @@ -3521,7 +3521,7 @@ fn scrolls_and_pans_move_the_view_by_whole_device_pixels() { /// another document, or when the device pixels a point changed. #[test] fn a_scrolls_leftover_pixel_part_carries_only_to_the_same_view() { - let view = View { zoom: 1.0, center: Point::new(100.0, 100.0), fitted: true, rotation: 0.0, artboard: 0 }; + let view = View { zoom: 1.0, center: Point::new(100.0, 100.0), fitted: true, rotation: 0.0, artboard: 0, outline: false }; let mut v = view; let rest = scroll_by(&mut v, 1, 1.0, vec2(0.4, -0.3), ScrollRest::default()); assert_eq!(v.center, view.center, "less than half a pixel does not move the view"); @@ -3765,6 +3765,64 @@ fn show_live_paint_gaps_draws_the_selected_groups_gaps_in_their_preview_color() assert!(!serde_json::from_value::(saved).unwrap().view.live_paint_gaps); } +/// #3797: View › Outline is a setting of each document's view. A document opened or made after +/// another was put in Outline opens in Preview, where a click inside its fill picks it, and each +/// document keeps its own setting. +#[test] +fn outline_is_per_document_and_new_documents_start_in_preview() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + app.sync_views(); + let inside = Point::new(70.0, 70.0); + let picks_fill = |app: &VectorcraftApp| super::outline::hit_at(app, inside, 1.0).is_some(); + assert!(picks_fill(&app), "Preview picks the fill"); + app.run("view.outline", json!({})).unwrap(); + assert!(app.outline_view() && app.view_info().outline); + assert!(!picks_fill(&app), "Outline picks only the path"); + // An SVG opened now opens in Preview, its fill drawn and picked. + let svg = + br##""##; + crate::io::open_bytes(&mut app, "b.svg", svg, None).unwrap(); + assert_eq!(app.session.active_index(), Some(1)); + assert!(!app.outline_view() && !app.view_info().outline, "the opened document is in Preview"); + assert!(picks_fill(&app)); + assert_eq!(crate::menus::dynamic_label(&app, "view.outline", "Outline"), "Outline"); + assert_eq!(crate::menus::checked(&app, "view.outline", &json!({})), Some(false)); + // A new document opens in Preview too. + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + assert!(!app.outline_view()); + // The first document is still in Outline. + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + assert!(app.outline_view() && !picks_fill(&app)); + assert_eq!(crate::menus::dynamic_label(&app, "view.outline", "Outline"), "Preview"); + assert_eq!(crate::menus::checked(&app, "view.outline", &json!({})), Some(true)); + // Without a document there is nothing to put in Outline. + while !app.session.documents().is_empty() { + app.session.execute("file.close", &json!({})).unwrap(); + } + app.sync_views(); + assert!(!app.outline_view() && !crate::menus::enabled(&app, "view.outline")); + assert!(app.run("view.outline", json!({})).is_err()); +} + +/// #3797: a preferences file saved while View › Outline was an interface setting still loads, with +/// its other view settings, and its Outline value does not put a document in Outline. +#[test] +fn old_outline_preference_loads_but_does_not_restore_outline() { + let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); + assert!(saved["view"].get("outline").is_none(), "Outline is not saved with the interface"); + saved["view"]["outline"] = json!(true); + saved["view"]["rulers"] = json!(true); + let ui = serde_json::from_value::(saved).unwrap().sanitized(); + assert!(ui.view.rulers, "the other view settings load"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui = ui; + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + assert!(!app.outline_view(), "a new document is in Preview"); +} + /// #511: a star shows a widget in each of its ten corners with Direct Selection (none with /// the Selection tool: it isn't a live shape); View → Hide Corner Widget hides them. #[test] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 99ca027cb2..fe01e91cc4 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -12,6 +12,13 @@ pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bo format!("{}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom, display_print_size).replace('%', " %")) } +/// The title of open document `i`'s tab, with its own view's zoom and Outline or Preview. +pub(super) fn doc_tab_title(app: &VectorcraftApp, i: usize, d: &vectorcraft_engine::DocState) -> String { + let view = app.views.get(i); + let zoom = view.map_or(1.0, |v| v.zoom); + tab_title(d, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -46,8 +53,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { .iter() .enumerate() .map(|(i, d)| { - let zoom = app.views.get(i).map(|v| v.zoom).unwrap_or(1.0); - let title = tab_title(d, zoom, app.ui.view.outline, app.session.prefs.display_print_size); + let title = doc_tab_title(app, i, d); let color = if Some(i) == active { t.text_strong } else { t.text_dim }; (title.clone(), ui.painter().layout_no_wrap(title, theme::semibold(title_size), color)) }) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index f32d3a9445..842ee1bc16 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -866,6 +866,18 @@ fn the_tab_title_names_the_opacity_mask_while_it_is_edited() { assert!(title(&s).ends_with("(RGB/Preview)")); } +/// #3797: each document's tab names its own Outline or Preview. +#[test] +fn only_the_outlined_documents_tab_reads_outline() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.run("view.outline", json!({})).unwrap(); + let titles: Vec = app.session.documents().iter().enumerate().map(|(i, d)| super::tabs::doc_tab_title(&app, i, d)).collect(); + assert!(titles[0].ends_with("(RGB/Preview)"), "{titles:?}"); + assert!(titles[1].ends_with("(RGB/Outline)"), "{titles:?}"); +} + /// One headless frame of the Control bar; returns the isolation button's rectangle, if it shows. fn isolation_button(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec) -> Option { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 300.0)); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a300757138..c586420a23 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -593,6 +593,10 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { let p = &req.params; let s = |k: &str| p.get(k).and_then(Value::as_str); + // Outline is a setting of the active document's view: without one, nothing is set. + if p.get("outline").is_some_and(Value::is_boolean) && app.session.active().is_none() { + return err("no document"); + } let mut r = Ok(Value::Null); if let Some(b) = s("brightness") { r = app.run("window.brightness", json!({"brightness": b})); @@ -613,7 +617,7 @@ fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { if let Some(want) = p.get(k).and_then(Value::as_bool) { let cur = match k { "rulers" => app.ui.view.rulers, - "outline" => app.ui.view.outline, + "outline" => app.outline_view(), "grid" => app.ui.view.grid, "smartGuides" => app.ui.view.smart_guides, _ => app.ui.view.bounding_box, diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 3e27607f39..ded29508ad 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -22,6 +22,24 @@ fn ui_set_turns_the_image_trace_preview_off_and_on() { } } +/// #3797: `ui.set` `outline` sets the active document's view; without a document it is an error +/// and sets nothing else either. +#[test] +fn ui_set_outline_sets_the_active_documents_view() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + for params in [json!({"outline": false}), json!({"outline": true, "grid": true})] { + let r = input_request(&mut app, "ui.set", params); + assert_eq!(r["ok"], false, "{r}"); + } + assert!(!app.ui.view.grid, "nothing is set"); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = input_request(&mut app, "ui.set", json!({"outline": true})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.outline_view()); + assert_eq!(app.views.iter().map(|v| v.outline).collect::>(), [false, true], "the other document stays in Preview"); +} + #[test] fn the_image_trace_preview_is_a_command() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index c95a17c461..d9888228c4 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -17,7 +17,7 @@ pub fn dynamic_label(app: &VectorcraftApp, id: &str, label: &str) -> String { fn view_toggle_label(app: &VectorcraftApp, id: &str) -> Option { let v = &app.ui.view; let text: String = match id { - "view.outline" => if v.outline { "Preview" } else { "Outline" }.into(), + "view.outline" => if app.outline_view() { "Preview" } else { "Outline" }.into(), "window.workspace.reset" => format!("Reset {}", app.ui.workspace), "view.edges" => if v.edges { "Hide Edges" } else { "Show Edges" }.into(), "view.template" => if v.templates { "Hide Template" } else { "Show Template" }.into(), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e7f80ecd81..b9e0b6ace9 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -184,7 +184,11 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { crate::panel_docking::reveal_panel(app, "separations").and_then(|_| app.session.execute(id, p).map_err(|e| e.to_string())) } - "view.outline" => flag(&mut app.ui.view.outline), + // Outline or Preview is a setting of the active document's view. + "view.outline" => match app.view_mut() { + Some(v) => flag(&mut v.outline), + None => Err("no document".into()), + }, _ => return None, }; Some(r) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index ad7f88c5c6..42456d7427 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -41,7 +41,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { selected_text(false).is_some_and(|t| t.vertical == (id == "type.orientation.vertical")) } "type.opticalMarginAlignment" => crate::panels::character::shared_text_flag(app, |t| t.optical_margin) == Some(true), - "view.outline" => v.outline, + "view.outline" => app.outline_view(), "view.pixelPreview" => v.pixel_preview, "view.trimView" => v.trim_view, "view.snapToPixel" => v.snap_to_pixel, @@ -205,6 +205,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { | "view.fitArtboard" | "view.fitAll" | "view.actualSize" + | "view.outline" | "view.rotate" => app.session.active().is_some(), "view.rotateToSelection" | crate::addons::arrange::ZOOM => app.session.active().is_some_and(|d| !d.selection.objects.is_empty()), id if id.starts_with("file.openRecent") => recent_slot(app, id).is_some(), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a78ee2b0f..533500d698 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -21,11 +21,15 @@ pub struct View { /// Size show it. #[serde(default)] pub artboard: usize, + /// View › Outline: the document's art is drawn as outlines. Each document has its own, and a + /// document opens in Preview. + #[serde(default)] + pub outline: bool, } impl Default for View { fn default() -> Self { - Self { zoom: 1.0, center: Point::new(306.0, 396.0), fitted: false, rotation: 0.0, artboard: 0 } + Self { zoom: 1.0, center: Point::new(306.0, 396.0), fitted: false, rotation: 0.0, artboard: 0, outline: false } } } @@ -45,6 +49,7 @@ impl View { fitted: true, rotation: if v.rotation.is_finite() { v.rotation } else { 0.0 }, artboard: 0, + outline: false, }) } } @@ -232,7 +237,6 @@ pub struct ViewFlags { pub guides: bool, pub smart_guides: bool, pub bounding_box: bool, - pub outline: bool, pub pixel_preview: bool, pub snap_to_grid: bool, pub snap_to_point: bool, @@ -271,7 +275,6 @@ impl Default for ViewFlags { guides: true, smart_guides: true, bounding_box: true, - outline: false, pixel_preview: false, snap_to_grid: false, snap_to_point: true, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8f09432303..d17704a530 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -101,7 +101,7 @@ the two can still win that race. | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | | `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls and Cmd- or Alt-wheel (Option on the Mac) zooms about the pointer; with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it | -| `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | +| `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | | `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value}` or `{fields: [{field, value}…]}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`), `__` fields, `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | From 06d037c1b254a2b944fcd8d48da17d2bc54d1ac4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:39:10 -0800 Subject: [PATCH 066/674] .ai import: a clipping path keeps its stroke A clipping path painted with a stroke (`W S`, `W B`) lost the stroke when a .ai file opened from its editing data. The clipping path now keeps it, and it paints over the clipped art as a clipping path's stroke does in VectorCraft. A gradient-filled clipping path stroked with `1 BB` or `2 BB` put the stroke on the painted copy of its fill, under the clipped art; it now goes on the clipping path too. Several clipping paths in one group make one compound path, which keeps their stroke, opacity and blend mode when they all have the same ones. --- crates/eps/src/import/ai/read/art.rs | 18 ++++++-- crates/eps/src/import/ai/read/containers.rs | 13 +++++- crates/eps/src/import/ai/tests.rs | 47 +++++++++++++++++++++ docs/file-format-parity.md | 2 +- 4 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index a32ea81daa..5e10d789f1 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -185,7 +185,8 @@ impl<'a> Reader<'a> { ..FillLayer::new(fill_paint.clone().unwrap_or(gs.fill.clone())) })); } - if stroke && !clip { + // A clipping path keeps its stroke, which paints over the art it clips. + if stroke { let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.width); st.cap = gs.cap; st.join = gs.join; @@ -297,11 +298,20 @@ impl<'a> Reader<'a> { Ok(()) } - /// Stroke the path just painted (a gradient-filled one, `1 BB` or `2 BB`) with the stroke's state. + /// Stroke the path just painted (a gradient-filled one, `1 BB` or `2 BB`) with the stroke's state. A clipping path + /// takes the stroke itself, not the painted copy of its fill. pub(super) fn stroke_last(&mut self) { let gs = self.gs.clone(); - let Some(n) = self.last_object() else { return }; - if !matches!(n.kind, NodeKind::Path { clipping: false, .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { + if !self.after_object { + return; + } + let Some(kids) = self.frames.last_mut().map(|f| &mut f.children) else { return }; + let Some(mut at) = kids.len().checked_sub(1) else { return }; + if kids.get(at).is_some_and(|n| self.clip_fills.contains(&n.id)) && at > 0 { + at -= 1; + } + let Some(n) = kids.get_mut(at) else { return }; + if !matches!(n.kind, NodeKind::Path { .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { return; } let mut st = StrokeLayer::new(gs.stroke.clone(), gs.width); diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 8d69d8114e..a894b425bf 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -195,8 +195,19 @@ impl<'a> Reader<'a> { 1 => clip.pop().map(|(_, n)| n), _ => { let rule = clip.first().map_or(FillRule::NonZero, |(_, n)| path_rule(n)); + // The compound path keeps the clipping paths' stroke, opacity and blend mode when they all have the same + // ones: it has one appearance for all its paths. + let look = |n: &Node| (n.appearance.clone(), n.opacity, n.blend); + let shared = + clip.split_first().and_then(|((_, first), others)| others.iter().all(|(_, n)| look(n) == look(first)).then(|| look(first))); let children = clip.into_iter().map(|(_, n)| Arc::new(n)).collect(); - Some(Node::new(self.doc.alloc_id(), NodeKind::Compound { children, rule })) + let mut n = Node::new(self.doc.alloc_id(), NodeKind::Compound { children, rule }); + if let Some((appearance, opacity, blend)) = shared { + n.appearance = appearance; + n.opacity = opacity; + n.blend = blend; + } + Some(n) } }; let clips = clip_node.is_some(); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index a0a24d8650..4d3e5e01c3 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -360,6 +360,53 @@ fn compound_paths_and_clipping() { assert!(*clip && matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); } +/// A stroked clipping path (`W S`, `W B`, or a gradient fill with `1 BB`) keeps its stroke on the clipping path, and a +/// fill goes on the painted copy under the clipped art. +#[test] +fn a_clipping_paths_stroke_stays_on_the_clipping_path() { + let blue = Some(Color::rgb(0.0, 0.0, 1.0)); + let red = Some(Color::rgb(1.0, 0.0, 0.0)); + // (clipping, fill colour, a gradient fill, stroke colour and width) of each of the clipping group's children. + let children = |doc: &Document| { + let NodeKind::Group { children, clip: true } = &art(doc)[0].kind else { panic!("{:?}", art(doc)[0].kind) }; + children + .iter() + .map(|c| { + let clipping = matches!(c.kind, NodeKind::Path { clipping: true, .. }); + (clipping, fill(c).color(), matches!(fill(c), Paint::Gradient(_)), c.appearance.stroke().map(|s| (s.paint.color(), s.width))) + }) + .collect::>() + }; + let under = rect_path(0.0, 0.0, 30.0, 30.0); + let clip = rect_path(5.0, 5.0, 25.0, 25.0); + let stroked = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nS\nQ\n"); + assert_eq!(children(&read_ok(&layer(&stroked)).doc), [(true, None, false, Some((blue, 3.0))), (false, red, false, None)]); + let both = format!("0 Ae\nq\n{RED}{under}f\n0 1 0 0 0 1 0 Xa\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nB\nQ\n"); + assert_eq!( + children(&read_ok(&layer(&both)).doc), + [(true, None, false, Some((blue, 3.0))), (false, Some(Color::rgb(0.0, 1.0, 0.0)), false, None), (false, red, false, None)] + ); + let defs = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n0 0 0 0 1 0 0 2 0 6 %_BS\n%_0 0 0 0 1 0 0 2 0 6 0 0 Bs\n\ + %_0 0 0 0 0 0 1 2 1 6 100 50 Bs\nBD\n%AI5_EndGradient\n"; + let gradient = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nBb\n0 0 0 0 Bh\n1 (G) 5 5 0 20 1 0 0 1 0 0 1 Bg\nf\n1 BB\nQ\n"); + assert_eq!( + children(&read_ok(&format!("{defs}{}", layer(&gradient))).doc), + [(true, None, false, Some((blue, 3.0))), (false, None, true, None), (false, red, false, None)] + ); + // Several clipping paths clip as one compound path, which keeps their stroke when they all have the same one. + let inner = rect_path(10.0, 10.0, 20.0, 20.0); + let compound_stroke = |first: &str, second: &str| { + let body = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{first}{clip}W\nS\n{second}{inner}W\nS\nQ\n"); + let doc = read_ok(&layer(&body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }), "{:?}", children[0].kind); + (children[0].appearance.stroke().map(|s| (s.paint.color(), s.width)), children[0].opacity, children[0].blend) + }; + assert_eq!(compound_stroke("", ""), (Some((blue, 3.0)), 1.0, BlendMode::Normal)); + assert_eq!(compound_stroke("9 0.5 0 0 0 Xy\n", ""), (Some((blue, 3.0)), 0.5, BlendMode::Lighten)); + assert_eq!(compound_stroke("", "5 w\n"), (None, 1.0, BlendMode::Normal), "strokes that differ"); +} + /// A clipping group's clipping path can sit alone in a group of its own, after the art it clips (`q … u W n U /// … Q`): it still clips the clipping group. #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 11440516d7..1f2f14bd81 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -88,7 +88,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format From db1144650232e481c3c9c3bffbfd399e349a203e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:55:44 -0800 Subject: [PATCH 067/674] .ai import: legacy type keeps its spacing, hanging punctuation and hyphenation Legacy type (`To` ... `TO`) now reads `min opt max TC` and `min opt max TW` into the paragraph's letter and word spacing, `hangingQuotes Tq` into Roman hanging punctuation, and `hyphenate limit lead tail max Th` into hyphenation on or off, After First, Before Last and the Hyphen Limit (0 when the limit flag is 0). Values are kept to the ranges the Justification and Hyphenation options take, and a spacing triple out of order goes back to its default. Operands of the legacy type attributes are read by their place: an attribute whose operands are missing, are not numbers, or are flags other than 0 and 1 stays as it was. Before, a value that was not a number shifted the later operands (`5 /x 7 Ti` set indents of 5, 7 and 0), and a bad `TA` or `Ta` turned kerning on or set the alignment to left. One long `Tx` no longer goes past the reader's limit on characters. --- crates/engine/tests/import_fuzz.rs | 7 + crates/eps/src/import/ai/legacy_text.rs | 158 ++++++++++++++++----- crates/eps/src/import/ai/read/ops.rs | 16 +-- crates/eps/src/import/ai/tests.rs | 107 ++++++++++++++ crates/eps/src/import/tests_illustrator.rs | 11 ++ docs/file-format-parity.md | 3 +- 6 files changed, 258 insertions(+), 44 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 931963de39..c54c8e1335 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3310,6 +3310,13 @@ fn arb_ai_token() -> impl Strategy { "9 Ta", "1e308 -1e308 1e308 Ti", "0 1 Tk", + "-1e308 0 1e308 TC", + "1e308 -1 5 TW", + "/x 100 200 TW", + "1 Tq", + "7 Tq", + "1 1 1e308 -1e308 4e9 Th", + "1 1 (2) 3 4 Th", "[39/quotesingle 128/Euro/eacute/nosuch 300/x TE", "[1e308/a -1/b TE", "\n%AI3_BeginEncoding: _Helvetica Helvetica\n[/_Helvetica/Helvetica 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n", diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 126619c13e..fec2539304 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -1,6 +1,7 @@ //! Type in the legacy format (version 7 specification §15): text objects `type To` … `TO`, their //! text path (`a b c d tx ty startPt Tp`, an area's frame or the path type runs along, `TP`), the -//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`), the paint style, and +//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's +//! letter and word spacing `TC TW`, hanging punctuation `Tq` and hyphenation `Th`), the paint style, and //! the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Final-form operators (the //! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the //! file's `TE` encoding, else as Windows-1252; a re-encoded font `/_name` is the font its @@ -78,8 +79,23 @@ impl TypeState { } } -fn num(vals: &[V], i: usize) -> Option { - vals.iter().filter_map(V::num).nth(i).filter(|v| v.is_finite()) +/// An operator's `N` operands, the last `N` values before it, when each is a finite number. +fn nums(vals: &[V]) -> Option<[f64; N]> { + let operands = vals.get(vals.len().checked_sub(N)?..)?; + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(operands) { + *o = v.num().filter(|n| n.is_finite())?; + } + Some(out) +} + +/// A flag operand: 0 or 1. +fn flag(v: f64) -> Option { + match v { + 0.0 => Some(false), + 1.0 => Some(true), + _ => None, + } } impl Reader<'_> { @@ -110,23 +126,28 @@ impl Reader<'_> { /// `type To`: a text object begins. pub(super) fn begin_text(&mut self, vals: &[V], hidden: bool) { self.end_path_quietly(); - let kind = num(vals, 0).map_or(0, |k| k as i64); + let kind = nums::<1>(vals).map_or(0, |[k]| k as i64); self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() }); } /// `a b c d tx ty startPt Tp`: the text path begins. pub(super) fn begin_text_path(&mut self, vals: &[V]) { self.end_path_quietly(); - let n: Vec = vals.iter().filter_map(V::num).collect(); let Some(t) = self.text.as_mut() else { return }; - if let Some(m) = n.get(..6).and_then(|m| <[f64; 6]>::try_from(m).ok()) { + // Seven operands, or the matrix alone. + let (m, start) = match vals.len() { + 7 => (vals.get(..6).and_then(nums::<6>), vals.get(6).and_then(V::num)), + 6 => (nums::<6>(vals), None), + _ => (None, None), + }; + if let Some(m) = m { let m = Affine::new(m); let det = m.determinant(); - if m.as_coeffs().iter().all(|v| v.is_finite()) && det.is_finite() && det.abs() > 1e-12 { + if det.is_finite() && det.abs() > 1e-12 { t.matrix = Some(m); } } - t.start = n.get(6).copied().filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); + t.start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); t.in_path = true; } @@ -150,56 +171,122 @@ impl Reader<'_> { } } - /// A character or paragraph attribute. + /// A character or paragraph attribute. An attribute whose operands are missing, are not + /// numbers, or are flags other than 0 and 1 stays as it was. pub(super) fn text_attr(&mut self, w: &str, vals: &[V]) { let st = &mut self.type_state; - let n0 = num(vals, 0); + let n0 = nums::<1>(vals).map(|[v]| v); match w { - "Tr" => st.render = n0.map_or(0, |v| v as i64), + "Tr" => { + if let Some(v) = n0 { + st.render = v as i64; + } + } "Tf" => { - if let Some(name) = vals.iter().find_map(|v| if let V::Name(n) = v { Some(n.clone()) } else { None }) { - let name = st - .fonts - .iter() - .find(|(new, _)| *new == name) - .map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); + // `/name size Tf`, or `/name size ascent descent Tf`. + let Some(at) = vals.iter().position(|v| matches!(v, V::Name(_))) else { return }; + if let Some(V::Name(name)) = vals.get(at) { + let name = + st.fonts.iter().find(|(new, _)| new == name).map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); let (family, style) = super::super::super::text::family_style(&name); st.style.font_family = family; st.style.font_style = style; st.style.font_version = None; } - if let Some(size) = num(vals, 0).filter(|s| *s > 0.0) { + if let Some(size) = vals.get(at + 1).and_then(V::num).filter(|s| s.is_finite() && *s > 0.0) { st.style.size = size.min(MAX_SIZE); } } - "Ts" => st.style.baseline_shift = n0.unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE), + "Ts" => { + if let Some(v) = n0 { + st.style.baseline_shift = v.clamp(-MAX_SIZE, MAX_SIZE); + } + } "Tz" => { + // `parallelScale perpendicularScale Tz`; before version 7, `scale Tz`. let scale = |v: f64| v.clamp(1.0, 10_000.0); - st.style.h_scale = n0.map_or(100.0, scale); - st.style.v_scale = num(vals, 1).map_or(100.0, scale); + let scales = match vals.len() { + 2 => nums::<2>(vals), + 1 => n0.map(|h| [h, 100.0]), + _ => None, + }; + if let Some([h, v]) = scales { + (st.style.h_scale, st.style.v_scale) = (scale(h), scale(v)); + } + } + "Tt" => { + if let Some(v) = n0 { + st.style.tracking = v.clamp(-10_000.0, 10_000.0); + } + } + "TA" => { + if let Some(auto) = n0.and_then(flag) { + st.style.kerning = if auto { None } else { Some(0.0) }; + } } - "Tt" => st.style.tracking = n0.unwrap_or(0.0).clamp(-10_000.0, 10_000.0), - "TA" => st.style.kerning = if n0 == Some(0.0) { Some(0.0) } else { None }, "Tl" => { - if let Some(l) = n0 { + // `leading paragraphLeading Tl`; before version 7, `leading Tl`. + let leading = match vals.len() { + 2 => nums::<2>(vals), + 1 => n0.map(|l| [l, 0.0]), + _ => None, + }; + if let Some([l, before]) = leading { let l = l.clamp(0.0, MAX_SIZE); // The automatic leading, 120% of the size, stays automatic. st.style.leading = if (l - st.style.size * 1.2).abs() < 1e-3 { None } else { Some(l) }; + st.para.space_before = before.clamp(-MAX_SIZE, MAX_SIZE); } - st.para.space_before = num(vals, 1).unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE); } "Ta" => { - st.para.justify = match n0.map(|v| v as i64) { - Some(1) => Justify::Center, - Some(2) => Justify::Right, - Some(3) => Justify::JustifyLeft, - Some(4) => Justify::JustifyAll, - _ => Justify::Left, + let justify = match n0 { + Some(0.0) => Some(Justify::Left), + Some(1.0) => Some(Justify::Center), + Some(2.0) => Some(Justify::Right), + Some(3.0) => Some(Justify::JustifyLeft), + Some(4.0) => Some(Justify::JustifyAll), + _ => None, + }; + if let Some(j) = justify { + st.para.justify = j; } } "Ti" => { - let indent = |i: usize| num(vals, i).unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE); - (st.para.first_line_indent, st.para.left_indent, st.para.right_indent) = (indent(0), indent(1), indent(2)); + if let Some(i) = nums::<3>(vals) { + let [first, left, right] = i.map(|v| v.clamp(-MAX_SIZE, MAX_SIZE)); + (st.para.first_line_indent, st.para.left_indent, st.para.right_indent) = (first, left, right); + } + } + // `min opt max TC` (letter spacing) and `min opt max TW` (word spacing), in percent of + // a space's width, as the paragraph's Justification options take them. + "TC" | "TW" => { + if let Some(v) = nums::<3>(vals) { + let j = &mut st.para.justification; + if w == "TC" { + j.letter_spacing = v; + } else { + j.word_spacing = v; + } + j.keep_in_range(); + } + } + // `hangingQuotes Tq`. + "Tq" => { + if let Some(on) = n0.and_then(flag) { + st.para.roman_hanging = on; + } + } + // `hyphenate limitHyphLines minLeadHyphen minTailHyphen maxHyphLines Th`, kept to the + // ranges `text.setFormat` takes. + "Th" => { + let Some([on, limit, lead, tail, max]) = nums::<5>(vals) else { return }; + let (Some(on), Some(limit)) = (flag(on), flag(limit)) else { return }; + let letters = |v: f64, lo: f64, hi: f64| v.round().clamp(lo, hi) as u32; + st.para.hyphenate = on; + let h = &mut st.para.hyphenation; + h.after_first = letters(lead, 1.0, 15.0); + h.before_last = letters(tail, 1.0, 15.0); + h.hyphen_limit = if limit { letters(max, 0.0, 25.0) } else { 0 }; } _ => {} } @@ -222,9 +309,12 @@ impl Reader<'_> { t.pending_break = true; return; } - if st.chars >= MAX_CHARS { + // As many characters as the file's allowance has left. + let room = MAX_CHARS.saturating_sub(st.chars); + if room == 0 { return; } + let decoded: String = decoded.chars().take(room).collect(); st.chars += decoded.chars().count(); let gs = &self.gs; let mut style = st.style.clone(); diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 7e7b797468..f48a8df82a 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -276,15 +276,13 @@ impl<'a> Reader<'a> { "TP" => self.end_text_path(), "TO" => self.end_text(hidden)?, "Tx" | "Tj" | "TX" => self.text_body(w, &vals), - "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" => self.text_attr(w, &vals), - // Attributes the reader doesn't keep (kerning pairs, spacing, hanging punctuation, - // Far-Eastern type) and final-form positions (§15.3). - "Tk" | "TK" | "TC" | "TW" | "Tq" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" - | "Tu" | "Xu" => {} - // Hyphenation and tab-ruler attributes the reader doesn't keep either (§22): `Th` - // hyphen control, `XL` hyphenation language, `Xb`/`XB` a tab definition (and the `Xe` - // tab descriptions between them). - "Th" | "XL" | "Xb" | "XB" | "Xe" => {} + "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" => self.text_attr(w, &vals), + // Attributes the reader doesn't keep (kerning pairs, Far-Eastern type) and final-form + // positions (§15.3). + "Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" | "Tu" | "Xu" => {} + // The hyphenation language and tab rulers, which the reader doesn't keep either (§22): `XL`, + // `Xb`/`XB` a tab definition (and the `Xe` tab descriptions between them). + "XL" | "Xb" | "XB" | "Xe" => {} "TE" => self.te(&vals), // An image whose samples follow in comment lines (read at `%AI5_EndRaster`). "XI" if self.raster.is_some() => { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 4d3e5e01c3..c53209fbc8 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3149,3 +3149,110 @@ fn an_objects_on_path_group_in_versioned_content_opens_once() { assert_eq!(kids[0].children().unwrap().len(), 5); assert!(kids[0].extras().objects_on_path.is_some()); } + +/// A file in the legacy format (version 7) whose layer holds `art`, crop marks 0 0 200 100. +fn stream7(art: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 3.0\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n", + layer(art) + ) +} + +/// The text objects of a legacy-format file whose layer holds `art`. +fn legacy_texts(art: &str) -> Vec { + let doc = match read(stream7(art).as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc) +} + +fn art_texts(doc: &Document) -> Vec { + art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() +} + +/// Point type at (10, 50): `attrs`, then the characters `text`. +fn point_type(attrs: &str, text: &str) -> String { + format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") +} + +/// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging +/// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its +/// first character, and they last into the next text object. +#[test] +fn legacy_type_keeps_its_spacing_hanging_punctuation_and_hyphenation() { + let two_paragraphs = + point_type("10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th", "One\\r").replace("TO\n", "0 0 5 TC\n0 Tq\n0 0 4 5 6 Th\n(Two) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "Three"))); + assert_eq!(texts.len(), 2); + let one = texts[0].para_at(0); + assert_eq!(one.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(one.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(one.roman_hanging && one.hyphenate); + let h = &one.hyphenation; + assert_eq!((h.after_first, h.before_last, h.hyphen_limit), (2, 3, 4)); + assert_eq!(h.words_longer_than, vectorcraft_doc::text::HyphenationOptions::default().words_longer_than, "no operand sets it"); + let two = texts[0].para_at(1); + assert_eq!(two.justification.letter_spacing, [0.0, 0.0, 5.0]); + assert_eq!(two.justification.word_spacing, [70.0, 110.0, 140.0], "word spacing stays"); + assert!(!two.roman_hanging && !two.hyphenate); + // Without the limit flag, any number of hyphens in a row. + assert_eq!((two.hyphenation.after_first, two.hyphenation.before_last, two.hyphenation.hyphen_limit), (4, 5, 0)); + // The next text object keeps them. + assert_eq!(texts[1].para_at(0), two); +} + +/// A legacy attribute whose operands are missing, are not numbers, or are flags other than 0 and +/// 1 leaves the attribute as it was, and operands are read by their place. +#[test] +fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { + let set = "10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th\n2 Ta\n0 TA\n5 6 7 Ti"; + let bad = "/x 15 20 TC\n110 140 TW\n2 Tq\n1 2 2 3 4 Th\n1 1 (2) 3 4 Th\n/x Ta\n2 TA\n5 /x 7 Ti"; + let texts = legacy_texts(&point_type(&format!("{set}\n{bad}"), "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(p.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(p.roman_hanging && p.hyphenate); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 3, 4)); + assert_eq!(p.justify, vectorcraft_doc::Justify::Right); + assert_eq!((p.first_line_indent, p.left_indent, p.right_indent), (5.0, 6.0, 7.0)); + assert_eq!(texts[0].runs[0].style.kerning, Some(0.0), "kerning stays off"); + // A scale or leading pair with a bad operand leaves both as they were; one operand is the + // horizontal scale (or the leading) of the format before version 7. + let texts = legacy_texts(&point_type("50 80 Tz\n14 3 Tl\n/x 120 Tz\n/x 20 Tl", "Hi")); + let st = &texts[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale, st.leading), (50.0, 80.0, Some(14.0))); + assert_eq!(texts[0].para_at(0).space_before, 3.0); + let st = &legacy_texts(&point_type("50 80 Tz\n120 Tz", "Hi"))[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale), (120.0, 100.0)); + // A start point that isn't a number leaves the matrix. + let good = &legacy_texts(&point_type("", "Hi"))[0]; + let bad = &legacy_texts(&point_type("", "Hi").replace("10 50 0 Tp", "10 50 /x Tp"))[0]; + assert_eq!(bad.xf, good.xf); +} + +/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum +/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges +/// `text.setFormat` takes. +#[test] +fn legacy_type_spacing_and_hyphenation_are_kept_in_range() { + let texts = legacy_texts(&point_type("-500 0 900 TC\n0 2000 5000 TW\n1 1 0 40 99 Th", "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [-100.0, 0.0, 500.0]); + assert_eq!(p.justification.word_spacing, [0.0, 1000.0, 1000.0]); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (1, 15, 25)); + let texts = legacy_texts(&point_type("5 0 0 TC\n200 100 80 TW", "Hi")); + let j = &texts[0].para_at(0).justification; + let d = vectorcraft_doc::text::JustificationOptions::default(); + assert_eq!((j.letter_spacing, j.word_spacing), (d.letter_spacing, d.word_spacing)); +} + +/// A file's legacy type is read up to its allowance of characters, a single long run included. +#[test] +fn one_long_run_of_legacy_type_stops_at_the_allowance() { + // The reader's allowance, `MAX_CHARS`. + const ALLOWANCE: usize = 1 << 22; + let long = "a".repeat(ALLOWANCE + 10); + let texts = legacy_texts(&point_type("", &long)); + assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); +} diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 7543e51588..f83475638d 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -147,6 +147,17 @@ fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() { let r = import(src.as_bytes()).unwrap(); assert!(!r.preview, "read through the layers, not a fallback preview"); assert!(!r.warnings.iter().any(|w| w.contains("doesn't know") || w.contains("couldn't be read")), "{:?}", r.warnings); + // `Th` sets the paragraph's hyphenation: off, 2 letters before and after a hyphen, and the + // limit of 99 hyphens in a row kept to the 25 `text.setFormat` takes. + let mut texts = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + texts.push(t.para_at(0).clone()); + } + }); + let [p] = texts.as_slice() else { panic!("{texts:?}") }; + assert!(!p.hyphenate); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25)); } /// An Illustrator 3 file of paths alone, as image editors export their paths (storytold/photocraft#6036): diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 1f2f14bd81..98260d60a3 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -81,7 +81,8 @@ private editing data. VectorCraft: 14; #868: round trip with Illustrator 2018 loses layers and groups), guides and non-printing construction lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` - without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. + without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, with its paragraphs' letter + and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). - Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. From c21ff5698eefa8c54899d2cfa96a9c6d222546e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 13:55:56 -0800 Subject: [PATCH 068/674] Tests: move the legacy type tests next to the text object tests The legacy type helpers and tests move from the end of crates/eps/src/import/ai/tests.rs to after text_objects_are_slots_named_after_their_story, and the helper stream7 is renamed type_stream7. --- crates/eps/src/import/ai/tests.rs | 214 +++++++++++++++--------------- 1 file changed, 107 insertions(+), 107 deletions(-) diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index c53209fbc8..92c9a46457 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1183,6 +1183,113 @@ fn text_objects_are_slots_named_after_their_story() { assert_eq!((a.len(), a[0].children().map(Vec::len), slot_of(a[1].name.as_deref())), (2, Some(1), Some(Some(7)))); } +/// A file in the legacy format (version 7) whose layer holds `art`, crop marks 0 0 200 100. +fn type_stream7(art: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 3.0\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n", + layer(art) + ) +} + +/// The text objects of a legacy-format file whose layer holds `art`. +fn legacy_texts(art: &str) -> Vec { + let doc = match read(type_stream7(art).as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc) +} + +fn art_texts(doc: &Document) -> Vec { + art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() +} + +/// Point type at (10, 50): `attrs`, then the characters `text`. +fn point_type(attrs: &str, text: &str) -> String { + format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") +} + +/// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging +/// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its +/// first character, and they last into the next text object. +#[test] +fn legacy_type_keeps_its_spacing_hanging_punctuation_and_hyphenation() { + let two_paragraphs = + point_type("10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th", "One\\r").replace("TO\n", "0 0 5 TC\n0 Tq\n0 0 4 5 6 Th\n(Two) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "Three"))); + assert_eq!(texts.len(), 2); + let one = texts[0].para_at(0); + assert_eq!(one.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(one.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(one.roman_hanging && one.hyphenate); + let h = &one.hyphenation; + assert_eq!((h.after_first, h.before_last, h.hyphen_limit), (2, 3, 4)); + assert_eq!(h.words_longer_than, vectorcraft_doc::text::HyphenationOptions::default().words_longer_than, "no operand sets it"); + let two = texts[0].para_at(1); + assert_eq!(two.justification.letter_spacing, [0.0, 0.0, 5.0]); + assert_eq!(two.justification.word_spacing, [70.0, 110.0, 140.0], "word spacing stays"); + assert!(!two.roman_hanging && !two.hyphenate); + // Without the limit flag, any number of hyphens in a row. + assert_eq!((two.hyphenation.after_first, two.hyphenation.before_last, two.hyphenation.hyphen_limit), (4, 5, 0)); + // The next text object keeps them. + assert_eq!(texts[1].para_at(0), two); +} + +/// A legacy attribute whose operands are missing, are not numbers, or are flags other than 0 and +/// 1 leaves the attribute as it was, and operands are read by their place. +#[test] +fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { + let set = "10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th\n2 Ta\n0 TA\n5 6 7 Ti"; + let bad = "/x 15 20 TC\n110 140 TW\n2 Tq\n1 2 2 3 4 Th\n1 1 (2) 3 4 Th\n/x Ta\n2 TA\n5 /x 7 Ti"; + let texts = legacy_texts(&point_type(&format!("{set}\n{bad}"), "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(p.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(p.roman_hanging && p.hyphenate); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 3, 4)); + assert_eq!(p.justify, vectorcraft_doc::Justify::Right); + assert_eq!((p.first_line_indent, p.left_indent, p.right_indent), (5.0, 6.0, 7.0)); + assert_eq!(texts[0].runs[0].style.kerning, Some(0.0), "kerning stays off"); + // A scale or leading pair with a bad operand leaves both as they were; one operand is the + // horizontal scale (or the leading) of the format before version 7. + let texts = legacy_texts(&point_type("50 80 Tz\n14 3 Tl\n/x 120 Tz\n/x 20 Tl", "Hi")); + let st = &texts[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale, st.leading), (50.0, 80.0, Some(14.0))); + assert_eq!(texts[0].para_at(0).space_before, 3.0); + let st = &legacy_texts(&point_type("50 80 Tz\n120 Tz", "Hi"))[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale), (120.0, 100.0)); + // A start point that isn't a number leaves the matrix. + let good = &legacy_texts(&point_type("", "Hi"))[0]; + let bad = &legacy_texts(&point_type("", "Hi").replace("10 50 0 Tp", "10 50 /x Tp"))[0]; + assert_eq!(bad.xf, good.xf); +} + +/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum +/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges +/// `text.setFormat` takes. +#[test] +fn legacy_type_spacing_and_hyphenation_are_kept_in_range() { + let texts = legacy_texts(&point_type("-500 0 900 TC\n0 2000 5000 TW\n1 1 0 40 99 Th", "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [-100.0, 0.0, 500.0]); + assert_eq!(p.justification.word_spacing, [0.0, 1000.0, 1000.0]); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (1, 15, 25)); + let texts = legacy_texts(&point_type("5 0 0 TC\n200 100 80 TW", "Hi")); + let j = &texts[0].para_at(0).justification; + let d = vectorcraft_doc::text::JustificationOptions::default(); + assert_eq!((j.letter_spacing, j.word_spacing), (d.letter_spacing, d.word_spacing)); +} + +/// A file's legacy type is read up to its allowance of characters, a single long run included. +#[test] +fn one_long_run_of_legacy_type_stops_at_the_allowance() { + // The reader's allowance, `MAX_CHARS`. + const ALLOWANCE: usize = 1 << 22; + let long = "a".repeat(ALLOWANCE + 10); + let texts = legacy_texts(&point_type("", &long)); + assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); +} + #[test] fn what_it_doesnt_read_is_an_error_where_it_shows() { let e = read(stream(&layer("1 2 frobnicate\n")).as_bytes()).unwrap_err(); @@ -3149,110 +3256,3 @@ fn an_objects_on_path_group_in_versioned_content_opens_once() { assert_eq!(kids[0].children().unwrap().len(), 5); assert!(kids[0].extras().objects_on_path.is_some()); } - -/// A file in the legacy format (version 7) whose layer holds `art`, crop marks 0 0 200 100. -fn stream7(art: &str) -> String { - format!( - "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 3.0\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n", - layer(art) - ) -} - -/// The text objects of a legacy-format file whose layer holds `art`. -fn legacy_texts(art: &str) -> Vec { - let doc = match read(stream7(art).as_bytes()) { - Ok(r) => r.doc, - Err(e) => panic!("{e}"), - }; - art_texts(&doc) -} - -fn art_texts(doc: &Document) -> Vec { - art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() -} - -/// Point type at (10, 50): `attrs`, then the characters `text`. -fn point_type(attrs: &str, text: &str) -> String { - format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") -} - -/// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging -/// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its -/// first character, and they last into the next text object. -#[test] -fn legacy_type_keeps_its_spacing_hanging_punctuation_and_hyphenation() { - let two_paragraphs = - point_type("10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th", "One\\r").replace("TO\n", "0 0 5 TC\n0 Tq\n0 0 4 5 6 Th\n(Two) Tx\nTO\n"); - let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "Three"))); - assert_eq!(texts.len(), 2); - let one = texts[0].para_at(0); - assert_eq!(one.justification.letter_spacing, [10.0, 15.0, 20.0]); - assert_eq!(one.justification.word_spacing, [70.0, 110.0, 140.0]); - assert!(one.roman_hanging && one.hyphenate); - let h = &one.hyphenation; - assert_eq!((h.after_first, h.before_last, h.hyphen_limit), (2, 3, 4)); - assert_eq!(h.words_longer_than, vectorcraft_doc::text::HyphenationOptions::default().words_longer_than, "no operand sets it"); - let two = texts[0].para_at(1); - assert_eq!(two.justification.letter_spacing, [0.0, 0.0, 5.0]); - assert_eq!(two.justification.word_spacing, [70.0, 110.0, 140.0], "word spacing stays"); - assert!(!two.roman_hanging && !two.hyphenate); - // Without the limit flag, any number of hyphens in a row. - assert_eq!((two.hyphenation.after_first, two.hyphenation.before_last, two.hyphenation.hyphen_limit), (4, 5, 0)); - // The next text object keeps them. - assert_eq!(texts[1].para_at(0), two); -} - -/// A legacy attribute whose operands are missing, are not numbers, or are flags other than 0 and -/// 1 leaves the attribute as it was, and operands are read by their place. -#[test] -fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { - let set = "10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th\n2 Ta\n0 TA\n5 6 7 Ti"; - let bad = "/x 15 20 TC\n110 140 TW\n2 Tq\n1 2 2 3 4 Th\n1 1 (2) 3 4 Th\n/x Ta\n2 TA\n5 /x 7 Ti"; - let texts = legacy_texts(&point_type(&format!("{set}\n{bad}"), "Hi")); - let p = texts[0].para_at(0); - assert_eq!(p.justification.letter_spacing, [10.0, 15.0, 20.0]); - assert_eq!(p.justification.word_spacing, [70.0, 110.0, 140.0]); - assert!(p.roman_hanging && p.hyphenate); - assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 3, 4)); - assert_eq!(p.justify, vectorcraft_doc::Justify::Right); - assert_eq!((p.first_line_indent, p.left_indent, p.right_indent), (5.0, 6.0, 7.0)); - assert_eq!(texts[0].runs[0].style.kerning, Some(0.0), "kerning stays off"); - // A scale or leading pair with a bad operand leaves both as they were; one operand is the - // horizontal scale (or the leading) of the format before version 7. - let texts = legacy_texts(&point_type("50 80 Tz\n14 3 Tl\n/x 120 Tz\n/x 20 Tl", "Hi")); - let st = &texts[0].runs[0].style; - assert_eq!((st.h_scale, st.v_scale, st.leading), (50.0, 80.0, Some(14.0))); - assert_eq!(texts[0].para_at(0).space_before, 3.0); - let st = &legacy_texts(&point_type("50 80 Tz\n120 Tz", "Hi"))[0].runs[0].style; - assert_eq!((st.h_scale, st.v_scale), (120.0, 100.0)); - // A start point that isn't a number leaves the matrix. - let good = &legacy_texts(&point_type("", "Hi"))[0]; - let bad = &legacy_texts(&point_type("", "Hi").replace("10 50 0 Tp", "10 50 /x Tp"))[0]; - assert_eq!(bad.xf, good.xf); -} - -/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum -/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges -/// `text.setFormat` takes. -#[test] -fn legacy_type_spacing_and_hyphenation_are_kept_in_range() { - let texts = legacy_texts(&point_type("-500 0 900 TC\n0 2000 5000 TW\n1 1 0 40 99 Th", "Hi")); - let p = texts[0].para_at(0); - assert_eq!(p.justification.letter_spacing, [-100.0, 0.0, 500.0]); - assert_eq!(p.justification.word_spacing, [0.0, 1000.0, 1000.0]); - assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (1, 15, 25)); - let texts = legacy_texts(&point_type("5 0 0 TC\n200 100 80 TW", "Hi")); - let j = &texts[0].para_at(0).justification; - let d = vectorcraft_doc::text::JustificationOptions::default(); - assert_eq!((j.letter_spacing, j.word_spacing), (d.letter_spacing, d.word_spacing)); -} - -/// A file's legacy type is read up to its allowance of characters, a single long run included. -#[test] -fn one_long_run_of_legacy_type_stops_at_the_allowance() { - // The reader's allowance, `MAX_CHARS`. - const ALLOWANCE: usize = 1 << 22; - let long = "a".repeat(ALLOWANCE + 10); - let texts = legacy_texts(&point_type("", &long)); - assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); -} From 0ccc6d9df55f0681acf97c9538ff2a6befcaea62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:03:21 +0700 Subject: [PATCH 069/674] .ai import: paths keep their notes and Show Center Squashed from #5129 onto main. --- crates/engine/tests/import_fuzz.rs | 11 ++- crates/eps/src/import/ai/lex.rs | 7 +- crates/eps/src/import/ai/read/art.rs | 5 + crates/eps/src/import/ai/read/directives.rs | 43 +++++++- crates/eps/src/import/ai/read/ops.rs | 7 ++ crates/eps/src/import/ai/read/types.rs | 11 ++- crates/eps/src/import/ai/tests.rs | 103 ++++++++++++++++++++ crates/eps/src/import/tests_illustrator.rs | 16 +++ docs/target-app-parity.md | 1 + 9 files changed, 198 insertions(+), 6 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index c54c8e1335..7ae7b1d634 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3117,7 +3117,7 @@ fn on_path_data( /// not included, so its program can't be run and its layers are read from it. const NAMED_PROLOG_AI: &str = "%!PS-Adobe-3.0\n%%BoundingBox: 0 0 200 100\n%%DocumentNeededResources: procset Adobe_packedarray 2.0 0\n%AI3_TemplateBox: 288 384 288 384\n%%EndComments\n\ %%BeginProlog\n%%IncludeResource: procset Adobe_packedarray 2.0 0\nAdobe_packedarray /initialize get exec\n%%EndProlog\n%%BeginSetup\n%AI5_Begin_NonPrinting\nNp\n%AI5_End_NonPrinting--\n%%EndSetup\n\ - %AI5_BeginLayer\n1 1 1 1 0 0 -1 191 63 255 Lb\n(A::B) Ln\n0 A\n0 R\n0 0 0 1 K\n0 i 1 J 1 j 0.8 w 4 M [2 1]0 d\n0 D\n10 10 m\n90 10 L\n90 90 L\n10 90 L\n10 10 L\nS\n\ + %AI5_BeginLayer\n1 1 1 1 0 0 -1 191 63 255 Lb\n(A::B) Ln\n0 A\n0 R\n0 0 0 1 K\n0 i 1 J 1 j 0.8 w 4 M [2 1]0 d\n0 D\n%AI3_Note:a (note)\n%AI5_NoteMore:more\n1 Ap\n10 10 m\n90 10 L\n90 90 L\n10 90 L\n10 10 L\nS\n%%Note:\n0 Ap\n\ u\n0.5 g\n20 20 m\n40 20 L\n40 40 L\nf\nU\n%AI5_BeginLayer\n0 1 1 1 0 0 3 0 0 0 Lb\n(Sub) Ln\n110 10 m\n190 90 L\nS\nLB\n%AI5_EndLayer--\nLB\n%AI5_EndLayer--\n\ %%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n"; @@ -3136,7 +3136,7 @@ proptest! { /// A `.ai` in PostScript form whose prolog is named, not included, damaged: read from its /// layers, or refused. #[test] - fn ps_form_ai_never_panics(cut in 0usize..1_200, edits in prop::collection::vec((0usize..1_200, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '%', 'u', 'U', 'L', 'b', 'B', 'i', 'A', 'K'])), 0..12)) { + fn ps_form_ai_never_panics(cut in 0usize..1_200, edits in prop::collection::vec((0usize..1_200, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '%', 'u', 'U', 'L', 'b', 'B', 'i', 'A', 'K', 'p', ':', '\u{e9}'])), 0..12)) { let text = mutate_text(NAMED_PROLOG_AI, cut, &edits); survive("mutated PostScript-form .ai", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; } @@ -3211,6 +3211,13 @@ fn arb_ai_token() -> impl Strategy { "O", "R", "XR", + // A path's note and Show Center (version 7 §5.3.1, §12). + "Ap", + "1 Ap", + "\n%AI3_Note: a (note) \n", + "\n%AI3_Note:\n", + "\n%AI5_NoteMore:more\n", + "\n%%Note:old\n", "w", "J", "j", diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index 9b81e29a8d..c4a138cd81 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -42,6 +42,8 @@ pub(super) struct Token<'a> { const PREVIEW: (&[u8], &[u8]) = (b"%AI26_BeginPlacedObjectPreview", b"%AI26_EndPlacedObjectPreview"); /// A placed file's markers, which a hidden one has on `%_` lines. const PLACE: [&[u8]; 2] = [b"%AI5_BeginPlace", b"%AI5_EndPlace"]; +/// A path's note comments, also read on `%_` lines. +const NOTES: [&[u8]; 3] = [b"%AI3_Note:", b"%%Note:", b"%AI5_NoteMore:"]; /// A binary section skipped whole: (begin, end) markers. const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument"); @@ -144,8 +146,9 @@ impl<'a> Lexer<'a> { if start { return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: false }); } - // So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. - if prefixed && PLACE.iter().any(|m| line.starts_with(m)) { + // So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. And a + // hidden path's note. + if prefixed && PLACE.iter().chain(&NOTES).any(|m| line.starts_with(m)) { return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true }); } // A comment later in a line. diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 5e10d789f1..98412ff700 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -233,6 +233,11 @@ impl<'a> Reader<'a> { .into(); copy }); + // The note and Show Center are the path's, not its painted copy's. + node.edit_attrs(|a| { + a.note = gs.note.clone().unwrap_or_default(); + a.show_center = gs.show_center; + }); let unread_bounds = unread.then(|| node.visual_bounds()).flatten(); let unread_id = node.id; self.add(node, hidden)?; diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 1d5806a3cc..ce5bfa41dc 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,5 +1,5 @@ use super::art::{four, sane, two}; -use super::types::{FLIP, Kind, MAX_HEX, MAX_PATTERNS, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED}; +use super::types::{FLIP, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED}; use super::{Arc, Node, PatternDef, Reader, Rect, Tok, V, marker}; impl<'a> Reader<'a> { @@ -49,6 +49,9 @@ impl<'a> Reader<'a> { } return Ok(()); } + if self.note_comment(c) { + return Ok(()); + } let m = marker(line); // A pattern's definition (one inside another's isn't read). if m == "BeginPattern" && self.pattern.is_none() { @@ -157,6 +160,44 @@ impl<'a> Reader<'a> { Ok(()) } + /// `%AI3_Note:` (or `%%Note:`) sets the note of the paths that follow, an empty one clearing it, + /// and `%AI5_NoteMore:` adds a line to it. The text is kept as written, up to [`MAX_NOTE`] + /// characters. + fn note_comment(&mut self, c: &[u8]) -> bool { + let (text, more) = if let Some(t) = c.strip_prefix(b"AI3_Note:").or_else(|| c.strip_prefix(b"%Note:")) { + (t, false) + } else if let Some(t) = c.strip_prefix(b"AI5_NoteMore:") { + (t, true) + } else { + return false; + }; + // Only as much of the line as the note can keep is decoded; a UTF-8 character the cut + // splits is left out. + let mut head = text.get(..text.len().min(4 * MAX_NOTE)).unwrap_or(text); + if head.len() < text.len() + && let Err(e) = std::str::from_utf8(head) + && e.error_len().is_none() + { + head = head.get(..e.valid_up_to()).unwrap_or(head); + } + let text = super::obj::text(head); + match (&mut self.gs.note, more) { + (Some(note), true) => { + note.push('\n'); + note.push_str(&text); + } + // A continuation with no note to continue. + (None, true) => return true, + (note, false) => *note = Some(text), + } + if let Some(note) = self.gs.note.as_mut() + && let Some((at, _)) = note.char_indices().nth(MAX_NOTE) + { + note.truncate(at); + } + true + } + /// Skip to the comment with marker `end` (sections of the same kind nested in it count, and /// versioned content in an alternate). fn skip_to(&mut self, end: &str) -> Result<(), String> { diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index f48a8df82a..6e12e89b19 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -158,6 +158,13 @@ impl<'a> Reader<'a> { "O" => self.gs.overprint_fill = Self::nums(&vals).last() == Some(&1.0), "R" => self.gs.overprint_stroke = Self::nums(&vals).last() == Some(&1.0), "XR" => self.gs.rule = if Self::nums(&vals).last() == Some(&1.0) { FillRule::EvenOdd } else { FillRule::NonZero }, + // Show Center (§12): 1 shows the center point of the paths that follow, and 0 leaves + // them at their default, which hides it on an imported path. + "Ap" => match Self::nums(&vals).last().copied() { + Some(1.0) => self.gs.show_center = Some(true), + Some(0.0) => self.gs.show_center = None, + _ => {} + }, "w" => { if let Some(v) = Self::nums(&vals).last().filter(|v| v.is_finite() && **v >= 0.0) { self.gs.width = *v; diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 3857cbe625..784108fe9f 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -40,6 +40,9 @@ pub(crate) const FLIP: Affine = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); /// Most patterns read (others can't fill art). pub(super) const MAX_PATTERNS: usize = 4096; +/// Most characters of a path's note read (the version 7 specification allows 254, §5.3.1). +pub(super) const MAX_NOTE: usize = 1024; + #[derive(Clone, Debug)] pub(crate) struct GState { pub(crate) fill: Paint, @@ -59,6 +62,11 @@ pub(crate) struct GState { pub(crate) overprint_stroke: bool, pub(super) locked: bool, pub(super) hidden: bool, + /// The note (`%AI3_Note:`) the paths that follow get, until another replaces it (`None`: no + /// note comment yet; empty: none). + pub(super) note: Option, + /// Show Center (`1 Ap`) for the paths that follow (`None`: the path's default). + pub(super) show_center: Option, } impl Default for GState { @@ -82,6 +90,8 @@ impl Default for GState { overprint_stroke: false, locked: false, hidden: false, + note: None, + show_center: None, } } } @@ -222,7 +232,6 @@ pub(super) const LINKED_PREVIEWS: &str = pub(super) const IGNORED: &[&str] = &[ "Ae", "AE", - "Ap", "As", "Xd", "Xr", diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 92c9a46457..96d0ba9411 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -118,6 +118,109 @@ fn groups_names_hidden_and_locked() { assert!(!hidden.visible); } +/// A node's Attributes panel note (empty: none). +fn note(n: &Node) -> String { + n.extras().attrs.as_deref().map(|a| a.note.clone()).unwrap_or_default() +} + +/// The notes of the first layer's objects, in order. +fn notes(doc: &Document) -> Vec { + art(doc).iter().map(|n| note(n)).collect() +} + +/// A note comment names the paths after it until another one replaces it, and an empty one clears +/// it (§5.3.1: `%AI3_Note: `). +#[test] +fn a_note_comment_is_the_note_of_the_paths_after_it() { + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let body = format!("%AI3_Note:hello\n{a}f\n{b}f\n%AI3_Note:\n{c}f\n%AI3_Note:world\n{d}f\n"); + assert_eq!(notes(&read_ok(&layer(&body)).doc), ["hello", "hello", "", "world"]); + // `%%Note:` sets it too. + assert_eq!(notes(&read_ok(&layer(&format!("%%Note:old style\n{a}f\n"))).doc), ["old style"]); + // A path without a note has no attributes. + assert!(art(&read_ok(&layer(&format!("{a}f\n"))).doc)[0].extras().attrs.is_none()); +} + +/// `%AI5_NoteMore:` adds a line to the note; the text is kept as written, and its bytes are read as +/// UTF-8, else Windows-1252. +#[test] +fn a_note_continues_on_more_lines_and_keeps_its_text() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let body = format!("%AI3_Note: two (words) caf@ \n%AI5_NoteMore:more\n{a}f\n"); + let data = stream(&layer(&body)).replace('@', "\u{1}").into_bytes(); + let data: Vec = data.into_iter().map(|b| if b == 1 { 0xE9 } else { b }).collect(); + assert_eq!(notes(&read(&data).unwrap().doc), [" two (words) café \nmore"]); + // A continuation of an empty note is its second line; one with no note before it is ignored. + assert_eq!(notes(&read_ok(&layer(&format!("%AI3_Note:\n%AI5_NoteMore:x\n{a}f\n"))).doc), ["\nx"]); + assert_eq!(notes(&read_ok(&layer(&format!("%AI5_NoteMore:x\n{a}f\n"))).doc), [""]); + // A note too long is cut at 1,024 characters, however many lines it has. + let long = format!("%AI3_Note:{}\n{}{a}f\n", "x".repeat(5000), "%AI5_NoteMore:yy\n".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc)[0].chars().count(), 1024); + let long = format!("%AI3_Note:x\n{}{a}f\n", "%AI5_NoteMore:yy\n".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc)[0].chars().count(), 1024); + // A long UTF-8 line stays UTF-8 where it is cut. + let long = format!("%AI3_Note:{}\n{a}f\n", "é".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc), ["é".repeat(1024)]); + // A note on a `%_` line is read too. + assert_eq!(notes(&read_ok(&layer(&format!("%_%AI3_Note:hidden\n{a}f\n"))).doc), ["hidden"]); +} + +/// A note before a group or a compound path isn't theirs: their paths keep their own. +#[test] +fn a_note_before_a_group_or_compound_path_is_not_theirs() { + let [a, b] = [0.0, 20.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + for (open, close) in [("u", "U"), ("*u", "*U")] { + let body = format!("%AI3_Note:outer\n0 Ae\n{open}\n%AI3_Note:inner\n{a}f\n{b}f\n{close}\n"); + let doc = read_ok(&layer(&body)).doc; + let top = &art(&doc)[0]; + assert_eq!(note(top), "", "{open}"); + let kids: Vec = top.children().unwrap().iter().map(|k| note(k)).collect(); + assert_eq!(kids, ["inner", "inner"], "{open}"); + } +} + +/// A clipping path's note is its own, not that of the copy that paints its fill. +#[test] +fn a_clipping_paths_note_is_not_copied_to_its_painted_fill() { + let body = + format!("0 Ae\nq\n{RED}%AI3_Note:clip\n{}W\nf\n%AI3_Note:\n{}f\nQ\n", rect_path(5.0, 5.0, 25.0, 25.0), rect_path(0.0, 0.0, 30.0, 30.0)); + let doc = read_ok(&layer(&body)).doc; + fn walk(nodes: &[Arc], out: &mut Vec<(bool, String)>) { + for n in nodes { + out.push((matches!(n.kind, NodeKind::Path { clipping: true, .. }), note(n))); + walk(n.children().map(Vec::as_slice).unwrap_or_default(), out); + } + } + let mut all = Vec::new(); + walk(&art(&doc), &mut all); + let noted: Vec<_> = all.iter().filter(|(_, n)| n == "clip").collect(); + assert_eq!(noted, [&(true, "clip".to_string())], "{all:?}"); + assert!(all.len() >= 3, "the painted copy is there: {all:?}"); +} + +/// `1 Ap` shows the center point of the paths after it until `0 Ap` (§12, showCenter), which leaves +/// them at an imported path's default: hidden. +#[test] +fn ap_shows_the_center_of_the_paths_after_it() { + let [a, b, c] = [0.0, 20.0, 40.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let ellipse = "50 0 m\n50 5.5 45.5 10 40 10 c\n34.5 10 30 5.5 30 0 c\n30 -5.5 34.5 -10 40 -10 c\n45.5 -10 50 -5.5 50 0 c\n"; + let body = format!("1 Ap\n{a}f\n{b}f\n0 Ap\n{c}f\n{ellipse}f\n2 Ap\n{a}f\n"); + let doc = read_ok(&layer(&body)).doc; + let shown: Vec<_> = art(&doc).iter().map(|n| (n.extras().attrs.as_deref().and_then(|a| a.show_center), n.shows_center())).collect(); + assert_eq!(shown, [(Some(true), true), (Some(true), true), (None, false), (None, false), (None, false)]); +} + +/// What a skipped section sets doesn't reach the art after it. +#[test] +fn a_note_or_ap_in_a_skipped_section_does_not_reach_the_art_after_it() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let body = format!("%AI3_BeginBrushPattern\n1 Ap\n%AI3_Note:brush\n{a}f\n%AI3_EndBrushPattern\n{}", layer(&format!("{a}f\n"))); + let doc = read_ok(&body).doc; + let n = &art(&doc)[0]; + assert_eq!(note(n), ""); + assert!(!n.shows_center()); +} + #[test] fn paths_colours_and_strokes() { let art_ = format!( diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index f83475638d..ebb8275b5c 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -257,6 +257,22 @@ fn a_version_7_palette_keeps_its_swatches_without_names() { assert_eq!(d.swatch("Gray K=0").unwrap().paint.color(), Some(Color::gray(0.0)), "1 g is white"); } +/// A version 8 file's paths keep their notes and Show Center. +#[test] +fn a_legacy_files_paths_keep_their_notes_and_show_center() { + let body = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Notes) Ln\n0 A\n%AI3_Note:first\n%AI5_NoteMore:second line\n1 Ap\n0 0 0 1 k\n{}\n\ + %AI3_Note:\n0 Ap\n{}\nLB\n%AI5_EndLayer--\n", + tri(10), + tri(40) + ); + let r = import(&ai(AI8, "", &body)).unwrap(); + let kids = r.document.layers[0].children().unwrap(); + let attrs: Vec<_> = kids.iter().map(|n| n.extras().attrs.as_deref().map(|a| (a.note.clone(), a.show_center))).collect(); + assert_eq!(attrs, [Some(("first\nsecond line".into(), Some(true))), None], "{:?}", r.warnings); + assert!(kids[0].shows_center() && !kids[1].shows_center()); +} + #[test] fn unbalanced_and_runaway_groups_are_read_safely() { // Ends without a beginning end nothing; groups left open hold the rest. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a340f6476a..4736272d74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,6 +1079,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + `.ai` and EPS editing-data import keeps each path's Attributes panel note (`%AI3_Note:`, `%%Note:`, more lines in `%AI5_NoteMore:`, up to 1,024 characters) and Show Center (`1 Ap`); a note or Show Center applies to every path after it until the next one, and a note before a group or compound path is not theirs (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_illustrator.rs`). A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part; CCITT Group 3 and planar files with extra channels are not read); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). From adb446049b131a6943f2cdca4b3338defc6b6b77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:54:14 -0800 Subject: [PATCH 070/674] Variables: Undo and Redo clear a highlight that names no variable Undo, Redo and a canceled undo group put back an earlier document but left the Variables panel highlight as it was. After renaming the highlighted variable and undoing, the highlight still named the new name: a variable defined later under that name showed highlighted without a click, and Delete removed it. Each of these paths now clears a highlight whose variable the restored document does not define, as Delete Variables and Load Variable Library already did. --- crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/cmd/variablecmds.rs | 4 +- crates/engine/src/cmd/variablecmds/library.rs | 4 +- crates/engine/src/doc_state.rs | 8 ++++ crates/engine/src/session/execute.rs | 1 + crates/engine/src/session/undo.rs | 2 + crates/engine/src/tests/variables.rs | 43 +++++++++++++++++++ 7 files changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 62a17bda3b..f252d09ff9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -498,6 +498,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); Ok(json!({ "undone": label })) } @@ -525,6 +526,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); Ok(json!({ "redone": label })) } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 9e589e8839..33799bc857 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -231,9 +231,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { let n = s.edit("Delete Variables", |d, _| Ok(d.variables.prune(&names)))?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; - if st.variables_highlight.as_ref().is_some_and(|h| st.doc.variables.variable(h).is_none()) { - st.variables_highlight = None; - } + st.drop_stale_variables_highlight(); st.revision += 1; Ok(json!({"deleted": n})) } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 937d4155e2..b410af042f 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -277,9 +277,7 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { })?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; - if st.variables_highlight.as_ref().is_some_and(|h| st.doc.variables.variable(h).is_none()) { - st.variables_highlight = None; - } + st.drop_stale_variables_highlight(); st.revision += 1; let skipped: Vec = lib.other.iter().map(|(name, t)| json!({"name": name, "trait": t})).collect(); let mut out = json!({ diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 30cf1e7e8d..dc1df88bed 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -352,6 +352,14 @@ impl DocState { self.revision += 1; } } + /// Clear the Variables panel highlight when the document defines no variable of that name + /// (deleted, or taken out by Undo or Redo), so a variable defined later under that name is + /// not highlighted without a click. + pub(crate) fn drop_stale_variables_highlight(&mut self) { + if self.variables_highlight.as_ref().is_some_and(|h| self.doc.variables.variable(h).is_none()) { + self.variables_highlight = None; + } + } /// Count the document as modified, as if never saved (a document restored by Data Recovery). pub fn mark_unsaved(&mut self) { self.saved_doc = Arc::new(Document::new(1.0, 1.0)); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index d3ffe41631..f4ebd87c42 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -219,6 +219,7 @@ impl Session { st.interaction = interaction; st.history = history; cmd::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); st.revision += 1; } if let Some(i) = active.and_then(|uid| self.docs.iter().position(|d| d.uid == uid)) { diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 2f750dc13c..c5f3f1595e 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -102,6 +102,7 @@ impl Session { deselect_hidden(&self.menu, &st.doc, &mut st.selection); st.sync_new_art(); cmd::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); st.revision += 1; // The journal drops only the canceled groups' own entries and keeps the ones made in other documents meanwhile. journal.extend(g.journal); @@ -230,6 +231,7 @@ impl Session { st.doc = doc; st.selection = selection; cmd::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); deselect_hidden(&menu, &st.doc, &mut st.selection); st.history.recost_last(&st.doc); st.revision += 1; diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index e1bfd3e2f2..5e0176f70c 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -893,6 +893,49 @@ fn highlight_follows_rename_and_clears_with_delete() { assert!(s.doc().unwrap().variables_highlight.is_none(), "a highlight of a deleted variable highlights nothing"); } +/// Undo of a rename takes the new name away, so the highlight that followed the rename goes +/// too: a variable defined later under that name is not highlighted, and Delete without names +/// does not delete it. +#[test] +fn undoing_a_rename_clears_the_highlight_of_the_new_name() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "A", "kind": "text"})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "A"})).unwrap(); + s.execute("variable.rename", &json!({"name": "A", "newName": "B"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none()); + s.execute("variable.define", &json!({"name": "B", "kind": "visibility"})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none(), "B was never clicked"); + assert!(s.execute("variable.delete", &json!({})).is_err(), "no variable highlighted"); + let vars = s.execute("variable.list", &json!({})).unwrap(); + assert_eq!(vars["variables"].as_array().unwrap().len(), 2); +} + +/// Undo of New Variable, Redo of Delete Variables and a canceled undo group each leave the +/// highlighted name undefined, and the highlight goes with it. +#[test] +fn undo_redo_and_a_canceled_group_clear_a_highlight_of_a_variable_they_remove() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "N", "kind": "text"})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "N"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none(), "undo of New Variable"); + + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("variable.delete", &json!({"names": ["N"]})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "N"})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none(), "redo of Delete Variables"); + + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + s.execute("variable.define", &json!({"name": "G", "kind": "text"})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "G"})).unwrap(); + s.execute("edit.undoGroup.end", &json!({"cancel": true})).unwrap(); + assert!(s.doc().unwrap().doc.variables.variable("G").is_none(), "the cancel took G back"); + assert!(s.doc().unwrap().variables_highlight.is_none(), "a canceled undo group"); +} + /// A row that hides an object must be able to show it again, and hiding it on the artboard /// (as the Layers panel does) is what a capture records: a visibility variable reads and /// writes its object's own visibility, which therefore never makes the object off limits. From 1be658c88cd6cedd4e0bf685b976451a2e7cd0da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:58:18 -0800 Subject: [PATCH 071/674] Variables: Export Data Sets refuses more data sets or variables than Import Data Sets reads dataset.export checked only the 1 MiB size, so a document with more than 1000 data sets or 256 variables exported a CSV that dataset.import then refused. Export now refuses such a document with a message naming the limit, and the messages have rows in every complete-message catalog. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/cmd/variablecmds/csv.rs | 8 ++++++ crates/engine/src/tests/variables.rs | 27 +++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 2 ++ crates/ui-egui/src/i18n/cs.tsv | 2 ++ crates/ui-egui/src/i18n/de.tsv | 2 ++ crates/ui-egui/src/i18n/el.tsv | 2 ++ crates/ui-egui/src/i18n/es.tsv | 2 ++ crates/ui-egui/src/i18n/fi.tsv | 2 ++ crates/ui-egui/src/i18n/fr.tsv | 2 ++ crates/ui-egui/src/i18n/hu.tsv | 2 ++ crates/ui-egui/src/i18n/it.tsv | 2 ++ crates/ui-egui/src/i18n/ja.tsv | 2 ++ crates/ui-egui/src/i18n/ka.tsv | 2 ++ crates/ui-egui/src/i18n/ko.tsv | 2 ++ crates/ui-egui/src/i18n/pl.tsv | 2 ++ crates/ui-egui/src/i18n/pt-br.tsv | 2 ++ crates/ui-egui/src/i18n/ru.tsv | 2 ++ crates/ui-egui/src/i18n/sv.tsv | 2 ++ crates/ui-egui/src/i18n/tests.rs | 33 +++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 2 ++ crates/ui-egui/src/i18n/uk.tsv | 2 ++ crates/ui-egui/src/i18n/vi.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 2 ++ 25 files changed, 111 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 33799bc857..6416c8eb16 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -740,7 +740,7 @@ pub fn specs() -> Vec { "Export Data Sets…", ["Window", "Variables"], None, - "{path?} write every dataset as CSV (header: name, then variables); without path → {csv, datasets}", + "{path?} write every dataset as CSV (header: name, then variables); without path → {csv, datasets}. Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads", has_doc, dataset_export ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index bf60c95085..65388fb16d 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -341,12 +341,20 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { } /// Export every dataset as CSV (`name` then variables). With `path`, write the file; else return `{csv}`. +/// A document with more data sets or variables than [`dataset_import`] reads is refused. pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.export"; let st = s.doc()?; if st.doc.variables.variables.is_empty() { return Err(bad(C, "define a variable first")); } + if st.doc.variables.datasets.len() > MAX_CSV_ROWS { + return Err(bad(C, format!("more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS}"))); + } + // The name column comes first, so the import's column cap leaves room for this many variables. + if st.doc.variables.variables.len() > MAX_CSV_COLS { + return Err(bad(C, format!("more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS}"))); + } let csv = datasets_to_csv(&st.doc.variables); if csv.len() > MAX_CSV_BYTES { return Err(bad(C, format!("CSV would be larger than {MAX_CSV_BYTES} bytes"))); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 5e0176f70c..f57f8a5972 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1325,6 +1325,33 @@ fn datasets_csv_keeps_spaces_in_quoted_cells() { assert_eq!(value("C"), text_value(" quoted ")); } +/// Export refuses a document with more data sets or variables than `dataset.import` reads, so +/// every file it writes imports back: 1,000 data sets and 256 variables export and import, and +/// one more of either is refused. +#[test] +fn datasets_export_refuses_more_than_import_reads() { + let mut s = session(); + let header: Vec = (1..=256).map(|i| format!("V{i}")).collect(); + let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect(); + s.execute("dataset.import", &json!({"csv": format!("name,{}\n{rows}", header.join(","))})).unwrap(); + let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + + s.execute("dataset.new", &json!({"name": "Set 1001"})).unwrap(); + let err = s.execute("dataset.export", &json!({})).unwrap_err().to_string(); + assert!(err.contains("more than 1000 data sets"), "{err}"); + s.execute("dataset.delete", &json!({"names": ["Set 1001"]})).unwrap(); + s.execute("dataset.export", &json!({})).unwrap(); + + s.execute("variable.define", &json!({"name": "V257", "kind": "text"})).unwrap(); + let err = s.execute("dataset.export", &json!({})).unwrap_err().to_string(); + assert!(err.contains("more than 256 variables"), "{err}"); + let dir = Folder::new("vars-csv-caps"); + let out = dir.file("sets.csv"); + assert!(s.execute("dataset.export", &json!({"path": out})).is_err()); + assert!(!std::path::Path::new(&out).exists(), "no file is written"); +} + /// A header row with a tab and no comma outside quotes makes tabs the separator; a quoted cell /// may then hold tabs and commas. A header row with a comma outside quotes keeps commas, even /// when a cell holds a tab. A tab-separated header with an unclosed quote fails with the reason. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd6172d6a6..21b2ff53fa 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5597,6 +5597,8 @@ digits Malayalam Malaiàlam @msg unsupported native docking operation operació d’acoblament nadiua no compatible @msg unsupported: {0} no compatible: {0} @msg variables are locked les variables estan blocades +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} més de {MAX_CSV_ROWS} conjunts de dades: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} més de {MAX_CSV_COLS} variables: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft no cerca a les carpetes d’altres aplicacions ni del sistema: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft no cerca a la carpeta Shared o Public d’Usuaris: {path} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 34c7f4e035..b1742b59bf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4786,6 +4786,8 @@ imageTrace Outline Obrys @msg unknown workspace (one of {_1}) neznámý pracovní prostor (jeden z {_1}) @msg unsupported: {0} nepodporováno: {0} @msg variables are locked proměnné jsou zamčené +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} více než {MAX_CSV_ROWS} sad dat: Importovat sady dat načte nejvýše {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} více než {MAX_CSV_COLS} proměnných: Importovat sady dat načte nejvýše {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} proměnné, které nejsou textové, byly vynechány: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` a `options.{key}: {inner}` si odporují: zadejte volbu jen jednou @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files soubory verze {0} nelze komprimovat: komprimované soubory otevírá až verze {COMPRESSED_SINCE} a novější diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 101bbefac6..d850991b15 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4395,6 +4395,8 @@ theme Appearance Erscheinungsbild @msg unknown workspace (one of {_1}) unbekannter Arbeitsbereich (einer von {_1}) @msg unsupported: {0} nicht unterstützt: {0} @msg variables are locked die Variablen sind gesperrt +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mehr als {MAX_CSV_ROWS} Datensätze: „Datensätze importieren“ liest höchstens {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mehr als {MAX_CSV_COLS} Variablen: „Datensätze importieren“ liest höchstens {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} die Variablen, die kein Text sind, wurden ausgelassen: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` und `options.{key}: {inner}` widersprechen sich: Option nur einmal angeben @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files Dateien der Version {0} können nicht komprimiert werden: Erst Version {COMPRESSED_SINCE} und neuer öffnen komprimierte Dateien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e704faade5..ca944e5e9e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4428,6 +4428,8 @@ digits Malayalam Μαλαγιάλαμ @msg unknown workspace (one of {_1}) άγνωστος χώρος εργασίας (ένας από τους {_1}) @msg unsupported: {0} δεν υποστηρίζεται: {0} @msg variables are locked οι μεταβλητές είναι κλειδωμένες +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} περισσότερα από {MAX_CSV_ROWS} σύνολα δεδομένων: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} περισσότερες από {MAX_CSV_COLS} μεταβλητές: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} οι μεταβλητές που δεν είναι κειμένου παραλείφθηκαν: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once τα `{key}: {top}` και `options.{key}: {inner}` διαφέρουν: δώστε την επιλογή μόνο μία φορά @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files τα αρχεία έκδοσης {0} δεν μπορούν να συμπιεστούν: μόνο η έκδοση {COMPRESSED_SINCE} και νεότερες ανοίγουν συμπιεσμένα αρχεία diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4ebddbe9a9..bc2b918aa3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4480,6 +4480,8 @@ axis Both Ambos @msg unknown workspace (one of {_1}) espacio de trabajo desconocido (uno de estos: {_1}) @msg unsupported: {0} no compatible: {0} @msg variables are locked las variables están bloqueadas +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} más de {MAX_CSV_ROWS} conjuntos de datos: Importar conjuntos de datos lee como máximo {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} más de {MAX_CSV_COLS} variables: Importar conjuntos de datos lee como máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} se omitieron las variables que no son de texto: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` y `options.{key}: {inner}` no coinciden: indique la opción una sola vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files los archivos de la versión {0} no se pueden comprimir: solo la versión {COMPRESSED_SINCE} y posteriores abren archivos comprimidos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7042b21f22..3d75fc5d75 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4688,6 +4688,8 @@ imageTrace Outline Ääriviiva @msg unknown workspace (one of {_1}) tuntematon työtila (jokin seuraavista: {_1}) @msg unsupported: {0} ei tuettu: {0} @msg variables are locked muuttujat on lukittu +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} yli {MAX_CSV_ROWS} tietojoukkoa: Tuo tietojoukot lukee enintään {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} yli {MAX_CSV_COLS} muuttujaa: Tuo tietojoukot lukee enintään {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} muut kuin tekstimuuttujat jätettiin pois: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` ja `options.{key}: {inner}` ovat ristiriidassa: anna asetus vain kerran @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files version {0} tiedostoja ei voi pakata: pakattuja tiedostoja voi avata vain versiosta {COMPRESSED_SINCE} alkaen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 48eb621eb9..c5b62d657b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4470,6 +4470,8 @@ axis Both Les deux @msg unknown workspace (one of {_1}) espace de travail inconnu (valeurs possibles : {_1}) @msg unsupported: {0} non pris en charge : {0} @msg variables are locked les variables sont verrouillées +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ({kinds}) ont été ignorées @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` et `options.{key}: {inner}` ne concordent pas. Indiquez l’option une seule fois @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files les fichiers de version {0} ne peuvent pas être compressés : seules les versions {COMPRESSED_SINCE} et ultérieures ouvrent les fichiers compressés diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 81f9482631..bdcbfa9925 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5250,6 +5250,8 @@ imageTrace Outline Körvonal @msg unsupported native docking operation nem támogatott natív dokkolási művelet @msg unsupported: {0} nem támogatott: {0} @msg variables are locked a változók zárolva vannak +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} több mint {MAX_CSV_ROWS} adatkészlet: az Adatkészletek importálása legfeljebb {MAX_CSV_ROWS} adatkészletet olvas be +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} több mint {MAX_CSV_COLS} változó: az Adatkészletek importálása legfeljebb {MAX_CSV_COLS} változót olvas be @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} a VectorCraft nem keres más alkalmazások és a rendszer mappáiban: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} a VectorCraft nem keres a Users alatti Shared és Public mappában: {path} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6acfaf3c9a..b912c4e8f5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4521,6 +4521,8 @@ axis Both Entrambi @msg unknown workspace (one of {_1}) area di lavoro sconosciuta (una delle seguenti: {_1}) @msg unsupported: {0} non supportato: {0} @msg variables are locked le variabili sono bloccate +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} più di {MAX_CSV_ROWS} set di dati: Importa set di dati ne legge al massimo {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} più di {MAX_CSV_COLS} variabili: Importa set di dati ne legge al massimo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} le variabili che non sono di testo sono state escluse: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` non coincidono: indicare l'opzione una sola volta @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files i file della versione {0} non possono essere compressi: solo la versione {COMPRESSED_SINCE} e successive aprono file compressi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bf3cd6bd1..0380bf4977 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4076,6 +4076,8 @@ swatch Bright Violet ビビッドバイオレット @msg Make Guides: select paths ガイドを作成: パスを選択してください @msg Release Guides: no guides ガイドを解除: ガイドがありません @msg variables are locked 変数がロックされています +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} データセットが {MAX_CSV_ROWS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_ROWS} 個までです +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 変数が {MAX_CSV_COLS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_COLS} 個までです @msg variables that aren't text were left out: {kinds} テキスト以外の変数は除外されました: {kinds} @msg guides are locked ガイドがロックされています @msg handle must be in or out handle には in または out を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cf411b072c..296a233f83 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5417,6 +5417,8 @@ imageTrace Outline კონტური @msg too many changed shortcuts ზედმეტად ბევრი შეცვლილი მალსახმობი @msg too many library panels were opened in this session ამ სესიაში ზედმეტად ბევრი ბიბლიოთეკის პანელი გაიხსნა @msg variables are locked ცვლადები ჩაკეტილია +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS}-ზე მეტი მონაცემთა ნაკრები: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_ROWS}-ს +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS}-ზე მეტი ცვლადი: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_COLS}-ს @msg variables that aren't text were left out: {kinds} ცვლადები, რომლებიც ტექსტი არ არის, გამოტოვებულია: {kinds} @msg x and y must be finite x და y სასრული უნდა იყოს @msg {id} opens another app: only the person at the keyboard can run it {id} სხვა აპს ხსნის: მისი გაშვება მხოლოდ კლავიატურასთან მყოფ ადამიანს შეუძლია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81f6c600c6..59baeea9f1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4003,6 +4003,8 @@ theme Appearance 외관 @msg Make Guides: select paths 안내선 만들기: 패스를 선택하세요 @msg Release Guides: no guides 안내선 해제: 안내선이 없습니다 @msg variables are locked 변수가 잠겨 있습니다 +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 데이터 세트가 {MAX_CSV_ROWS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_ROWS}개를 읽습니다 +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 변수가 {MAX_CSV_COLS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_COLS}개를 읽습니다 @msg variables that aren't text were left out: {kinds} 텍스트가 아닌 변수는 제외되었습니다: {kinds} @msg guides are locked 안내선이 잠겨 있습니다 @msg handle must be in or out handle은 in 또는 out이어야 합니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14825f83cf..8f292c0d9c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4612,6 +4612,8 @@ imageTrace Outline Kontur @msg unknown workspace (one of {_1}) nieznany obszar roboczy (jeden z: {_1}) @msg unsupported: {0} nieobsługiwane: {0} @msg variables are locked zmienne są zablokowane +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} więcej niż {MAX_CSV_ROWS} zestawów danych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} więcej niż {MAX_CSV_COLS} zmiennych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} pominięto zmienne, które nie są tekstowe: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` i `options.{key}: {inner}` są sprzeczne: podaj opcję tylko raz @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files plików w wersji {0} nie można kompresować: skompresowane pliki otwierają tylko wersje {COMPRESSED_SINCE} i nowsze diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 96a31c3e57..f4c43bdb8a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4052,6 +4052,8 @@ axis Both Ambos @msg unknown workspace (one of {_1}) espaço de trabalho desconhecido (um de {_1}) @msg unsupported: {0} não suportado: {0} @msg variables are locked as variáveis estão bloqueadas +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mais de {MAX_CSV_ROWS} conjuntos de dados: Importar Conjuntos de Dados lê no máximo {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mais de {MAX_CSV_COLS} variáveis: Importar Conjuntos de Dados lê no máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} as variáveis que não são de texto foram omitidas: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` não coincidem: informe a opção uma só vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files arquivos da versão {0} não podem ser compactados: somente a versão {COMPRESSED_SINCE} e posteriores abrem arquivos compactados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fdb51b80df..9798ffe64e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4516,6 +4516,8 @@ axis Both Оба @msg unknown workspace (one of {_1}) неизвестная рабочая среда (одна из: {_1}) @msg unsupported: {0} не поддерживается: {0} @msg variables are locked переменные заблокированы +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} больше {MAX_CSV_ROWS} наборов данных: «Импортировать наборы данных» читает не более {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} больше {MAX_CSV_COLS} переменных: «Импортировать наборы данных» читает не более {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} переменные, которые не являются текстовыми, пропущены: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` и `options.{key}: {inner}` противоречат друг другу: укажите параметр только один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файлы версии {0} не могут быть сжаты: только версия {COMPRESSED_SINCE} и новее открывают сжатые файлы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e2dddf022b..1b6429b628 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4379,6 +4379,8 @@ axis Both Båda @msg unknown workspace (one of {_1}) okänd arbetslayout (en av {_1}) @msg unsupported: {0} stöds inte: {0} @msg variables are locked variablerna är låsta +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} fler än {MAX_CSV_ROWS} datauppsättningar: Importera datauppsättningar läser högst {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} fler än {MAX_CSV_COLS} variabler: Importera datauppsättningar läser högst {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} variabler som inte är text utelämnades: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` och `options.{key}: {inner}` stämmer inte överens: ange alternativet bara en gång @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files filer i version {0} kan inte komprimeras: endast version {COMPRESSED_SINCE} och senare kan öppna komprimerade filer diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7e5ca938c6..b0da961f07 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1736,6 +1736,39 @@ fn saved_tracing_preset_errors_are_translated() { } } +/// Export Data Sets' refusals of more data sets or variables than Import Data Sets reads are +/// translated in every language that translates every message. +#[test] +fn dataset_export_limit_errors_are_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect(); + s.execute("dataset.import", &json!({"csv": format!("name,V1\n{rows}")})).unwrap(); + s.execute("dataset.new", &json!({"name": "Set 1001"})).unwrap(); + let mut errors = vec![]; + let e = s.execute("dataset.export", &json!({})).unwrap_err(); + let want = "more than 1000 data sets: Import Data Sets reads at most 1000"; + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + errors.push((e.to_string(), want)); + s.execute("dataset.delete", &json!({"names": ["Set 1001"]})).unwrap(); + for i in 2..=257 { + s.execute("variable.define", &json!({"name": format!("V{i}"), "kind": "text"})).unwrap(); + } + let e = s.execute("dataset.export", &json!({})).unwrap_err(); + let want = "more than 256 variables: Import Data Sets reads at most 256"; + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + errors.push((e.to_string(), want)); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, want) in &errors { + let shown = message(lang, e); + assert!(!shown.contains(want), "{code}: {shown}"); + } + } +} + /// The status bar's line for an EPS file whose PostScript stops on an error, opened partly or /// refused, and the refusal's dialog keep the error's name as PostScript spells it and its meaning, /// which each language shows as its catalog translates the meaning. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9ecf2ccf93..66e00165b4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5334,6 +5334,8 @@ theme Appearance Görünüm @msg the spine has no segments omurganın segmenti yok @msg too many library panels were opened in this session bu oturumda çok fazla kütüphane paneli açıldı @msg variables are locked değişkenler kilitli +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS} veri setinden fazla: Veri Kümelerini İçe Aktar en fazla {MAX_CSV_ROWS} tane okur +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS} değişkenden fazla: Veri Kümelerini İçe Aktar en fazla {MAX_CSV_COLS} tane okur @msg x and y must be finite x ve y sonlu olmalıdır @msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 eski .ai dosyalarını yazar; bir .ait şablonu her zaman PDF uyumludur @msg Edit Original opens image and document files only; “{name}” is not one Özgünü Düzenle yalnızca görüntü ve belge dosyalarını açar; “{name}” bunlardan biri değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d348440a2c..ce992f29ab 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4505,6 +4505,8 @@ axis Both Обидві @msg unknown workspace (one of {_1}) невідоме робоче середовище (одна з: {_1}) @msg unsupported: {0} не підтримується: {0} @msg variables are locked змінні заблоковані +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} більше ніж {MAX_CSV_ROWS} наборів даних: «Імпортувати набори даних» читає не більше {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} більше ніж {MAX_CSV_COLS} змінних: «Імпортувати набори даних» читає не більше {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} змінні, що не є текстовими, пропущено: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` і `options.{key}: {inner}` суперечать одне одному: вкажіть параметр лише один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файли версії {0} не можуть бути стиснуті: тільки версія {COMPRESSED_SINCE} і новіші відкривають стислі файли diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 09652ede2b..9bb1c58a82 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4912,6 +4912,8 @@ theme Appearance Giao diện @msg unsupported native docking operation thao tác neo gốc không được hỗ trợ @msg unsupported: {0} không được hỗ trợ: {0} @msg variables are locked biến số bị khóa +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} hơn {MAX_CSV_ROWS} tập dữ liệu: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} hơn {MAX_CSV_COLS} biến số: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft không tìm kiếm trong thư mục của ứng dụng khác hoặc hệ thống: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft không tìm kiếm thư mục Shared hoặc Public trong Users: {path} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 841bd4528a..027d9c29d1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3471,6 +3471,8 @@ digits Malayalam 马拉雅拉姆数字 Lock Variables 锁定变量 Unlock Variables 解锁变量 @msg variables are locked 变量已锁定 +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 数据集超过 {MAX_CSV_ROWS} 个:“导入数据集”最多读取 {MAX_CSV_ROWS} 个 +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 变量超过 {MAX_CSV_COLS} 个:“导入数据集”最多读取 {MAX_CSV_COLS} 个 @msg variables that aren't text were left out: {kinds} 已省略非文本变量:{kinds} List Variables 列出变量 Bind Variable 绑定变量 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a515d59a74..ce25e4b0dc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4459,6 +4459,8 @@ digits Malayalam 馬來亞拉姆數字 Lock Variables 鎖定變數 Unlock Variables 解除鎖定變數 @msg variables are locked 變數已鎖定 +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 資料集超過 {MAX_CSV_ROWS} 個:「匯入資料集」最多讀取 {MAX_CSV_ROWS} 個 +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 變數超過 {MAX_CSV_COLS} 個:「匯入資料集」最多讀取 {MAX_CSV_COLS} 個 @msg variables that aren't text were left out: {kinds} 已略過非文字變數:{kinds} List Variables 列出變數 Bind Variable 綁定變數 From 660102064f449c19a16d2b67207900c85d328f06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:59:49 -0800 Subject: [PATCH 072/674] Variables: Import Data Sets reports why a cell was refused dataset.import replaced the reason for a refused cell with "value for `X` must match its variable kind", so a visibility value such as maybe and a graph value over 262,144 bytes gave the same message. The error now keeps the line and gives the reason, and both messages have a row in every complete-message catalog. --- crates/engine/src/cmd/variablecmds/csv.rs | 24 +++++++++---------- crates/engine/src/tests/variables.rs | 17 ++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 2 ++ crates/ui-egui/src/i18n/cs.tsv | 2 ++ crates/ui-egui/src/i18n/de.tsv | 2 ++ crates/ui-egui/src/i18n/el.tsv | 2 ++ crates/ui-egui/src/i18n/es.tsv | 2 ++ crates/ui-egui/src/i18n/fi.tsv | 2 ++ crates/ui-egui/src/i18n/fr.tsv | 2 ++ crates/ui-egui/src/i18n/hu.tsv | 2 ++ crates/ui-egui/src/i18n/it.tsv | 2 ++ crates/ui-egui/src/i18n/ja.tsv | 2 ++ crates/ui-egui/src/i18n/ka.tsv | 2 ++ crates/ui-egui/src/i18n/ko.tsv | 2 ++ crates/ui-egui/src/i18n/pl.tsv | 2 ++ crates/ui-egui/src/i18n/pt-br.tsv | 2 ++ crates/ui-egui/src/i18n/ru.tsv | 2 ++ crates/ui-egui/src/i18n/sv.tsv | 2 ++ crates/ui-egui/src/i18n/tests.rs | 28 +++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 2 ++ crates/ui-egui/src/i18n/uk.tsv | 2 ++ crates/ui-egui/src/i18n/vi.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 2 ++ docs/mcp.md | 3 ++- 25 files changed, 100 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 65388fb16d..ee61436fac 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -152,17 +152,19 @@ fn csv_escape(s: &str) -> String { if s.is_empty() || s.contains([',', '"', '\n', '\r']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } } -/// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). -fn parse_visible_cell(s: &str, var: &str, cmd: &str) -> Result { +/// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). An error names the +/// file line `line`. +fn parse_visible_cell(s: &str, var: &str, line: usize, cmd: &str) -> Result { match s.trim().to_ascii_lowercase().as_str() { "true" | "1" | "yes" => Ok(true), "false" | "0" | "no" => Ok(false), - _ => Err(bad(cmd, format!("value for `{var}` must be true or false"))), + _ => Err(bad(cmd, format!("line {line}: value for `{var}` must be true or false"))), } } -/// The value of a cell. A quoted empty text cell is an empty text value; any other empty cell is no value. -fn cell_to_value(kind: VariableKind, cell: &str, quoted: bool, var: &str, cmd: &str) -> Result> { +/// The value of a cell on file line `line`. A quoted empty text cell is an empty text value; any +/// other empty cell is no value. An error names the line and the reason. +fn cell_to_value(kind: VariableKind, cell: &str, quoted: bool, var: &str, line: usize, cmd: &str) -> Result> { // A text cell is not trimmed here (the parser trims unquoted cells); image, graph and // visibility cells are trimmed. let t = if kind == VariableKind::Text { cell } else { cell.trim() }; @@ -173,8 +175,8 @@ fn cell_to_value(kind: VariableKind, cell: &str, quoted: bool, var: &str, cmd: & VariableKind::Text => DataValue::Text(t.to_string()), VariableKind::Image => DataValue::Image(t.to_string()), VariableKind::Graph if t.len() <= MAX_GRAPH_CSV => DataValue::Graph(t.to_string()), - VariableKind::Graph => return Err(bad(cmd, format!("value for `{var}` is longer than {MAX_GRAPH_CSV} bytes"))), - VariableKind::Visibility => DataValue::Visible(parse_visible_cell(t, var, cmd)?), + VariableKind::Graph => return Err(bad(cmd, format!("line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes"))), + VariableKind::Visibility => DataValue::Visible(parse_visible_cell(t, var, line, cmd)?), })) } @@ -310,12 +312,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { for &(col, ref var, kind) in &columns { let cell = row.get(col).map(String::as_str).unwrap_or(""); let was_quoted = quoted.get(col).copied().unwrap_or(false); - match cell_to_value(kind, cell, was_quoted, var, C) { - Ok(Some(v)) => { - values.insert(var.clone(), v); - } - Ok(None) => {} - Err(_) => return Err(bad(C, format!("line {line}: value for `{var}` must match its variable kind"))), + if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? { + values.insert(var.clone(), v); } } parsed.push(DataSet { name, values }); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index f57f8a5972..7650df6a2e 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1416,6 +1416,23 @@ fn datasets_csv_row_errors_name_the_file_line() { assert!(long.contains("line 3:") && long.contains("longer than 255"), "{long}"); } +/// A refused cell's error gives its line and why the value was refused: a visibility value that +/// isn't true or false, or a graph value longer than the graph data limit. +#[test] +fn datasets_csv_cell_errors_say_why() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); + let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); + let maybe = error(&mut s, "name,Show\nX,maybe"); + let want = "line 2: value for `Show` must be true or false"; + assert!(matches!(&maybe, EngineError::BadParams { msg, .. } if msg == want), "{maybe}"); + let long = error(&mut s, &format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000))); + let want = "line 2: value for `Sales` is longer than 262144 bytes"; + assert!(matches!(&long, EngineError::BadParams { msg, .. } if msg == want), "{long}"); + assert!(s.doc().unwrap().doc.variables.datasets.is_empty()); +} + /// A header cell that names no variable defines one, unbound, in the import's undo step: `#` /// defines a visibility variable, `@` defines an image variable, and a cell without a prefix /// defines a text variable. Importing the file again finds them; a prefix of the other kind, a diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 21b2ff53fa..6564f158d2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5086,6 +5086,8 @@ digits Malayalam Malaiàlam @msg lang must be one of {_1} lang ha de ser un de {_1} @msg larger than 256 MB més gran de 256 MB @msg layers can't be wrap objects les capes no poden ser objectes d’embolcall +@msg line {line}: value for `{var}` must be true or false línia {line}: el valor de `{var}` ha de ser true o false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes línia {line}: el valor de `{var}` ocupa més de {MAX_GRAPH_CSV} bytes @msg library panel `{given}` isn't missing its library al panell de biblioteca `{given}` no li falta la biblioteca @msg library panel `{given}` isn't open el panell de biblioteca `{given}` no està obert @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les imatges enllaçades mostren la previsualització de baixa resolució desada al fitxer fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b1742b59bf..eb9709c6f5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4472,6 +4472,8 @@ imageTrace Outline Obrys @msg join needs open paths spojení vyžaduje otevřené cesty @msg lang must be one of {_1} lang musí být jedno z {_1} @msg layers can't be wrap objects vrstvy nemohou být objekty obtékání +@msg line {line}: value for `{var}` must be true or false řádek {line}: hodnota pro `{var}` musí být true nebo false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes řádek {line}: hodnota pro `{var}` je delší než {MAX_GRAPH_CSV} bajtů @msg missing `folder` chybí `folder` @msg missing `id` (see plugin.list) chybí `id` (viz plugin.list) @msg missing `name` chybí `name` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d850991b15..789baa3dd3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4079,6 +4079,8 @@ theme Appearance Erscheinungsbild @msg join needs open paths zum Zusammenfügen sind offene Pfade nötig @msg lang must be one of {_1} lang muss einer der folgenden Werte sein: {_1} @msg layers can't be wrap objects Ebenen können keine Umflussobjekte sein +@msg line {line}: value for `{var}` must be true or false Zeile {line}: der Wert für `{var}` muss true oder false sein +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes Zeile {line}: der Wert für `{var}` ist länger als {MAX_GRAPH_CSV} Byte @msg missing `folder` `folder` fehlt @msg missing `id` (see plugin.list) `id` fehlt (siehe plugin.list) @msg missing `name` `name` fehlt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ca944e5e9e..521e8761ac 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4119,6 +4119,8 @@ digits Malayalam Μαλαγιάλαμ @msg join needs open paths η ένωση απαιτεί ανοιχτές διαδρομές @msg lang must be one of {_1} η γλώσσα πρέπει να είναι μία από τις {_1} @msg layers can't be wrap objects τα επίπεδα δεν μπορούν να είναι αντικείμενα αναδίπλωσης +@msg line {line}: value for `{var}` must be true or false γραμμή {line}: η τιμή για το `{var}` πρέπει να είναι true ή false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes γραμμή {line}: η τιμή για το `{var}` είναι μεγαλύτερη από {MAX_GRAPH_CSV} byte @msg missing `folder` λείπει το `folder` @msg missing `id` (see plugin.list) λείπει το `id` (δείτε plugin.list) @msg missing `name` λείπει το `name` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index bc2b918aa3..a262f90b6f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4165,6 +4165,8 @@ axis Both Ambos @msg join needs open paths unir necesita trazados abiertos @msg lang must be one of {_1} lang debe ser uno de estos: {_1} @msg layers can't be wrap objects las capas no pueden ser objetos para ceñir +@msg line {line}: value for `{var}` must be true or false línea {line}: el valor de `{var}` debe ser true o false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes línea {line}: el valor de `{var}` ocupa más de {MAX_GRAPH_CSV} bytes @msg missing `folder` falta `folder` @msg missing `id` (see plugin.list) falta `id` (consulta plugin.list) @msg missing `name` falta `name` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3d75fc5d75..764b84f2db 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4380,6 +4380,8 @@ imageTrace Outline Ääriviiva @msg join needs open paths liittäminen vaatii avoimia polkuja @msg lang must be one of {_1} lang-arvon on oltava jokin seuraavista: {_1} @msg layers can't be wrap objects tasot eivät voi olla rivitysobjekteja +@msg line {line}: value for `{var}` must be true or false rivi {line}: muuttujan `{var}` arvon on oltava true tai false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes rivi {line}: muuttujan `{var}` arvo on pidempi kuin {MAX_GRAPH_CSV} tavua @msg missing `folder` `folder` puuttuu @msg missing `id` (see plugin.list) `id` puuttuu (ks. plugin.list) @msg missing `name` `name` puuttuu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c5b62d657b..c9625a8730 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4155,6 +4155,8 @@ axis Both Les deux @msg join needs open paths la jonction nécessite des tracés ouverts @msg lang must be one of {_1} lang doit valoir l’une de ces valeurs : {_1} @msg layers can't be wrap objects les calques ne peuvent pas être des objets d’habillage +@msg line {line}: value for `{var}` must be true or false ligne {line} : la valeur de `{var}` doit valoir true ou false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes ligne {line} : la valeur de `{var}` dépasse {MAX_GRAPH_CSV} octets @msg missing `folder` `folder` manquant @msg missing `id` (see plugin.list) `id` manquant (voir plugin.list) @msg missing `name` `name` manquant diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index bdcbfa9925..fc7937377a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4810,6 +4810,8 @@ imageTrace Outline Körvonal @msg lang must be one of {_1} a lang értéke ezek egyike lehet: {_1} @msg larger than 256 MB nagyobb 256 MB-nál @msg layers can't be wrap objects réteg nem lehet körbefuttató objektum +@msg line {line}: value for `{var}` must be true or false {line}. sor: a(z) `{var}` értéke csak true vagy false lehet +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes {line}. sor: a(z) `{var}` értéke hosszabb {MAX_GRAPH_CSV} bájtnál @msg Live Paint Merge: select a Live Paint group and the paths to add Élő festés egyesítése: jelölj ki egy élőfestés-csoportot és a hozzáadandó útvonalakat @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first Az élő festés útvonalakat és összetett útvonalakat fogad: előbb alakítsd útvonallá a szöveget, a képeket és a többi objektumot @msg Live Paint: select paths or compound paths Élő festés: jelölj ki útvonalakat vagy összetett útvonalakat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b912c4e8f5..0cc2f2d912 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4206,6 +4206,8 @@ axis Both Entrambi @msg join needs open paths per unire servono tracciati aperti @msg lang must be one of {_1} lang deve essere uno dei seguenti: {_1} @msg layers can't be wrap objects i livelli non possono essere oggetti di avvolgimento +@msg line {line}: value for `{var}` must be true or false riga {line}: il valore di `{var}` deve essere true o false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes riga {line}: il valore di `{var}` supera i {MAX_GRAPH_CSV} byte @msg missing `folder` manca `folder` @msg missing `id` (see plugin.list) manca `id` (vedi plugin.list) @msg missing `name` manca `name` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0380bf4977..eb24f7595c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4285,6 +4285,8 @@ swatch Bright Violet ビビッドバイオレット @msg node {_1} is not text ノード {_1} はテキストではありません @msg Text Wrap: select a wrap object テキストの回り込み: 回り込みオブジェクトを選択してください @msg layers can't be wrap objects レイヤーは回り込みオブジェクトにできません +@msg line {line}: value for `{var}` must be true or false {line} 行目: `{var}` の値には true または false を指定してください +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes {line} 行目: `{var}` の値が {MAX_GRAPH_CSV} バイトを超えています @msg no threaded text selected スレッドテキストが選択されていません @msg Create Outlines: select text objects アウトラインを作成: テキストオブジェクトを選択してください @msg paste unavailable 貼り付けを使用できません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 296a233f83..883e00dcac 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3938,6 +3938,8 @@ font-technology Variable ცვლადი @msg join needs open paths შეერთებას ღია ტრაექტორიები სჭირდება @msg lang must be one of {_1} lang უნდა იყოს ერთ-ერთი: {_1} @msg layers can't be wrap objects შრეები შემოსავლელი ობიექტები ვერ იქნება +@msg line {line}: value for `{var}` must be true or false სტრიქონი {line}: `{var}`-ის მნიშვნელობა უნდა იყოს true ან false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes სტრიქონი {line}: `{var}`-ის მნიშვნელობა {MAX_GRAPH_CSV} ბაიტზე გრძელია @msg missing `folder` აკლია `folder` @msg missing `id` (see plugin.list) აკლია `id` (იხ. plugin.list) @msg missing `name` აკლია `name` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 59baeea9f1..0164762a5e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4212,6 +4212,8 @@ theme Appearance 외관 @msg node {_1} is not text 노드 {_1}은(는) 텍스트가 아닙니다 @msg Text Wrap: select a wrap object 텍스트 감싸기: 감싸기 개체를 선택하세요 @msg layers can't be wrap objects 레이어는 감싸기 개체가 될 수 없습니다 +@msg line {line}: value for `{var}` must be true or false {line}행: `{var}`의 값은 true 또는 false여야 합니다 +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes {line}행: `{var}`의 값이 {MAX_GRAPH_CSV}바이트보다 깁니다 @msg no threaded text selected 선택한 연결 텍스트가 없습니다 @msg Create Outlines: select text objects 윤곽선 만들기: 텍스트 개체를 선택하세요 @msg paste unavailable 붙여넣을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8f292c0d9c..5d57e77cf8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4295,6 +4295,8 @@ imageTrace Outline Kontur @msg join needs open paths łączenie wymaga otwartych ścieżek @msg lang must be one of {_1} lang musi mieć jedną z wartości: {_1} @msg layers can't be wrap objects warstwy nie mogą być obiektami oblewanymi +@msg line {line}: value for `{var}` must be true or false wiersz {line}: wartość `{var}` musi być true lub false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes wiersz {line}: wartość `{var}` jest dłuższa niż {MAX_GRAPH_CSV} bajtów @msg missing `folder` brak `folder` @msg missing `id` (see plugin.list) brak `id` (patrz plugin.list) @msg missing `name` brak `name` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f4c43bdb8a..c725ba6c6c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3739,6 +3739,8 @@ axis Both Ambos @msg join needs open paths unir exige traçados abertos @msg lang must be one of {_1} lang deve ser um de {_1} @msg layers can't be wrap objects camadas não podem ser objetos de quebra +@msg line {line}: value for `{var}` must be true or false linha {line}: o valor de `{var}` deve ser true ou false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes linha {line}: o valor de `{var}` tem mais de {MAX_GRAPH_CSV} bytes @msg missing `folder` falta `folder` @msg missing `id` (see plugin.list) falta `id` (veja plugin.list) @msg missing `name` falta `name` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9798ffe64e..f28fa3fca2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4201,6 +4201,8 @@ axis Both Оба @msg join needs open paths соединение требует открытых контуров @msg lang must be one of {_1} lang должен быть одним из: {_1} @msg layers can't be wrap objects слои не могут быть объектами обтекания +@msg line {line}: value for `{var}` must be true or false строка {line}: значение `{var}` должно быть true или false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes строка {line}: значение `{var}` длиннее {MAX_GRAPH_CSV} байт @msg missing `folder` отсутствует `folder` @msg missing `id` (see plugin.list) отсутствует `id` (см. plugin.list) @msg missing `name` отсутствует `name` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1b6429b628..6f30ec2e0c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4070,6 +4070,8 @@ axis Both Båda @msg join needs open paths foga samman kräver öppna banor @msg lang must be one of {_1} lang måste vara något av {_1} @msg layers can't be wrap objects lager kan inte vara radbrytningsobjekt +@msg line {line}: value for `{var}` must be true or false rad {line}: värdet för `{var}` måste vara true eller false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes rad {line}: värdet för `{var}` är längre än {MAX_GRAPH_CSV} byte @msg missing `folder` `folder` saknas @msg missing `id` (see plugin.list) `id` saknas (se plugin.list) @msg missing `name` `name` saknas diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b0da961f07..6bbfb107b2 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1796,6 +1796,34 @@ fn postscript_errors_keep_their_name_and_meaning() { } } +/// Import Data Sets' errors for a refused cell are translated in every language that translates +/// every message, with the line and the variable kept. +#[test] +fn dataset_import_cell_errors_are_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); + let mut errors = vec![]; + for (csv, want) in [ + ("name,Show\nX,maybe".to_string(), "line 2: value for `Show` must be true or false"), + (format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000)), "line 2: value for `Sales` is longer than 262144 bytes"), + ] { + let e = s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + errors.push((e.to_string(), want)); + } + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, want) in &errors { + let shown = message(lang, e); + assert!(!shown.contains(want) && shown.contains('2') && shown.contains('`'), "{code}: {shown}"); + } + } +} + /// The errors of the parameter checks that many commands share (a number given as text, a missing /// number or index, a fraction for a whole number, `ids` that aren't a list of object ids, an /// object id that is negative or names no object, a date that isn't Unix seconds) fill their diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 66e00165b4..8f6e7c4911 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3932,6 +3932,8 @@ axis Both Her İkisi @msg join needs open paths katılmak için açık yollara ihtiyaç var @msg lang must be one of {_1} dil {_1}'den biri olmalıdır @msg layers can't be wrap objects katmanlar sarma nesneleri olamaz +@msg line {line}: value for `{var}` must be true or false satır {line}: `{var}` değeri true veya false olmalıdır +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes satır {line}: `{var}` değeri {MAX_GRAPH_CSV} bayttan uzun @msg missing `folder` 'klasör' eksik @msg missing `id` (see plugin.list) `kimlik` eksik (bkz. eklenti.liste) @msg missing `name` "isim" eksik diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ce992f29ab..86a10d0d46 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4190,6 +4190,8 @@ axis Both Обидві @msg join needs open paths з’єднання вимагає відкритих контурів @msg lang must be one of {_1} lang має бути одним з: {_1} @msg layers can't be wrap objects шари не можуть бути об’єктами обтікання +@msg line {line}: value for `{var}` must be true or false рядок {line}: значення `{var}` має бути true або false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes рядок {line}: значення `{var}` довше за {MAX_GRAPH_CSV} байтів @msg missing `folder` відсутня `folder` @msg missing `id` (see plugin.list) відсутня `id` (див. plugin.list) @msg missing `name` відсутня `name` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9bb1c58a82..deb4955613 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4460,6 +4460,8 @@ theme Appearance Giao diện @msg lang must be one of {_1} lang phải là một trong {_1} @msg larger than 256 MB lớn hơn 256 MB @msg layers can't be wrap objects lớp không thể là đối tượng bọc +@msg line {line}: value for `{var}` must be true or false dòng {line}: giá trị của `{var}` phải là true hoặc false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes dòng {line}: giá trị của `{var}` dài hơn {MAX_GRAPH_CSV} byte @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel ảnh liên kết hiển thị bản xem trước độ phân giải thấp đã lưu trong tệp cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết @msg Live Paint Merge: select a Live Paint group and the paths to add Hợp nhất tô trực tiếp: chọn nhóm tô trực tiếp và các đường dẫn để thêm @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first Tô trực tiếp nhận đường dẫn và đường dẫn phức: hãy chuyển văn bản, hình ảnh và các đối tượng khác thành đường dẫn trước diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 027d9c29d1..305c4c5995 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4010,6 +4010,8 @@ imageTrace Outline 轮廓 @msg node {_1} is not text 节点 {_1} 不是文字 @msg Text Wrap: select a wrap object 文本绕排:请选择一个绕排对象 @msg layers can't be wrap objects 图层不能作为绕排对象 +@msg line {line}: value for `{var}` must be true or false 第 {line} 行:`{var}` 的值必须是 true 或 false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes 第 {line} 行:`{var}` 的值超过 {MAX_GRAPH_CSV} 字节 @msg no threaded text selected 未选择串接文本 @msg Create Outlines: select text objects 创建轮廓:请选择文本对象 @msg paste unavailable 无法粘贴 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ce25e4b0dc..3ba21bee0b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1931,6 +1931,8 @@ file-filter Templates 範本 @msg node {_1} is not text 節點 {_1} 不是文字 @msg Text Wrap: select a wrap object 文字繞圖:請選取繞圖物件 @msg layers can't be wrap objects 圖層不能作為繞圖物件 +@msg line {line}: value for `{var}` must be true or false 第 {line} 行:`{var}` 的值必須是 true 或 false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes 第 {line} 行:`{var}` 的值超過 {MAX_GRAPH_CSV} 位元組 @msg no threaded text selected 未選取串連文字 @msg Create Outlines: select text objects 建立外框:請選取文字物件 @msg paste unavailable 無法貼上 diff --git a/docs/mcp.md b/docs/mcp.md index 50f73e7b70..5a080ea972 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1644,7 +1644,8 @@ already walks Image Trace. Short agent entry points: `dataset.export {path?}` (CSV: `name`, then one column per variable). `dataset.import` also reads tab-separated files, and files whose first header cell isn't `name`: every header cell is then a variable, and the rows take the first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file - line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the + line the row starts on, and an error about a value says why it was refused: a visibility value other than true, + false, 1, 0, yes or no, or a graph value longer than 262,144 bytes. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph From 386bfc881e50ae696c48091f141d5535320770db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 11:51:18 -0800 Subject: [PATCH 073/674] Docs: move the import value error note next to the data set warning --- docs/mcp.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 5a080ea972..aa997a323d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1644,8 +1644,7 @@ already walks Image Trace. Short agent entry points: `dataset.export {path?}` (CSV: `name`, then one column per variable). `dataset.import` also reads tab-separated files, and files whose first header cell isn't `name`: every header cell is then a variable, and the rows take the first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file - line the row starts on, and an error about a value says why it was refused: a visibility value other than true, - false, 1, 0, yes or no, or a graph value longer than 262,144 bytes. A header cell that names no variable defines one, unbound, in the same undo step as the + line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph @@ -1776,6 +1775,9 @@ new variables without binding them, `dataset.select`, `dataset.next` and `datase has a value for". A data set with a value for a bound variable gives no warning even when every object bound to it is locked; `skipped` counts those objects. +A `dataset.import` error about a value says why it was refused: a visibility value other than true, false, 1, 0, yes +or no, or a graph value longer than 262,144 bytes. + `dataset.update {all?}` writes what the bound objects hold now into the active data set, for each variable that the data set holds. A variable whose objects report no value, because they are locked, inside a locked layer or group, or deleted, keeps the data set's value. With `all: true` it also adds every other variable that the From 06221ce545ff1ab73697c0a2d1c938286284b993 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:22:15 -0800 Subject: [PATCH 074/674] Variables: a CSV header that names one variable twice is refused dataset.import read two header cells that named one variable (City and City, or Shown and #Shown) into the same column, so each row kept only the last non-blank cell and the other value was dropped without a word. The import is now refused with the two column numbers, and the message has a row in every complete-message catalog. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/cmd/variablecmds/csv.rs | 8 ++++++-- crates/engine/src/tests/variables.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 3 ++- 26 files changed, 71 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 6416c8eb16..03636d11f0 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -731,7 +731,7 @@ pub fn specs() -> Vec { "Import Data Sets…", ["Window", "Variables"], None, - "{path? | data? | dataBase64? | csv?} load datasets from CSV, comma- or tab-separated (header: name, then variable names; one row per dataset; without the name column every header is a variable and the rows take the first free names Data Set 1, 2…). A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so is a header that would define a variable while the variables are locked. Rows whose name already exists are replaced → {imported, updated, names, defined}", + "{path? | data? | dataBase64? | csv?} load datasets from CSV, comma- or tab-separated (header: name, then variable names; one row per dataset; without the name column every header is a variable and the rows take the first free names Data Set 1, 2…). A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. Rows whose name already exists are replaced → {imported, updated, names, defined}", has_doc, dataset_import ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index ee61436fac..8f23772a3f 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -252,8 +252,8 @@ fn header_variable( /// names; the other headers name variables, as [`header_variable`] reads them, and the /// variables the document doesn't define yet are defined, unbound. Without the `name` column, /// every header names a variable and the rows take the first free names "Data Set 1", "Data -/// Set 2" and so on. Existing rows of the same name are replaced; new names are appended. One -/// undo step. +/// Set 2" and so on. Two headers that name one variable are refused. Existing rows of the same +/// name are replaced; new names are appended. One undo step. pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.import"; let bytes = datasets_csv_bytes(p, C)?; @@ -277,6 +277,10 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("empty header in column {}", i + 1))); } let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?; + if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) { + let (first, column) = (first + 1, i + 1); + return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`"))); + } columns.push((i, name, kind)); } // Lock Variables refuses New Variable, so the import is refused when a header would define one. diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 7650df6a2e..776cf19785 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1519,6 +1519,28 @@ fn datasets_csv_refuses_graph_data_file_columns() { assert!(vars.variables.is_empty() && vars.datasets.is_empty()); } +/// Two header cells that name one variable, by the same name or by a name and its prefix, are +/// refused with both columns, and the import changes nothing. +#[test] +fn datasets_csv_refuses_two_columns_for_one_variable() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap(); + let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); + for (csv, first, second, var) in [ + ("name,City,City\nR,Paris,Rome", 2, 3, "City"), + ("name,City,City\nR,Paris,", 2, 3, "City"), + ("City,Title,City\nParis,x,Rome", 1, 3, "City"), + ("name,Shown,#Shown\nR,true,false", 2, 3, "Shown"), + ("Title\t@Photo\t@ Photo\nx\ta.png\tb.png", 2, 3, "Photo"), + ] { + let err = error(&mut s, csv); + assert!(err.contains(&format!("columns {first} and {second} both name the variable `{var}`")), "{csv}: {err}"); + } + let vars = &s.doc().unwrap().doc.variables; + assert_eq!(vars.variables.len(), 1); + assert!(vars.datasets.is_empty()); +} + /// While the variables are locked, an import is refused when a header cell would define a /// variable, as New Variable is, and a file whose headers all name variables imports. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 6564f158d2..f1b7faf27b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5248,6 +5248,7 @@ digits Malayalam Malaiàlam @msg not found no s’ha trobat @msg not in pattern editing mode no esteu en mode d’edició de motius @msg finish editing the pattern first acabeu primer l’edició del motiu +@msg columns {first} and {column} both name the variable `{name}` les columnes {first} i {column} anomenen totes dues la variable `{name}` @msg nothing encoded no s’ha codificat res @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no s’ha aplicat res del conjunt de dades {name}: cap objecte està vinculat a una variable per a la qual tingui un valor @msg nothing selected no hi ha res seleccionat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index eb9709c6f5..4c9139f121 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5473,6 +5473,7 @@ mark-style Japanese Japonské @msg Batch: {count} processed, {failed} failed Dávka: zpracováno {count}, selhalo {failed} @msg choose a destination folder vyberte cílovou složku @msg choose a source folder vyberte zdrojovou složku +@msg columns {first} and {column} both name the variable `{name}` sloupce {first} a {column} uvádějí stejnou proměnnou `{name}` @msg open a document with data sets otevřete dokument se sadami dat @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ze sady dat {name} se nic nepoužilo: žádný objekt není svázán s proměnnou, pro kterou má hodnotu @msg the action has no steps akce nemá žádné kroky diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 789baa3dd3..7bd2983cd5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5050,6 +5050,7 @@ effect Soft Weich @msg Batch: {count} processed, {failed} failed Stapelverarbeitung: {count} verarbeitet, {failed} fehlgeschlagen @msg choose a destination folder wählen Sie einen Zielordner @msg choose a source folder wählen Sie einen Quellordner +@msg columns {first} and {column} both name the variable `{name}` die Spalten {first} und {column} nennen beide die Variable `{name}` @msg open a document with data sets öffnen Sie ein Dokument mit Datensätzen @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for aus dem Datensatz {name} wurde nichts angewendet: kein Objekt ist an eine Variable gebunden, für die er einen Wert hat @msg the action has no steps die Aktion hat keine Schritte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 521e8761ac..20bd8c7eea 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5404,6 +5404,7 @@ effect Points Σημεία @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης +@msg columns {first} and {column} both name the variable `{name}` οι στήλες {first} και {column} ονομάζουν και οι δύο τη μεταβλητή `{name}` @msg open a document with data sets ανοίξτε ένα έγγραφο με σύνολα δεδομένων @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for δεν εφαρμόστηκε τίποτα από το σύνολο δεδομένων {name}: κανένα αντικείμενο δεν είναι συνδεδεμένο με μεταβλητή για την οποία έχει τιμή @msg select an Intertwine group επιλέξτε μια ομάδα διαπλοκής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a262f90b6f..26a13dddeb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5414,6 +5414,7 @@ mark-style Japanese Japonesas @msg Batch: {count} processed, {failed} failed Lote: {count} procesados, {failed} con error @msg choose a destination folder elija una carpeta de destino @msg choose a source folder elija una carpeta de origen +@msg columns {first} and {column} both name the variable `{name}` las columnas {first} y {column} nombran la misma variable `{name}` @msg open a document with data sets abra un documento con conjuntos de datos @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no se aplicó nada del conjunto de datos {name}: ningún objeto está vinculado a una variable para la que tenga un valor @msg the action has no steps la acción no tiene pasos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 764b84f2db..12edcafb73 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5416,6 +5416,7 @@ mark-style Japanese Japanilainen @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio +@msg columns {first} and {column} both name the variable `{name}` sarakkeet {first} ja {column} nimeävät molemmat muuttujan `{name}` @msg open a document with data sets avaa asiakirja, jossa on tietojoukkoja @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for tietojoukosta {name} ei käytetty mitään: mitään objektia ei ole sidottu muuttujaan, jolle siinä on arvo @msg select an Intertwine group valitse lomitusryhmä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c9625a8730..6e8e1eeb2f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5470,6 +5470,7 @@ theme Appearance Apparence @msg Batch: {count} processed, {failed} failed Traitement par lots : {count} traités, {failed} en échec @msg choose a destination folder choisissez un dossier de destination @msg choose a source folder choisissez un dossier source +@msg columns {first} and {column} both name the variable `{name}` les colonnes {first} et {column} nomment toutes deux la variable `{name}` @msg open a document with data sets ouvrez un document avec des jeux de données @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for rien du jeu de données {name} n’a été appliqué, car aucun objet n’est lié à une variable pour laquelle il a une valeur @msg the action has no steps l'action n'a aucune étape diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fc7937377a..c028358a39 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5458,6 +5458,7 @@ imageTrace Outline Körvonal @msg Batch: {count} processed, {failed} failed Kötegelt feldolgozás: {count} feldolgozva, {failed} sikertelen @msg choose a destination folder válasszon célmappát @msg choose a source folder válasszon forrásmappát +@msg columns {first} and {column} both name the variable `{name}` a(z) {first}. és a(z) {column}. oszlop ugyanazt a változót nevezi meg: `{name}` @msg open a document with data sets nyisson meg egy adatkészleteket tartalmazó dokumentumot @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ebből az adatkészletből semmi sem lett alkalmazva: {name}; egyetlen objektum sincs olyan változóhoz kötve, amelynek értéke van benne @msg the action has no steps a műveletnek nincsenek lépései diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0cc2f2d912..8f2f93c212 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5085,6 +5085,7 @@ lighting Light Luce @msg Batch: {count} processed, {failed} failed Elaborazione batch: {count} elaborati, {failed} non riusciti @msg choose a destination folder scegli una cartella di destinazione @msg choose a source folder scegli una cartella di origine +@msg columns {first} and {column} both name the variable `{name}` le colonne {first} e {column} indicano entrambe la variabile `{name}` @msg open a document with data sets apri un documento con set di dati @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for non è stato applicato nulla del set di dati {name}: nessun oggetto è associato a una variabile per cui ha un valore @msg the action has no steps l'azione non ha passaggi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index eb24f7595c..4767449f19 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5130,6 +5130,7 @@ lighting Light ライト @msg Batch: {count} processed, {failed} failed バッチ: {count} 件を処理、{failed} 件が失敗しました @msg choose a destination folder 出力先フォルダーを選択してください @msg choose a source folder ソースフォルダーを選択してください +@msg columns {first} and {column} both name the variable `{name}` 列 {first} と列 {column} が同じ変数 `{name}` を指定しています @msg open a document with data sets データセットのあるドキュメントを開いてください @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for データセット {name} から何も適用されませんでした: 値のある変数にバインドされたオブジェクトがありません @msg the action has no steps アクションにステップがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 883e00dcac..dd7083cc9b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5121,6 +5121,7 @@ imageTrace Outline კონტური @msg Batch: {count} processed, {failed} failed პაკეტური დამუშავება: დამუშავდა {count}, ვერ დამუშავდა {failed} @msg choose a destination folder აირჩიეთ დანიშნულების საქაღალდე @msg choose a source folder აირჩიეთ წყარო საქაღალდე +@msg columns {first} and {column} both name the variable `{name}` სვეტები {first} და {column} ორივე ასახელებს ცვლადს `{name}` @msg open a document with data sets გახსენით დოკუმენტი მონაცემთა ნაკრებებით @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for მონაცემთა ნაკრები {name}: არაფერი გამოყენებულა; არცერთი ობიექტი არ არის მიბმული ცვლადზე, რომელსაც მასში მნიშვნელობა აქვს @msg the action has no steps მოქმედებას ნაბიჯები არ აქვს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0164762a5e..af51f5883e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5048,6 +5048,7 @@ lighting Light 광원 @msg Batch: {count} processed, {failed} failed 일괄 처리: {count}개 처리됨, {failed}개 실패 @msg choose a destination folder 대상 폴더를 선택하세요 @msg choose a source folder 소스 폴더를 선택하세요 +@msg columns {first} and {column} both name the variable `{name}` {first}열과 {column}열이 모두 같은 변수 `{name}`을(를) 가리킵니다 @msg open a document with data sets 데이터 세트가 있는 문서를 여세요 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 데이터 세트 {name}에서 적용된 항목이 없습니다: 값이 있는 변수에 연결된 개체가 없습니다 @msg the action has no steps 액션에 단계가 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5d57e77cf8..ed0396deac 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5325,6 +5325,7 @@ mark-style Japanese Japońskie @msg Batch: {count} processed, {failed} failed Przetwarzanie wsadowe: przetworzono {count}, niepowodzenia: {failed} @msg choose a destination folder wybierz folder docelowy @msg choose a source folder wybierz folder źródłowy +@msg columns {first} and {column} both name the variable `{name}` kolumny {first} i {column} wskazują tę samą zmienną `{name}` @msg open a document with data sets otwórz dokument z zestawami danych @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for z zestawu danych {name} nic nie zastosowano: żaden obiekt nie jest powiązany ze zmienną, dla której ma on wartość @msg the action has no steps operacja nie ma kroków diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c725ba6c6c..19d52c9814 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5347,6 +5347,7 @@ mark-style Japanese Japonesas @msg Batch: {count} processed, {failed} failed Lote: {count} processados, {failed} com falha @msg choose a destination folder escolha uma pasta de destino @msg choose a source folder escolha uma pasta de origem +@msg columns {first} and {column} both name the variable `{name}` as colunas {first} e {column} nomeiam a mesma variável `{name}` @msg open a document with data sets abra um documento com conjuntos de dados @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for nada do conjunto de dados {name} foi aplicado: nenhum objeto está vinculado a uma variável para a qual ele tem um valor @msg the action has no steps a ação não tem etapas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f28fa3fca2..a8407da965 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5080,6 +5080,7 @@ lighting Light Свет @msg Batch: {count} processed, {failed} failed Пакетная обработка: обработано {count}, с ошибкой {failed} @msg choose a destination folder выберите папку назначения @msg choose a source folder выберите исходную папку +@msg columns {first} and {column} both name the variable `{name}` столбцы {first} и {column} указывают одну и ту же переменную `{name}` @msg open a document with data sets откройте документ с наборами данных @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for из набора данных {name} ничего не применено: ни один объект не привязан к переменной, для которой в нём есть значение @msg the action has no steps в действии нет шагов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6f30ec2e0c..2382ce365d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5408,6 +5408,7 @@ theme Appearance Utseende @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp +@msg columns {first} and {column} both name the variable `{name}` kolumnerna {first} och {column} anger båda variabeln `{name}` @msg open a document with data sets öppna ett dokument med datauppsättningar @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for inget i datauppsättningen {name} användes: inget objekt är bundet till en variabel som den har ett värde för @msg select an Intertwine group markera en sammanflätningsgrupp diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 6bbfb107b2..e6dcf53c53 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1705,6 +1705,25 @@ fn blend_spine_param_errors_say_what_is_wrong() { assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == "select a blend or give `id`"), "{e}"); } +/// Import Data Sets' refusal of two header cells that name one variable is translated in every +/// language that translates every message. +#[test] +fn dataset_import_repeated_column_error_is_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s.execute("dataset.import", &json!({"csv": "name,City,City\nR,Paris,Rome"})).unwrap_err(); + let want = "columns 2 and 3 both name the variable `City`"; + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + let e = e.to_string(); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &e); + assert!(!shown.contains(want), "{code}: {shown}"); + } +} + /// The errors of saving, renaming and deleting a tracing preset are translated in every language /// that translates every message. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8f6e7c4911..b8f648a0c5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5359,6 +5359,7 @@ theme Appearance Görünüm @msg its zlib compression is damaged zlib sıkıştırması hasarlı @msg its Zstandard compression is damaged Zstandard sıkıştırması hasarlı @msg it decompresses to more than {_1} MB açıldığında {_1} MB'tan fazla alan kaplıyor +@msg columns {first} and {column} both name the variable `{name}` {first} ve {column} numaralı sütunların ikisi de `{name}` değişkenini adlandırıyor @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them dosyanın değişkenleri ve veri kümeleri okunmadı (değişkenler: {variables}, veri kümeleri: {data_sets}): Değişkenler paneli bunları listelemiyor @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for {name} veri kümesinden hiçbir şey uygulanmadı: değer içerdiği bir değişkene bağlı hiçbir nesne yok @msg select an Objects on Path group bir Yol Üzerindeki Nesneler grubu seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 86a10d0d46..ecb2074931 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5065,6 +5065,7 @@ lighting Light Світло @msg Batch: {count} processed, {failed} failed Пакетна обробка: оброблено {count}, з помилкою {failed} @msg choose a destination folder виберіть папку призначення @msg choose a source folder виберіть вихідну папку +@msg columns {first} and {column} both name the variable `{name}` стовпці {first} і {column} вказують одну й ту саму змінну `{name}` @msg open a document with data sets відкрийте документ із наборами даних @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for з набору даних {name} нічого не застосовано: жоден об’єкт не прив’язано до змінної, для якої в ньому є значення @msg the action has no steps у дії немає кроків diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index deb4955613..8a6a9935ce 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5068,6 +5068,7 @@ theme Appearance Giao diện @msg Batch: {count} processed, {failed} failed Hàng loạt: đã xử lý {count}, lỗi {failed} @msg choose a destination folder hãy chọn thư mục đích @msg choose a source folder hãy chọn thư mục nguồn +@msg columns {first} and {column} both name the variable `{name}` cột {first} và cột {column} cùng chỉ định biến số `{name}` @msg open a document with data sets hãy mở một tài liệu có tập dữ liệu @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for không có gì trong tập dữ liệu {name} được áp dụng: không có đối tượng nào được gắn với biến số mà tập dữ liệu có giá trị @msg the action has no steps hành động không có bước nào diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 305c4c5995..5903547021 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4532,6 +4532,7 @@ imageTrace Outline 轮廓 @msg Batch: {count} processed, {failed} failed 批处理:已处理 {count} 个,失败 {failed} 个 @msg choose a destination folder 请选择目标文件夹 @msg choose a source folder 请选择源文件夹 +@msg columns {first} and {column} both name the variable `{name}` 第 {first} 列和第 {column} 列都指定了变量 `{name}` @msg open a document with data sets 请打开包含数据集的文档 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 数据集 {name} 未应用任何内容:没有对象绑定到该数据集中有值的变量 @msg the action has no steps 该动作没有步骤 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3ba21bee0b..e4a439e9bc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2448,6 +2448,7 @@ file-filter Templates 範本 @msg Batch: {count} processed, {failed} failed 批次:已處理 {count} 個,失敗 {failed} 個 @msg choose a destination folder 請選擇目的地資料夾 @msg choose a source folder 請選擇來源資料夾 +@msg columns {first} and {column} both name the variable `{name}` 第 {first} 欄和第 {column} 欄都指定了變數 `{name}` @msg open a document with data sets 請開啟含有資料集的文件 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 資料集 {name} 未套用任何內容:沒有物件綁定到該資料集中有值的變數 @msg the action has no steps 動作沒有步驟 diff --git a/docs/mcp.md b/docs/mcp.md index aa997a323d..77a079b4b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1648,7 +1648,8 @@ already walks Image Trace. Short agent entry points: rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph - data files) is refused. The reply's `defined` lists the variables the import defined. While the variables are + data files) is refused, and so are two cells that name one variable (`City` twice, or `Shown` and `#Shown`). The + reply's `defined` lists the variables the import defined. While the variables are locked, an import whose header would define a variable fails with "variables are locked". - Variable libraries: `variable.loadLibrary {path|xml|dataBase64}` (the Variables panel menu's Load Variable Library…) replaces the document's variables and data sets with a variable library's in one undo step. The library From d9024f9c3125d7b1c59ff33c752656056f52e3e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:03:53 +0700 Subject: [PATCH 075/674] Variables: a command that changes nothing adds no undo step Squashed from #5130 onto main. --- crates/engine/src/cmd/graph/data.rs | 8 +- crates/engine/src/cmd/variablecmds.rs | 98 +++++++++++++++---- crates/engine/src/tests/variables.rs | 130 ++++++++++++++++++++++++++ docs/mcp.md | 5 + 4 files changed, 220 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 0e69e0240e..913d52522e 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -87,16 +87,20 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { } /// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with -/// `csv` does. +/// `csv` does. Data the graph already holds leaves the graph as it is. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { let Some(node) = d.node(id) else { return Err(EngineError::NoNode(id)); }; - let Some(mut spec) = node.extras().graph.as_deref().cloned() else { + let Some(current) = node.extras().graph.as_deref() else { return Err(bad("graph.applyCsv", format!("node {} is not a graph", id.0))); }; + let mut spec = current.clone(); apply_data(&mut spec, &json!({ "csv": csv })); keep_right_series(&mut spec); + if spec == *current { + return Ok(()); + } regenerate(d, id, spec) } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 03636d11f0..873a694e29 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -14,7 +14,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{DataSet, DataValue, NodeId, NodeKind, Variable, VariableKind, Variables}; +use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection, Variable, VariableKind, Variables}; use super::edit::selected_roots; use super::fileio::{absolute_path, read_file_head, write_file}; @@ -44,6 +44,66 @@ fn selection_and_unlocked(s: &Session) -> std::result::Result<(), String> { variables_unlocked(s) } +/// Ends a typing session as [`Session::edit`] would, before a helper below compares the document, +/// so the typing is its own undo step whether or not the command then changes anything. +fn settle_typing(s: &mut Session) -> Result<()> { + if !s.previewing && super::typing_in_progress(s) { + super::settle_interaction(s)?; + } + Ok(()) +} + +/// [`Session::edit`] for a command that changes only the variables and data sets and may change +/// nothing, such as binding art to the variable it already has: `f` runs on a copy of them, and +/// only a copy that differs becomes an undo step. When nothing changed, the undo and redo steps and +/// the saved state stay as they were. +fn edit_variables(s: &mut Session, label: &str, f: impl FnOnce(&mut Variables) -> Result) -> Result { + settle_typing(s)?; + let st = s.doc()?; + let mut vars = st.doc.variables.clone(); + let v = f(&mut vars)?; + if vars != st.doc.variables { + s.edit(label, |d, _| { + d.variables = vars; + Ok(()) + })?; + } + Ok(v) +} + +/// [`Session::edit`] for applying a data set, which may change nothing when the art already shows +/// the active row: `f` runs on a copy of the document and the selection, and only a document that +/// differs becomes an undo step, with the selection `f` left. When the document did not change, the +/// undo and redo steps and the saved state stay as they were, and a selection `f` changed is set +/// without an undo step. When the active row is applied again and the art already shows it, +/// threaded type is compared after its story flows through its frames, as [`Session::edit`] flows +/// it; any other change is an undo step without that extra flow. +fn edit_if_changed(s: &mut Session, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result) -> Result { + settle_typing(s)?; + let st = s.doc()?; + let mut doc = (*st.doc).clone(); + let mut sel = st.selection.clone(); + let v = f(&mut doc, &mut sel)?; + let vars = &st.doc.variables; + if doc != *st.doc + && !doc.text_threads.is_empty() + && doc.variables == *vars + && vars.active_dataset.as_deref().and_then(|n| vars.dataset(n)).is_some_and(|ds| ds.matches(&st.doc.captured_values())) + { + super::threads::reflow(&st.doc, &mut doc); + } + if doc != *st.doc { + s.edit(label, |d, selection| { + *d = doc; + *selection = sel; + Ok(()) + })?; + } else if sel != st.selection { + s.select(|_, selection| *selection = sel)?; + } + Ok(v) +} + fn var_name(p: &Value, cmd: &str) -> Result { named(str_param(p, "name"), "name", cmd) } @@ -228,7 +288,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { // Without `names`, the highlighted variable: what the panel's bin and the menu item delete. let highlighted = s.doc()?.variables_highlight.clone(); let names = names_param(p, "variable.delete", highlighted, "no variable highlighted")?; - let n = s.edit("Delete Variables", |d, _| Ok(d.variables.prune(&names)))?; + let n = edit_variables(s, "Delete Variables", |v| Ok(v.prune(&names)))?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; st.drop_stale_variables_highlight(); @@ -277,7 +337,7 @@ fn bind(s: &mut Session, p: &Value) -> Result { check_bindable(doc, &ids, kind, C)?; // Binding again is not a second binding, and says so rather than counting as a change. let already: Vec = ids.iter().filter(|id| doc.variables.objects_of(&name).contains(id)).map(|id| id.0).collect(); - let n = s.edit("Bind Variable", |d, _| Ok(ids.iter().filter(|id| d.variables.bind(**id, &name)).count()))?; + let n = edit_variables(s, "Bind Variable", |v| Ok(ids.iter().filter(|id| v.bind(**id, &name)).count()))?; Ok(json!({"variable": name, "ids": ids.iter().map(|i| i.0).collect::>(), "bound": n, "already": already})) } @@ -285,13 +345,13 @@ fn unbind(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.unbind"; let ids = checked_ids_or_selection(s, p, C)?; let name = defined_variable(s, p, C)?; - let n = s.edit("Unbind Variable", |d, _| { + let n = edit_variables(s, "Unbind Variable", |vars| { let mut n = 0; for id in &ids { // With `variable` only that one binding goes; without it, every one the object has. match &name { - Some(v) => n += usize::from(d.variables.unbind(*id, v)), - None => n += usize::from(d.variables.bindings.remove(id).is_some()), + Some(v) => n += usize::from(vars.unbind(*id, v)), + None => n += usize::from(vars.bindings.remove(id).is_some()), } } Ok(n) @@ -344,8 +404,8 @@ fn dataset_set(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.set"; let name = var_name(p, C)?; let values = values_param(&s.doc()?.doc.variables, p, C)?; - let (set, removed) = s.edit("Edit Data Set", |d, _| { - let ds = d.variables.datasets.iter_mut().find(|x| x.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; + let (set, removed) = edit_variables(s, "Edit Data Set", |v| { + let ds = v.datasets.iter_mut().find(|x| x.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; let removed: Vec = ds.values.keys().filter(|k| !values.contains_key(*k)).cloned().collect(); ds.values = values.clone(); Ok((values.len(), removed)) @@ -415,8 +475,8 @@ fn dataset_update(s: &mut Session, p: &Value) -> Result { if values.is_empty() { return Err(bad(C, "bind something to a variable first")); } - let (written, left) = s.edit("Update Data Set", |d, _| { - let ds = d.variables.datasets.iter_mut().find(|d| d.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; + let (written, left) = edit_variables(s, "Update Data Set", |vars| { + let ds = vars.datasets.iter_mut().find(|d| d.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; let mut written = BTreeSet::new(); for (var, value) in &values { if all || ds.values.contains_key(var) { @@ -424,7 +484,7 @@ fn dataset_update(s: &mut Session, p: &Value) -> Result { written.insert(var.as_str()); } } - let left: Vec = d.variables.variables.iter().filter(|v| !written.contains(v.name.as_str())).map(|v| v.name.clone()).collect(); + let left: Vec = vars.variables.iter().filter(|v| !written.contains(v.name.as_str())).map(|v| v.name.clone()).collect(); Ok((written.len(), left)) })?; Ok(json!({"name": name, "values": written, "left": left})) @@ -434,14 +494,14 @@ fn dataset_delete(s: &mut Session, p: &Value) -> Result { // Without `names`, the active dataset: what the panel's Delete Data Set deletes. let active = s.doc()?.doc.variables.active_dataset.clone(); let names = names_param(p, "dataset.delete", active, "no active data set")?; - let n = s.edit("Delete Data Sets", |d, _| { - let before = d.variables.datasets.len(); - d.variables.datasets.retain(|d| !names.contains(&d.name)); + let n = edit_variables(s, "Delete Data Sets", |v| { + let before = v.datasets.len(); + v.datasets.retain(|d| !names.contains(&d.name)); // The active dataset's own name is the one that goes, not a variable's. - if d.variables.active_dataset.as_ref().is_some_and(|a| names.contains(a)) { - d.variables.active_dataset = None; + if v.active_dataset.as_ref().is_some_and(|a| names.contains(a)) { + v.active_dataset = None; } - Ok(before - d.variables.datasets.len()) + Ok(before - v.datasets.len()) })?; Ok(json!({"deleted": n})) } @@ -464,7 +524,7 @@ fn dataset_list(s: &mut Session, _p: &Value) -> Result { fn apply_dataset(s: &mut Session, name: &str) -> Result { const C: &str = "dataset.select"; let doc_path = s.doc()?.path.clone(); - let (applied, skipped, mut typed, bound) = s.edit("Apply Data Set", |d, sel| { + let (applied, skipped, mut typed, bound) = edit_if_changed(s, "Apply Data Set", |d, sel| { let ds = d.variables.dataset(name).cloned().ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; // One object may be driven by several variables; walk them in definition order, so two // text variables on the same object land the later one's value and both are counted. @@ -714,7 +774,7 @@ pub fn specs() -> Vec { "Select Data Set", ["Window", "Variables"], None, - "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too); a text value bound to a frame of threaded text replaces the whole story → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits, the story's last frame for threaded text; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}", + "{name} apply a dataset in one undo step (none when it leaves the document as it was), deselecting every selected object left hidden or locked (the key object too); a text value bound to a frame of threaded text replaces the whole story → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits, the story's last frame for threaded text; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}", has_doc, dataset_select ), diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 776cf19785..f470242ded 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1936,3 +1936,133 @@ fn graph_variable_applies_csv_and_captures() { let r = rect(&mut s); assert!(s.execute("variable.bind", &json!({"variable": name, "ids": [r.0]})).is_err()); } + +/// A Variables command that leaves the document as it was (binding art to the variable it already +/// has, unbinding art that has none, deleting a variable or data set that does not exist, writing a +/// row's own values back, applying the active data set again) records no undo step: the step to +/// redo stays, and the document stays unmodified. +#[test] +fn a_variables_command_that_changes_nothing_records_no_undo_step() { + let dir = Folder::new("vars-noop"); + let red_path = dir.file("red.png"); + write(&red_path, &png(8, 8, RED)); + let mut s = session(); + let t = text(&mut s, "Alice"); + let r = rect(&mut s); + let img = place(&mut s, &red_path); + let other = rect(&mut s); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Photo", "ids": [img.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Bob", "Show": false, "Photo": red_path}})).unwrap(); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + let a = json!({"name": "A", "values": {"Name": "Bob", "Show": false, "Photo": red_path}}); + let calls = [ + ("variable.bind", json!({"variable": "Show", "ids": [r.0]})), + ("variable.unbind", json!({"ids": [other.0]})), + ("variable.unbind", json!({"variable": "Name", "ids": [r.0]})), + ("variable.delete", json!({"names": ["Nope"]})), + ("dataset.delete", json!({"names": ["Nope"]})), + ("dataset.set", a), + ("dataset.update", json!({})), + ("dataset.update", json!({"all": true})), + ("dataset.select", json!({"name": "A"})), + ("dataset.next", json!({})), + ("dataset.prev", json!({})), + ]; + for (cmd, p) in calls { + super::select_with_a_step_to_redo(&mut s, &[other]); + let before = super::history(&s); + assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); + s.execute(cmd, &p).unwrap(); + assert_eq!(super::history(&s), before, "{cmd} {p}"); + } + assert_eq!(plain(&s, t), "Bob"); + // Applying the row again still deselects the art it leaves hidden, without an undo step. + s.execute("select.set", &json!({"ids": [r.0, other.0]})).unwrap(); + assert!(s.doc().unwrap().selection.objects.contains(&r), "the hidden rectangle is selected"); + let before = super::history(&s); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + assert_eq!((super::history(&s), s.doc().unwrap().selection.objects.clone()), (before, vec![other])); + // A command that changes something is still one undo step, and it clears Redo. + super::select_with_a_step_to_redo(&mut s, &[other]); + let undo = super::history(&s).0; + s.execute("variable.bind", &json!({"variable": "Show", "ids": [other.0]})).unwrap(); + assert_eq!(super::history(&s), (undo + 1, 0, true)); + s.execute("dataset.new", &json!({"name": "B", "values": {"Name": "Cy"}})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let undo = super::history(&s).0; + s.execute("dataset.next", &json!({})).unwrap(); + assert_eq!((super::history(&s), plain(&s, t)), ((undo + 1, 0, true), "Cy".to_string())); +} + +/// A Variables command that changes nothing, run while the Type tool is typing, still ends the +/// typing session as one that changes something does: the typing is its own undo step, and the +/// next keystroke starts a new one. +#[test] +fn a_variables_command_that_changes_nothing_ends_the_typing() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let v = ViewInfo::default(); + let t = text(&mut s, "Hello"); + let r = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 50, "height": 40})).unwrap(); + let r = NodeId(r["id"].as_u64().unwrap()); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {"Show": true}})).unwrap(); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + for (cmd, p) in [("variable.bind", json!({"variable": "Show", "ids": [r.0]})), ("dataset.select", json!({"name": "A"}))] { + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("!", v).unwrap(); + assert!(crate::cmd::typing_in_progress(&s), "{cmd}"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute(cmd, &p).unwrap(); + assert!(!crate::cmd::typing_in_progress(&s), "{cmd}"); + let labels: Vec = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing")), "{cmd}"); + } +} + +/// Applying the active data set again to threaded type that already holds the row's story records +/// no undo step. +#[test] +fn applying_a_story_row_again_records_no_undo_step() { + let (mut s, a, b, _) = threaded(200); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Orig"})).unwrap(); + s.execute("dataset.select", &json!({"name": "Orig"})).unwrap(); + assert!(!plain(&s, b).is_empty()); + super::select_with_a_step_to_redo(&mut s, &[a]); + let before = super::history(&s); + s.execute("dataset.select", &json!({"name": "Orig"})).unwrap(); + assert_eq!(super::history(&s), before); +} + +/// Applying the active data set again to a graph whose data already matches the row records no +/// undo step, and a row with other data still rebuilds the graph in one. +#[test] +fn applying_a_graph_row_again_records_no_undo_step() { + let mut s = session(); + let graph = json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",Sales\nA,1\nB,2"}); + let id = s.execute("graph.create", &graph).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("variable.makeGraphDynamic", &json!({})).unwrap(); + let name = s.execute("variable.list", &json!({})).unwrap()["variables"][0]["name"].as_str().unwrap().to_string(); + s.execute("dataset.new", &json!({"name": "A", "values": {name.clone(): ",Sales\nA,10\nB,20"}})).unwrap(); + s.execute("dataset.new", &json!({"name": "B", "values": {name: ",Sales\nA,3\nB,4"}})).unwrap(); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[NodeId(id)]); + let before = super::history(&s); + let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + assert_eq!((v["applied"].as_u64(), super::history(&s)), (Some(1), before)); + s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!(super::history(&s), (before.0 + 1, 0, true)); +} diff --git a/docs/mcp.md b/docs/mcp.md index 77a079b4b8..7b9c59a14f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1743,6 +1743,11 @@ Brushes panel's New Brush button, its menu's New Brush… and art dropped on the Brush Options for the new brush; for a scatter, art or pattern brush they preview the art from `brush.selectionArt`. Their OK runs `brush.new {type, name, params, ids?}`, and Cancel adds no brush. +`variable.bind`, `variable.unbind`, `variable.delete`, `dataset.set`, `dataset.update`, `dataset.delete`, +`dataset.select`, `dataset.next` and `dataset.prev` add no undo step when they leave the document as it was, such as +binding art to a variable it already has or applying the active data set again: the steps to redo stay, and a saved +document stays unmodified. + `dataset.select`, `dataset.next` and `dataset.prev` reply `{name, applied, skipped}`. They add `overflow: [id…]` when area type or type on a path whose text they rewrote doesn't fit, as `text.setText` does (see [Fitting area type](#fitting-area-type-auto-size-shrink-text-to-fit-overflow)). They skip an object that is From d0749dde4116bfcd4c9780e25a9354e7085c9e2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:07:45 +0700 Subject: [PATCH 076/674] Variables: Update Data Set keeps a row's values when every bound object is locked Squashed from #5126 onto main. --- crates/engine/src/cmd/variablecmds.rs | 35 ++++++++++++++++----------- crates/engine/src/tests/variables.rs | 34 ++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 3 ++- 24 files changed, 78 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 873a694e29..70a5af9381 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -442,6 +442,9 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let values = st.doc.captured_values(); if values.is_empty() { + if anything_bound(&st.doc) { + return Err(bad(C, "no bound object reports a value (locked objects and embedded images report none)")); + } return Err(bad(C, "bind something to a variable first")); } let name = match optional_name(p, "name", C)? { @@ -464,32 +467,36 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { /// variable the row holds. A variable whose objects report no value (locked, inside a locked /// layer or group, or gone) keeps the row's value. With `all`, every other variable the /// objects report a value for is added to the row. Without an active row there is nothing to -/// update, so say so rather than picking one. +/// update, so say so rather than picking one. With every bound object locked, no value is +/// written; an update that writes no value adds no undo step. fn dataset_update(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.update"; let all = bool_or(p, "all", false); - let values = s.doc()?.doc.captured_values(); - let Some(name) = s.doc()?.doc.variables.active_dataset.clone() else { + let st = s.doc()?; + let Some(name) = st.doc.variables.active_dataset.clone() else { return Err(bad(C, "no active data set")); }; - if values.is_empty() { + if !anything_bound(&st.doc) { return Err(bad(C, "bind something to a variable first")); } - let (written, left) = edit_variables(s, "Update Data Set", |vars| { + let ds = st.doc.variables.dataset(&name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; + let writes: BTreeMap = st.doc.captured_values().into_iter().filter(|(var, _)| all || ds.values.contains_key(var)).collect(); + let left: Vec = st.doc.variables.variables.iter().filter(|v| !writes.contains_key(&v.name)).map(|v| v.name.clone()).collect(); + let written = writes.len(); + edit_variables(s, "Update Data Set", |vars| { let ds = vars.datasets.iter_mut().find(|d| d.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; - let mut written = BTreeSet::new(); - for (var, value) in &values { - if all || ds.values.contains_key(var) { - ds.values.insert(var.clone(), value.clone()); - written.insert(var.as_str()); - } - } - let left: Vec = vars.variables.iter().filter(|v| !written.contains(v.name.as_str())).map(|v| v.name.clone()).collect(); - Ok((written.len(), left)) + ds.values.extend(writes); + Ok(()) })?; Ok(json!({"name": name, "values": written, "left": left})) } +/// Whether any object in the document is bound to a variable. A locked one counts: it is +/// bound, though it reports no value. +fn anything_bound(doc: &Document) -> bool { + doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some()) +} + fn dataset_delete(s: &mut Session, p: &Value) -> Result { // Without `names`, the active dataset: what the panel's Delete Data Set deletes. let active = s.doc()?.doc.variables.active_dataset.clone(); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index f470242ded..84a2779775 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -709,6 +709,40 @@ fn updating_keeps_a_value_the_art_does_not_report() { } } +/// With every bound object locked, Update keeps the whole row and adds no undo step, and +/// Capture says the bound objects report no value rather than asking for a binding. +#[test] +fn updating_with_every_bound_object_locked_keeps_the_row() { + let mut s = session(); + let t = text(&mut s, "First"); + s.execute("variable.define", &json!({"name": "Label", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Label", "ids": [t.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "Row", "values": {"Label": "Second"}})).unwrap(); + s.execute("dataset.select", &json!({"name": "Row"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [t.0], "locked": true})).unwrap(); + + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + for params in [json!({}), json!({"all": true})] { + let v = s.execute("dataset.update", ¶ms).unwrap(); + assert_eq!((v["values"].clone(), v["left"].clone()), (json!(0), json!(["Label"])), "{params}: {v}"); + let sets = s.execute("dataset.list", &json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"], json!({"Label": {"text": "Second"}}), "{params}: {sets}"); + } + assert_eq!(steps(&s), before, "an update that writes nothing is not a step"); + + let e = s.execute("dataset.capture", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no bound object reports a value"), "{e}"); + assert_eq!(s.execute("dataset.list", &json!({})).unwrap()["datasets"].as_array().unwrap().len(), 1); + + // With nothing bound at all, both still ask for a binding. + s.execute("variable.unbind", &json!({"ids": [t.0]})).unwrap(); + for cmd in ["dataset.update", "dataset.capture"] { + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains("bind something to a variable first"), "{cmd}: {e}"); + } +} + /// A variable defined after a row was captured stays out of that row on Update, and joins it /// with `all: true`. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f1b7faf27b..205991cbce 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5251,6 +5251,7 @@ digits Malayalam Malaiàlam @msg columns {first} and {column} both name the variable `{name}` les columnes {first} i {column} anomenen totes dues la variable `{name}` @msg nothing encoded no s’ha codificat res @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no s’ha aplicat res del conjunt de dades {name}: cap objecte està vinculat a una variable per a la qual tingui un valor +@msg no bound object reports a value (locked objects and embedded images report none) cap objecte vinculat no informa d’un valor (els objectes bloquejats i les imatges incrustades no n’informen cap) @msg nothing selected no hi ha res seleccionat @msg nothing to align no hi ha res per alinear @msg nothing to distort no hi ha res per distorsionar diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4c9139f121..a6d23ba3cd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5476,6 +5476,7 @@ mark-style Japanese Japonské @msg columns {first} and {column} both name the variable `{name}` sloupce {first} a {column} uvádějí stejnou proměnnou `{name}` @msg open a document with data sets otevřete dokument se sadami dat @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ze sady dat {name} se nic nepoužilo: žádný objekt není svázán s proměnnou, pro kterou má hodnotu +@msg no bound object reports a value (locked objects and embedded images report none) žádný svázaný objekt nevrací hodnotu (zamčené objekty a vložené obrazy žádnou nevracejí) @msg the action has no steps akce nemá žádné kroky # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7bd2983cd5..1433e9d1cb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5053,6 +5053,7 @@ effect Soft Weich @msg columns {first} and {column} both name the variable `{name}` die Spalten {first} und {column} nennen beide die Variable `{name}` @msg open a document with data sets öffnen Sie ein Dokument mit Datensätzen @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for aus dem Datensatz {name} wurde nichts angewendet: kein Objekt ist an eine Variable gebunden, für die er einen Wert hat +@msg no bound object reports a value (locked objects and embedded images report none) kein gebundenes Objekt liefert einen Wert (gesperrte Objekte und eingebettete Bilder liefern keinen) @msg the action has no steps die Aktion hat keine Schritte # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 20bd8c7eea..f28611c541 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5407,6 +5407,7 @@ effect Points Σημεία @msg columns {first} and {column} both name the variable `{name}` οι στήλες {first} και {column} ονομάζουν και οι δύο τη μεταβλητή `{name}` @msg open a document with data sets ανοίξτε ένα έγγραφο με σύνολα δεδομένων @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for δεν εφαρμόστηκε τίποτα από το σύνολο δεδομένων {name}: κανένα αντικείμενο δεν είναι συνδεδεμένο με μεταβλητή για την οποία έχει τιμή +@msg no bound object reports a value (locked objects and embedded images report none) κανένα συνδεδεμένο αντικείμενο δεν αναφέρει τιμή (τα κλειδωμένα αντικείμενα και οι ενσωματωμένες εικόνες δεν αναφέρουν καμία) @msg select an Intertwine group επιλέξτε μια ομάδα διαπλοκής @msg select an Objects on Path group επιλέξτε μια ομάδα αντικειμένων σε διαδρομή @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects μια διαδρομή μέσα σε σύνθετη διαδρομή, ανάμειξη, περίβλημα, επανάληψη ή ομάδα διαπλοκής δεν μπορεί να δεχτεί αντικείμενα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 26a13dddeb..dbd5dfb238 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5417,6 +5417,7 @@ mark-style Japanese Japonesas @msg columns {first} and {column} both name the variable `{name}` las columnas {first} y {column} nombran la misma variable `{name}` @msg open a document with data sets abra un documento con conjuntos de datos @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no se aplicó nada del conjunto de datos {name}: ningún objeto está vinculado a una variable para la que tenga un valor +@msg no bound object reports a value (locked objects and embedded images report none) ningún objeto vinculado informa de un valor (los objetos bloqueados y las imágenes incrustadas no informan de ninguno) @msg the action has no steps la acción no tiene pasos # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 12edcafb73..e232c972a8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5419,6 +5419,7 @@ mark-style Japanese Japanilainen @msg columns {first} and {column} both name the variable `{name}` sarakkeet {first} ja {column} nimeävät molemmat muuttujan `{name}` @msg open a document with data sets avaa asiakirja, jossa on tietojoukkoja @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for tietojoukosta {name} ei käytetty mitään: mitään objektia ei ole sidottu muuttujaan, jolle siinä on arvo +@msg no bound object reports a value (locked objects and embedded images report none) mikään sidottu objekti ei ilmoita arvoa (lukitut objektit ja upotetut kuvat eivät ilmoita arvoa) @msg select an Intertwine group valitse lomitusryhmä @msg select an Objects on Path group valitse Objektit polulla -ryhmä @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects yhdistelmäpolun, sulautuksen, vääristyskuoren, toiston tai lomitusryhmän sisällä olevaan polkuun ei voi kiinnittää objekteja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6e8e1eeb2f..789e40c815 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5473,6 +5473,7 @@ theme Appearance Apparence @msg columns {first} and {column} both name the variable `{name}` les colonnes {first} et {column} nomment toutes deux la variable `{name}` @msg open a document with data sets ouvrez un document avec des jeux de données @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for rien du jeu de données {name} n’a été appliqué, car aucun objet n’est lié à une variable pour laquelle il a une valeur +@msg no bound object reports a value (locked objects and embedded images report none) aucun objet lié ne fournit de valeur (les objets verrouillés et les images incorporées n’en fournissent aucune) @msg the action has no steps l'action n'a aucune étape # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c028358a39..76dc225e81 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5461,6 +5461,7 @@ imageTrace Outline Körvonal @msg columns {first} and {column} both name the variable `{name}` a(z) {first}. és a(z) {column}. oszlop ugyanazt a változót nevezi meg: `{name}` @msg open a document with data sets nyisson meg egy adatkészleteket tartalmazó dokumentumot @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ebből az adatkészletből semmi sem lett alkalmazva: {name}; egyetlen objektum sincs olyan változóhoz kötve, amelynek értéke van benne +@msg no bound object reports a value (locked objects and embedded images report none) egyetlen kötött objektum sem ad értéket (a zárolt objektumok és a beágyazott képek nem adnak értéket) @msg the action has no steps a műveletnek nincsenek lépései # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2f93c212..ad25ad87c4 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5088,6 +5088,7 @@ lighting Light Luce @msg columns {first} and {column} both name the variable `{name}` le colonne {first} e {column} indicano entrambe la variabile `{name}` @msg open a document with data sets apri un documento con set di dati @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for non è stato applicato nulla del set di dati {name}: nessun oggetto è associato a una variabile per cui ha un valore +@msg no bound object reports a value (locked objects and embedded images report none) nessun oggetto associato restituisce un valore (gli oggetti bloccati e le immagini incorporate non ne restituiscono) @msg the action has no steps l'azione non ha passaggi # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4767449f19..804186dd67 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5133,6 +5133,7 @@ lighting Light ライト @msg columns {first} and {column} both name the variable `{name}` 列 {first} と列 {column} が同じ変数 `{name}` を指定しています @msg open a document with data sets データセットのあるドキュメントを開いてください @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for データセット {name} から何も適用されませんでした: 値のある変数にバインドされたオブジェクトがありません +@msg no bound object reports a value (locked objects and embedded images report none) 値を返すバインドされたオブジェクトがありません (ロックされたオブジェクトと埋め込み画像は値を返しません) @msg the action has no steps アクションにステップがありません # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index dd7083cc9b..250e0f384e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5124,6 +5124,7 @@ imageTrace Outline კონტური @msg columns {first} and {column} both name the variable `{name}` სვეტები {first} და {column} ორივე ასახელებს ცვლადს `{name}` @msg open a document with data sets გახსენით დოკუმენტი მონაცემთა ნაკრებებით @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for მონაცემთა ნაკრები {name}: არაფერი გამოყენებულა; არცერთი ობიექტი არ არის მიბმული ცვლადზე, რომელსაც მასში მნიშვნელობა აქვს +@msg no bound object reports a value (locked objects and embedded images report none) არცერთი მიბმული ობიექტი არ აბრუნებს მნიშვნელობას (ჩაკეტილი ობიექტები და ჩაშენებული გამოსახულებები მნიშვნელობას არ აბრუნებს) @msg the action has no steps მოქმედებას ნაბიჯები არ აქვს Convert to Straight Lines სწორ ხაზებად გარდაქმნა Corner Point Angle Threshold: კუთხოვანი წერტილის კუთხის ზღვარი: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index af51f5883e..3ee9cb9d4c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5051,6 +5051,7 @@ lighting Light 광원 @msg columns {first} and {column} both name the variable `{name}` {first}열과 {column}열이 모두 같은 변수 `{name}`을(를) 가리킵니다 @msg open a document with data sets 데이터 세트가 있는 문서를 여세요 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 데이터 세트 {name}에서 적용된 항목이 없습니다: 값이 있는 변수에 연결된 개체가 없습니다 +@msg no bound object reports a value (locked objects and embedded images report none) 값을 보고하는 연결된 개체가 없습니다(잠긴 개체와 포함된 이미지는 값을 보고하지 않습니다) @msg the action has no steps 액션에 단계가 없습니다 # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ed0396deac..5830a1b6ab 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5328,6 +5328,7 @@ mark-style Japanese Japońskie @msg columns {first} and {column} both name the variable `{name}` kolumny {first} i {column} wskazują tę samą zmienną `{name}` @msg open a document with data sets otwórz dokument z zestawami danych @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for z zestawu danych {name} nic nie zastosowano: żaden obiekt nie jest powiązany ze zmienną, dla której ma on wartość +@msg no bound object reports a value (locked objects and embedded images report none) żaden powiązany obiekt nie zwraca wartości (zablokowane obiekty i osadzone obrazy nie zwracają żadnej) @msg the action has no steps operacja nie ma kroków # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 19d52c9814..00c6192224 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5350,6 +5350,7 @@ mark-style Japanese Japonesas @msg columns {first} and {column} both name the variable `{name}` as colunas {first} e {column} nomeiam a mesma variável `{name}` @msg open a document with data sets abra um documento com conjuntos de dados @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for nada do conjunto de dados {name} foi aplicado: nenhum objeto está vinculado a uma variável para a qual ele tem um valor +@msg no bound object reports a value (locked objects and embedded images report none) nenhum objeto vinculado informa um valor (objetos bloqueados e imagens incorporadas não informam nenhum) @msg the action has no steps a ação não tem etapas @msg Angles require two straight segments Ângulos exigem dois segmentos retos @msg Choose a circle or a perfect arc Escolha um círculo ou um arco perfeito diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a8407da965..50d1ca1bdd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5083,6 +5083,7 @@ lighting Light Свет @msg columns {first} and {column} both name the variable `{name}` столбцы {first} и {column} указывают одну и ту же переменную `{name}` @msg open a document with data sets откройте документ с наборами данных @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for из набора данных {name} ничего не применено: ни один объект не привязан к переменной, для которой в нём есть значение +@msg no bound object reports a value (locked objects and embedded images report none) ни один привязанный объект не сообщает значение (заблокированные объекты и внедрённые изображения не сообщают значений) @msg the action has no steps в действии нет шагов # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2382ce365d..8ca7a39271 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5411,6 +5411,7 @@ theme Appearance Utseende @msg columns {first} and {column} both name the variable `{name}` kolumnerna {first} och {column} anger båda variabeln `{name}` @msg open a document with data sets öppna ett dokument med datauppsättningar @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for inget i datauppsättningen {name} användes: inget objekt är bundet till en variabel som den har ett värde för +@msg no bound object reports a value (locked objects and embedded images report none) inget bundet objekt rapporterar ett värde (låsta objekt och inbäddade bilder rapporterar inget) @msg select an Intertwine group markera en sammanflätningsgrupp @msg select an Objects on Path group markera en grupp med objekt på bana @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects en bana inuti en sammansatt bana, en blandning, ett kuvert, en upprepning eller en sammanflätningsgrupp kan inte ta emot objekt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b8f648a0c5..c893d81f38 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5362,6 +5362,7 @@ theme Appearance Görünüm @msg columns {first} and {column} both name the variable `{name}` {first} ve {column} numaralı sütunların ikisi de `{name}` değişkenini adlandırıyor @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them dosyanın değişkenleri ve veri kümeleri okunmadı (değişkenler: {variables}, veri kümeleri: {data_sets}): Değişkenler paneli bunları listelemiyor @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for {name} veri kümesinden hiçbir şey uygulanmadı: değer içerdiği bir değişkene bağlı hiçbir nesne yok +@msg no bound object reports a value (locked objects and embedded images report none) bağlı hiçbir nesne bir değer bildirmiyor (kilitli nesneler ve gömülü görüntüler değer bildirmez) @msg select an Objects on Path group bir Yol Üzerindeki Nesneler grubu seçin @msg the Simplify slider is not open Basitleştirme kaydırıcısı açık değil @msg the Smooth slider is not open Düzgünleştirme kaydırıcısı açık değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ecb2074931..2676d107e6 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5068,6 +5068,7 @@ lighting Light Світло @msg columns {first} and {column} both name the variable `{name}` стовпці {first} і {column} вказують одну й ту саму змінну `{name}` @msg open a document with data sets відкрийте документ із наборами даних @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for з набору даних {name} нічого не застосовано: жоден об’єкт не прив’язано до змінної, для якої в ньому є значення +@msg no bound object reports a value (locked objects and embedded images report none) жоден прив’язаний об’єкт не повідомляє значення (заблоковані об’єкти та вбудовані зображення не повідомляють значень) @msg the action has no steps у дії немає кроків # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8a6a9935ce..42de855e0c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5071,6 +5071,7 @@ theme Appearance Giao diện @msg columns {first} and {column} both name the variable `{name}` cột {first} và cột {column} cùng chỉ định biến số `{name}` @msg open a document with data sets hãy mở một tài liệu có tập dữ liệu @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for không có gì trong tập dữ liệu {name} được áp dụng: không có đối tượng nào được gắn với biến số mà tập dữ liệu có giá trị +@msg no bound object reports a value (locked objects and embedded images report none) không có đối tượng được gắn nào báo cáo giá trị (đối tượng bị khóa và hình ảnh nhúng không báo cáo giá trị nào) @msg the action has no steps hành động không có bước nào # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5903547021..53a2e2847d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4535,6 +4535,7 @@ imageTrace Outline 轮廓 @msg columns {first} and {column} both name the variable `{name}` 第 {first} 列和第 {column} 列都指定了变量 `{name}` @msg open a document with data sets 请打开包含数据集的文档 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 数据集 {name} 未应用任何内容:没有对象绑定到该数据集中有值的变量 +@msg no bound object reports a value (locked objects and embedded images report none) 没有绑定的对象报告值 (锁定的对象和嵌入的图像不报告值) @msg the action has no steps 该动作没有步骤 # Import Shortcut Set (Keyboard Shortcuts › Import…, File › Open of a .kys file) and its commands. Import Shortcut Set 导入快捷键组 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e4a439e9bc..0e9c6b5f29 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2451,6 +2451,7 @@ file-filter Templates 範本 @msg columns {first} and {column} both name the variable `{name}` 第 {first} 欄和第 {column} 欄都指定了變數 `{name}` @msg open a document with data sets 請開啟含有資料集的文件 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 資料集 {name} 未套用任何內容:沒有物件綁定到該資料集中有值的變數 +@msg no bound object reports a value (locked objects and embedded images report none) 沒有綁定的物件回報值 (鎖定的物件和內嵌的影像不回報值) @msg the action has no steps 動作沒有步驟 @msg cancelled; nothing was changed 已取消;未做任何變更 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 「儲存」會寫入 {_1},而非 {_2}:若要寫入該格式,請使用 file.saveAsTemplate diff --git a/docs/mcp.md b/docs/mcp.md index 7b9c59a14f..ca9b00379d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1788,7 +1788,8 @@ or no, or a graph value longer than 262,144 bytes. data set holds. A variable whose objects report no value, because they are locked, inside a locked layer or group, or deleted, keeps the data set's value. With `all: true` it also adds every other variable that the objects report a value for. The reply gives `values`, the number of values it wrote, and `left`, the variables it -did not write. +did not write. When every bound object is locked, it writes no value and adds no undo step, and `dataset.capture` +returns the error "no bound object reports a value (locked objects and embedded images report none)". ## Graphic styles From a6ce22da5cc9c32680b0b68a8bdbdb89d9ae3cdb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 10:02:06 -0800 Subject: [PATCH 077/674] Variables: an import or library load that changes nothing adds no undo step dataset.import and variable.loadLibrary added an undo step, cleared Redo and marked a saved document modified even when the variables and data sets came out as they were, such as the same CSV or library loaded again. Both now build the new variables on a copy and record a step only when it differs. variable.loadLibrary's params text and docs/mcp.md say so. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/cmd/variablecmds/csv.rs | 33 +++++++----- crates/engine/src/cmd/variablecmds/library.rs | 22 +++++--- crates/engine/src/tests/variables.rs | 53 +++++++++++++++++++ docs/mcp.md | 3 +- 5 files changed, 89 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 70a5af9381..66948e692e 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -816,7 +816,7 @@ pub fn specs() -> Vec { "Load Variable Library…", ["Window", "Variables"], None, - "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step. Every variable of the document is deleted with its bindings and values, and every data set is deleted; then variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}", + "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every variable of the document is deleted with its bindings and values, and every data set is deleted; then variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}", has_doc, load_library ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 8f23772a3f..f9e170c596 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -324,21 +324,26 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { } let names: Vec = parsed.iter().map(|d| d.name.clone()).collect(); let new_variables: Vec = defined.iter().map(|v| v.name.clone()).collect(); - let (imported, updated) = s.edit("Import Data Sets", |d, _| { - d.variables.variables.extend(defined); - let mut imported = 0usize; - let mut updated = 0usize; - for row in parsed { - if let Some(existing) = d.variables.datasets.iter_mut().find(|x| x.name == row.name) { - *existing = row; - updated += 1; - } else { - d.variables.datasets.push(row); - imported += 1; - } + let mut vars = s.doc()?.doc.variables.clone(); + vars.variables.extend(defined); + let (mut imported, mut updated) = (0usize, 0usize); + for row in parsed { + if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) { + *existing = row; + updated += 1; + } else { + vars.datasets.push(row); + imported += 1; } - Ok((imported, updated)) - })?; + } + // The import is one undo step, and an import that leaves the variables and data sets as they + // were adds none. + if vars != s.doc()?.doc.variables { + s.edit("Import Data Sets", |d, _| { + d.variables = vars; + Ok(()) + })?; + } Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables})) } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index b410af042f..cdd2ba4d0c 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -249,7 +249,8 @@ fn parse_library(xml: &str, cmd: &str) -> Result { } /// Load Variable Library: replace the document's variables and data sets with a variable library's -/// ([`parse_library`]) in one undo step. Every variable of the document is deleted with its bindings +/// ([`parse_library`]) in one undo step, or none when the document already holds what the library +/// gives. Every variable of the document is deleted with its bindings /// and values, and every data set is deleted. The library's text variables are then defined, /// unbound, and its data sets are added. The library's variables of other kinds are left out, named /// in `skipped` and in a warning. @@ -268,13 +269,18 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { } let added: Vec = lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(); let names: Vec = lib.datasets.iter().map(|d| d.name.clone()).collect(); - s.edit("Load Variable Library", |d, _| { - d.variables.prune(&deleted); - d.variables.variables.extend(added); - d.variables.datasets = lib.datasets; - d.variables.active_dataset = None; - Ok(()) - })?; + let mut vars = s.doc()?.doc.variables.clone(); + vars.prune(&deleted); + vars.variables.extend(added); + vars.datasets = lib.datasets; + vars.active_dataset = None; + // A load that leaves the variables and data sets as they were adds no undo step. + if vars != s.doc()?.doc.variables { + s.edit("Load Variable Library", |d, _| { + d.variables = vars; + Ok(()) + })?; + } // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; st.drop_stale_variables_highlight(); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 84a2779775..1844d9f20d 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1762,6 +1762,59 @@ fn a_variable_library_replaces_every_variable_and_data_set() { assert_eq!(s.doc().unwrap().doc.variables, before, "one undo step brings everything back"); } +/// An import or a library load that leaves the variables and data sets as they were (the same CSV +/// imported again, a row rewritten with its own values, the same library loaded again) records no +/// undo step: the step to redo stays, and the document stays unmodified. An import or load that +/// changes something is still one undo step. +#[test] +fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() { + let mut s = session(); + let t = text(&mut s, "Alice"); + let csv = "name,Name,#Shown\nA,Ann,true\nB,Bob,false\n"; + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + for csv in [csv, "name\tName\t#Shown\nB\tBob\tfalse\n", "Name,#Shown\nAnn,true\n"] { + super::select_with_a_step_to_redo(&mut s, &[t]); + let before = super::history(&s); + assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); + let r = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + if csv.starts_with("name") { + assert_eq!((super::history(&s), r["imported"].clone()), (before, json!(0)), "{csv}"); + } else { + // Without a name column the row is a new data set, which is a change. + assert_eq!((super::history(&s), r["imported"].clone()), ((before.0 + 1, 0, true), json!(1)), "{csv}"); + } + } + super::select_with_a_step_to_redo(&mut s, &[t]); + let undo = super::history(&s).0; + s.execute("dataset.import", &json!({"csv": "name,Name\nB,Cy\n"})).unwrap(); + assert_eq!(super::history(&s), (undo + 1, 0, true)); + + let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["Ann"])]), ("B", &[("Name", &["Bob"])])]); + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[t]); + let before = super::history(&s); + let r = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!((super::history(&s), r["names"].clone()), (before, json!(["A", "B"]))); + // Binding the variable makes the next load a change: it deletes the binding. + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[t]); + let undo = super::history(&s).0; + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(super::history(&s), (undo + 1, 0, true)); + + // While the variables are locked, a library without text variables still loads its data sets, + // and loading it again changes nothing. + let mut s = session(); + let t = text(&mut s, "Alice"); + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + let xml = library(&[("Shown", "other")], &[("B", &[])]); + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[t]); + let before = super::history(&s); + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(super::history(&s), before); +} + /// A library that is refused leaves the document's variables and data sets as they were. #[test] fn a_refused_variable_library_deletes_nothing() { diff --git a/docs/mcp.md b/docs/mcp.md index ca9b00379d..f98195ed33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1652,7 +1652,8 @@ already walks Image Trace. Short agent entry points: reply's `defined` lists the variables the import defined. While the variables are locked, an import whose header would define a variable fails with "variables are locked". - Variable libraries: `variable.loadLibrary {path|xml|dataBase64}` (the Variables panel menu's Load Variable - Library…) replaces the document's variables and data sets with a variable library's in one undo step. The library + Library…) replaces the document's variables and data sets with a variable library's in one undo step. A load, like a + `dataset.import`, adds no undo step when it leaves the variables and data sets as they were. The library is XML whose `variableSets` element holds `variableSet` elements, each with a `variables` element of `variable` elements (`varName`, `trait`) and a `sampleDataSets` element of `sampleDataSet` elements (`dataSetName`). Every variable of the document is deleted with its bindings and values, and every data set is deleted. Then the library's From 78014a1b436f0de44b35cca9cc55f3e6753b4576 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:08:28 +0700 Subject: [PATCH 078/674] Variables: Import Data Sets and Load Variable Library record their step through edit_variables --- crates/engine/src/cmd/variablecmds/csv.rs | 32 ++++++++----------- crates/engine/src/cmd/variablecmds/library.rs | 18 ++++------- 2 files changed, 21 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index f9e170c596..47376d78f1 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -324,26 +324,22 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { } let names: Vec = parsed.iter().map(|d| d.name.clone()).collect(); let new_variables: Vec = defined.iter().map(|v| v.name.clone()).collect(); - let mut vars = s.doc()?.doc.variables.clone(); - vars.variables.extend(defined); - let (mut imported, mut updated) = (0usize, 0usize); - for row in parsed { - if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) { - *existing = row; - updated += 1; - } else { - vars.datasets.push(row); - imported += 1; - } - } // The import is one undo step, and an import that leaves the variables and data sets as they // were adds none. - if vars != s.doc()?.doc.variables { - s.edit("Import Data Sets", |d, _| { - d.variables = vars; - Ok(()) - })?; - } + let (imported, updated) = super::edit_variables(s, "Import Data Sets", |vars| { + vars.variables.extend(defined); + let (mut imported, mut updated) = (0usize, 0usize); + for row in parsed { + if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) { + *existing = row; + updated += 1; + } else { + vars.datasets.push(row); + imported += 1; + } + } + Ok((imported, updated)) + })?; Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables})) } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index cdd2ba4d0c..7e57b23754 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -269,18 +269,14 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { } let added: Vec = lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(); let names: Vec = lib.datasets.iter().map(|d| d.name.clone()).collect(); - let mut vars = s.doc()?.doc.variables.clone(); - vars.prune(&deleted); - vars.variables.extend(added); - vars.datasets = lib.datasets; - vars.active_dataset = None; // A load that leaves the variables and data sets as they were adds no undo step. - if vars != s.doc()?.doc.variables { - s.edit("Load Variable Library", |d, _| { - d.variables = vars; - Ok(()) - })?; - } + super::edit_variables(s, "Load Variable Library", |vars| { + vars.prune(&deleted); + vars.variables.extend(added); + vars.datasets = lib.datasets; + vars.active_dataset = None; + Ok(()) + })?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; st.drop_stale_variables_highlight(); From f024f5a5f258b9028a79269bddb63876b513d048 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:10:05 +0700 Subject: [PATCH 079/674] Variables: Export Data Sets marks visibility and image columns with # and @ Squashed from #5141 onto main. --- crates/engine/src/cmd/variablecmds.rs | 5 +- crates/engine/src/cmd/variablecmds/csv.rs | 85 ++++++++++++++++++--- crates/engine/src/tests/variables.rs | 91 +++++++++++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 3 + 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 | 3 + 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 | 3 + 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 | 3 + 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 + crates/ui-egui/src/panels/variables.rs | 37 +++++++++ docs/mcp.md | 8 +- 31 files changed, 287 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 66948e692e..96b3c2a7a4 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -5,7 +5,8 @@ //! variable, or a graph root to a `graph` variable (CSV data), put a row of values in //! each dataset, and `dataset.select` swaps the whole document to that row in one undo //! step. `dataset.import` / `dataset.export` move those rows as CSV (header: `name` -//! then variable names); import also reads tab-separated files, files without the +//! then variable names, which export writes with `#` before a visibility variable and `@` +//! before an image variable); import also reads tab-separated files, files without the //! `name` column, and header cells that define new variables (`#` for visibility, `@` for //! image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the //! text variables and data sets of a variable library, the XML file of the reference app's Save @@ -807,7 +808,7 @@ pub fn specs() -> Vec { "Export Data Sets…", ["Window", "Variables"], None, - "{path?} write every dataset as CSV (header: name, then variables); without path → {csv, datasets}. Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads", + "{path?} write every dataset as CSV (header: name, then one column per variable: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)", has_doc, dataset_export ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 47376d78f1..507c153f8e 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -187,12 +187,66 @@ fn value_to_cell(v: &DataValue) -> String { } } -/// Build the CSV of every dataset (header `name` then variables in definition order). -fn datasets_to_csv(vars: &Variables) -> String { +/// The header cell that [`datasets_to_csv`] writes for `v`, as [`header_variable`] reads it: `#` +/// before a visibility variable's name, `@` before an image variable's name, and the name alone +/// for a text or graph variable. +fn export_header(v: &Variable) -> String { + match v.kind { + VariableKind::Visibility => format!("#{}", v.name), + VariableKind::Image => format!("@{}", v.name), + VariableKind::Text | VariableKind::Graph => v.name.clone(), + } +} + +/// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`] +/// writes, in a document without the variables: the first list names the variables whose header +/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values +/// aren't true or false, a header that names a variable an earlier column named), and the second +/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`, +/// and a graph variable, which no header cell defines). +fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { + const C: &str = "dataset.import"; + let none = BTreeMap::new(); + let mut defined = Vec::new(); + let (mut refused, mut other) = (Vec::new(), Vec::new()); + let mut seen = BTreeSet::new(); + for (i, v) in vars.variables.iter().enumerate() { + let header = export_header(v); + let cell = header.trim(); + // Column 1 holds the dataset names. + let read = if cell.is_empty() { None } else { header_variable(cell, i + 2, &none, &mut defined, C).ok() }; + // The import refuses a header that names a variable an earlier column named. + let Some((name, kind)) = read.filter(|(name, _)| seen.insert(name.clone())) else { + refused.push(v.name.as_str()); + continue; + }; + let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| { + let cell = value_to_cell(val); + cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() + }); + if !cells_read { + refused.push(v.name.as_str()); + } else if name != v.name || kind != v.kind { + other.push(v.name.as_str()); + } + } + (refused, other) +} + +/// Build the CSV of every dataset (header `name` then each variable's [`export_header`] in +/// definition order). Refused when a variable's header is another variable's name, which the +/// import reads as that variable (a visibility variable `Show` next to a text variable `#Show`). +fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result { + let names: BTreeSet<&str> = vars.variables.iter().map(|v| v.name.as_str()).collect(); let mut out = String::from("name"); for v in &vars.variables { + let header = export_header(v); + if header != v.name && names.contains(header.as_str()) { + let (name, other) = (&v.name, &header); + return Err(bad(cmd, format!("the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them"))); + } out.push(','); - out.push_str(&csv_escape(&v.name)); + out.push_str(&csv_escape(&header)); } out.push('\n'); for ds in &vars.datasets { @@ -205,7 +259,7 @@ fn datasets_to_csv(vars: &Variables) -> String { } out.push('\n'); } - out + Ok(out) } /// The variable that a datasets CSV header cell (trimmed, not empty) in 1-based `column` names, @@ -343,7 +397,10 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables})) } -/// Export every dataset as CSV (`name` then variables). With `path`, write the file; else return `{csv}`. +/// Export every dataset as CSV ([`datasets_to_csv`]). With `path`, write the file; else return +/// `{csv}`. The reply's `warning` names the variables whose column makes a document without them +/// refuse the file, or else the variables it doesn't read back with their kind +/// ([`kinds_a_new_document_loses`]); the app shows it in its status bar. /// A document with more data sets or variables than [`dataset_import`] reads is refused. pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.export"; @@ -358,16 +415,26 @@ pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result { if st.doc.variables.variables.len() > MAX_CSV_COLS { return Err(bad(C, format!("more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS}"))); } - let csv = datasets_to_csv(&st.doc.variables); + let csv = datasets_to_csv(&st.doc.variables, C)?; if csv.len() > MAX_CSV_BYTES { return Err(bad(C, format!("CSV would be larger than {MAX_CSV_BYTES} bytes"))); } - match str_param(p, "path") { + let mut out = match str_param(p, "path") { Some(path) => { let path = absolute_path(path); write_file(&path, csv.as_bytes())?; - Ok(json!({"path": path, "datasets": st.doc.variables.datasets.len()})) + json!({"path": path, "datasets": st.doc.variables.datasets.len()}) } - None => Ok(json!({"csv": csv, "datasets": st.doc.variables.datasets.len()})), + None => json!({"csv": csv, "datasets": st.doc.variables.datasets.len()}), + }; + let (refused, lost) = kinds_a_new_document_loses(&st.doc.variables); + let list = |vars: &[&str]| vars.iter().map(|n| format!("`{n}`")).collect::>().join(", "); + if !refused.is_empty() { + let names = list(&refused); + out["warning"] = json!(format!("a new document refuses this file because of these variables: {names}")); + } else if !lost.is_empty() { + let names = list(&lost); + out["warning"] = json!(format!("a new document won't read these variables back with their kind: {names}")); } + Ok(out) } diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 1844d9f20d..c54350cc9a 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1521,13 +1521,13 @@ fn datasets_csv_header_prefixes_define_variables() { #[test] fn datasets_csv_exact_names_win_over_prefixes() { let mut s = session(); - for (name, kind) in [("#Shown", "text"), ("@Photo", "visibility"), ("%Chart", "graph"), ("Shown", "visibility")] { + for (name, kind) in [("#Shown", "text"), ("@Photo", "visibility"), ("%Chart", "graph"), ("Shown", "image")] { s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); } - let values = json!({"#Shown": "hello", "@Photo": true, "%Chart": ",Q\nX,3", "Shown": false}); + let values = json!({"#Shown": "hello", "@Photo": true, "%Chart": ",Q\nX,3", "Shown": "s.png"}); s.execute("dataset.new", &json!({"name": "A", "values": values})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - assert!(csv.starts_with("name,#Shown,@Photo,%Chart,Shown\n"), "{csv}"); + assert!(csv.starts_with("name,#Shown,#@Photo,%Chart,@Shown\n"), "{csv}"); s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap(); let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); assert_eq!((imp["imported"].as_u64(), imp["defined"].clone()), (Some(1), json!([]))); @@ -1535,10 +1535,91 @@ fn datasets_csv_exact_names_win_over_prefixes() { assert_eq!(value("#Shown"), Some(vectorcraft_doc::DataValue::Text("hello".into()))); assert_eq!(value("@Photo"), Some(vectorcraft_doc::DataValue::Visible(true))); assert_eq!(value("%Chart"), Some(vectorcraft_doc::DataValue::Graph(",Q\nX,3".into()))); - assert_eq!(value("Shown"), Some(vectorcraft_doc::DataValue::Visible(false))); + assert_eq!(value("Shown"), Some(vectorcraft_doc::DataValue::Image("s.png".into()))); assert_eq!(s.doc().unwrap().doc.variables.variables.len(), 4); } +/// `dataset.export` writes `#` before a visibility variable's header and `@` before an image +/// variable's, so a document without the variables reads the file back with their kinds. The +/// reply's `warning` names the variables it doesn't: a text variable whose name starts with `#`, +/// `@` or `%`, and a graph variable. +#[test] +fn datasets_csv_export_marks_visibility_and_image_columns() { + let mut s = session(); + for (name, kind) in [("Name", "text"), ("Show", "visibility"), ("Photo", "image")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Ann", "Show": false, "Photo": "a.png"}})).unwrap(); + let out = s.execute("dataset.export", &json!({})).unwrap(); + assert_eq!(out["csv"], "name,Name,#Show,@Photo\nA,Ann,false,a.png\n"); + assert!(out.get("warning").is_none(), "{out}"); + + let mut fresh = session(); + let imp = fresh.execute("dataset.import", &json!({"csv": out["csv"]})).unwrap(); + assert_eq!(imp["defined"], json!(["Name", "Show", "Photo"])); + let listed = fresh.execute("variable.list", &json!({})).unwrap(); + let kinds: Vec<_> = listed["variables"].as_array().unwrap().iter().map(|v| v["kind"].clone()).collect(); + assert_eq!(kinds, [json!("text"), json!("visibility"), json!("image")]); + let value = |var: &str| fresh.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned(); + assert_eq!(value("Show"), Some(vectorcraft_doc::DataValue::Visible(false))); + assert_eq!(value("Photo"), Some(vectorcraft_doc::DataValue::Image("a.png".into()))); + + for (name, kind) in [("#Tag", "text"), ("Chart", "graph"), ("@Note", "text")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let out = s.execute("dataset.export", &json!({})).unwrap(); + assert_eq!(out["warning"], "a new document won't read these variables back with their kind: `#Tag`, `Chart`, `@Note`"); + assert!(out["csv"].as_str().unwrap().starts_with("name,Name,#Show,@Photo,#Tag,Chart,@Note\n"), "{out}"); +} + +/// The export's `warning` names the variables whose column a document without the variables +/// refuses, so it doesn't import the file: a `%` header, a `#` header whose values aren't true or +/// false, and a header that names a variable an earlier column defined with another kind. A +/// header that names such a variable with its kind is read with that kind, and is listed as one +/// read back with another kind. +#[test] +fn datasets_csv_export_warns_of_headers_a_new_document_refuses() { + let export = |vars: &[(&str, &str)], values: Value| { + let mut s = session(); + for (name, kind) in vars { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + s.execute("dataset.new", &json!({"name": "A", "values": values})).unwrap(); + let out = s.execute("dataset.export", &json!({})).unwrap(); + let refused = session().execute("dataset.import", &json!({"csv": out["csv"]})).is_err(); + (out["warning"].as_str().unwrap_or("").to_string(), refused) + }; + let refuses = |names: &str| format!("a new document refuses this file because of these variables: {names}"); + let loses = |names: &str| format!("a new document won't read these variables back with their kind: {names}"); + + assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (refuses("`%Rate`"), true)); + assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "hello"})), (refuses("`#Tag`"), true)); + assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "yes"})), (loses("`#Tag`"), false)); + assert_eq!(export(&[("#Seen", "text"), ("Seen", "image")], json!({})), (refuses("`Seen`"), true)); + assert_eq!(export(&[("#Seen", "text"), ("Seen", "text")], json!({})), (refuses("`Seen`"), true)); +} + +/// `dataset.export` is refused, naming both variables, when a variable's header is another +/// variable's name, which an import reads as that variable; with `path`, no file is written. +#[test] +fn datasets_csv_export_refuses_a_header_that_names_another_variable() { + let dir = Folder::new("vars-csv-header"); + for (first, second) in + [(("Show", "visibility"), ("#Show", "text")), (("Photo", "image"), ("@Photo", "graph")), (("X", "visibility"), ("#X", "image"))] + { + let mut s = session(); + for (name, kind) in [first, second] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let e = s.execute("dataset.export", &json!({})).unwrap_err().to_string(); + let (name, other) = (first.0, second.0); + assert!(e.contains(&format!("for `{name}` would read back as the variable `{other}`")), "{e}"); + let out = dir.file("sets.csv"); + assert!(s.execute("dataset.export", &json!({"path": out})).is_err()); + assert!(!std::path::Path::new(&out).exists(), "{out}"); + } +} + /// A `%` header cell that isn't a variable's name (graph data files) is refused with its column, /// and the import defines nothing. #[test] @@ -1621,7 +1702,7 @@ fn datasets_csv_round_trips_and_rejects_bad_input() { let exported = s.execute("dataset.export", &json!({})).unwrap(); let csv = exported["csv"].as_str().unwrap().to_string(); - assert!(csv.starts_with("name,Name,Show,Photo\n"), "{csv}"); + assert!(csv.starts_with("name,Name,#Show,@Photo\n"), "{csv}"); assert!(csv.contains("Alice") && csv.contains("Bob") && csv.contains("false"), "{csv}"); // Clear rows, import again, apply B. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f3f6cbfbb6..367da9cb33 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4348,6 +4348,9 @@ axis Both И двете @msg unsupported: {0} не се поддържа: {0} @msg variables are locked променливите са заключени @msg variables that aren't text were left out: {kinds} променливите, които не са текстови, бяха пропуснати: {kinds} +@msg a new document won't read these variables back with their kind: {names} нов документ няма да прочете тези променливи обратно с техния вид: {names} +@msg a new document refuses this file because of these variables: {names} нов документ отказва този файл заради тези променливи: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заглавието `{header}` за `{name}` ще бъде прочетено като променливата `{other}`: преименувайте едната от тях @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файловете от версия {0} не могат да бъдат компресирани: само версия {COMPRESSED_SINCE} и по-нови отварят компресирани файлове @msg width and height are at least 1 pixel ширината и височината са най-малко 1 пиксел @msg workspace name can't be empty името на работното пространство не може да бъде празно diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7efa9c0e7..035a87d75c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4747,6 +4747,9 @@ imageTrace Outline Obris @msg unsupported: {0} nepodržano: {0} @msg variables are locked varijable su zaključane @msg variables that aren't text were left out: {kinds} izostavljene su varijable koje nisu tekst: {kinds} +@msg a new document won't read these variables back with their kind: {names} novi dokument neće ponovo učitati ove varijable s njihovom vrstom: {names} +@msg a new document refuses this file because of these variables: {names} novi dokument odbija ovu datoteku zbog ovih varijabli: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them zaglavlje `{header}` za `{name}` učitalo bi se kao varijabla `{other}`: preimenujte jednu od njih @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` i `options.{key}: {inner}` se ne slažu: navedite opciju jednom @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files datoteke verzije {0} ne mogu se komprimirati: komprimirane datoteke otvaraju samo verzija {COMPRESSED_SINCE} i novije @msg width and height are at least 1 pixel širina i visina su najmanje 1 piksel diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 205991cbce..dee5c31384 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5604,6 +5604,9 @@ digits Malayalam Malaiàlam @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} més de {MAX_CSV_ROWS} conjunts de dades: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} més de {MAX_CSV_COLS} variables: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} +@msg a new document won't read these variables back with their kind: {names} un document nou no tornarà a llegir aquestes variables amb el seu tipus: {names} +@msg a new document refuses this file because of these variables: {names} un document nou rebutja aquest fitxer a causa d'aquestes variables: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them la capçalera `{header}` de `{name}` es tornaria a llegir com la variable `{other}`: canvieu el nom d’una de les dues @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft no cerca a les carpetes d’altres aplicacions ni del sistema: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft no cerca a la carpeta Shared o Public d’Usuaris: {path} @msg VectorCraft failed to start: {e} VectorCraft no s’ha pogut iniciar: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a6d23ba3cd..9b0218d5ca 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4791,6 +4791,9 @@ imageTrace Outline Obrys @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} více než {MAX_CSV_ROWS} sad dat: Importovat sady dat načte nejvýše {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} více než {MAX_CSV_COLS} proměnných: Importovat sady dat načte nejvýše {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} proměnné, které nejsou textové, byly vynechány: {kinds} +@msg a new document won't read these variables back with their kind: {names} nový dokument tyto proměnné nenačte zpět s jejich druhem: {names} +@msg a new document refuses this file because of these variables: {names} nový dokument tento soubor kvůli těmto proměnným odmítne: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them záhlaví `{header}` pro `{name}` by se načetlo jako proměnná `{other}`: jednu z nich přejmenujte @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` a `options.{key}: {inner}` si odporují: zadejte volbu jen jednou @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files soubory verze {0} nelze komprimovat: komprimované soubory otevírá až verze {COMPRESSED_SINCE} a novější @msg width and height are at least 1 pixel šířka i výška jsou alespoň 1 obrazový bod diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5a23913424..5cfe139d8b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5138,6 +5138,9 @@ mark-style Japanese Japansk Export Data Sets… Eksportér datasæt… Load Variable Library… Indlæs variabelbibliotek… @msg variables that aren't text were left out: {kinds} variabler, der ikke er tekst, blev udeladt: {kinds} +@msg a new document won't read these variables back with their kind: {names} et nyt dokument læser ikke disse variabler tilbage med deres type: {names} +@msg a new document refuses this file because of these variables: {names} et nyt dokument afviser denne fil på grund af disse variabler: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them overskriften `{header}` for `{name}` ville blive læst som variablen `{other}`: omdøb en af dem Make Graph Dynamic Gør diagram dynamisk Batch… Batch… Source Folder: Kildemappe: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1433e9d1cb..d23d59d4ec 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4400,6 +4400,9 @@ theme Appearance Erscheinungsbild @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mehr als {MAX_CSV_ROWS} Datensätze: „Datensätze importieren“ liest höchstens {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mehr als {MAX_CSV_COLS} Variablen: „Datensätze importieren“ liest höchstens {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} die Variablen, die kein Text sind, wurden ausgelassen: {kinds} +@msg a new document won't read these variables back with their kind: {names} ein neues Dokument liest diese Variablen nicht mit ihrer Art zurück: {names} +@msg a new document refuses this file because of these variables: {names} ein neues Dokument lehnt diese Datei wegen dieser Variablen ab: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them die Kopfzeile `{header}` für `{name}` würde als die Variable `{other}` gelesen: Benennen Sie eine der beiden um @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` und `options.{key}: {inner}` widersprechen sich: Option nur einmal angeben @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files Dateien der Version {0} können nicht komprimiert werden: Erst Version {COMPRESSED_SINCE} und neuer öffnen komprimierte Dateien @msg width and height are at least 1 pixel Breite und Höhe betragen mindestens 1 Pixel diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f28611c541..e2a1118481 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4433,6 +4433,9 @@ digits Malayalam Μαλαγιάλαμ @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} περισσότερα από {MAX_CSV_ROWS} σύνολα δεδομένων: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} περισσότερες από {MAX_CSV_COLS} μεταβλητές: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} οι μεταβλητές που δεν είναι κειμένου παραλείφθηκαν: {kinds} +@msg a new document won't read these variables back with their kind: {names} ένα νέο έγγραφο δεν θα διαβάσει ξανά αυτές τις μεταβλητές με το είδος τους: {names} +@msg a new document refuses this file because of these variables: {names} ένα νέο έγγραφο απορρίπτει αυτό το αρχείο λόγω αυτών των μεταβλητών: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them η κεφαλίδα `{header}` για το `{name}` θα διαβαζόταν ως η μεταβλητή `{other}`: μετονομάστε μία από τις δύο @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once τα `{key}: {top}` και `options.{key}: {inner}` διαφέρουν: δώστε την επιλογή μόνο μία φορά @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files τα αρχεία έκδοσης {0} δεν μπορούν να συμπιεστούν: μόνο η έκδοση {COMPRESSED_SINCE} και νεότερες ανοίγουν συμπιεσμένα αρχεία @msg width and height are at least 1 pixel το πλάτος και το ύψος πρέπει να είναι τουλάχιστον 1 εικονοστοιχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index dbd5dfb238..9e63d5266b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4485,6 +4485,9 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} más de {MAX_CSV_ROWS} conjuntos de datos: Importar conjuntos de datos lee como máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} más de {MAX_CSV_COLS} variables: Importar conjuntos de datos lee como máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} se omitieron las variables que no son de texto: {kinds} +@msg a new document won't read these variables back with their kind: {names} un documento nuevo no volverá a leer estas variables con su tipo: {names} +@msg a new document refuses this file because of these variables: {names} un documento nuevo rechaza este archivo por estas variables: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them el encabezado `{header}` de `{name}` se leería como la variable `{other}`: cambie el nombre de una de las dos @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` y `options.{key}: {inner}` no coinciden: indique la opción una sola vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files los archivos de la versión {0} no se pueden comprimir: solo la versión {COMPRESSED_SINCE} y posteriores abren archivos comprimidos @msg width and height are at least 1 pixel el ancho y el alto son de al menos 1 píxel diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e232c972a8..13f2d85be4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4693,6 +4693,9 @@ imageTrace Outline Ääriviiva @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} yli {MAX_CSV_ROWS} tietojoukkoa: Tuo tietojoukot lukee enintään {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} yli {MAX_CSV_COLS} muuttujaa: Tuo tietojoukot lukee enintään {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} muut kuin tekstimuuttujat jätettiin pois: {kinds} +@msg a new document won't read these variables back with their kind: {names} uusi asiakirja ei lue näitä muuttujia takaisin niiden lajin mukaisina: {names} +@msg a new document refuses this file because of these variables: {names} uusi asiakirja hylkää tämän tiedoston näiden muuttujien vuoksi: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them muuttujan `{name}` otsikko `{header}` luettaisiin muuttujaksi `{other}`: nimeä toinen niistä uudelleen @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` ja `options.{key}: {inner}` ovat ristiriidassa: anna asetus vain kerran @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files version {0} tiedostoja ei voi pakata: pakattuja tiedostoja voi avata vain versiosta {COMPRESSED_SINCE} alkaen @msg width and height are at least 1 pixel leveys ja korkeus ovat vähintään 1 pikseli diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 789e40c815..213bdb3d39 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4475,6 +4475,9 @@ axis Both Les deux @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ({kinds}) ont été ignorées +@msg a new document won't read these variables back with their kind: {names} un nouveau document ne relira pas ces variables avec leur type : {names} +@msg a new document refuses this file because of these variables: {names} un nouveau document refuse ce fichier à cause de ces variables : {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’en-tête `{header}` de `{name}` serait relu comme la variable `{other}` : renommez l’une des deux @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` et `options.{key}: {inner}` ne concordent pas. Indiquez l’option une seule fois @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files les fichiers de version {0} ne peuvent pas être compressés : seules les versions {COMPRESSED_SINCE} et ultérieures ouvrent les fichiers compressés @msg width and height are at least 1 pixel la largeur et la hauteur valent au moins 1 pixel diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 76dc225e81..5396a64557 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5255,6 +5255,9 @@ imageTrace Outline Körvonal @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} több mint {MAX_CSV_ROWS} adatkészlet: az Adatkészletek importálása legfeljebb {MAX_CSV_ROWS} adatkészletet olvas be @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} több mint {MAX_CSV_COLS} változó: az Adatkészletek importálása legfeljebb {MAX_CSV_COLS} változót olvas be @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} +@msg a new document won't read these variables back with their kind: {names} egy új dokumentum nem a fajtájukkal olvassa vissza ezeket a változókat: {names} +@msg a new document refuses this file because of these variables: {names} egy új dokumentum ezen változók miatt elutasítja ezt a fájlt: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them a(z) `{name}` változó `{header}` fejléce a(z) `{other}` változóként olvasódna vissza: nevezze át az egyiket @msg VectorCraft doesn't search other apps' or the system's folders: {path} a VectorCraft nem keres más alkalmazások és a rendszer mappáiban: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} a VectorCraft nem keres a Users alatti Shared és Public mappában: {path} @msg VectorCraft failed to start: {e} A VectorCraft nem tudott elindulni: {e} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 89633ae991..1ae04500b4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5138,6 +5138,9 @@ mark-style Japanese Jepang Export Data Sets… Ekspor himpunan data… Load Variable Library… Muat pustaka variabel… @msg variables that aren't text were left out: {kinds} variabel yang bukan teks dihilangkan: {kinds} +@msg a new document won't read these variables back with their kind: {names} dokumen baru tidak akan membaca kembali variabel ini dengan jenisnya: {names} +@msg a new document refuses this file because of these variables: {names} dokumen baru menolak file ini karena variabel berikut: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them header `{header}` untuk `{name}` akan terbaca sebagai variabel `{other}`: ganti nama salah satunya Make Graph Dynamic Jadikan grafik dinamis Batch… Batch… Source Folder: Folder sumber: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ad25ad87c4..b34a730a75 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4526,6 +4526,9 @@ axis Both Entrambi @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} più di {MAX_CSV_ROWS} set di dati: Importa set di dati ne legge al massimo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} più di {MAX_CSV_COLS} variabili: Importa set di dati ne legge al massimo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} le variabili che non sono di testo sono state escluse: {kinds} +@msg a new document won't read these variables back with their kind: {names} un nuovo documento non rileggerà queste variabili con il loro tipo: {names} +@msg a new document refuses this file because of these variables: {names} un nuovo documento rifiuta questo file a causa di queste variabili: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’intestazione `{header}` di `{name}` verrebbe riletta come la variabile `{other}`: rinomina una delle due @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` non coincidono: indicare l'opzione una sola volta @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files i file della versione {0} non possono essere compressi: solo la versione {COMPRESSED_SINCE} e successive aprono file compressi @msg width and height are at least 1 pixel larghezza e altezza sono di almeno 1 pixel diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 804186dd67..e7b1a1bf34 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4079,6 +4079,9 @@ swatch Bright Violet ビビッドバイオレット @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} データセットが {MAX_CSV_ROWS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_ROWS} 個までです @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 変数が {MAX_CSV_COLS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_COLS} 個までです @msg variables that aren't text were left out: {kinds} テキスト以外の変数は除外されました: {kinds} +@msg a new document won't read these variables back with their kind: {names} 新しいドキュメントでは、これらの変数は元の種類で読み込まれません: {names} +@msg a new document refuses this file because of these variables: {names} 新しいドキュメントは、これらの変数のためにこのファイルを拒否します: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` の見出し `{header}` は変数 `{other}` として読み込まれます: どちらかの名前を変更してください @msg guides are locked ガイドがロックされています @msg handle must be in or out handle には in または out を指定してください @msg no saved selection recalled 保存した選択範囲を呼び出していません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 250e0f384e..2dafb7cebb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5424,6 +5424,9 @@ imageTrace Outline კონტური @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS}-ზე მეტი მონაცემთა ნაკრები: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_ROWS}-ს @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS}-ზე მეტი ცვლადი: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_COLS}-ს @msg variables that aren't text were left out: {kinds} ცვლადები, რომლებიც ტექსტი არ არის, გამოტოვებულია: {kinds} +@msg a new document won't read these variables back with their kind: {names} ახალი დოკუმენტი ამ ცვლადებს მათი ტიპით ვერ წაიკითხავს: {names} +@msg a new document refuses this file because of these variables: {names} ახალი დოკუმენტი ამ ფაილს ამ ცვლადების გამო უარყოფს: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`-ის სათაური `{header}` წაიკითხება როგორც ცვლადი `{other}`: გადაარქვით სახელი ერთ-ერთს @msg x and y must be finite x და y სასრული უნდა იყოს @msg {id} opens another app: only the person at the keyboard can run it {id} სხვა აპს ხსნის: მისი გაშვება მხოლოდ კლავიატურასთან მყოფ ადამიანს შეუძლია @msg “{name}” is not a file „{name}“ ფაილი არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3ee9cb9d4c..2cb947582f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4006,6 +4006,9 @@ theme Appearance 외관 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 데이터 세트가 {MAX_CSV_ROWS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_ROWS}개를 읽습니다 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 변수가 {MAX_CSV_COLS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_COLS}개를 읽습니다 @msg variables that aren't text were left out: {kinds} 텍스트가 아닌 변수는 제외되었습니다: {kinds} +@msg a new document won't read these variables back with their kind: {names} 새 문서는 이 변수들을 원래 종류로 다시 읽지 않습니다: {names} +@msg a new document refuses this file because of these variables: {names} 새 문서는 이 변수들 때문에 이 파일을 거부합니다: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`의 머리글 `{header}`은(는) 변수 `{other}`(으)로 다시 읽힙니다: 둘 중 하나의 이름을 바꾸십시오 @msg guides are locked 안내선이 잠겨 있습니다 @msg handle must be in or out handle은 in 또는 out이어야 합니다 @msg no saved selection recalled 불러온 저장된 선택 영역이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3448536832..11e489e562 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5493,6 +5493,9 @@ swatch Bright Violet Felviolet @msg the spine has no segments de as heeft geen segmenten @msg variables are locked variabelen zijn vergrendeld @msg variables that aren't text were left out: {kinds} variabelen die geen tekst zijn, zijn weggelaten: {kinds} +@msg a new document won't read these variables back with their kind: {names} een nieuw document leest deze variabelen niet terug met hun soort: {names} +@msg a new document refuses this file because of these variables: {names} een nieuw document weigert dit bestand vanwege deze variabelen: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them de kop `{header}` voor `{name}` zou worden gelezen als de variabele `{other}`: wijzig de naam van een van beide @msg x and y must be finite x en y moeten eindig zijn @msg Persistent libraries not found: {files} Permanente bibliotheken niet gevonden: {files} @msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` is geen bibliotheekpaneel (zie window.swatchLibrary) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5830a1b6ab..c042bc487f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4617,6 +4617,9 @@ imageTrace Outline Kontur @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} więcej niż {MAX_CSV_ROWS} zestawów danych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} więcej niż {MAX_CSV_COLS} zmiennych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} pominięto zmienne, które nie są tekstowe: {kinds} +@msg a new document won't read these variables back with their kind: {names} nowy dokument nie odczyta tych zmiennych z ich rodzajem: {names} +@msg a new document refuses this file because of these variables: {names} nowy dokument odrzuca ten plik z powodu tych zmiennych: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them nagłówek `{header}` dla `{name}` zostałby odczytany jako zmienna `{other}`: zmień nazwę jednej z nich @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` i `options.{key}: {inner}` są sprzeczne: podaj opcję tylko raz @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files plików w wersji {0} nie można kompresować: skompresowane pliki otwierają tylko wersje {COMPRESSED_SINCE} i nowsze @msg width and height are at least 1 pixel szerokość i wysokość muszą wynosić co najmniej 1 piksel diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 00c6192224..8f86b811cb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4057,6 +4057,9 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mais de {MAX_CSV_ROWS} conjuntos de dados: Importar Conjuntos de Dados lê no máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mais de {MAX_CSV_COLS} variáveis: Importar Conjuntos de Dados lê no máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} as variáveis que não são de texto foram omitidas: {kinds} +@msg a new document won't read these variables back with their kind: {names} um novo documento não lerá essas variáveis de volta com o tipo delas: {names} +@msg a new document refuses this file because of these variables: {names} um novo documento recusa este arquivo por causa destas variáveis: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them o cabeçalho `{header}` de `{name}` seria lido como a variável `{other}`: renomeie uma delas @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` não coincidem: informe a opção uma só vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files arquivos da versão {0} não podem ser compactados: somente a versão {COMPRESSED_SINCE} e posteriores abrem arquivos compactados @msg width and height are at least 1 pixel largura e altura têm pelo menos 1 pixel diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 50d1ca1bdd..c28d4e979c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4521,6 +4521,9 @@ axis Both Оба @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} больше {MAX_CSV_ROWS} наборов данных: «Импортировать наборы данных» читает не более {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} больше {MAX_CSV_COLS} переменных: «Импортировать наборы данных» читает не более {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} переменные, которые не являются текстовыми, пропущены: {kinds} +@msg a new document won't read these variables back with their kind: {names} новый документ не прочитает эти переменные обратно с их типом: {names} +@msg a new document refuses this file because of these variables: {names} новый документ отклоняет этот файл из-за этих переменных: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` будет прочитан как переменная `{other}`: переименуйте одну из них @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` и `options.{key}: {inner}` противоречат друг другу: укажите параметр только один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файлы версии {0} не могут быть сжаты: только версия {COMPRESSED_SINCE} и новее открывают сжатые файлы @msg width and height are at least 1 pixel ширина и высота должны быть не менее 1 пикселя diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8ca7a39271..a42ba37e24 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4384,6 +4384,9 @@ axis Both Båda @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} fler än {MAX_CSV_ROWS} datauppsättningar: Importera datauppsättningar läser högst {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} fler än {MAX_CSV_COLS} variabler: Importera datauppsättningar läser högst {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} variabler som inte är text utelämnades: {kinds} +@msg a new document won't read these variables back with their kind: {names} ett nytt dokument läser inte tillbaka dessa variabler med deras typ: {names} +@msg a new document refuses this file because of these variables: {names} ett nytt dokument avvisar den här filen på grund av dessa variabler: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them rubriken `{header}` för `{name}` skulle läsas som variabeln `{other}`: byt namn på en av dem @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` och `options.{key}: {inner}` stämmer inte överens: ange alternativet bara en gång @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files filer i version {0} kan inte komprimeras: endast version {COMPRESSED_SINCE} och senare kan öppna komprimerade filer @msg width and height are at least 1 pixel bredd och höjd är minst 1 pixel diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c893d81f38..f6f841f6cb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5523,6 +5523,9 @@ theme Appearance Görünüm @msg an image has no pixels and was left out piksel içermeyen bir görüntü dışarıda bırakıldı @msg thumbnail: no page {n} (the file has 1) thumbnail: {n}. sayfa yok (dosyada 1 sayfa var) @msg variables that aren't text were left out: {kinds} metin olmayan değişkenler dışarıda bırakıldı: {kinds} +@msg a new document won't read these variables back with their kind: {names} yeni bir belge bu değişkenleri türleriyle geri okumaz: {names} +@msg a new document refuses this file because of these variables: {names} yeni bir belge bu değişkenler nedeniyle bu dosyayı reddeder: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{header}` başlığı `{other}` değişkeni olarak okunur: birini yeniden adlandırın Collapse Panel Group Panel Grubunu Daralt @msg panel is not in a dock group panel bir yuva grubunda değil @msg only a dock group above or below others collapses, not one beside another yalnızca diğerlerinin üstünde veya altındaki bir yuva grubu daraltılabilir, yanındaki değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2676d107e6..0685758bfa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4510,6 +4510,9 @@ axis Both Обидві @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} більше ніж {MAX_CSV_ROWS} наборів даних: «Імпортувати набори даних» читає не більше {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} більше ніж {MAX_CSV_COLS} змінних: «Імпортувати набори даних» читає не більше {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} змінні, що не є текстовими, пропущено: {kinds} +@msg a new document won't read these variables back with their kind: {names} новий документ не прочитає ці змінні назад з їхнім видом: {names} +@msg a new document refuses this file because of these variables: {names} новий документ відхиляє цей файл через ці змінні: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` буде прочитано як змінну `{other}`: перейменуйте одну з них @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` і `options.{key}: {inner}` суперечать одне одному: вкажіть параметр лише один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файли версії {0} не можуть бути стиснуті: тільки версія {COMPRESSED_SINCE} і новіші відкривають стислі файли @msg width and height are at least 1 pixel ширина та висота повинні бути не менше 1 пікселя diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 42de855e0c..75e0f7af4e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4917,6 +4917,9 @@ theme Appearance Giao diện @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} hơn {MAX_CSV_ROWS} tập dữ liệu: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} hơn {MAX_CSV_COLS} biến số: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} +@msg a new document won't read these variables back with their kind: {names} tài liệu mới sẽ không đọc lại các biến số này đúng loại: {names} +@msg a new document refuses this file because of these variables: {names} tài liệu mới sẽ từ chối tệp này vì các biến số sau: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them tiêu đề `{header}` của `{name}` sẽ được đọc thành biến số `{other}`: hãy đổi tên một trong hai @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft không tìm kiếm trong thư mục của ứng dụng khác hoặc hệ thống: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft không tìm kiếm thư mục Shared hoặc Public trong Users: {path} @msg VectorCraft failed to start: {e} VectorCraft khởi động thất bại: {e} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 53a2e2847d..815667fb9b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3474,6 +3474,9 @@ digits Malayalam 马拉雅拉姆数字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 数据集超过 {MAX_CSV_ROWS} 个:“导入数据集”最多读取 {MAX_CSV_ROWS} 个 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 变量超过 {MAX_CSV_COLS} 个:“导入数据集”最多读取 {MAX_CSV_COLS} 个 @msg variables that aren't text were left out: {kinds} 已省略非文本变量:{kinds} +@msg a new document won't read these variables back with their kind: {names} 新文档不会按原类型读回这些变量:{names} +@msg a new document refuses this file because of these variables: {names} 新文档会因这些变量而拒绝此文件:{names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的标题 `{header}` 会被读作变量 `{other}`:请重命名其中一个 List Variables 列出变量 Bind Variable 绑定变量 Unbind Variable 解除变量绑定 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0e9c6b5f29..27ae8fed5c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4466,6 +4466,9 @@ digits Malayalam 馬來亞拉姆數字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 資料集超過 {MAX_CSV_ROWS} 個:「匯入資料集」最多讀取 {MAX_CSV_ROWS} 個 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 變數超過 {MAX_CSV_COLS} 個:「匯入資料集」最多讀取 {MAX_CSV_COLS} 個 @msg variables that aren't text were left out: {kinds} 已略過非文字變數:{kinds} +@msg a new document won't read these variables back with their kind: {names} 新文件不會以原類型讀回這些變數:{names} +@msg a new document refuses this file because of these variables: {names} 新文件會因這些變數而拒絕此檔案:{names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的標題 `{header}` 會被讀作變數 `{other}`:請重新命名其中一個 List Variables 列出變數 Bind Variable 綁定變數 Unbind Variable 解除變數綁定 diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 1f7a90598e..e45e618acf 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -489,6 +489,43 @@ mod tests { } } + /// Export Data Sets…'s warnings about variables a new document doesn't read back with their + /// kind and about variables that make it refuse the file show in the status bar, and so does + /// its refusal of a header that is another variable's name; all three are translated in every + /// language but English. + #[test] + fn the_export_data_sets_warning_shows_in_the_status_bar() { + use crate::i18n::{Lang, message}; + let mut app = app_with_data(); + let dir = std::env::temp_dir().join(format!("vc-export-warning-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("sets.csv"); + app.run("variable.define", json!({"name": "#Tag", "kind": "text"})).unwrap(); + app.run("dataset.export", json!({"path": path})).unwrap(); + assert_eq!(app.ui.status, "a new document won't read these variables back with their kind: `#Tag`"); + let warning = app.ui.status.clone(); + app.run("variable.define", json!({"name": "%Rate", "kind": "text"})).unwrap(); + app.run("dataset.export", json!({"path": path})).unwrap(); + assert_eq!(app.ui.status, "a new document refuses this file because of these variables: `%Rate`"); + let refuses = app.ui.status.clone(); + app.run("variable.delete", json!({"names": ["%Rate"]})).unwrap(); + app.run("variable.define", json!({"name": "Tag", "kind": "visibility"})).unwrap(); + assert!(app.run("dataset.export", json!({"path": path})).is_err()); + let refused = app.ui.status.clone(); + assert!(refused.contains("would read back as the variable `#Tag`"), "{refused}"); + let _ = std::fs::remove_dir_all(&dir); + let langs: Vec = Lang::all().filter(|l| l.code() != "en").collect(); + assert!(langs.len() >= 23, "{} languages", langs.len()); + for l in langs { + let shown = message(l, &warning); + assert!(!shown.contains("won't read") && shown.contains("`#Tag`"), "{}: {shown}", l.code()); + let shown = message(l, &refuses); + assert!(!shown.contains("refuses") && shown.contains("`%Rate`"), "{}: {shown}", l.code()); + let shown = message(l, &refused); + assert!(!shown.contains("would read back") && shown.contains("`#Tag`") && shown.contains("`Tag`"), "{}: {shown}", l.code()); + } + } + /// What the panel acts on is the highlight, and only while it names a variable: a stale one /// (deleted elsewhere, undone) highlights nothing, so Delete and Options… stay disabled. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f98195ed33..55d6d44d78 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1646,7 +1646,13 @@ already walks Image Trace. Short agent entry points: first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without - a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; + a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image + variable's as `@Photo`, and a text or graph variable's as its name alone. Its reply's `warning` names the variables + whose header or values make an import into a document without them refuse the file (a `%` header, a `#` header + whose values aren't true or false). Otherwise it names the variables that such an import does not read back with + their kind: text variables whose names start with `#` or `@`, and graph variables. Export is refused, naming both variables, when a variable's header is + another variable's name (a visibility variable `Show` next to a text variable `#Show`). A prefixed cell whose name + is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph data files) is refused, and so are two cells that name one variable (`City` twice, or `Shown` and `#Shown`). The reply's `defined` lists the variables the import defined. While the variables are From 664fe8a12b556afe791a9a318b75480a1a3bd574 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:56:52 -0800 Subject: [PATCH 080/674] .ai import: Stylize effects open with their saved settings An object whose art style holds Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble now opens as itself with those effects live, in their order. Feather is read under the name and key the files use (`Adobe Fuzzy Mask`, `Radius`). Each setting is read only when it is written as its kind (`/Int`, `/Real`, a fill style for a color) with a value in range. An unknown key or choice, a missing setting, or a Scribble with a color of its own keeps the drawn look, where the reader used to cast, clamp or default the value. --- crates/engine/tests/import_fuzz.rs | 23 +++ crates/eps/src/import/ai/style.rs | 234 ++++++++++++++++++---- crates/eps/src/import/ai/style/tests.rs | 255 ++++++++++++++++++------ crates/eps/src/import/ai/tests.rs | 10 +- docs/file-format-parity.md | 4 + docs/target-app-parity.md | 2 + 6 files changed, 432 insertions(+), 96 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 7ae7b1d634..d24f69d00f 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3401,6 +3401,29 @@ fn arb_ai_token() -> impl Strategy { "(Fill Style Filter) 0 0 /Filter ,", "(Adobe Outer Glow) 1 0 /Filter ,", "(Adobe Drop Shadow) 1 0 /Filter ,", + "(Adobe Inner Glow) 1 0 /Filter ,", + "(Adobe Fuzzy Mask) 1 0 /Filter ,", + "(Adobe Round Corners) 1 0 /Filter ,", + "(Adobe Scribble Fill) 1 0 /Filter ,", + "(Chain Style Filter) 0 0 /Filter ,", + "/Dictionary : /NotRecorded ,", + "; /Dict ;", + "2.5 /Int (blnd) ,", + "99 /Int (csrc) ,", + "1e308 /Int (gtyp) ,", + "1 /Int (gtyp) ,", + "-13 /Real (vert) ,", + "14 /Real (Radius) ,", + "-1e308 /Real (radius) ,", + "67 /Real (Angle) ,", + "0.17 /Real (Scribbliness) ,", + "1e308 /Real (Spacing) ,", + "(x) /String (note) ,", + "1 /Bool (usePSLBlur) ,", + "16 /Int (Adobe Effect Expand Before Version) ,", + "/FillStyle : 0 O\n0 0 0 0 1 0 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,", + "/FillStyle : 0 O\nBb\n2 (G) 0 0 0 1 1 0 0 1 0 0 Bg\n0 BB\n/Def ;\n (gclr) ,", + "(sclr) ,", "1 /Visible ,", "2 /FillOrStroke ,", "1 /Bool (BSDashAdj) ,", diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index ede1ae8e93..20950c9657 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -48,8 +48,12 @@ use super::obj::V; use super::paint; const GLOW: &str = "Adobe Outer Glow"; // brand-ok: the filter's name in the files -const FEATHER: &str = "Adobe Feather"; // brand-ok: the filter's name in the files +const INNER_GLOW: &str = "Adobe Inner Glow"; // brand-ok: the filter's name in the files +const FEATHER: &str = "Adobe Fuzzy Mask"; // brand-ok: the filter's name in the files const SHADOW: &str = "Adobe Drop Shadow"; // brand-ok: the filter's name in the files +const ROUND_CORNERS: &str = "Adobe Round Corners"; // brand-ok: the filter's name in the files +const SCRIBBLE: &str = "Adobe Scribble Fill"; // brand-ok: the filter's name in the files +const EXPAND_VERSION: &str = "Adobe Effect Expand Before Version"; // brand-ok: the key's name in the files const DEFORM: &str = "Adobe Deform"; // brand-ok: the filter's name in the files const OFFSET: &str = "Adobe Offset Path"; // brand-ok: the filter's name in the files const TRANSFORM: &str = "Adobe Transform"; // brand-ok: the filter's name in the files @@ -94,8 +98,8 @@ pub(super) struct ArtStyle { /// The style reads as [`Self::items`] and [`Self::effects`]. pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with - /// no transparency or effects of their own, and only Outer Glow, Feather and Drop Shadow on the - /// object: what any object is read with. Type takes the other plain styles too (its drawn look + /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, + /// Feather, Round Corners and Scribble on the object: what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, /// Its fills and strokes, bottom first. @@ -148,6 +152,17 @@ impl Default for ItemLook { } } +/// How a filter's dictionary writes an entry: `value /Int (key) ,`, `/Real`, `/Bool`, a fill's +/// style (`/FillStyle : … /Def ; (key) ,`), or anything else. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Int, + Real, + Bool, + Fill, + Other, +} + #[derive(Debug)] struct Filter { name: String, @@ -156,6 +171,8 @@ struct Filter { parent: Option, compound: bool, params: HashMap, + /// How each key of its dictionary is written. + kinds: HashMap, /// Its dictionary's arrays (`/Array : v /Real , … ; (key) ,`), by key. arrays: HashMap>, fill: Option, @@ -184,6 +201,7 @@ impl Default for Filter { parent: None, compound: false, params: HashMap::new(), + kinds: HashMap::new(), arrays: HashMap::new(), fill: None, stroke: None, @@ -223,6 +241,10 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { }; let mut array: Option> = None; let mut dict_array: Option> = None; + // A paint style being read as a dictionary entry: its key follows its `/Def ;`. + let mut style_entry: Option = None; + // A name of a basic filter's that may be an entry's type, with the string that follows it. + let mut other_entry: Option> = None; let mut lex = Lexer::new(data); while let Some(t) = lex.next_token() { if let (Some(a), Tok::Num(v)) = (array.as_mut(), &t.tok) { @@ -231,14 +253,21 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { } match t.tok { Tok::Num(v) => operands.push(V::Num(v)), - Tok::Str(s) | Tok::Hex(s) => operands.push(V::Str(s)), + Tok::Str(s) | Tok::Hex(s) => { + if let Some(key @ None) = other_entry.as_mut() { + *key = Some(String::from_utf8_lossy(&s).into_owned()); + } + operands.push(V::Str(s)); + } Tok::Name(n) => match n { b"KnownStyle" => { finish(name.take(), &mut filters); operands.clear(); open.clear(); - (pending, in_basic) = (None, false); + (pending, in_basic, style_entry, other_entry) = (None, false, None, None); } + b"FillStyle" => style_entry = Some(Kind::Fill), + b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other), b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(V::text), b"CompoundFilter" => pending = Some(true), b"BasicFilter" => pending = Some(false), @@ -271,17 +300,31 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { a.extend(value); continue; } + let kind = match n { + b"Int" => Kind::Int, + b"Real" => Kind::Real, + _ => Kind::Bool, + }; // The key follows: `value /Real (key) ,`. - if let (Some(value), Some(Tok::Str(key))) = (value, lex.next_token().map(|t| t.tok)) + if let Some(Tok::Str(key)) = lex.next_token().map(|t| t.tok) && let Some(f) = filters.last_mut() { - f.params.insert(String::from_utf8_lossy(&key).into_owned(), value); + let key = String::from_utf8_lossy(&key).into_owned(); + match value { + Some(value) => f.params.insert(key.clone(), value), + None => f.params.remove(&key), + }; + f.kinds.insert(key, kind); } continue; } + // Perhaps an entry of another type (`(text) /String (key) ,`): its key, if any, is + // the string before the `,`. + _ if in_basic => other_entry = Some(None), _ => {} }, Tok::Word(w) => { + let entry = other_entry.take().flatten(); let op = std::str::from_utf8(w).unwrap_or_default(); if op == "[" { array = Some(vec![]); @@ -304,6 +347,15 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { if op == ";" && !in_basic { open.pop(); } + if op == "," { + let key = match style_entry.take() { + Some(kind) => operands.iter().rev().find_map(V::text).map(|k| (k, kind)), + None => entry.map(|k| (k, Kind::Other)), + }; + if let (Some((key, kind)), Some(f)) = (key, filters.last_mut()) { + f.kinds.insert(key, kind); + } + } if let Some(f) = filters.last_mut() { paint_op(f, op, &operands); } @@ -428,39 +480,144 @@ fn width_profile(arrays: &HashMap>) -> Option { (!uniform).then_some(WidthProfile { points }) } +/// A Stylize effect's dictionary, read only as it is written: each setting a key of the kind it +/// names, with a finite value in the effect's range. +struct Settings<'a>(&'a Filter); + +impl Settings<'_> { + /// Every key is one of `known`, or one of `fixed` holding the value it names. + /// The choices (`blnd`, `csrc`, `gtyp`) are written as `/Int`, the colors as fill styles and + /// the other settings as `/Real`. + fn only(&self, known: &[&str], fixed: &[(&str, Kind, f64)]) -> bool { + let f = self.0; + let kind_of = |key: &str| match key { + "blnd" | "csrc" | "gtyp" => Kind::Int, + "sclr" | "gclr" => Kind::Fill, + _ => Kind::Real, + }; + f.arrays.is_empty() + && f.kinds.iter().all(|(key, kind)| { + (known.contains(&key.as_str()) && kind_of(key) == *kind) + || fixed.iter().any(|(k, want, v)| k == key && want == kind && f.params.get(key.as_str()) == Some(v)) + }) + } + + fn real(&self, key: &str, range: std::ops::RangeInclusive) -> Option { + (self.0.kinds.get(key) == Some(&Kind::Real)).then_some(())?; + self.0.params.get(key).copied().filter(|v| v.is_finite() && range.contains(v)) + } + + /// A choice numbered from 0 to `max`. + fn choice(&self, key: &str, max: u8) -> Option { + (self.0.kinds.get(key) == Some(&Kind::Int)).then_some(())?; + let v = self.0.params.get(key).copied().filter(|v| v.is_finite() && v.fract() == 0.0 && (0.0..=f64::from(max)).contains(v))?; + Some(v as usize) + } + + /// The blend mode in `blnd`, numbered as transparency's (`Xy`). + fn mode(&self) -> Option { + Some(super::read::blend_name(self.choice("blnd", 15)?)) + } + + /// The color of the fill style written as `key`: a solid color, in Normal at full opacity. + fn color(&self, key: &str) -> Option { + let f = self.0; + let normal = f.xy.is_none_or(|(mode, opacity)| mode == 0 && opacity >= 1.0); + (f.kinds.get(key) == Some(&Kind::Fill) && !f.gradient && f.pattern.is_none() && normal).then_some(())?; + f.fill.as_ref()?.color() + } +} + +/// Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners and Scribble (`None`: another +/// filter). `Some(None)` is one whose settings aren't all read: an unknown key, a key of another +/// kind, a value out of range or a missing setting keeps the drawn look. The keys are LiveEffect +/// XML's +/// (https://community.adobe.com/questions-652/pageitem-applyeffect-liveeffectxml-769450). +fn stylize(f: &Filter) -> Option> { + let s = Settings(f); + let opacity = || Some(s.real("opac", 0.0..=1.0)? * 100.0); + Some(match f.name.as_str() { + // `horz` and `vert` are the X and Y Offset, right and down + // (https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-drop-shadows.html); + // `csrc` 0 is Color (`sclr`), 1 Darkness (`dark`, a percent). `blur` is half the catalog's. + SHADOW => (|| { + let fixed = [("pair", Kind::Bool, 1.0), ("usePSLBlur", Kind::Bool, 1.0), (EXPAND_VERSION, Kind::Int, 16.0)]; + s.only(&["blnd", "opac", "horz", "vert", "blur", "csrc", "dark", "sclr"], &fixed).then_some(())?; + let mut params = json!({ + "mode": s.mode()?, + "opacity": opacity()?, + "blur": 2.0 * s.real("blur", 0.0..=500.0)?, + "x": s.real("horz", -1e4..=1e4)?, + "y": s.real("vert", -1e4..=1e4)?, + }); + if s.choice("csrc", 1)? == 0 { + params["color"] = json!(s.color("sclr")?); + } else { + params["shade"] = json!("darkness"); + params["darkness"] = json!(s.real("dark", 0.0..=100.0)?); + if let Some(c) = s.color("sclr") { + params["color"] = json!(c); + } + } + Some(("stylize.dropShadow", params)) + })(), + // `gtyp` 0 is Center, 1 Edge (https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-an-inner-or-outer-glow.html); + // `blur` is the catalog's. + INNER_GLOW => (|| { + s.only(&["blnd", "opac", "blur", "gtyp", "gclr"], &[]).then_some(())?; + let source = if s.choice("gtyp", 1)? == 0 { "center" } else { "edge" }; + let params = json!({ + "mode": s.mode()?, + "opacity": opacity()?, + "blur": s.real("blur", 0.0..=1000.0)?, + "color": s.color("gclr")?, + "source": source, + }); + Some(("stylize.innerGlow", params)) + })(), + // `blur` is half the catalog's. + GLOW => (|| { + s.only(&["blnd", "opac", "blur", "sclr"], &[("usePSLBlur", Kind::Bool, 1.0), (EXPAND_VERSION, Kind::Int, 16.0)]).then_some(())?; + let params = json!({"mode": s.mode()?, "opacity": opacity()?, "blur": 2.0 * s.real("blur", 0.0..=500.0)?, "color": s.color("sclr")?}); + Some(("stylize.outerGlow", params)) + })(), + // https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/feather-object-edges.html + FEATHER => s.only(&["Radius"], &[]).then(|| s.real("Radius", 0.0..=1000.0)).flatten().map(|r| ("stylize.feather", json!({"radius": r}))), + ROUND_CORNERS => { + s.only(&["radius"], &[]).then(|| s.real("radius", 0.0..=1e4)).flatten().map(|r| ("stylize.roundCorners", json!({"radius": r}))) + } + // `Angle` in degrees; widths, spacings and overlaps in points; `Scribbliness` (Curviness) + // and `ScribbleVariation` as fractions. The catalog's Scribble has no color, so a Scribble + // with `sclr` keeps the drawn look. + SCRIBBLE => (|| { + let keys = + ["Angle", "EdgeOverlap", "EdgeOverlapVariation", "StrokeWidth", "Scribbliness", "ScribbleVariation", "Spacing", "SpacingVariation"]; + s.only(&keys, &[]).then_some(())?; + let params = json!({ + "angle": s.real("Angle", -360.0..=360.0)?, + "overlap": s.real("EdgeOverlap", -1000.0..=1000.0)?, + "overlapVariation": s.real("EdgeOverlapVariation", 0.0..=100.0)?, + "strokeWidth": s.real("StrokeWidth", 0.01..=1000.0)?, + "curviness": s.real("Scribbliness", 0.0..=1.0)? * 100.0, + "curvinessVariation": s.real("ScribbleVariation", 0.0..=1.0)? * 100.0, + "spacing": s.real("Spacing", 0.1..=1000.0)?, + "spacingVariation": s.real("SpacingVariation", 0.0..=100.0)?, + }); + Some(("stylize.scribble", params)) + })(), + _ => return None, + }) +} + /// The live effect filter `f` is, when it is one read here. fn effect(f: &Filter) -> Option { + if let Some(stylized) = stylize(f) { + let (id, params) = stylized?; + return Some(Effect { id: id.into(), params, visible: f.visible }); + } let param = |k: &str| f.params.get(k).copied().filter(|v| v.is_finite()); let flag = |k: &str| param(k).is_some_and(|v| v != 0.0); - let mode = |default: usize| super::read::blend_name(param("blnd").map_or(default, |v| v.max(0.0) as usize)); - let color = f.fill.as_ref().and_then(Paint::color).unwrap_or(vectorcraft_color::Color::BLACK); let (id, params) = match f.name.as_str() { - // `blur`'s scale isn't publicly documented: read as the Gaussian's σ, an effect's blur being 2σ. - GLOW => ( - "stylize.outerGlow", - json!({"mode": mode(2), "opacity": param("opac").unwrap_or(0.75) * 100.0, "blur": 2.0 * param("blur").unwrap_or(5.0), "color": color}), - ), - // LiveEffect XML uses `radius`; art styles abbreviate it `rad` (public scripting posts on applyEffect). - FEATHER => ("stylize.feather", json!({"radius": param("rad").or_else(|| param("radius")).unwrap_or(5.0)})), - SHADOW => { - let mut params = json!({ - "mode": mode(1), - "opacity": param("opac").unwrap_or(0.75) * 100.0, - "blur": 2.0 * param("blur").unwrap_or(5.0), - // Undocumented; read as the dialog's offsets, not flipped like art-space y: its default 7/7 pt is - // right and down (https://helpx.adobe.com/illustrator/using/drop-shadows-glows-feathering.html). - "x": param("horz").unwrap_or(7.0), - "y": param("vert").unwrap_or(7.0), - "color": color, - }); - // A `csrc` of 1 is Darkness, the object's own colors with black added; any value other than 0 is read as - // Darkness. `dark` is the percent of black (0 to 100, where `opac` is a fraction), and 100 when it is missing or not finite. - if param("csrc").unwrap_or(0.0) != 0.0 { - params["shade"] = json!("darkness"); - params["darkness"] = json!(param("dark").map_or(100.0, |v| v.clamp(0.0, 100.0))); - } - ("stylize.dropShadow", params) - } // Effect › Warp: `DeformStyle` numbers the styles from 1 as the dialog lists them, `Rotate` // is Vertical, and the bend and distortions are fractions. DEFORM => { @@ -657,7 +814,12 @@ fn style(filters: &[Filter]) -> ArtStyle { && count(false) <= 1 && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Stroke { .. } | StyleItem::Gradient { .. })) && st.looks.iter().all(|l| l.visible && l.opacity >= 1.0 && l.blend == BlendMode::Normal && l.effects.is_empty()) - && st.effects.iter().all(|e| matches!(e.id.as_str(), "stylize.outerGlow" | "stylize.feather" | "stylize.dropShadow")); + && st.effects.iter().all(|e| { + matches!( + e.id.as_str(), + "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "stylize.roundCorners" | "stylize.scribble" + ) + }); st } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 964b74f10b..9ba5838f39 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -26,94 +26,236 @@ fn dashes_aligned_to_corners_keep_the_drawn_look() { assert!(!art_styles(data)["Stitches"].plain); } -#[test] -fn a_drop_shadow_offset_down_points_down() { - // GUARDS: the document has y down; flipping `vert` like an art-space y would turn the dialog's - // default shadow (7 pt right, 7 pt down) upwards. - let data = b"/KnownStyle :\n(Shade) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n7 /Real (horz) ,\n7 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(data); - let [shadow] = styles["Shade"].effects.as_slice() else { panic!("{:?}", styles["Shade"]) }; - assert_eq!((shadow.params["x"].as_f64(), shadow.params["y"].as_f64()), (Some(7.0), Some(7.0))); -} - /// The style `Shade`: a Drop Shadow whose dictionary holds `keys`. fn shadow_style(keys: &str) -> ArtStyle { + effect_style("Adobe Drop Shadow", keys) +} + +/// The style `Fx`: an effect `name` on the whole object, its dictionary holding `keys`. +fn effect_style(name: &str, keys: &str) -> ArtStyle { let data = format!( - "/KnownStyle :\n(Shade) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n;\n" + "/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n;\n" ); - art_styles(data.as_bytes()).remove("Shade").unwrap_or_default() + art_styles(data.as_bytes()).remove("Fx").unwrap_or_default() +} + +/// A colour entry `key`: a fill style in RGB `r g b`. +fn color_entry(key: &str, rgb: &str) -> String { + format!("/FillStyle : 0 O\n0 0 0 0 {rgb} Xa\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Def ;\n ({key}) ,\n") +} + +/// A Drop Shadow's dictionary: every setting, with Color or Darkness set by `shade`. +fn shadow_keys(shade: &str) -> String { + format!( + "2 /Int (blnd) ,\n0.43 /Real (opac) ,\n37 /Real (dark) ,\n-13 /Real (vert) ,\n11 /Real (horz) ,\n17 /Real (blur) ,\n{}{shade}", + color_entry("sclr", "0 1 0") + ) +} + +/// `style`'s one effect on the whole object. +fn only_effect(style: &ArtStyle) -> &Effect { + assert!(style.plain, "{style:?}"); + let [e] = style.effects.as_slice() else { panic!("{style:?}") }; + e +} + +/// `params[key]`, a number within rounding of `want`. +fn near(params: &serde_json::Value, key: &str, want: f64) { + let got = params[key].as_f64(); + assert!(got.is_some_and(|v| (v - want).abs() < 1e-9), "{key}: {got:?}, not {want}: {params}"); +} + +#[test] +fn a_drop_shadow_reads_its_settings() { + // GUARDS: `vert` read as an art-space y would flip a shadow offset down to up. + let style = shadow_style(&shadow_keys("0 /Int (csrc) ,\n")); + let shadow = only_effect(&style); + let p = &shadow.params; + assert_eq!( + (shadow.id.as_str(), &p["mode"], &p["color"]), + ("stylize.dropShadow", &json!("Screen"), &json!(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0))) + ); + for (key, want) in [("x", 11.0), ("y", -13.0), ("blur", 34.0), ("opacity", 43.0)] { + near(p, key, want); + } + assert_eq!((p.get("shade"), p.get("darkness")), (None, None)); } #[test] fn a_drop_shadow_with_darkness_reads_its_darkness() { - // GUARDS: a `csrc` other than 0 made the style not plain, and the object came in as its drawn look. - let style = shadow_style("1 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n1 /Int (csrc) ,\n50 /Real (dark) ,\n"); - assert!(style.plain, "{style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{style:?}") }; - let p = &shadow.params; + let shadow = only_effect(&shadow_style(&shadow_keys("1 /Int (csrc) ,\n"))).clone(); + assert_eq!((&shadow.params["shade"], &shadow.params["darkness"]), (&json!("darkness"), &json!(37.0))); +} + +#[test] +fn a_drop_shadow_with_settings_not_read_keeps_the_drawn_look() { + // GUARDS: an unknown `csrc` was read as Darkness, `blnd` was cast to a mode, a missing setting + // took a default and an unknown key was skipped: each became an editable shadow the file doesn't draw. + let full = shadow_keys("0 /Int (csrc) ,\n"); + let cases = [ + full.replace("0 /Int (csrc)", "99 /Int (csrc)"), + full.replace("2 /Int (blnd)", "99 /Int (blnd)"), + full.replace("2 /Int (blnd)", "2.5 /Int (blnd)"), + full.replace("0 /Int (csrc)", "0.5 /Int (csrc)"), + full.replace("11 /Real (horz)", "11 /Int (horz)"), + full.replace("37 /Real (dark)", "37 /Int (dark)"), + full.replace("2 /Int (blnd)", "2 /Real (blnd)"), + full.replace("0.43 /Real (opac)", "1.5 /Real (opac)"), + full.replace("11 /Real (horz) ,\n", ""), + full.replace(&color_entry("sclr", "0 1 0"), ""), + full.replace("0 1 0 0 0 Xy", "2 0.5 0 0 0 Xy"), + format!("{full}1 /Real (spread) ,\n"), + format!("{full}0 /Bool (pair) ,\n"), + format!("{full}(x) /String (note) ,\n"), + format!("{full}3 4 /RealPointRelToROrigin (spot) ,\n"), + shadow_keys("1 /Int (csrc) ,\n").replace("37 /Real (dark)", "250 /Real (dark)"), + shadow_keys("1 /Int (csrc) ,\n").replace("37 /Real (dark)", "(fifty) /Real (dark)"), + ]; + for keys in cases { + assert!(!shadow_style(&keys).plain, "{keys}"); + } + let observed = format!("{full}1 /Bool (pair) ,\n1 /Bool (usePSLBlur) ,\n16 /Int (Adobe Effect Expand Before Version) ,\n"); + assert!(shadow_style(&observed).plain); +} + +#[test] +fn an_inner_glow_reads_its_settings() { + let keys = + |gtyp: &str| format!("10 /Int (blnd) ,\n0.41 /Real (opac) ,\n13 /Real (blur) ,\n{}{gtyp} /Int (gtyp) ,\n", color_entry("gclr", "1 0 0")); + let style = effect_style("Adobe Inner Glow", &keys("0")); + let glow = only_effect(&style); + let p = &glow.params; assert_eq!( - (shadow.id.as_str(), &p["shade"], &p["darkness"], &p["opacity"], &p["blur"]), - ("stylize.dropShadow", &json!("darkness"), &json!(50.0), &json!(75.0), &json!(10.0)) + (glow.id.as_str(), &p["mode"], &p["source"], &p["color"]), + ("stylize.innerGlow", &json!("Difference"), &json!("center"), &json!(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))) ); + near(p, "opacity", 41.0); + near(p, "blur", 13.0); + assert!(style.simple); + assert_eq!(only_effect(&effect_style("Adobe Inner Glow", &keys("1"))).params["source"], json!("edge")); + assert!(!effect_style("Adobe Inner Glow", &keys("2")).plain); } #[test] -fn a_drop_shadow_darkness_is_100_percent_when_missing_and_kept_within_0_to_100() { - for (dark, want) in [("", 100.0), ("(fifty) /Real (dark) ,\n", 100.0), ("250 /Real (dark) ,\n", 100.0), ("-5 /Real (dark) ,\n", 0.0)] { - let style = shadow_style(&format!("1 /Int (csrc) ,\n{dark}")); - assert!(style.plain, "{dark:?}: {style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{dark:?}: {style:?}") }; - assert_eq!((&shadow.params["shade"], &shadow.params["darkness"]), (&json!("darkness"), &json!(want)), "{dark:?}"); +fn an_outer_glow_reads_its_settings_and_keeps_the_drawn_look_for_others() { + let keys = format!( + "16 /Int (Adobe Effect Expand Before Version) ,\n10 /Int (blnd) ,\n0.42 /Real (opac) ,\n19 /Real (blur) ,\n{}1 /Bool (usePSLBlur) ,\n", + color_entry("sclr", "0 0 1") + ); + let glow = only_effect(&effect_style("Adobe Outer Glow", &keys)).clone(); + assert_eq!((glow.id.as_str(), &glow.params["mode"]), ("stylize.outerGlow", &json!("Difference"))); + near(&glow.params, "opacity", 42.0); + near(&glow.params, "blur", 38.0); + for other in [ + format!("{keys}1 /Real (spread) ,\n"), + keys.replace("19 /Real (blur)", "19 /Int (blur)"), + keys.replace("1 /Bool (usePSLBlur)", "0 /Bool (usePSLBlur)"), + ] { + assert!(!effect_style("Adobe Outer Glow", &other).plain, "{other}"); } } #[test] -fn a_drop_shadow_with_color_keeps_its_params() { - // GUARDS: a `csrc` of 0, or none, is Color; its shadow has neither `shade` nor `darkness`. - for csrc in ["", "0 /Int (csrc) ,\n50 /Real (dark) ,\n"] { - let style = shadow_style(&format!("2 /Int (blnd) ,\n0.5 /Real (opac) ,\n{csrc}")); - assert!(style.plain, "{csrc:?}: {style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{csrc:?}: {style:?}") }; - let want = json!({"mode": "Screen", "opacity": 50.0, "blur": 10.0, "x": 7.0, "y": 7.0, "color": vectorcraft_color::Color::BLACK}); - assert_eq!(shadow.params, want, "{csrc:?}"); +fn a_feather_reads_its_radius() { + // GUARDS: Feather was looked for under another name and key, so the files' Feather kept the drawn look. + let style = effect_style("Adobe Fuzzy Mask", "14 /Real (Radius) ,\n"); + let feather = only_effect(&style); + assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(14.0))); + assert!(style.simple); + for other in ["14 /Real (radius) ,\n", "", "-1 /Real (Radius) ,\n"] { + assert!(!effect_style("Adobe Fuzzy Mask", other).plain, "{other}"); } } #[test] -fn a_feather_reads_its_radius_from_rad() { - let data = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n12 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(data); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(12.0))); +fn round_corners_read_their_radius() { + let style = effect_style("Adobe Round Corners", "21 /Real (radius) ,\n"); + let round = only_effect(&style); + assert_eq!((round.id.as_str(), round.params["radius"].as_f64()), ("stylize.roundCorners", Some(21.0))); + assert!(style.simple); + for other in ["21 /Real (Radius) ,\n", "21 /Int (radius) ,\n", "-1 /Real (radius) ,\n"] { + assert!(!effect_style("Adobe Round Corners", other).plain, "{other}"); + } +} + +/// A Scribble's dictionary with every setting. +const SCRIBBLE_KEYS: &str = "0.8 /Real (SpacingVariation) ,\n0.23 /Real (ScribbleVariation) ,\n4 /Real (EdgeOverlapVariation) ,\n67 /Real (Angle) ,\n\ + 2.3 /Real (StrokeWidth) ,\n-7 /Real (EdgeOverlap) ,\n0.17 /Real (Scribbliness) ,\n13 /Real (Spacing) ,\n"; + +#[test] +fn a_scribble_reads_its_settings() { + let style = effect_style("Adobe Scribble Fill", SCRIBBLE_KEYS); + let scribble = only_effect(&style); + assert_eq!(scribble.id, "stylize.scribble"); + let want = [ + ("angle", 67.0), + ("overlap", -7.0), + ("overlapVariation", 4.0), + ("strokeWidth", 2.3), + ("curviness", 17.0), + ("curvinessVariation", 23.0), + ("spacing", 13.0), + ("spacingVariation", 0.8), + ]; + for (key, v) in want { + near(&scribble.params, key, v); + } + assert!(style.simple); } #[test] -fn a_feather_falls_back_to_radius_and_defaults_to_five_points() { - let with_name = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n3 /Real (radius) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(with_name); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!(feather.params["radius"].as_f64(), Some(3.0)); +fn a_scribble_with_a_colour_or_settings_not_read_keeps_the_drawn_look() { + let cases = [ + format!("{SCRIBBLE_KEYS}{}", color_entry("sclr", "0 1 0")), + format!("{SCRIBBLE_KEYS}0.5 /Real (MinDensity) ,\n"), + SCRIBBLE_KEYS.replace("13 /Real (Spacing) ,\n", ""), + SCRIBBLE_KEYS.replace("0.17 /Real (Scribbliness)", "17 /Real (Scribbliness)"), + ]; + for keys in cases { + assert!(!effect_style("Adobe Scribble Fill", &keys).plain, "{keys}"); + } +} - let bare = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(bare); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!(feather.params["radius"].as_f64(), Some(5.0)); +#[test] +fn effects_on_the_object_keep_their_order() { + let data = format!( + "/KnownStyle :\n(Two) /Name ,\n/ActiveStyle :\n{}", + compound( + "Chain Style Filter", + &[basic("Adobe Round Corners", "10 /Real (radius) ,\n"), basic("Adobe Drop Shadow", &shadow_keys("0 /Int (csrc) ,\n"))] + ) + ); + let st = &art_styles(data.as_bytes())["Two"]; + assert!(st.plain && st.simple, "{st:?}"); + assert_eq!(st.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.roundCorners", "stylize.dropShadow"]); +} + +#[test] +fn a_glow_on_one_fill_stays_on_that_fill() { + // An ordinary object keeps the drawn look (`simple` is false); type takes the fill's glow. + let glow = basic( + "Adobe Inner Glow", + &format!("2 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n{}1 /Int (gtyp) ,\n", color_entry("gclr", "1 1 1")), + ); + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), glow]); + let data = + format!("/KnownStyle :\n(Lit) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + let st = &art_styles(data.as_bytes())["Lit"]; + assert!(st.plain && !st.simple, "{st:?}"); + assert!(st.effects.is_empty()); + assert_eq!(st.looks[0].effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.innerGlow"]); } #[test] fn art_styles_clear_operands_beyond_the_cap() { let mut data = Vec::from( - b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n", + b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n", ); for _ in 0..80 { data.extend_from_slice(b"1 "); } - data.extend_from_slice(b"/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n"); + data.extend_from_slice(b"/Dictionary : /NotRecorded ,\n5 /Real (Radius) ,\n; /Dict ;\n /Part ,\n;\n"); let styles = art_styles(&data); let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; assert_eq!(feather.params["radius"].as_f64(), Some(5.0)); @@ -121,7 +263,8 @@ fn art_styles_clear_operands_beyond_the_cap() { #[test] fn art_styles_ignore_filters_beyond_the_cap() { - const UNIT: &[u8] = b"/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n"; + const UNIT: &[u8] = + b"/BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Real (Radius) ,\n; /Dict ;\n /Part ,\n"; let mut data = Vec::from(b"/KnownStyle :\n(Capped) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n"); for _ in 0..MAX_FILTERS + 16 { @@ -309,7 +452,7 @@ fn contents_above_some_items_count_them() { #[test] fn an_effect_not_read_here_keeps_the_drawn_look() { - let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Adobe Scribble Fill", "")]); + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Adobe Zig Zag", "")]); let data = format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); assert!(!art_styles(data.as_bytes())["Odd"].plain); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 96d0ba9411..05f33e6a3e 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2080,12 +2080,14 @@ const ART_STYLES: &str = "%AI9_BeginArtStyles\n\ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n\ + 0 /Int (csrc) ,\n/FillStyle : 0 O\n0 0 0 1 0 0 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n\ /KnownStyle :\n(Lit) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n1 (G) 0 0 0 1 1 0 0 1 0 0 Bg\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Outer Glow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n0.5 /Real (opac) ,\n2 /Real (blur) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Outer Glow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n2 /Int (blnd) ,\n0.5 /Real (opac) ,\n2 /Real (blur) ,\n\ + /FillStyle : 0 O\n0 0 0 0 1 1 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,\n; /Dict ;\n /Part ,\n;\n\ %AI9_EndArtStyles\n"; #[test] @@ -2114,7 +2116,7 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n8 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n8 /Real (Radius) ,\n; /Dict ;\n /Part ,\n;\n\ %AI9_EndArtStyles\n"; let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Soft) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); @@ -2156,7 +2158,7 @@ fn a_styled_object_inside_a_drawn_look_survives_it() { /// that shadow, not as its drawn look. #[test] fn an_object_with_a_darkness_shadow_comes_in_as_itself() { - let styles = ART_STYLES.replace("3 /Real (horz) ,\n", "1 /Int (csrc) ,\n50 /Real (dark) ,\n3 /Real (horz) ,\n"); + let styles = ART_STYLES.replace("0 /Int (csrc) ,\n", "1 /Int (csrc) ,\n50 /Real (dark) ,\n"); let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (Blue) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); let r = read_ok(&format!("{styles}{}", layer(&art_))); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 98260d60a3..2c7fc01094 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -79,6 +79,9 @@ private editing data. VectorCraft: opens a file with that prolog from its program, as the format. - **Known failures in users' files:** layer structure flattened or multiplied (#951: 109 layers instead of 14; #868: round trip with Illustrator 2018 loses layers and groups), guides and non-printing construction + lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects + that are not read or have settings that are not read, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` + without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, with its paragraphs' letter @@ -89,6 +92,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4736272d74..326a9cc951 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1207,6 +1207,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Drop Shadow's Darkness:** Effect › Stylize › Drop Shadow… has Color and Darkness as radio buttons, each with its field, and the Appearance panel's inline editor has the two radio buttons in its Shade row (`shade`: `color` or `darkness`; `darkness`: 0 to 100%, 100 by default). Color is the default, and a shadow saved without these keys draws as before. With Darkness, the stored source-color model determines the adjustment before document/profile conversion and blur: subtract Darkness/100 from each RGB channel, clamped at zero, or add it to CMYK black K and Gray black, clamped at one, preserving CMYK C/M/Y. At the near-100% endpoint the shadow source becomes gray black before conversion. Shadow opacity stays separate. Original gradient stops follow the same application rule before interpolation; exact resource-level gradient parity remains open. Application SVG export keeps a live filter for simple uniform sRGB sources and uses rendered shadow images for other working RGB profiles, source models and gradients. Low-level SVG filter output warns when this preparation is needed; proportional intermediate SVG filters are not misread as additive Darkness. Exact spot/custom-color and composite-source parity remain open, and resulting CMYK ink values follow the application color pipeline. CSS export leaves the shadow out and marks the object unsupported. When a `.ai`, EPS or PDF opens from its editing data, a Drop Shadow with Darkness in an object's art style is read as one with Color is, with the shadow's Darkness percentage (100% when the style gives none). Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 428 (PDF page 434). +- **Stylize effects in `.ai` and EPS editing data:** an object whose art style holds Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble opens with those effects live, in their order, with their saved settings. A key the reader does not know, a missing or out-of-range setting, or a Scribble with a color of its own keeps the object's drawn look. + - **Live objects after document changes:** a blend, envelope or repeat, with or without an effect of its own, is evaluated again when one of these changes: the tiling of a pattern whose tiles an envelope bends (Distort Pattern Fills), a symbol shown inside a symbol, a pattern or an opacity mask, the fonts of its type, a placed document's file once the file is read, and the color settings. A gradient mesh, with or without an effect of its own, is colored again when the color settings change. - **Blend, mesh and envelope points by number:** `object.blend.spine.moveAnchor`, `reshapeSegment` and `removeAnchor`, `object.mesh.setPointColor`, `movePoint` and `deletePoint`, and `object.envelope.setMeshPoint` refuse an `anchor`, `segment` or `index` that is not a whole number, and `object.envelope.setMeshPoint` refuses a negative `index`. Specified Steps (`object.blend.make`, `object.blend.options`) and the rows and columns of `object.mesh.create`, `object.envelope.makeWithMesh` and `resetWithMesh` must be whole numbers too. From e130cf3e0c247b3e4c29bdccb4d18b7e070aed7e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:11:47 +0700 Subject: [PATCH 081/674] .ai import: Convert to Shape opens live on paths and type Squashed from #5142 onto main. --- crates/engine/tests/import_fuzz.rs | 56 ++++++++++ crates/eps/src/import/ai/style.rs | 74 ++++++++++++- crates/eps/src/import/ai/style/tests.rs | 136 ++++++++++++++++++++++++ crates/eps/src/import/ai/tests.rs | 39 +++++++ crates/eps/src/import/tests_native.rs | 38 +++++++ docs/file-format-parity.md | 1 + docs/target-app-parity.md | 1 + 7 files changed, 341 insertions(+), 4 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index d24f69d00f..ea03a6bfc8 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3439,6 +3439,18 @@ fn arb_ai_token() -> impl Strategy { "/Def ;", "/Execution ;", "[5 5] 1e308 d", + "(Adobe Shape Effects) 1 0 /Filter ,", + "0 /Visible ,", + "(Rectangle) /UnicodeString (DisplayString) ,", + "2 /Int (Shape) ,", + "1e999 /Int (Shape) ,", + "1 /Real (Absolute) ,", + "-1e308 /Real (RelWidth) ,", + "1e5 /Real (RelHeight) ,", + "NaN /Real (AbsWidth) ,", + "0 /Real (AbsHeight) ,", + "-9 /Real (CornerRadius) ,", + "1 /Bool (Absolute) ,", "-0.5 /Real ,", "1.5 /Real ,", "-2 /Real ,", @@ -3470,6 +3482,50 @@ fn deflated(data: &[u8]) -> Vec { proptest! { #![proptest_config(config())] + /// Art styles with Convert to Shape whose dictionary holds any of its entries, and unknown ones, + /// as any kind, with any value (huge, tiny, not a number, a string), repeated or left out, shown + /// or hidden, on a path, a group and type, on the whole object or on its fill. + #[test] + fn ai_convert_to_shape_never_panics( + entries in prop::collection::vec(( + prop::sample::select(vec![ + "Shape", "Absolute", "AbsWidth", "AbsHeight", "RelWidth", "RelHeight", "CornerRadius", "DisplayString", "futureKey", + ]), + prop::sample::select(vec!["Int", "Real", "Bool", "UnicodeString", "String"]), + prop_oneof![ + (-1e4f64..1e4).prop_map(|v| v.to_string()), + prop::sample::select(vec!["0", "1", "2", "3", "-1", "0.5", "1e-300", "1e308", "-1e308", "1e999", "NaN", "(x)", ""]).prop_map(str::to_string), + ], + ), 0..16), + visible in any::(), + on_fill in any::(), + ) { + use vectorcraft_testkit::ai; + let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); + let basic = |name: &str, body: &str| format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n"); + let compound = |name: &str, kids: &[String]| format!("/CompoundFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat()); + let fill = basic("Fill Style Filter", "/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n"); + let effect = basic("Adobe Shape Effects", &keys).replacen("1 /Visible", if visible { "1 /Visible" } else { "0 /Visible" }, 1); + let bare = compound("Chain Style Filter", &[effect.clone(), basic("Conduit Filter", "")]); + let root = if on_fill { + compound("Chain Style Filter", &[compound("Stack Style Filter", &[compound("Chain Style Filter", &[fill, effect]), basic("Conduit Filter", "")])]) + } else { + compound("Chain Style Filter", &[effect, compound("Stack Style Filter", &[fill, basic("Conduit Filter", "")])]) + }; + let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}/KnownStyle :\n(Bare) /Name ,\n/ActiveStyle :\n{bare}%AI9_EndArtStyles\n"); + let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_"); + let art = format!( + "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\n0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_0 Ae\n%_u\n%_{hidden}f\n%_U\n1 (Bare) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n", + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(100.0, 20.0, 180.0, 60.0) + ); + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); + survive("Convert to Shape art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("Convert to Shape art style in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + /// Hostile editing data in Illustrator EPS and `.ai` files: operators in any order with any /// operands, sections and dictionaries left open, images of any size. #[test] diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 20950c9657..3da062f8dd 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -59,6 +59,7 @@ const OFFSET: &str = "Adobe Offset Path"; // brand-ok: the filter's name in the const TRANSFORM: &str = "Adobe Transform"; // brand-ok: the filter's name in the files const GAUSSIAN: &str = "Adobe PSL Gaussian Blur"; // brand-ok: the filter's name in the files const BAS_RELIEF: &str = "PSAdapter_plugin_BsRl"; +const SHAPE_EFFECTS: &str = "Adobe Shape Effects"; // brand-ok: the filter's name in the files const CHAIN: &str = "Chain Style Filter"; const STACK: &str = "Stack Style Filter"; @@ -99,7 +100,7 @@ pub(super) struct ArtStyle { pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, - /// Feather, Round Corners and Scribble on the object: what any object is read with. Type takes the other plain styles too (its drawn look + /// Feather, Round Corners, Scribble and Convert to Shape on the object: what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, /// Its fills and strokes, bottom first. @@ -326,6 +327,11 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { Tok::Word(w) => { let entry = other_entry.take().flatten(); let op = std::str::from_utf8(w).unwrap_or_default(); + if op == "," + && let (Some(key), Some(f)) = (entry, filters.last_mut()) + { + f.kinds.insert(key, Kind::Other); + } if op == "[" { array = Some(vec![]); continue; @@ -609,6 +615,55 @@ fn stylize(f: &Filter) -> Option> { }) } +/// The largest size or radius Convert to Shape reads, in points. +const MAX_SHAPE_SIZE: f64 = 1e5; + +/// Convert to Shape: Rectangle, Rounded Rectangle or Ellipse, with an absolute size or one relative +/// to the object, and a corner radius +/// (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). +/// The keys are LiveEffect XML's: `Shape` 0 Rectangle, 1 Rounded Rectangle, 2 Ellipse +/// (https://community.adobe.com/questions-652/effect-convert-to-shape-ellipse-in-javascript-761645), +/// `Absolute` 1 for an absolute `AbsWidth` × `AbsHeight`, else `RelWidth` and `RelHeight` added to +/// each side, and `CornerRadius`; a missing size is 18 pt a side or 36 pt, and a missing radius +/// 9 pt. `None`: a key, a kind or a value that isn't read, which keeps the drawn look. +fn shape_effect(f: &Filter) -> Option { + const SIZES: [&str; 5] = ["AbsWidth", "AbsHeight", "RelWidth", "RelHeight", "CornerRadius"]; + let known = f.kinds.iter().all(|(key, kind)| match key.as_str() { + "DisplayString" => *kind == Kind::Other, + "Shape" => *kind == Kind::Int, + key => (key == "Absolute" || SIZES.contains(&key)) && *kind == Kind::Real, + }); + if !known || !f.arrays.is_empty() || f.fill.is_some() || f.stroke.is_some() || f.gradient || f.pattern.is_some() { + return None; + } + // A written size is a finite number from `min`; a missing one is `default`. + let size = |key: &str, min: f64, default: f64| match f.kinds.get(key) { + None => Some(default), + Some(_) => f.params.get(key).copied().filter(|v| v.is_finite() && (min..=MAX_SHAPE_SIZE).contains(v)), + }; + let shape = f.params.get("Shape").copied().filter(|_| f.kinds.get("Shape") == Some(&Kind::Int))?; + let absolute = match f.params.get("Absolute").copied() { + Some(0.0) => false, + Some(1.0) => true, + _ => return None, + }; + let (rel_w, rel_h) = (size("RelWidth", -MAX_SHAPE_SIZE, 18.0)?, size("RelHeight", -MAX_SHAPE_SIZE, 18.0)?); + let (abs_w, abs_h, radius) = (size("AbsWidth", 0.0, 36.0)?, size("AbsHeight", 0.0, 36.0)?, size("CornerRadius", 0.0, 9.0)?); + let id = match shape { + 0.0 => "convertToShape.rectangle", + 1.0 => "convertToShape.roundedRectangle", + // A relative Ellipse in the file is drawn round the enlarged box, and VectorCraft's inside + // it: it keeps its drawn look. + 2.0 if absolute => "convertToShape.ellipse", + _ => return None, + }; + let mut params = json!({"relative": !absolute, "extraW": 2.0 * rel_w, "extraH": 2.0 * rel_h, "width": abs_w, "height": abs_h}); + if id == "convertToShape.roundedRectangle" { + params["radius"] = json!(radius); + } + Some(Effect { id: id.into(), params, visible: f.visible }) +} + /// The live effect filter `f` is, when it is one read here. fn effect(f: &Filter) -> Option { if let Some(stylized) = stylize(f) { @@ -662,6 +717,7 @@ fn effect(f: &Filter) -> Option { GAUSSIAN => ("blur.gaussian", json!({"radius": param("blur").unwrap_or(5.0).clamp(0.0, 1000.0)})), // Its settings are in a Photoshop plug-in's binary block: the effect's defaults stand in. BAS_RELIEF => ("sketch.basRelief", json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"})), + SHAPE_EFFECTS => return shape_effect(f), _ => return None, }; Some(Effect { id: id.into(), params, visible: f.visible }) @@ -748,9 +804,11 @@ impl Builder<'_> { (look.blend, look.opacity) = (super::read::blend_mode(mode), opacity); } } + // Convert to Shape on one fill or stroke isn't read yet: what it draws there is + // the drawn look's. _ => match effect(c) { - Some(e) => look.effects.push(e), - None => self.plain = false, + Some(e) if !e.id.starts_with("convertToShape.") => look.effects.push(e), + _ => self.plain = false, }, } } @@ -817,7 +875,15 @@ fn style(filters: &[Filter]) -> ArtStyle { && st.effects.iter().all(|e| { matches!( e.id.as_str(), - "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "stylize.roundCorners" | "stylize.scribble" + "stylize.dropShadow" + | "stylize.innerGlow" + | "stylize.outerGlow" + | "stylize.feather" + | "stylize.roundCorners" + | "stylize.scribble" + | "convertToShape.rectangle" + | "convertToShape.roundedRectangle" + | "convertToShape.ellipse" ) }); st diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 9ba5838f39..c08c496763 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -469,3 +469,139 @@ fn a_hidden_fill_comes_in_hidden() { assert!(st.plain, "{st:?}"); assert_eq!(st.looks.iter().map(|l| l.visible).collect::>(), [false, true]); } + +/// A Convert to Shape filter whose dictionary holds `keys`. +fn shape(keys: &str) -> String { + basic("Adobe Shape Effects", &format!("(Shape) /UnicodeString (DisplayString) ,\n{keys}")) +} + +/// The style `Boxed`: a fill and a stroke, and `effects` on the whole object after them. +fn shape_style(effects: &[String]) -> ArtStyle { + let stack = compound( + "Stack Style Filter", + &[ + basic("Stroke Style Filter", "/StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n"), + fill("0 0 0 0 1 1 1 Xa"), + ], + ); + let mut kids = vec![stack]; + kids.extend_from_slice(effects); + let data = format!("/KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &kids)); + art_styles(data.as_bytes()).remove("Boxed").unwrap_or_default() +} + +/// Every setting of a Relative or Absolute size, with a corner radius. +const SIZES: &str = "150 /Real (AbsWidth) ,\n40 /Real (AbsHeight) ,\n20 /Real (RelWidth) ,\n6 /Real (RelHeight) ,\n15 /Real (CornerRadius) ,\n"; + +#[test] +fn convert_to_shape_comes_in_live_with_its_settings() { + // GUARDS: `Adobe Shape Effects` wasn't read, so an object with it kept its drawn look. + for (keys, id, want) in [ + ( + format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + ( + format!("1 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.roundedRectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0, "radius": 15.0}), + ), + ( + format!("2 /Int (Shape) ,\n1 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.ellipse", + json!({"relative": false, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + ( + format!("0 /Int (Shape) ,\n1 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.rectangle", + json!({"relative": false, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + // A relative size alone, and one that shrinks the shape: each is added to every side. + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n20 /Real (RelWidth) ,\n6 /Real (RelHeight) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 36.0, "height": 36.0}), + ), + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n-10 /Real (RelWidth) ,\n-4 /Real (RelHeight) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": -20.0, "extraH": -8.0, "width": 36.0, "height": 36.0}), + ), + // Missing sizes: 18 pt a side, 36 pt, and a 9 pt radius. + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n20 /Real (RelWidth) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 36.0, "width": 36.0, "height": 36.0}), + ), + ( + "1 /Int (Shape) ,\n1 /Real (Absolute) ,\n".to_string(), + "convertToShape.roundedRectangle", + json!({"relative": false, "extraW": 36.0, "extraH": 36.0, "width": 36.0, "height": 36.0, "radius": 9.0}), + ), + ] { + let st = shape_style(&[shape(&keys)]); + assert!(st.plain && st.simple, "{keys}: {st:?}"); + let [e] = st.effects.as_slice() else { panic!("{keys}: {:?}", st.effects) }; + assert_eq!((e.id.as_str(), &e.params, e.visible), (id, &want, true), "{keys}"); + assert_eq!(st.items.len(), 2, "{keys}"); + } +} + +#[test] +fn convert_to_shape_keeps_its_place_among_effects_and_its_visibility() { + let offset = basic("Adobe Offset Path", "2 /Int (jntp) ,\n4 /Real (mlim) ,\n4 /Real (ofst) ,\n"); + let st = shape_style(&[shape(&format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}")), offset.clone()]); + assert!(st.plain, "{st:?}"); + let ids: Vec<_> = st.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["convertToShape.rectangle", "path.offsetPath"]); + // Offset Path isn't read on objects other than type yet. + assert!(!st.simple); + // A hidden one stays, hidden, with its settings. + let hidden = shape(&format!("1 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}")).replacen("1 /Visible", "0 /Visible", 1); + let st = shape_style(&[hidden]); + assert!(st.plain && st.simple, "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{:?}", st.effects) }; + assert_eq!( + (e.id.as_str(), e.visible, &e.params["radius"], &e.params["extraW"]), + ("convertToShape.roundedRectangle", false, &json!(15.0), &json!(40.0)) + ); +} + +#[test] +fn convert_to_shape_settings_that_arent_read_keep_the_drawn_look() { + let valid = format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"); + assert!(shape_style(&[shape(&valid)]).plain); + for keys in [ + // Another shape, a shape that isn't a whole number or an /Int, and a missing one. + valid.replace("0 /Int (Shape)", "3 /Int (Shape)"), + valid.replace("0 /Int (Shape)", "0.5 /Int (Shape)"), + valid.replace("0 /Int (Shape)", "0 /Real (Shape)"), + valid.replace("0 /Int (Shape) ,\n", ""), + // A mode other than 0 and 1, or a missing one. + valid.replace("0 /Real (Absolute)", "2 /Real (Absolute)"), + valid.replace("0 /Real (Absolute) ,\n", ""), + valid.replace("0 /Real (Absolute)", "0 /Int (Absolute)"), + // Sizes that aren't finite numbers, negative absolute sizes and radii, and huge ones. + valid.replace("20 /Real (RelWidth)", "NaN /Real (RelWidth)"), + valid.replace("6 /Real (RelHeight)", "1e999 /Real (RelHeight)"), + valid.replace("6 /Real (RelHeight)", "(x) /Real (RelHeight)"), + valid.replace("150 /Real (AbsWidth)", "-150 /Real (AbsWidth)"), + valid.replace("15 /Real (CornerRadius)", "-1 /Real (CornerRadius)"), + valid.replace("20 /Real (RelWidth)", "1e6 /Real (RelWidth)"), + valid.replace("40 /Real (AbsHeight)", "40 /Int (AbsHeight)"), + // A key that isn't read. + format!("{valid}1 /Real (Future) ,\n"), + format!("{valid}(x) /String (Future) ,\n"), + // A relative Ellipse. + valid.replace("0 /Int (Shape)", "2 /Int (Shape)"), + ] { + let st = shape_style(&[shape(&keys)]); + assert!(!st.plain, "{keys}: {st:?}"); + } + // On one fill: the drawn look, for type too. + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), shape(&valid)]); + let data = + format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + assert!(!art_styles(data.as_bytes())["Odd"].plain); +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 05f33e6a3e..a11e89139e 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2128,6 +2128,45 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +#[test] +fn an_object_with_convert_to_shape_comes_in_as_itself_with_the_effect_live() { + // GUARDS: `Adobe Shape Effects` wasn't read, so the object came in as its drawn look. + let styles = |keys: &str| { + format!( + "%AI9_BeginArtStyles\n\ + /KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Shape Effects) 1 0 /Filter ,\n1 /Visible ,\n(ShapeEffect.aip) /PluginFileName ,\n(Shape) /Title ,\n\ + /Dictionary : /NotRecorded ,\n(Rectangle) /UnicodeString (DisplayString) ,\n{keys}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n" + ) + }; + let hidden_rect = rect_path(20.0, 20.0, 90.0, 60.0).replace('\n', "\n%_"); + // The drawn look is the shape: 20 pt wider on each side and 6 pt taller. + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Boxed) XW\n", rect_path(0.0, 14.0, 110.0, 66.0)); + let keys = "0 /Int (Shape) ,\n150 /Real (AbsWidth) ,\n0 /Real (Absolute) ,\n40 /Real (AbsHeight) ,\n20 /Real (RelWidth) ,\n15 /Real (CornerRadius) ,\n6 /Real (RelHeight) ,\n"; + let r = read_ok(&format!("{}{}", styles(keys), layer(&art_))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}"); + let b = a[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (70.0, 40.0), "the object keeps its own path"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance.effects) }; + assert_eq!( + (e.id.as_str(), e.params["relative"].as_bool(), e.params["extraW"].as_f64(), e.params["extraH"].as_f64()), + ("convertToShape.rectangle", Some(true), Some(40.0), Some(12.0)) + ); + // A shape that isn't read: the drawn look. + let r = read_ok(&format!("{}{}", styles(&keys.replace("0 /Int (Shape)", "7 /Int (Shape)")), layer(&art_))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 94127e8cfd..49c1f1f61c 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2956,6 +2956,44 @@ fn type_with_a_stacked_art_style_comes_in_as_type_with_that_appearance() { check(&r.document, &r.warnings); } +#[test] +fn type_with_convert_to_shape_comes_in_as_type_with_it_live() { + // GUARDS: `Adobe Shape Effects` wasn't read, and type with it came in without its art style, + // the style's drawing beside it as paths. + let shape = "/BasicFilter :\n(Adobe Shape Effects) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + (RoundedRectangle) /UnicodeString (DisplayString) ,\n1 /Int (Shape) ,\n0 /Real (Absolute) ,\n4 /Real (RelWidth) ,\n\ + 2 /Real (RelHeight) ,\n3 /Real (CornerRadius) ,\n; /Dict ;\n /Part ,\n"; + let stack = "/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n"; + let styles = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + {shape}{stack};\n /Part ,\n%AI9_EndArtStyles\n" + ); + let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf"; + let look = format!("u\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{drawing}\nU\n9 () XW\n"); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let art = native_with_text(&(styles + &layer("Art", true, &format!("{look}{own}1 (Boxed) XW\n"))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let (mut texts, mut paths) = (vec![], 0); + d.walk(|n| match &n.kind { + NodeKind::Text(t) => texts.push((t.plain_text(), n.appearance.effects.clone())), + NodeKind::Path { .. } => paths += 1, + _ => {} + }); + let [(text, effects)] = texts.as_slice() else { panic!("{texts:?} {notes:?}") }; + assert_eq!((text.as_str(), paths), ("Bang", 0), "{notes:?}"); + let [e] = effects.as_slice() else { panic!("{effects:?}") }; + assert_eq!( + (e.id.as_str(), &e.params), + ( + "convertToShape.roundedRectangle", + &serde_json::json!({"relative": true, "extraW": 8.0, "extraH": 4.0, "width": 36.0, "height": 36.0, "radius": 3.0}) + ) + ); +} + #[test] fn point_type_without_a_matrix_is_placed_by_its_layout() { // GUARDS: Illustrator 24 leaves an unturned, unscaled point type's matrix out of its frame; such diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2c7fc01094..6371aea8f1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -92,6 +92,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow or Convert to Shape comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 326a9cc951..02504f89f9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1076,6 +1076,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From 54b79c02b059a087332d5937cc77199c598bb3a1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:27:45 +0700 Subject: [PATCH 082/674] .ai import: Convert to Shape records string entries through the shared dictionary parser --- crates/eps/src/import/ai/style.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 3da062f8dd..c2b305bdcb 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -327,11 +327,6 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { Tok::Word(w) => { let entry = other_entry.take().flatten(); let op = std::str::from_utf8(w).unwrap_or_default(); - if op == "," - && let (Some(key), Some(f)) = (entry, filters.last_mut()) - { - f.kinds.insert(key, Kind::Other); - } if op == "[" { array = Some(vec![]); continue; From 6bf2941f28f25a398cd211257a0f2c1f2b04a6da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:28:39 -0700 Subject: [PATCH 083/674] Docs: .ai guides are no longer listed as lost #5057 opens ruler guides and guide objects from a .ai's editing data and closed #779. The File formats row of docs/target-app-parity.md, the known failures in docs/file-format-parity.md, G9 in docs/gaps.md and docs/roadmap.md still listed guides as lost. --- docs/file-format-parity.md | 4 ++++ docs/gaps.md | 3 +-- docs/roadmap.md | 4 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6371aea8f1..0e11ca08f6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -78,6 +78,10 @@ private editing data. VectorCraft: (gradients filled with their first stop's colour, type left to the apps that read the format). VectorCraft opens a file with that prolog from its program, as the format. - **Known failures in users' files:** layer structure flattened or multiplied (#951: 109 layers instead of + 14; #868: round trip with Illustrator 2018 loses layers and groups), some files 4× slower to open since the + editing data is read whole (#758), live effects, brushes and symbols come in as their drawn look (#637; + pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type + (`To` … `TO`) since #868; guides open as ruler guides and guide paths since #5057 (#779). 14; #868: round trip with Illustrator 2018 loses layers and groups), guides and non-printing construction lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects that are not read or have settings that are not read, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` diff --git a/docs/gaps.md b/docs/gaps.md index 5c04e87040..1abcecc5bd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -160,8 +160,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done (2026-10-16):** EPS legacy mesh corners and vector opacity masks retained; winding-declared compound member groups keep shared paint. Raster print-page minification no longer causes a false editing-data fallback; comparison limits remain unchanged. Synthetic regressions cover damage and missing artwork. This narrows G9; scores and estimates unchanged. - **Missing:** faithful layer and group structure from the editing data in real files (#951: 109 layers instead - of 14), guides and non-printing construction - lines (#779), open speed on large files (#758), live effects, brushes and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope + of 14), open speed on large files (#758), live effects, brushes and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope (undocumented): a PDF-compatible `.ai` opens in Illustrator 2018 without its layers and groups (#868). Save As `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification instead, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and diff --git a/docs/roadmap.md b/docs/roadmap.md index 979eb11214..abfaea70ba 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -58,13 +58,13 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | Set type: point and area type, Character and Paragraph styles, threading, outlines | yes | type core 80%; styles, threading, Create Outlines and font matching tested ([type-parity.md](type-parity.md)); justification options missing (not blocking) | 0 | | Organise layers and artboards and export assets (Export for Screens, SVG, PNG, PDF per artboard) | yes | Layers panel rework, Artboards panel and tool, Export for Screens and Asset Export done; Art Optimized supersample closes ghost borders (#983 / #1037) | 0 | | Print production: CMYK and spot colour, bleed and marks, PDF/X out, separations preview | yes | PDF/X-1a/3/4, presets, marks and bleed, ICC output intent, Separations Preview, Print with PostScript output | 0 | -| Exchange files with Illustrator users: open their `.ai`/EPS/PDF, hand back a file they can open | partial (doesn't block alpha) | `.ai`, EPS and PDF open as editable art, but real files can get the wrong layer structure (#951) and lose guides (#779); Save As `.ai` is PDF-compatible, which Illustrator opens without its own editing data (#868), or legacy version 7, which keeps layers, groups and type as text, one artboard per file, and waits for users' testing. EPS legacy mesh corners, vector opacity masks and raster print-page comparison now preserve editable art under synthetic regressions. This is the beta main-format gap ([gaps.md](gaps.md) G9) | 10–20 (for beta) | +| Exchange files with Illustrator users: open their `.ai`/EPS/PDF, hand back a file they can open | partial (doesn't block alpha) | `.ai`, EPS and PDF open as editable art, but real files can get the wrong layer structure (#951); Save As `.ai` is PDF-compatible, which Illustrator opens without its own editing data (#868), or legacy version 7, which keeps layers, groups and type as text, one artboard per file, and waits for users' testing. EPS legacy mesh corners, vector opacity masks and raster print-page comparison now preserve editable art under synthetic regressions. This is the beta main-format gap ([gaps.md](gaps.md) G9) | 10–20 (for beta) | ## Current focus 1. **Interaction-fidelity pass** (G1) by tool, from [ui-parity.md](ui-parity.md): Pen and Curvature, Direct Selection, smart guides and snapping first. 60–90 h, parallel by tool. -2. **`.ai` files from real users** (G9): layer structure (#951), guides (#779). 10–20 h. +2. **`.ai` files from real users** (G9): layer structure (#951). 10–20 h. 3. **Launch and stability** (G10): the Windows and Linux start-up reports. 20–35 h. 4. **Core-tool bugs** (G11): SVG units reverting to points (#864) and a Transform effect in a fill's or stroke's own effects (#885). Shape Builder regions (#937), Asset Export ghost borders (#983 / #1037) and the stalling bezier drag preview (#834) are fixed. 8–15 h. 5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 02504f89f9..73f40007b5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -145,7 +145,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | From afeb4a85746bdf5f77f6d111a26d01bcb87b938a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 00:42:13 -0700 Subject: [PATCH 084/674] Docs: the .ai issue counts in G9 and the file-exchange discount are dated Both passages still name guides among the open .ai issues. They now say the counts were measured on 2026-10-10, before #779 closed. --- docs/gaps.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 1abcecc5bd..2bef5bff57 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -169,7 +169,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall omitted, hidden objects go to a hidden layer, are omitted or made visible), and type is set again in the reader's fonts. Legacy type in `.ai` files in PostScript form is read on open. It waits for testing by users who hand files back. -- **Evidence:** the issues above; 28 of the 350 issues are about `.ai`/EPS (about 22 people, the most common single +- **Evidence:** the issues above; 28 of the 350 issues measured on 2026-10-10 are about `.ai`/EPS (about 22 people, the most common single format theme), 20 fixed, and the 8 open ones are about structure (layers, guides, speed, live objects), not missing art. No real-file `.ai` corpus (users' files may be used locally, never committed). - **Impact:** blocks anyone who hands files back to Illustrator users. Opening and reworking their own archive diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 73f40007b5..2df8531f84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -221,7 +221,7 @@ generative AI, pen tilt, languages beyond their own) are left out. **Essentials: The discounts, with the evidence: - **Illustrator's own files (×0.92).** `.ai` and EPS open as editable art by reading their PDF/PostScript and the - structure of the editing data. Users do open legacy files a lot: 28 of the 350 issues (8%, ~22 people) are + structure of the editing data. Users do open legacy files a lot: 28 of the 350 issues measured on 2026-10-10 (8%, ~22 people) are about `.ai`/EPS, the most common single format theme. 20 of the 28 are fixed (often the same day). The 8 open ones are about structure, not missing art: layers flattened or multiplied (#951: 109 layers instead of 14; #868), guides lost (#779), slower opening (#758), live effects, brushes and symbols as their drawn look From 9596130be49340c0faaf99ffad5e2587e70c85c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:46:41 -0700 Subject: [PATCH 085/674] .ai import: Objects on Path records measure each group once Each Objects on Path record measured the bounds of every object it names, and checked its path, before it was turned down. A thousand copies of a record whose object is a group of 20,000 paths took 5.6 s to open instead of about 50 ms. A record now checks its group and ids first, and the path and objects of a group are measured for one record at most. --- crates/eps/src/import/ai/read/on_path.rs | 34 +++++++++++------ crates/eps/src/import/ai/tests.rs | 48 ++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 11 deletions(-) diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs index 909d611315..4fe14e8545 100644 --- a/crates/eps/src/import/ai/read/on_path.rs +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -131,13 +131,15 @@ pub(super) fn apply(doc: &mut Document, found: &OnPath) { // Where every object with an id is, found in one walk of the tree (setting a record doesn't // move anything). let at = doc.index_paths(found.tags.keys().copied()); + // The groups whose path and objects have been measured. + let mut tried = HashSet::new(); for r in &found.records { // A record that doesn't match leaves the group as it was read. - let _ = apply_one(doc, found, &at, r); + let _ = apply_one(doc, found, &at, &mut tried, r); } } -fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap>, r: &Record) -> Option<()> { +fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap>, tried: &mut HashSet, r: &Record) -> Option<()> { // The one object still in the document with the id `uuid` (a commented copy may have gone). let resolve = |uuid: &str| -> Option<(NodeId, &Vec)> { let mut live = found.ids.get(uuid)?.iter().filter_map(|id| at.get(id).map(|p| (*id, p))); @@ -150,26 +152,36 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap return None; } let (_, group_at) = path_at.split_last()?; + let g = doc.node_at(group_at)?; + let NodeKind::Group { children, clip: false } = &g.kind else { return None }; + if g.extras().objects_on_path.is_some() || children.len() != r.ids.len() { + return None; + } let mut seen = HashSet::from([path]); - let mut members = Vec::with_capacity(rest.len()); + let mut placed = Vec::with_capacity(rest.len()); for (i, uuid) in rest.iter().enumerate() { let (id, place) = resolve(uuid)?; let tag = found.tags.get(&id)?; if !seen.insert(id) || place.split_last().map(|(_, up)| up) != Some(group_at) || tag.key_path || tag.order != Some(i as f64) { return None; } - // The frame the object is drawn in: turned by its angle (the document's y points down) - // about the center of its bounds. - let angle = -tag.angle?; - let center = doc.node_at(place)?.geometric_bounds()?.center(); - members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); + placed.push((id, place, -tag.angle?)); } - let g = doc.node_at(group_at)?; - let NodeKind::Group { children, clip: false } = &g.kind else { return None }; - if g.extras().objects_on_path.is_some() || children.len() != seen.len() || children.iter().any(|c| !seen.contains(&c.id)) { + if children.iter().any(|c| !seen.contains(&c.id)) { + return None; + } + // What is left depends on the group's objects alone, so each group is measured once. + if !tried.insert(g.id) { return None; } attachable_path(children.iter().find(|c| c.id == path)?)?; + let mut members = Vec::with_capacity(placed.len()); + for (id, place, angle) in placed { + // The frame the object is drawn in: turned by its angle (the document's y points down) + // about the center of its bounds. + let center = doc.node_at(place)?.geometric_bounds()?.center(); + members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); + } let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate }; doc.node_mut_at(group_at)?.extras_mut().objects_on_path = Some(Box::new(on_path)); Some(()) diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index a11e89139e..9ef13e271b 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3400,3 +3400,51 @@ fn an_objects_on_path_group_in_versioned_content_opens_once() { assert_eq!(kids[0].children().unwrap().len(), 5); assert!(kids[0].extras().objects_on_path.is_some()); } + +/// The path and objects of a group are measured once however many records name it: a thousand +/// copies of a record open about as fast as one copy followed by 999 records whose path id is +/// missing, when the group opens live, when its long path has no length, and when its first object +/// is a group of many paths and its last object has no bounds. +#[test] +fn repeated_objects_on_path_records_dont_measure_the_objects_again() { + use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record}; + let paths: String = (0..20_000).map(|i| format!("{}f\n", rect_path(f64::from(i % 200), 40.0, f64::from(i % 200) + 1.0, 46.0))).collect(); + let big = format!("u\n{RED}{paths}U\n{}", on_path_member(ON_PATH_IDS[1], Some(0), 0.0)); + let empty = format!("u\nU\n{}", on_path_member(ON_PATH_IDS[2], Some(1), 0.0)); + let still = format!("20 20 m\n{}S\n", "20 20 L\n".repeat(20_000)); + let cases = [ + ("a live group", OPEN_PATH.to_string(), big.clone(), 2, true), + ("a path without length", still, big.clone(), 2, false), + ("an object without bounds", OPEN_PATH.to_string(), format!("{big}{empty}"), 3, false), + ]; + for (why, path, objects, n, live) in cases { + let ids = &ON_PATH_IDS[..n]; + let group = format!( + "0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n2 w\n{path}{}{objects}U\n", + on_path_member(ids[0], None, 0.0) + ); + let record = on_path_record(ALIGN_ON_PATH, ids, &on_path_options(n - 1, 4, 0.0, "")); + let (start, end) = (record.find("%_/Dictionary :\n%_1 /Int").unwrap(), record.find("%_; (Constraint Data)").unwrap()); + let copy = &record[start..end]; + let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000"); + let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]); + let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]); + let time = |data: &str| { + let started = std::time::Instant::now(); + let doc = read_ok(&format!("{data}{}", layer(&group))).doc; + let elapsed = started.elapsed(); + let g = art(&doc)[0].clone(); + assert_eq!(g.children().unwrap().len(), n, "{why}"); + assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}"); + elapsed + }; + // The fastest of three runs each, taken in turn, so that other tests running at the same + // time weigh on both. + let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX); + for _ in 0..3 { + fastest_one = fastest_one.min(time(&one)); + fastest_many = fastest_many.min(time(&many)); + } + assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}"); + } +} From cbd4dd5599df01aa859a934053e352a6bbea9410 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:57:10 -0700 Subject: [PATCH 086/674] Docs: list every case where an unread .ai object still sends the file to its page The file-format and progress docs named three of the cases in which an unread object's page art is not used and the file comes in as its page. The import also does this when the object lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, and when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's (`replace_unread` and `copy_page_resources` in `crates/eps/src/import/native/build.rs`). --- docs/file-format-parity.md | 1 + docs/target-app-parity.md | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0e11ca08f6..2a2ecbe9bf 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -96,6 +96,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow or Convert to Shape comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2df8531f84..2294563f63 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1074,6 +1074,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). When the editing data of a `.ai` or EPS is for a page of another size than the file's, the warning that its layers weren't read gives both sizes in points, and the scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion (#2034; `crates/eps/src/import/tests_native.rs`). A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From bb354fc92ad8f185d785ea5ae222e47309bbf33b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:54:32 -0700 Subject: [PATCH 087/674] .ai import: page art moved to its artboard takes its pattern tiles along Art taken from a `.ai`'s PDF part on a later page is moved to where the editing data puts that artboard. The move left pattern fills and strokes where they were, so their tiles no longer lined up with the art. This happened in three places: the page art that stands in for an unread object (#5050), the page's type given to text objects, and the art on each page when the file comes in as its PDF part with the artboard layout kept. Each move now transforms the pattern tiles too. --- crates/eps/src/import/native/build.rs | 8 +- crates/eps/src/import/native/layers.rs | 4 +- crates/eps/src/import/tests_native.rs | 104 +++++++++++++++++++++++++ 3 files changed, 112 insertions(+), 4 deletions(-) diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index bf0a8d4a5a..b4f8ee30c4 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -15,6 +15,10 @@ pub(super) enum Page { Artboard, } +/// How art moved from a page to its place in the layers' document transforms: its pattern tiles +/// move with it. +pub(super) const PAGE_MOVE: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: false, patterns: true }; + /// The page (`visible`, the file read as its page) and the place of its area in the layers' /// document. pub(super) struct Frame<'a> { @@ -177,7 +181,7 @@ pub(super) fn build_from( None => shift, }; for n in object.iter_mut() { - Arc::make_mut(n).transform(shift, false); + Arc::make_mut(n).transform(shift, PAGE_MOVE); } } // An EPS saved as its artboard has the art outside it left out of its page. @@ -681,7 +685,7 @@ fn replace_unread( for &i in &selected { let mut copy = Node::clone(&art[i].node); if let Some(shift) = moves.get(page) { - copy.transform(*shift, false); + copy.transform(*shift, PAGE_MOVE); } found.push(Arc::new(reid_page_art(doc, ©))); claimed.insert(i, art[i].end); diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 6be56c200d..c4e961c476 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{Page, build, build_from}; +use super::build::{PAGE_MOVE, Page, build, build_from}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -204,7 +204,7 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { let fit = |p: &Rect| (p.intersect(r).area().max(0.0), -(p.center() - r.center()).hypot()); let Some((i, _)) = pages.iter().map(fit).enumerate().max_by(|(_, a), (_, b)| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))) else { continue }; if let Some(v) = moves.get(i).filter(|v| **v != Vec2::ZERO) { - Arc::make_mut(child).transform(Affine::translate(*v), false); + Arc::make_mut(child).transform(Affine::translate(*v), PAGE_MOVE); } } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 49c1f1f61c..15b3e21caa 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -832,6 +832,43 @@ fn unread_object_on_second_artboard_takes_second_page_art() { assert_eq!(bounds, vectorcraft_geom::Rect::new(50.0, 196.0, 54.0, 200.0)); } +#[test] +fn page_art_from_second_artboard_moves_its_pattern_tile() { + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let second = "u\n0 0 1 0 k\n50 -100 m\n54 -100 L\n54 -96 L\n50 -96 L\nf\nZZ\nU"; + let art = native(&(boards.to_string() + dots + &layer("Live", true, &square(10, 10)) + &layer("Mixed", true, second))); + let (editing, _) = crate::ai_alone(&private(&native(&format!("{dots}{}", layer("Live", true, &square(10, 10)))))).unwrap(); + let source = editing.pattern("Dots").unwrap(); + let mut page = pdf_part(10.0, 86.0); + let mut pattern = source.clone(); + pattern.art = source.art.iter().map(|node| std::sync::Arc::new(page.reid(node))).collect(); + page.patterns.push(pattern); + let mut board = page.artboards[0].clone(); + (board.id, board.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + page.artboards.push(board); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(170.0, 46.0, 174.0, 50.0)); + let paint = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let node = Node::path(page.alloc_id(), path, appearance); + let layer = page.layers[0].id; + page.insert(Some(layer), 1, node).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + let replacement = &doc.layers[1].children().unwrap()[0].children().unwrap()[0]; + assert_eq!(replacement.visual_bounds().unwrap(), vectorcraft_geom::Rect::new(50.0, 196.0, 54.0, 200.0)); + let Some(vectorcraft_color::Paint::Pattern { xf, .. }) = replacement.appearance.fill().map(|f| &f.paint) else { + panic!("the page art's pattern fill is kept: {:?}", replacement.appearance); + }; + assert_eq!(*xf, vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(-120.0, 150.0))); +} + #[test] fn unknown_operator_between_objects_falls_back() { let body = format!("{}\nZZ\n{}", square(50, 10), square(70, 10)); @@ -1443,6 +1480,38 @@ fn an_ai_file_read_as_its_pdf_part_keeps_its_artboard_layout() { assert!((moved[1] - vectorcraft_geom::Point::new(100.0, 1600.0)).hypot() < 1e-6, "the second's art goes with its page: {moved:?}"); } +#[test] +fn art_moved_with_its_page_moves_its_pattern_tile() { + // Two 100-point artboards, the second 50 below the first; an operator this doesn't know, so + // the layers aren't read. + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let art = native(&(boards.to_string() + &layer("Art", true, &(square(10, 10) + "\n1 Zz")))); + // The PDF part: the second page 20 points right of the first, with a pattern-filled square. + let mut pdf = pdf_part(10.0, 10.0); + let mut page = pdf.artboards[0].clone(); + (page.id, page.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + pdf.artboards.push(page); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(130.0, 10.0, 134.0, 14.0)); + let paint = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let (id, layer_id) = (pdf.alloc_id(), pdf.layers[0].id); + pdf.insert(Some(layer_id), 1, Node::path(id, path, appearance)).unwrap(); + let (d, w, read) = crate::layered_ai(&private(&art), pdf, vec![], false, false, 1.0); + assert!(!read, "{w:?}"); + let square = &d.layers[0].children().unwrap()[1]; + assert_eq!(square.visual_bounds().unwrap().origin(), vectorcraft_geom::Point::new(10.0, 160.0)); + let Some(vectorcraft_color::Paint::Pattern { xf, .. }) = square.appearance.fill().map(|f| &f.paint) else { + panic!("the square keeps its pattern fill: {:?}", square.appearance); + }; + assert_eq!(*xf, vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(-120.0, 150.0))); +} + #[test] fn a_gray_is_a_grayscale_colour() { // `g` is a gray: 0.25 is 75 % of the black ink, as the page's own CMYK black says; the colour @@ -2126,6 +2195,41 @@ fn type_on_a_later_artboard_of_an_ai_file_goes_to_its_text_object() { assert!(!w.iter().any(|w| w.contains("with another's") || w.contains("doesn't draw")), "{w:?}"); } +#[test] +fn page_type_on_a_later_artboard_moves_its_pattern_tile() { + // As above, with a frame this doesn't read, so the text object takes the page's type, which + // has a pattern fill. + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let doc = last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8341.5), (0.0, 0.0), 0.0)])); + let art = native_with_text(&(boards.to_string() + &layer("Art", true, &(square(10, 10) + &text_object(0)))), &doc); + let mut pdf = pdf_part(10.0, 86.0); + let mut page = pdf.artboards[0].clone(); + (page.id, page.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + pdf.artboards.push(page); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(178.5, 50.0), "Hi there", style); + let (id, layer_id) = (pdf.alloc_id(), pdf.layers[0].id); + let mut node = Node::new(id, NodeKind::Text(Box::new(text))); + let paint = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + node.appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + } + .into(); + pdf.insert(Some(layer_id), 1, node).unwrap(); + let (d, w, read) = crate::layered_ai(&private(&art), pdf, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + let texts: Vec<&Node> = d.layers[0].children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| &**n).collect(); + assert_eq!(texts.len(), 1, "{w:?}"); + let Some(vectorcraft_color::Paint::Pattern { xf, .. }) = texts[0].appearance.fill().map(|f| &f.paint) else { + panic!("the page's type keeps its pattern fill: {:?}", texts[0].appearance); + }; + assert_eq!(*xf, vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(-120.0, 150.0))); +} + /// A global process colour (`Xk`) or a pattern fill on a sublayer no longer sends a `.ai` to its /// PDF part, which has only the top-level layers (#1025). #[test] From ecd184510c32dc8dbac4996eaefb107268553543 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 19:07:17 -0700 Subject: [PATCH 088/674] Place: Word .doc styles are resolved once and damaged property tables are refused Each style's formatting is now worked out once, on top of the style it is based on, and each property run's formatting once, so a document with many hidden paragraphs or long style chains no longer resolves the chains again for every paragraph and run. Character styles are applied as a change to the paragraph's formatting. A bin table whose file positions do not rise, a property page listed twice, pages whose runs overlap, and styles based on each other in a loop are refused as damaged, as MS-DOC requires (PlcBteChpx, ChpxFkp, StdfBase). Property runs refer to their page instead of copying it. --- crates/engine/src/cmd/place/doc.rs | 324 ++++++++++++++++++++------ crates/engine/src/tests/textimport.rs | 66 +++++- docs/mcp.md | 5 +- 3 files changed, 314 insertions(+), 81 deletions(-) diff --git a/crates/engine/src/cmd/place/doc.rs b/crates/engine/src/cmd/place/doc.rs index 41f269c502..f46634b077 100644 --- a/crates/engine/src/cmd/place/doc.rs +++ b/crates/engine/src/cmd/place/doc.rs @@ -39,7 +39,8 @@ //! other stories, tracked changes and tables. A stream larger than [`MAX_STREAM`] bytes, a main //! text longer than [`text::MAX_TEXT`] characters, more than [`MAX_PIECES`] pieces or //! [`MAX_PAGES`] property pages, and placed type of more than [`MAX_PARAGRAPHS`] paragraphs or -//! [`MAX_RUNS`] runs are refused, and so is a structure that lies outside its stream. +//! [`MAX_RUNS`] runs are refused, and so are a structure that lies outside its stream, property +//! pages whose runs are listed twice or overlap, and styles based on each other in a loop. use std::io::{Cursor, Read}; @@ -71,8 +72,6 @@ const MAX_PIECES: usize = 100_000; const MAX_PAGES: usize = 16_384; /// The most styles read from the style sheet (`Stshif.cstd` is below 0x0FFE). const MAX_STYLES: usize = 0x0FFE; -/// The most styles one style's chain of `istdBase` takes in. -const MAX_BASED_ON: usize = 32; /// The most fonts read from the font table (SttbfFfn's `cData` is at most 0x7FF0). const MAX_FONTS: usize = 0x7FF0; /// The most bytes of a font name kept. @@ -359,17 +358,21 @@ enum Fkp { } /// The file positions `start..end` and the properties a property page gives them. -struct Run { +struct Run<'a> { start: u32, end: u32, /// The paragraph style (Papx only). istd: u16, - grpprl: Vec, + /// The properties, in their property page. + grpprl: &'a [u8], } /// The runs of the property pages the bin table `plc` (PlcBteChpx or PlcBtePapx) points to, in -/// the WordDocument stream `wd`, ordered by file position. -fn runs(wd: &[u8], plc: &[u8], kind: Fkp, cmd: &str) -> Result> { +/// the WordDocument stream `wd`, ordered by file position. The bin table's file positions rise +/// ("MUST be sorted in ascending order", and a PlcBteChpx "MUST NOT contain duplicate stream +/// offsets"), and so do the runs of its pages one after another: a page listed twice, or pages +/// whose runs overlap, are damaged. +fn runs<'a>(wd: &'a [u8], plc: &[u8], kind: Fkp, cmd: &str) -> Result>> { let broken = || damaged(cmd, "its character or paragraph properties are damaged"); if plc.len() < 4 || !(plc.len() - 4).is_multiple_of(8) { return Err(broken()); @@ -378,19 +381,28 @@ fn runs(wd: &[u8], plc: &[u8], kind: Fkp, cmd: &str) -> Result> { if n > MAX_PAGES { return Err(bad(cmd, format!("the Word document has more than {MAX_PAGES} pages of properties, too many to place"))); } - let mut out = vec![]; + let fcs = (0..=n).map(|i| u32_at(plc, 4 * i)).collect::>>().ok_or_else(broken)?; + if fcs.windows(2).any(|w| w.first() >= w.get(1)) { + return Err(broken()); + } + let mut out: Vec> = vec![]; for i in 0..n { // PnFkpChpx and PnFkpPapx: the page number in bits 0 to 21. let pn = u32_at(plc, 4 * (n + 1) + 4 * i).ok_or_else(broken)? & 0x003F_FFFF; let page = bytes_at(wd, pn as usize * 512, 512).ok_or_else(broken)?; + let first = out.len(); page_runs(page, kind, &mut out).ok_or_else(broken)?; + // A page's own runs rise (rgfc); its first starts at or after the end of the page before. + let before = first.checked_sub(1).and_then(|k| out.get(k)).map(|r| r.end); + if before.zip(out.get(first)).is_some_and(|(end, r)| r.start < end) { + return Err(broken()); + } } - out.sort_by_key(|r| r.start); Ok(out) } /// The runs of one 512-byte property page; None when it is damaged. -fn page_runs(page: &[u8], kind: Fkp, out: &mut Vec) -> Option<()> { +fn page_runs<'a>(page: &'a [u8], kind: Fkp, out: &mut Vec>) -> Option<()> { let count = usize::from(*page.get(511)?); let most = if kind == Fkp::Chpx { 0x65 } else { 0x1D }; if count == 0 || count > most { @@ -402,10 +414,10 @@ fn page_runs(page: &[u8], kind: Fkp, out: &mut Vec) -> Option<()> { let entry = 4 * (count + 1) + if kind == Fkp::Chpx { i } else { 13 * i }; let offset = usize::from(*page.get(entry)?) * 2; let (istd, grpprl) = match (offset, kind) { - (0, _) => (0, vec![]), + (0, _) => (0, &[][..]), (_, Fkp::Chpx) => { let cb = usize::from(*page.get(offset)?); - (0, bytes_at(page, offset + 1, cb).filter(|_| offset + 1 + cb <= 511)?.to_vec()) + (0, bytes_at(page, offset + 1, cb).filter(|_| offset + 1 + cb <= 511)?) } (_, Fkp::Papx) => { // PapxInFkp: 2 × cb − 1 bytes, or (cb = 0) 2 × cb′ bytes after cb′. @@ -414,9 +426,11 @@ fn page_runs(page: &[u8], kind: Fkp, out: &mut Vec) -> Option<()> { cb => (offset + 1, 2 * cb - 1), }; let grp = bytes_at(page, at, len).filter(|_| at + len <= 511 && len >= 2)?; - (u16_at(grp, 0)?, grp.get(2..)?.to_vec()) + (u16_at(grp, 0)?, grp.get(2..)?) } }; + // rgfc "MUST be sorted in ascending order and MUST NOT contain duplicates": each run ends + // where the next starts. if end <= start { return None; } @@ -473,10 +487,14 @@ struct Style { chpx: Vec, } -/// The style sheet: its styles by istd and its default font. +/// The style sheet: each style's formatting with that of the styles it is based on, by istd, and +/// its default font. #[derive(Default)] struct Sheet { - styles: Vec>, + /// Paragraph styles: their paragraph formatting and their text's. + paragraph: Vec>, + /// Character styles: what they do to the formatting of the text they are applied to. + character: Vec>, /// `Stshif.ftcAsci`. font: Option, } @@ -500,23 +518,74 @@ impl Sheet { // LPStd records start on even offsets. at += 2 + usize::from(len) + usize::from(len) % 2; } - Ok(Self { styles, font }) + let root = (Para::default(), Chars { font, ..Chars::default() }); + let paragraph = resolve(&styles, 1, root, |(mut para, chars), s| { + para.apply(&s.papx); + (para, chars.with(&CharsChange::of(&s.chpx))) + }) + .ok_or_else(broken)?; + let character = resolve(&styles, 2, CharsChange::default(), |change, s| change.then(&CharsChange::of(&s.chpx))).ok_or_else(broken)?; + Ok(Self { paragraph, character, font }) } - /// Style `istd` of kind `stk` and the styles it is based on, the first of the chain first. - fn chain(&self, istd: u16, stk: u8) -> Vec<&Style> { - let mut seen: Vec = vec![]; - let mut chain = vec![]; - let mut next = istd; - while next != NO_STYLE && !seen.contains(&next) && seen.len() < MAX_BASED_ON { - let Some(s) = self.styles.get(usize::from(next)).and_then(Option::as_ref).filter(|s| s.stk == stk) else { break }; - seen.push(next); - chain.push(s); - next = s.base; - } - chain.reverse(); - chain + /// Paragraph style `istd`'s paragraph formatting and its text's; the document defaults when + /// it is no paragraph style. + fn paragraph_style(&self, istd: u16) -> (Para, Chars) { + self.paragraph.get(usize::from(istd)).copied().flatten().unwrap_or((Para::default(), Chars { font: self.font, ..Chars::default() })) } + + /// What character style `istd` does to text; nothing when it is no character style. + fn character_style(&self, istd: u16) -> CharsChange { + self.character.get(usize::from(istd)).copied().flatten().unwrap_or_default() + } +} + +/// The formatting of each style of `styles` of kind `stk` with that of the styles it is based on: +/// `root` with `own` applied for each style of its chain of `istdBase`, the first of the chain +/// first. Each style's formatting is worked out once, on that of the style it is based on. A chain +/// ends at a style of another kind or none. None when `istdBase` makes a loop (which it "MUST +/// NOT", StdfBase). +fn resolve(styles: &[Option + + "##; + let img = render_artboard(&import(svg).unwrap()); + assert_eq!(img.over_white(30, 30), [0, 0, 255]); + assert_eq!(img.over_white(130, 30), [255, 0, 0]); +} From b4d3ae41bfd6e64620f930fa35eec01a410c7895 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 03:04:04 -0800 Subject: [PATCH 251/674] SVG: made-up ids skip the file's taken ids once Each id made up on import starts where the last one stopped instead of at the number of ids made so far, so a file that already holds many of the made-up ids does not make every new id try them all again. The ids made up are the same. --- crates/svg/src/import/prepass.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index 8ed8259482..a635b88d5a 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -42,6 +42,8 @@ pub(crate) struct Edits { ids: HashMap, /// The ids in the file and those made up, read when the first id is made up. taken: Option>, + /// The number the next made-up id is tried with: the numbers below it are made up or taken. + next: usize, /// Declarations added to elements' `style`s, by element: (where they go, whether the element /// has a `style` attribute, the declarations, XML-escaped). styles: HashMap, @@ -62,13 +64,12 @@ impl Edits { return id.clone(); } let taken = self.taken.get_or_insert_with(|| n.document().descendants().filter_map(|e| e.attribute("id")).map(str::to_string).collect()); - let mut i = self.ids.len(); let id = loop { - let id = format!("{MADE_UP_ID}{i}"); + let id = format!("{MADE_UP_ID}{}", self.next); + self.next += 1; if !taken.contains(&id) { break id; } - i += 1; }; taken.insert(id.clone()); self.set(svg, n, "id", &id); @@ -415,3 +416,25 @@ pub(super) fn labels(xml: &roxmltree::Document) -> HashMap { }) .collect() } + +#[cfg(test)] +mod tests { + use super::*; + + /// A file that already holds the made-up ids does not make each new id try them all again: + /// 5,000 ids made up past 50,000 taken ones take a moment, not 250 million tries. + #[test] + fn made_up_ids_skip_the_taken_ones_once() { + let taken: String = (0..50_000).map(|i| format!("")).collect(); + let bare = "".repeat(5_000); + let svg = format!("{taken}{bare}"); + let doc = roxmltree::Document::parse(&svg).unwrap(); + let rects: Vec = doc.descendants().filter(|n| n.has_tag_name("rect")).collect(); + let mut edits = Edits::default(); + let start = std::time::Instant::now(); + let ids: Vec = rects.iter().map(|n| edits.id(&svg, *n)).collect(); + assert!(start.elapsed() < std::time::Duration::from_secs(1), "{:?}", start.elapsed()); + assert_eq!(ids.first().map(String::as_str), Some(format!("{MADE_UP_ID}50000").as_str())); + assert_eq!(ids.iter().collect::>().len(), ids.len()); + } +} From 7c7a127ec84498f83ead2703c5c791bfc5c5cdc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 03:09:08 -0800 Subject: [PATCH 252/674] SVG: a thin ellipse far from the origin imports with standard handles An ellipse whose radius is smaller than the point tolerance at its coordinates, but at least two f32 steps, now imports as the four-anchor ellipse instead of usvg's curves with rounded handles. --- crates/svg/src/import/convert.rs | 10 ++++++---- crates/svg/tests/it/basic_shapes.rs | 10 ++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index e640880e7e..2a777b3423 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -156,14 +156,16 @@ pub(super) fn drawn_ellipse(p: &usvg::tiny_skia_path::Path) -> Option 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: points match within a few of its steps at the size of the coordinates. - let tol = 16.0 * f64::from(f32::EPSILON) * [x0, x1, y0, y1].iter().fold(1.0f64, |m, v| m.max(v.abs())); + // usvg works in f32: points match within a few of its steps at the size of the coordinates, and + // a radius of fewer than two steps does not survive the conversion. + let step = f64::from(f32::EPSILON) * [x0, x1, y0, y1].iter().fold(1.0f64, |m, v| m.max(v.abs())); + let tol = 16.0 * step; let axes = [Point::new(x1, c.y), Point::new(c.x, y1), Point::new(x0, c.y), Point::new(c.x, y0)]; let off = 1e-3 + 4.0 * tol / rx.min(ry); let on_ellipse = |q: &Point| (((q.x - c.x) / rx).powi(2) + ((q.y - c.y) / ry).powi(2) - 1.0).abs() <= off; if !closed - || rx <= tol - || ry <= tol + || rx < 2.0 * step + || ry < 2.0 * step || 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) diff --git a/crates/svg/tests/it/basic_shapes.rs b/crates/svg/tests/it/basic_shapes.rs index 8d76739b47..da759b1978 100644 --- a/crates/svg/tests/it/basic_shapes.rs +++ b/crates/svg/tests/it/basic_shapes.rs @@ -164,9 +164,10 @@ fn circles_and_ellipses_import_as_the_ellipse_drawn() { - "#; + + "#; let back = paths(&import(svg).unwrap()); - assert_eq!(back.len(), 4); + assert_eq!(back.len(), 5); let circle = &back[0].subpaths[0].anchors; let want: Vec = [(100.0, 70.0), (60.0, 110.0), (20.0, 70.0), (60.0, 30.0)].map(|(x, y)| Point::new(x, y)).into(); assert_eq!(circle.len(), 4); @@ -182,6 +183,11 @@ fn circles_and_ellipses_import_as_the_ellipse_drawn() { // A small circle far from the origin too. let far = &back[3].subpaths[0].anchors; assert!(far.len() == 4 && far[0].p.distance(Point::new(40_000_400.0, 0.0)) < 8.0, "{far:?}"); + // A radius of a few of f32's steps at its coordinates, with handles of the standard length. + let thin = &back[4].subpaths[0].anchors; + let handle = thin.first().map(|a| a.h_out - a.p); + assert!(thin.len() == 4 && thin[0].p.distance(Point::new(1_000_036.0, 1_000_000.0)) < 0.25, "{thin:?}"); + assert!(handle.is_some_and(|h| h.x.abs() < 1e-6 && (h.y - shapes::KAPPA).abs() < 1e-6), "{thin:?}"); } #[test] From 2a51404e7433d02bc0f0b7c4e6686010ec964978 Mon Sep 17 00:00:00 2001 From: Rahul Ranjan Date: Mon, 2 Nov 2026 11:17:49 +0000 Subject: [PATCH 253/674] i18n(ru): translate the 130 strings the report listed as missing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Russian catalog covered 6,126 of the 6,256 interface strings: the workspace names (Essentials, Painting, Typography…), their Reset entries, the artboard and dimension annotations, the PDF and export preset names, the library panel sentences and several control-channel messages still fell back to English. Adds the 130 missing entries in the catalog's TSV format with the Illustrator-style vocabulary the catalog already uses (монтажная область, выносные линии, плашечные цвета, трассировка). After this the report lists nothing missing for ru. Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- crates/ui-egui/src/i18n/ru.tsv | 132 +++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cb6cbd10b9..11ced1266c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6220,3 +6220,135 @@ breakText Glyphs Глифы Create Swatch Legend Создать легенду образцов Create Swatch Legend… Создать легенду образцов… HEX HEX + +# The strings the report listed as missing for ru. + 1 Layer 1 слой + 4K UHD 4K UHD + 8K UHD 8K UHD + A3 A3 + A4 A4 + A5 A5 + A6 A6 + Arrow Scale: Масштаб стрелок: + Arrow Style: Стиль стрелок: + Art and Bright Colors Художественные и яркие цвета + Artboard Options: edit with the Artboard tool Параметры монтажной области: измените их инструментом «Монтажная область» + Automate Автоматизация + Automation Автоматизация + B4 B4 + B5 B5 + CRLF (Windows) CRLF (Windows) + Check for Updates… Проверить обновления… + Color Table (4 colors) Таблица цветов (4 цвета) + Create PDF layers from top-level layers Создавать PDF-слои из слоёв верхнего уровня + Current Colors (0) Текущие цвета (0) + Differences from VectorCraft Default: Отличия от значений VectorCraft по умолчанию: + Differences from [Default]: Отличия от [По умолчанию]: + Dimension Lines Размерные линии + Dimension Text Размерный текст + Dot Gain 15% Растискивание 15 % + Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Перетащите сюда объекты, цвета и стили текста, чтобы использовать их в разных документах. Библиотеки хранятся на этом компьютере — учётная запись не нужна. + Essentials Основные + Essentials Classic Основные (классические) + Expand 1 Selected Разбить 1 объект + Extension Lines Выносные линии + Extension: Выносная линия: + Font Size: Размер шрифта: + Graphic Styles (4) Стили графики (4) + Gray Gamma 2.2 Gray Gamma 2.2 + HDTV 1080p HDTV 1080p + HDTV 720p HDTV 720p + Hide Extension Lines Скрыть выносные линии + Hide Units Скрыть единицы + Invalid panel layout; restored the default dock Недопустимая раскладка панелей; восстановлена стыковка по умолчанию + Japanese Double Postcard Японская двойная открытка + Japanese Envelope #3 Японский конверт №3 + Japanese Envelope #4 Японский конверт №4 + Japanese Postcard Японская открытка + Kaku #2 Каку №2 + Kaku #3 Каку №3 + LF (macOS, Linux) LF (macOS, Linux) + Layout Макет + Legal Legal + Line Type: Тип линии: + Line Weight: Толщина линии: + Load Variable Library Загрузить библиотеку переменных + OpenType OpenType + PDF 1.7 PDF 1.7 + PDF/X-1a:2001 PDF/X-1a:2001 + PDF/X-3:2002 PDF/X-3:2002 + PDF/X-4:2010 PDF/X-4:2010 + Painting Рисование + Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Часть ArtCraft. MIT OR Apache-2.0. Шрифты: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Значки: Lucide (ISC) + VectorCraft. + Phone 375×812 Телефон 375×812 + Photo Low Fidelity Фото (низкое качество) + Preparing the image… Подготовка изображения… + Print & Proof Печать и цветопроба + Printing & Proofing Печать и цветопроба + Printing and Proofing Печать и цветопроба + RECENT (1) НЕДАВНИЕ (1) + RGB RGB + Reset Automation Сбросить «Автоматизация» + Reset Essentials Classic Сбросить «Основные (классические)» + Reset Layout Сбросить «Макет» + Reset Painting Сбросить «Рисование» + Reset Printing and Proofing Сбросить «Печать и цветопроба» + Reset Tracing Сбросить «Трассировка» + Reset Typography Сбросить «Типографика» + Reset Web Сбросить «Веб» + Restricted Colors Ограниченные цвета + Right-click an item to move it into this group. Щёлкните объект правой кнопкой мыши, чтобы переместить его в эту группу. + SVG 1.1 SVG 1.1 + Scale X Масштаб X + Scale X: Масштаб X: + Scale Y Масштаб Y + Scale Y: Масштаб Y: + Selected Styles Only (0) Только выбранные стили (0) + Selected Swatches Only (0) Только выбранные образцы (0) + Shear: Наклон: + Simplified Chinese Упрощённый китайский + Spot Colors (0) Плашечные цвета (0) + Tablet 1024×768 Планшет 1024×768 + Tabloid Tabloid + Touch Сенсорный + Tracing Трассировка + Tracing the colors… Трассировка цветов… + Typography Типографика + UTF-16 (Unicode) UTF-16 (Unicode) + Units & Scale Единицы и масштаб + VectorCraft VectorCraft + VectorCraft Updates Обновления VectorCraft + Video 1920×1080 Видео 1920×1080 + Video 3840×2160 Видео 3840×2160 + Web Веб + Web 1280×720 Веб 1280×720 + WebP WebP + Yonroku-ban Ёнроку-бан + [1P-High View] [1P — высокое качество] + [1P-Low View] [1P — низкое качество] + [1P-Normal View] [1P — обычное качество] + [2P-High View] [2P — высокое качество] + [2P-Low View] [2P — низкое качество] + [2P-Normal View] [2P — обычное качество] + [3P-Low View] [3P — низкое качество] + [3P-Normal View] [3P — обычное качество] + [High Quality Print] [Высококачественная печать] + [High Resolution] [Высокое разрешение] + [Low Resolution] [Низкое разрешение] + [Medium Resolution] [Среднее разрешение] + [PDF/X-1a:2001] [PDF/X-1a:2001] + [PDF/X-3:2002] [PDF/X-3:2002] + [PDF/X-4:2010] [PDF/X-4:2010] + [Smallest File Size] [Минимальный размер файла] + [VectorCraft Default] [Значения VectorCraft по умолчанию] + sRGB IEC61966-2.1 sRGB IEC61966-2.1 +@id file.close Закрыть файл +@id pathfinder.add Объединить +@msg give corners of the path: anchors between two straight sides укажите углы контура: опорные точки между двумя прямыми сторонами +@msg image '{key}' has no pixels and was left out изображение '{key}' не содержит пикселов и было пропущено +@msg not an RTF file: it doesn't start with {\\rtf это не файл RTF: он не начинается с {\\rtf +@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG это файл PostScript (.ai, сохранённый в старом формате или без совместимости с PDF, либо EPS-файл), который пока нельзя открыть: сохраните его как PDF, .ai с совместимостью с PDF или SVG +@msg this kind of brush has no options dialog yet у кистей этого типа пока нет диалога параметров +digits Hindi Хинди +font-script Japanese Японский +shape Open Открытый From 442ae20e14a92dcacabe35214ac13ff97223f8b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 03:22:10 -0800 Subject: [PATCH 254/674] SVG: made-up ids skip every id the file names An id the importer writes into an element no longer matches a style sheet's #id selector or a link that no element matched before. The ids are read from the decoded attribute values and text of the file, once. --- crates/svg/src/import/prepass.rs | 38 ++++++++++++++++++++--------- crates/svg/tests/it/basic_shapes.rs | 26 ++++++++++++++++++++ 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index a635b88d5a..245392fda3 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -40,8 +40,9 @@ pub(crate) struct Edits { list: Vec<(std::ops::Range, String)>, /// The ids made up so far, by element. ids: HashMap, - /// The ids in the file and those made up, read when the first id is made up. - taken: Option>, + /// The numbers `n` of the `{MADE_UP_ID}n` the file names (as an element's id, in a style + /// sheet's `#id` selector or in a `#id` link to no element), read when the first id is made up. + taken: Option>, /// The number the next made-up id is tried with: the numbers below it are made up or taken. next: usize, /// Declarations added to elements' `style`s, by element: (where they go, whether the element @@ -55,7 +56,7 @@ impl Edits { } /// The id of element `n` (in `svg`), made up and written in when it has none. A made-up id is - /// one no element of the file has. + /// one the file does not name ([`named_made_up_ids`]). pub(super) fn id(&mut self, svg: &str, n: XNode) -> String { if let Some(id) = n.attribute("id").filter(|id| !id.is_empty()) { return id.to_string(); @@ -63,15 +64,12 @@ impl Edits { if let Some(id) = self.ids.get(&n.id()) { return id.clone(); } - let taken = self.taken.get_or_insert_with(|| n.document().descendants().filter_map(|e| e.attribute("id")).map(str::to_string).collect()); - let id = loop { - let id = format!("{MADE_UP_ID}{}", self.next); + let taken = self.taken.get_or_insert_with(|| named_made_up_ids(n.document())); + while taken.contains(&self.next) { self.next += 1; - if !taken.contains(&id) { - break id; - } - }; - taken.insert(id.clone()); + } + let id = format!("{MADE_UP_ID}{}", self.next); + self.next += 1; self.set(svg, n, "id", &id); self.ids.insert(n.id(), id.clone()); id @@ -121,6 +119,24 @@ impl Edits { } } +/// The number after each [`MADE_UP_ID`] followed by digits in the attribute values and text of +/// `xml`, read with their character references decoded (numbers too large for a `usize` left out). +fn named_made_up_ids(xml: &roxmltree::Document) -> HashSet { + fn numbers(s: &str) -> impl Iterator + '_ { + s.match_indices(MADE_UP_ID).filter_map(|(at, _)| { + let rest = s.get(at + MADE_UP_ID.len()..)?; + let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); + rest.get(..digits)?.parse().ok() + }) + } + let mut taken = HashSet::new(); + for n in xml.descendants() { + taken.extend(n.attributes().flat_map(|a| numbers(a.value()))); + taken.extend(n.text().filter(|_| n.is_text()).into_iter().flat_map(numbers)); + } + taken +} + /// usvg reads `` and `` as plain groups, drops what isn't displayed and reads linked /// files on its own. Before it runs, the SVG is changed so that what we keep can be found: /// * every `` and every `` of a `` gets an id when it has none diff --git a/crates/svg/tests/it/basic_shapes.rs b/crates/svg/tests/it/basic_shapes.rs index da759b1978..25d13cb31c 100644 --- a/crates/svg/tests/it/basic_shapes.rs +++ b/crates/svg/tests/it/basic_shapes.rs @@ -209,3 +209,29 @@ fn circles_import_without_changing_ids_or_style_matches() { assert_eq!(img.over_white(30, 30), [0, 0, 255]); assert_eq!(img.over_white(130, 30), [255, 0, 0]); } + +#[test] +fn circles_import_without_an_id_the_file_names() { + // A style sheet's rule for an id no element has does not reach the circle. + let svg = r##" + + "##; + let img = render_artboard(&import(svg).unwrap()); + assert_eq!(img.over_white(30, 30), [0, 0, 0]); +} + +#[test] +fn circles_import_without_an_id_a_use_names() { + // A `` of an id no element has does not show the circle, nor does one that writes the + // id with a character reference. + for href in ["#vectorcraft-id-0", "#vectorcraft-id-0"] { + let svg = format!( + r##" + + "## + ); + let img = render_artboard(&import(&svg).unwrap()); + assert_eq!(img.over_white(30, 30), [0, 0, 0], "{href}"); + assert_eq!(img.over_white(130, 30), [255, 255, 255], "{href}"); + } +} From 3976989cb74864eb7c98d5d3fe01627d6f421974 Mon Sep 17 00:00:00 2001 From: Rahul Ranjan Date: Mon, 2 Nov 2026 11:27:09 +0000 Subject: [PATCH 255/674] i18n(sv): translate the 22 strings the report listed as missing The Swedish catalog lacked 22 interface strings: the workspace names (Essentials, Painting, Typography, Web, Touch), the 1P/2P/3P view preset names and the Hindi digit-script name. Adds them with the vocabulary the catalog already uses (Utskrift, Teckenstorlek). After this the report lists nothing missing for sv. Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- crates/ui-egui/src/i18n/sv.tsv | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b8cc549339..0e7b5d75c9 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6295,3 +6295,27 @@ breakText Glyphs Glyfer Create Swatch Legend Skapa färgrutelegend Create Swatch Legend… Skapa färgrutelegend… HEX HEX + +# The strings the report listed as missing for sv. + Automation Automation + Essentials Grundläggande + Essentials Classic Grundläggande (klassiska) + Font Size: Teckenstorlek: + Layout Layout + OpenType OpenType + Painting Målning + Printing and Proofing Utskrift och korrektur + Touch Pek + Tracing Spårning + Typography Typografi + VectorCraft VectorCraft + Web Webb + [1P-High View] [1P — hög kvalitet] + [1P-Low View] [1P — låg kvalitet] + [1P-Normal View] [1P — normal kvalitet] + [2P-High View] [2P — hög kvalitet] + [2P-Low View] [2P — låg kvalitet] + [2P-Normal View] [2P — normal kvalitet] + [3P-Low View] [3P — låg kvalitet] + [3P-Normal View] [3P — normal kvalitet] +digits Hindi Hindi From fa8addaa125fc9500506ac0cb45effa5e03cbd6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 03:37:17 -0800 Subject: [PATCH 256/674] =?UTF-8?q?Select:=20Same=20=E2=80=BA=20Text=20Fil?= =?UTF-8?q?l=20&=20Stroke=20Color=20selects=20type=20whose=20fill=20and=20?= =?UTF-8?q?stroke=20both=20match?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Select › Same › Text Fill & Stroke Color (select.same.textFillAndStrokeColor) selects the type objects with a run of characters whose fill and stroke both match the first character of the first selected type. Type that matches only the fill or only the stroke, or has the fill in one run and the stroke in another, is left out. The entry follows Text Stroke Color in the menu and has a row in every catalog. --- crates/engine/src/cmd/docmenu.rs | 9 ++++++ crates/engine/src/tests/menucmds.rs | 43 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/menus/tests.rs | 22 +++++++++++++++ crates/ui-egui/src/menus/tree.rs | 1 + docs/mcp.md | 7 +++++ docs/target-app-parity.md | 1 + 32 files changed, 109 insertions(+) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index dc6d2a6559..3d77bde156 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -66,6 +66,15 @@ pub fn specs() -> Vec { "select.same.textStrokeColor", |a, b| a.stroke == b.stroke )), + cmd!( + "select.same.textFillAndStrokeColor", + "Text Fill & Stroke Color", + ["Select", "Same"], + None, + "{} select the type objects with characters whose fill and stroke both match the first character of the first selected type → {count}", + has_selection, + |s, _| same_text(s, "select.same.textFillAndStrokeColor", |a, b| a.fill == b.fill && a.stroke == b.stroke) + ), cmd!( "select.object.directionHandles", "Direction Handles", diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 7bac52cc9c..f378554562 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1948,6 +1948,49 @@ fn select_same_font_size_and_fill() { assert!(s.execute("select.same.fontSize", &json!({})).is_err()); } +/// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke +/// both match the first character of the selected type: the same fill with another stroke, or the +/// same stroke with another fill, is left out, and in type with several runs one run has to match +/// both. +#[test] +fn select_same_text_fill_and_stroke_color_needs_both_to_match() { + let mut s = session(); + let typed = |s: &mut Session, y: f64, fill: &str, stroke: &str| { + let id = id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type"})).unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "fill": fill, "stroke": stroke})).unwrap(); + id + }; + let (red, blue, green) = ("#ff0000", "#0000ff", "#00ff00"); + let a = typed(&mut s, 20.0, red, blue); + let both = typed(&mut s, 60.0, red, blue); + let same_fill = typed(&mut s, 100.0, red, green); + let same_stroke = typed(&mut s, 140.0, green, blue); + // Mixed runs: "ty" matches both; the other runs do not. + let mixed = typed(&mut s, 180.0, green, green); + s.execute("text.setRangeStyle", &json!({"id": mixed.0, "start": 0, "end": 2, "fill": red, "stroke": blue})).unwrap(); + // Mixed runs where one run has the fill and another the stroke: no run matches both. + let split = typed(&mut s, 220.0, green, green); + s.execute("text.setRangeStyle", &json!({"id": split.0, "start": 0, "end": 2, "fill": red})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": split.0, "start": 2, "end": 4, "stroke": blue})).unwrap(); + let r = rect(&mut s, 300.0, 0.0, 5.0, 5.0); + s.execute("paint.setFill", &json!({"ids": [r.0], "color": red})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + sel(&mut s, &[a]); + assert_eq!(s.execute("select.same.textFillAndStrokeColor", &json!({})).unwrap()["count"], 3); + assert_eq!(selected(&s), vec![a, both, mixed]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "selecting adds no undo step"); + // The single-attribute commands take the type that matches one of the two. + sel(&mut s, &[a]); + assert_eq!(s.execute("select.same.textFillColor", &json!({})).unwrap()["count"], 5); + assert_eq!(selected(&s), vec![a, both, same_fill, mixed, split]); + sel(&mut s, &[a]); + assert_eq!(s.execute("select.same.textStrokeColor", &json!({})).unwrap()["count"], 5); + assert_eq!(selected(&s), vec![a, both, same_stroke, mixed, split]); + // With no type selected the command reports it. + sel(&mut s, &[r]); + assert!(s.execute("select.same.textFillAndStrokeColor", &json!({})).is_err()); +} + #[test] fn select_same_link_block_series_selects_the_frames_of_a_thread() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 073f577150..dd5f4c07d9 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3306,6 +3306,7 @@ digits Malayalam Малаялам Templates… Шаблони… Text Displayed in Cell: Текст, показван в клетката: Text Export Options Опции за експортиране на текст + Text Fill & Stroke Color Цвят на запълване и щрих на текста Text Fill Color Цвят на запълване на текста Text Import Options Опции за импортиране на текст Text Stroke Color Цвят на щриха на текста diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 80e02fbe46..a8763ad744 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -426,6 +426,7 @@ Variable Font Varijabilni font Text Fill Color Boja ispune teksta Text Stroke Color Boja poteza teksta + Text Fill & Stroke Color Boja ispune i poteza teksta All on Same Layers Sve na istim slojevima Direction Handles Ručke smjera Brush Strokes Potezi četkicom diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b6985fb130..f85398a17f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4225,6 +4225,7 @@ digits Malayalam Malaiàlam Text Displayed in Cell Text mostrat a la cel·la Text Displayed in Cell: Text mostrat a la cel·la: Text Export Options Opcions d’exportació de text + Text Fill & Stroke Color Color de farciment i traç del text Text Fill Color Color de farciment del text Text Import Options Opcions d’importació de text Text Orientation Orientació del text diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 367be32b2c..a84716c786 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -434,6 +434,7 @@ Variable Font Variabilní písmo Text Fill Color Barva výplně textu Text Stroke Color Barva tahu textu + Text Fill & Stroke Color Barva výplně a tahu textu All on Same Layers Vše ve stejných vrstvách Direction Handles Směrové úchyty Brush Strokes Tahy štětcem diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7b077a50ad..535034c211 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -393,6 +393,7 @@ Variable Font Variabel skrifttype Text Fill Color Tekstfyldfarve Text Stroke Color Tekststregfarve + Text Fill & Stroke Color Tekstfyld- og stregfarve All on Same Layers Alt på samme lag Direction Handles Retningshåndtag Brush Strokes Penselstrøg diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c87b45d229..7ca638c7d8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3334,6 +3334,7 @@ effect Points Punkte Templates… Vorlagen… Text Displayed in Cell: In der Zelle angezeigter Text: Text Export Options Textexportoptionen + Text Fill & Stroke Color Flächen- und Konturfarbe des Texts Text Fill Color Flächenfarbe des Texts Text Import Options Textimportoptionen Text Stroke Color Konturfarbe des Texts diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 615e0e6ee0..5af81bbb0f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3727,6 +3727,7 @@ digits Malayalam Μαλαγιάλαμ Templates Folder Φάκελος προτύπων Text Displayed in Cell: Κείμενο που εμφανίζεται στο κελί: Text Export Options Επιλογές εξαγωγής κειμένου + Text Fill & Stroke Color Χρώμα γεμίσματος και περιγράμματος κειμένου Text Fill Color Χρώμα γεμίσματος κειμένου Text Import Options Επιλογές εισαγωγής κειμένου Text Stroke Color Χρώμα περιγράμματος κειμένου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c4d4a196b6..0d65000e21 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3390,6 +3390,7 @@ digits Malayalam Malayálam Templates… Plantillas… Text Displayed in Cell: Texto mostrado en la celda: Text Export Options Opciones de exportación de texto + Text Fill & Stroke Color Color de relleno y trazo del texto Text Fill Color Color de relleno del texto Text Import Options Opciones de importación de texto Text Stroke Color Color de trazo del texto diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7d571168f5..9dacd5899a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -431,6 +431,7 @@ Variable Font Muuttuva fontti Text Fill Color Tekstin täyttöväri Text Stroke Color Tekstin viivan väri + Text Fill & Stroke Color Tekstin täytön ja viivan väri All on Same Layers Kaikki samoilla tasoilla Direction Handles Suuntakahvat Brush Strokes Sivellinviivat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4372280dbd..9d2263a908 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3382,6 +3382,7 @@ digits Malayalam Malayalam Templates… Modèles… Text Displayed in Cell: Texte affiché dans la cellule : Text Export Options Options d’exportation du texte + Text Fill & Stroke Color Couleur de fond et de contour du texte Text Fill Color Couleur de fond du texte Text Import Options Options d’importation du texte Text Stroke Color Couleur de contour du texte diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9890ecf5a9..7658ebb64f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4043,6 +4043,7 @@ mark-style Japanese Japán Text Displayed in Cell A cellában megjelenő szöveg Text Displayed in Cell: A cellában megjelenő szöveg: Text Export Options Szövegexportálási beállítások + Text Fill & Stroke Color Szöveg kitöltő- és körvonalszíne Text Fill Color Szöveg kitöltőszíne Text Import Options Szövegimportálási beállítások Text Stroke Color Szöveg körvonalszíne diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index d8ceeacad7..8ebc696221 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -393,6 +393,7 @@ Variable Font Font variabel Text Fill Color Warna isian teks Text Stroke Color Warna stroke teks + Text Fill & Stroke Color Warna isian & stroke teks All on Same Layers Semua di lapisan yang sama Direction Handles Gagang arah Brush Strokes Sapuan kuas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1f6ffb4cf5..39f1632e50 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3426,6 +3426,7 @@ digits Malayalam Malayalam Templates… Modelli… Text Displayed in Cell: Testo visualizzato nella cella: Text Export Options Opzioni di esportazione testo + Text Fill & Stroke Color Colore riempimento e traccia testo Text Fill Color Colore riempimento testo Text Import Options Opzioni di importazione testo Text Stroke Color Colore traccia testo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3d6849e46c..ddf2f044b9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -463,6 +463,7 @@ digits Malayalam マラヤーラム数字 Variable Font バリアブルフォント Text Fill Color テキストカラー (塗り) Text Stroke Color テキストカラー (線) + Text Fill & Stroke Color テキストカラー (塗りと線) All on Same Layers 同じレイヤー上のすべて Direction Handles 方向線ハンドル Brush Strokes ブラシストローク diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1a01580e2e..80b0a74761 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -350,6 +350,7 @@ Font Size შრიფტის ზომა Text Fill Color ტექსტის შევსების ფერი Text Stroke Color ტექსტის კონტურის ფერი + Text Fill & Stroke Color ტექსტის შევსებისა და კონტურის ფერი All on Same Layers ყველა იმავე შრეებზე Direction Handles მიმართულების სახელურები Brush Strokes ფუნჯის შტრიხები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5f24419728..8e12b5f267 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -456,6 +456,7 @@ digits Malayalam 말라얄람어 Variable Font 가변 글꼴 Text Fill Color 문자 칠 색상 Text Stroke Color 문자 선 색상 + Text Fill & Stroke Color 문자 칠 및 선 색상 All on Same Layers 같은 레이어의 모두 Direction Handles 방향 핸들 Brush Strokes 브러시 선 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d7ccca2114..f2a970cbde 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -407,6 +407,7 @@ Variable Font Variabel lettertype Text Fill Color Tekstvulkleur Text Stroke Color Tekstcontourkleur + Text Fill & Stroke Color Tekstvul- en contourkleur All on Same Layers Alles op dezelfde lagen Direction Handles Richtingsgrepen Brush Strokes Penseelstreken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index be0a2a24b4..30ec4f06e3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -394,6 +394,7 @@ Variable Font Czcionka zmienna Text Fill Color Kolor wypełnienia tekstu Text Stroke Color Kolor obrysu tekstu + Text Fill & Stroke Color Kolor wypełnienia i obrysu tekstu All on Same Layers Wszystko na tych samych warstwach Direction Handles Uchwyty kierunkowe Brush Strokes Pociągnięcia pędzla diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2f07e53096..82104e63ec 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2781,6 +2781,7 @@ digits Malayalam Malaiala Templates… Modelos… Text Displayed in Cell: Texto Exibido na Célula: Text Export Options Opções de Exportação de Texto + Text Fill & Stroke Color Cor de Preenchimento e Traçado do Texto Text Fill Color Cor de Preenchimento do Texto Text Import Options Opções de Importação de Texto Text Stroke Color Cor do Traçado do Texto diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cb6cbd10b9..a52c486034 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3421,6 +3421,7 @@ digits Malayalam Малаялам Templates… Шаблоны… Text Displayed in Cell: Текст, отображаемый в ячейке: Text Export Options Параметры экспорта текста + Text Fill & Stroke Color Цвет заливки и обводки текста Text Fill Color Цвет заливки текста Text Import Options Параметры импорта текста Text Stroke Color Цвет обводки текста diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b8cc549339..3f8be38fde 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3312,6 +3312,7 @@ digits Malayalam Malayalam Templates… Mallar… Text Displayed in Cell: Text som visas i cellen: Text Export Options Alternativ för textexport + Text Fill & Stroke Color Textens fyllnads- och konturfärg Text Fill Color Textens fyllnadsfärg Text Import Options Alternativ för textimport Text Stroke Color Textens konturfärg diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9009af8ae1..808e55ad93 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3205,6 +3205,7 @@ digits Malayalam Malayalam Templates… Şablonlar… Text Displayed in Cell: Hücrede Görüntülenen Metin: Text Export Options Metin Dışa Aktarma Seçenekleri + Text Fill & Stroke Color Metin Dolgu ve Kontur Rengi Text Fill Color Metin Dolgu Rengi Text Import Options Metin İçe Aktarma Seçenekleri Text Stroke Color Metin Kontur Rengi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7535b5357c..bda2cd2787 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3419,6 +3419,7 @@ effect Points Точки Templates… Шаблони… Text Displayed in Cell: Текст, що відображається в комірці: Text Export Options Параметри експорту тексту + Text Fill & Stroke Color Колір заливки та обведення тексту Text Fill Color Колір заливки тексту Text Import Options Параметри імпорту тексту Text Stroke Color Колір обведення тексту diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 07852ac9fd..4957824ea1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3748,6 +3748,7 @@ mark-style Japanese Kiểu Nhật Text Văn bản Text Displayed in Cell: Văn bản hiển thị trong ô: Text Export Options Tùy chọn xuất văn bản + Text Fill & Stroke Color Màu tô & nét văn bản Text Fill Color Màu tô văn bản Text Import Options Tùy chọn nhập văn bản Text Stroke Color Màu nét văn bản diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d609725c4e..b8123733f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3258,6 +3258,7 @@ digits Malayalam 马拉雅拉姆数字 Templates… 模板… Text Displayed in Cell: 单元格中显示的文字: Text Export Options 文本导出选项 + Text Fill & Stroke Color 文字填色和描边颜色 Text Fill Color 文字填色 Text Import Options 文本导入选项 Text Stroke Color 文字描边颜色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 32dbb3ba2b..a8b514b8a9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4276,6 +4276,7 @@ digits Malayalam 馬來亞拉姆數字 Templates… 範本… Text Displayed in Cell: 儲存格中顯示的文字: Text Export Options 文字匯出選項 + Text Fill & Stroke Color 文字填色與筆畫顏色 Text Fill Color 文字填色 Text Import Options 文字匯入選項 Text Stroke Color 文字筆畫顏色 diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 04769b2c60..4b46453ca7 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -527,6 +527,28 @@ fn select_same_link_block_series_selects_a_thread_from_the_menu() { assert_eq!(json!(ids), json!([a, b])); } +#[test] +fn select_same_text_fill_and_stroke_color_follows_text_stroke_color_in_the_menu() { + let mut app = app_with_a_rectangle(); + let entries = menu_entries(&app); + let at = |id: &str| entries.iter().position(|e| e.command.as_deref() == Some(id)); + let entry = at("select.same.textFillAndStrokeColor").map(|i| &entries[i]).expect("menu entry"); + assert_eq!((entry.path.clone(), entry.label.as_str()), (vec!["Select".to_string(), "Same".to_string()], "Text Fill & Stroke Color")); + assert_eq!(at("select.same.textStrokeColor").map(|i| i + 1), at("select.same.textFillAndStrokeColor")); + let text = |app: &mut VectorcraftApp, y: i32, fill: &str, stroke: &str| { + let id = app.run("text.create", json!({"x": 0, "y": y, "text": "type"})).unwrap()["id"].clone(); + app.run("text.setRangeStyle", json!({"id": id.clone(), "start": 0, "end": 4, "fill": fill, "stroke": stroke})).unwrap(); + id + }; + let a = text(&mut app, 40, "#ff0000", "#0000ff"); + let b = text(&mut app, 80, "#ff0000", "#0000ff"); + let _ = text(&mut app, 120, "#ff0000", "#00ff00"); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); + invoke(&mut app, "select.same.textFillAndStrokeColor", json!({})); + let ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|i| i.0).collect(); + assert_eq!(json!(ids), json!([a, b])); +} + #[test] fn edit_selection_opens_its_dialog_on_the_saved_selections() { let mut app = app_with_a_rectangle(); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 9eabfc6814..d197ee9061 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -470,6 +470,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Font Size", "select.same.fontSize"), c("Text Fill Color", "select.same.textFillColor"), c("Text Stroke Color", "select.same.textStrokeColor"), + c("Text Fill & Stroke Color", "select.same.textFillAndStrokeColor"), ], ), sub( diff --git a/docs/mcp.md b/docs/mcp.md index 07fbd7b556..2a7cd68247 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1431,6 +1431,13 @@ everything in it, and `select.all`, `select.allOnArtboard` and `select.inverse` among the objects beside it in its group or layer, passing over hidden and locked objects and sublayers. When there is no such object, the selection stays as it is. +`select.same.textFillAndStrokeColor` (Select › Same › Text Fill & Stroke Color) selects the type objects that have +characters whose fill and stroke both match the first character of the first selected type, and returns `{count}`. +`select.same.textFillColor` and `select.same.textStrokeColor` compare the fill or the stroke alone. In type with +several runs, one run has to match both: type with the fill in one run and the stroke in another is left out. The fill +and stroke of other objects are not compared. Without type among the selected objects it returns the error "select a +text object", and it records no undo step. + ## Shaper Groups `shaper.releaseSource {source, group?}` takes the original shape `source` out of its Shaper Group: the shape becomes a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..e946b2d4a7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -891,6 +891,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Rasterize on a frame of threaded text takes it out of the thread with the text it shows, which the image draws, and the other frames keep the text they hold. When the last frame is rasterized, the text it has no room for goes after the text of the last frame that stays. Type › Create Outlines, Object › Expand and Object › Expand Appearance on a frame of threaded text take it out of the thread with the text it shows, which the outlines draw, and the other frames keep the text they hold. When the last frame is outlined, the text it has no room for goes after the text of the last frame that stays. When Expand Appearance keeps the frame as type in a group with its shadow, outer glow or Crop Marks, the type stays in the thread. The public help on threads ([Create text threads between objects](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html), [Remove or break text threads between objects](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/remove-or-break-text-threads-between-objects.html)) does not describe outlining a threaded frame; this handling is VectorCraft's own behavior. Select › Same › Link Block Series selects every frame of the threads of the selected type; type in no thread selects itself (`select.same.linkBlockSeries`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); selecting several threads at once and type in no thread selecting itself are VectorCraft's own behavior. + Select › Same › Text Fill & Stroke Color selects the type whose characters match both the fill and the stroke of the selected type (`select.same.textFillAndStrokeColor`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); requiring one run of characters to match both is VectorCraft's own behavior. Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. From 5ba035aba4dc834ef59d13d234ed3a929ac335a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 03:45:45 -0800 Subject: [PATCH 257/674] Type: an inline graphic takes its character's manual kerning A manual kerning value on an inline graphic's character was stored and shown but did not move the text after it. The graphic's advance now includes the value, as a letter's does, and in right-to-left horizontal type its art moves right by the value, so the space goes between it and the next character in reading order. Auto and Optical kerning still apply no font pairs to an inline graphic. --- crates/text/src/layout.rs | 5 ++-- crates/text/src/shape.rs | 26 ++++++++++++----- crates/text/src/tests/inline.rs | 50 +++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 73 insertions(+), 9 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index a7665612ce..67b5c3c7c7 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -226,8 +226,9 @@ impl Ctx<'_> { let upright = self.vertical && !self.on_path && g.tcy.is_none() && stands_upright(g); let lead = if upright { 0.0 } else { g.lead }; let local = match &g.inline { - // Inline graphics: art space to glyph space (no font outline). - Some(ib) => Affine::translate((-lead, -g.bshift)) * ib.xf, + // Inline graphics: art space to glyph space (no font outline), moved along the line by + // right-to-left manual kerning as a glyph is. + Some(ib) => Affine::translate((g.kern_shift - lead, -g.bshift)) * ib.xf, // Baseline shift moves the glyph across its line, and Character Rotation then turns it // about its shifted pen position, so the shift is across the line at any rotation. // Right-to-left manual kerning moves that pen position along the line. diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index e2ba0a8a9a..c5f82071d8 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -401,7 +401,7 @@ pub(crate) fn shape_range( let b = bytes.end; if let Some(art) = art { if let Some(face) = db.style_face(st).or_else(|| db.face_covering('a')) { - out.push(inline_glyph(&face, st, art, source_runs.start, a..b, text, level_at(a))); + out.push(inline_glyph(&face, st, art, source_runs.start, a..b, text, level_at(a), feats.vertical)); } continue; } @@ -795,10 +795,21 @@ fn shaping_script(c: char) -> Script { /// /// The art is scaled uniformly to `scale` x the font size tall, its left edge on the pen and its /// vertical centre on the middle of the cap height raised by the inline's shift (see -/// [`InlineArt`]). Its advance is the scaled art width plus tracking; the glyph's ascent and -/// descent grow to the art's extent so a tall graphic opens up its line. A missing symbol takes a -/// square of the same height and draws nothing. -fn inline_glyph(face: &Arc, st: &CharStyle, art: &InlineArt, run: usize, range: Range, text: &str, level: Level) -> SGlyph { +/// [`InlineArt`]). Its advance is the scaled art width plus tracking and its character's manual +/// kerning, which right to left in horizontal type also moves the art right by the value, as it +/// moves a letter's glyph. The glyph's ascent and descent grow to the art's extent so a tall +/// graphic opens up its line. A missing symbol takes a square of the same height and draws nothing. +#[allow(clippy::too_many_arguments)] +fn inline_glyph( + face: &Arc, + st: &CharStyle, + art: &InlineArt, + run: usize, + range: Range, + text: &str, + level: Level, + vertical: bool, +) -> SGlyph { let size = if st.size.is_finite() { st.size.max(0.0) } else { 0.0 }; let vs = if st.v_scale.is_finite() { st.v_scale / 100.0 } else { 1.0 }; let km = size / face.upem; @@ -815,7 +826,8 @@ fn inline_glyph(face: &Arc, st: &CharStyle, art: &InlineArt, run: usiz _ => (kurbo::Affine::IDENTITY, h, None), }; let tracking = st.tracking / 1000.0 * size; - let adv = width + if tracking.is_finite() { tracking } else { 0.0 }; + let manual_kern = st.kerning.map(|v| v / 1000.0 * size).filter(|k| k.is_finite()).unwrap_or(0.0); + let adv = width + if tracking.is_finite() { tracking } else { 0.0 } + manual_kern; SGlyph { face: face.clone(), gid: 0, @@ -825,7 +837,7 @@ fn inline_glyph(face: &Arc, st: &CharStyle, art: &InlineArt, run: usiz adv: if adv.is_finite() { adv } else { 0.0 }, dx: 0.0, dy: 0.0, - kern_shift: 0.0, + kern_shift: if level.is_rtl() && !vertical { manual_kern } else { 0.0 }, // Not used to draw (the art has its own transform), but they make the glyph's em box // its run's em: Character Alignment and Top-to-Top leading treat an inline graphic as a // character of its run's size, whatever its scale (see `layout::glyph_em`). diff --git a/crates/text/src/tests/inline.rs b/crates/text/src/tests/inline.rs index ebc90351dd..d492608cc5 100644 --- a/crates/text/src/tests/inline.rs +++ b/crates/text/src/tests/inline.rs @@ -248,6 +248,56 @@ fn inline_art_in_a_right_to_left_paragraph_is_placed_by_the_bidi_reordering() { assert!(inline_rtl && inline < first); } +/// A manual kerning value on an inline graphic's character spaces it from the next character in +/// reading order by the distance the same value spaces a letter of its size: left to right, right +/// to left and down a vertical column. The character before it keeps its place, and a graphic's 0 +/// sets the text as no value does. +#[test] +fn manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter() { + let db = FontDb::global(); + // `before`, then the graphic (or `letter` in its place) with `kerning`, then `after`. + let set = |before: &str, letter: Option<&str>, after: &str, kerning: Option, vertical: bool| { + let mut t = TextObject::point(Point::ZERO, before, style(20.0)); + let st = CharStyle { kerning, ..style(20.0) }; + t.runs.push(match letter { + Some(c) => TextRun::new(c, st), + None => TextRun::inline(art(1.0), st), + }); + t.runs.push(TextRun::new(after, style(20.0))); + t.vertical = vertical; + let l = layout(db, &t); + let ink = |run: usize, last: bool| { + let mut g: Vec<&PositionedGlyph> = l.glyphs.iter().filter(|g| g.run == run).collect(); + g.sort_by_key(|g| g.byte); + let g = if last { g.last() } else { g.first() }; + g.expect("glyph").xf * Point::ZERO + }; + assert_eq!(l.inlines.len(), usize::from(letter.is_none())); + // Distance along the line: across the page, or down the column. + let along = |a: Point, b: Point| if vertical { (b.y - a.y).abs() } else { (b.x - a.x).abs() }; + let (previous, middle, next) = (ink(0, true), ink(1, false), ink(2, false)); + (along(previous, middle), along(middle, next), l.glyphs.iter().map(|g| (g.origin, g.advance)).collect::>()) + }; + for (before, letter, after, vertical) in [("A", "X", "B", false), ("אב", "ג", "דה", false), ("ab", "x", "cd", true)] { + for letter in [None, Some(letter)] { + let (before_plain, after_plain, plain) = set(before, letter, after, Some(0.0), vertical); + let (before_kerned, after_kerned, _) = set(before, letter, after, Some(200.0), vertical); + // 200/1000 em of 20 pt. + assert!((after_kerned - after_plain - 4.0).abs() < 1e-6, "{before:?} {letter:?}: {after_plain} -> {after_kerned}"); + assert!((before_kerned - before_plain).abs() < 1e-6, "{before:?} {letter:?}: {before_plain} -> {before_kerned}"); + if letter.is_some() { + // A letter's 0 also turns off its font's kerning pairs; a graphic has none. + continue; + } + let (_, _, none) = set(before, letter, after, None, vertical); + assert!( + plain.iter().zip(&none).all(|(a, b)| (a.0 - b.0).hypot() < 1e-9 && (a.1 - b.1).abs() < 1e-9), + "{before:?} {letter:?}: 0 sets the text as no value does" + ); + } + } +} + /// Character Alignment: an inline graphic's em box is its run's, whatever its scale. It moves with /// its run's text when that is smaller than the line's largest characters, and a big graphic in /// small text doesn't make its line's small characters move. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..434e5c1efd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -875,6 +875,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own. Optical keeps its mode across cosmetic style runs. Choosing Optical clears manual pair values, as Auto does, and leaves additive tracking intact; a manual value typed afterwards replaces that pair's correction ([Adjust kerning and tracking](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-kerning-and-tracking.html)). Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) ("Kerning is the process of adding or subtracting space between specific pairs of characters."). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. +- **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). From 750c34c2470f2805f2127966cfbebbcea68516ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 04:35:56 -0800 Subject: [PATCH 258/674] Recolor Artwork: the Edit tab shows the colors on a smooth wheel, a segmented wheel or as color bars Buttons beside the Edit tab's wheel switch between the smooth color wheel, a segmented wheel of solid patches (24 hues by 5 saturations, its markers moving as freely as on the smooth wheel) and color bars: one solid bar per recolored color in row order, where a click selects a bar's row for the color sliders and a drag moves the row without changing a color. The dialog opens on the smooth wheel and keeps the choice while it is open; the dialog field is `display` (`smooth`, `segmented`, `bars`). --- crates/ui-egui/src/dialogs/recolor.rs | 116 ++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/tests/recolor.rs | 233 ++++++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 3 +- crates/ui-egui/src/widgets/color.rs | 59 ++++++- docs/control-protocol.md | 5 +- docs/target-app-parity.md | 1 + 32 files changed, 513 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 70e69a78c5..5efa3ef6e3 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -15,7 +15,11 @@ //! saturation wheel with a marker per new colour (drag one; with linked handles they all turn and //! scale together), a brightness slider, the harmony rules, and the color sliders with their mode //! menu, whose Global Adjust shows Saturation, Brightness, Temperature and Luminosity (-100% to -//! 100%, 0% changes nothing), which change every new color at once. The preset menu sets up a 1, 2 or 3 +//! 100%, 0% changes nothing), which change every new color at once. The buttons beside the wheel +//! show the new colors on the smooth wheel, on a segmented wheel (solid patches of 24 hues by 5 +//! saturations; its markers move as freely) or as color bars (one per new color, in row order: click +//! one to select it for the sliders, drag one to move its row, which changes no color); the dialog +//! opens on the smooth wheel. The preset menu sets up a 1, 2 or 3 //! colour job or a library. Opened on a colour group (Edit or Apply Color Group), OK also rewrites //! the group with the new colours (renamed by `groupName`); without art only the group changes. //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new @@ -28,8 +32,8 @@ //! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for //! a gray and Tint for a spot color; `global`: Global Adjust, on the Edit tab), `globalAdjust` //! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s -//! `globalAdjust` in every slider mode). Changing `colors`, a preserve flag or `limitTo` reduces -//! the rows again. +//! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`; +//! unset: `smooth`). Changing `colors`, a preserve flag or `limitTo` reduces the rows again. use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -65,6 +69,9 @@ const CMD: &str = "recolor.apply"; const CURRENT_W: f32 = 250.0; /// Diameter of the Edit tab's colour wheel. const WHEEL: f32 = 220.0; +/// Height of the Edit tab's color bars area (the wheel with its Brightness slider), and of a bar. +const BARS_H: f32 = WHEEL + 31.0; +const BAR_H: f32 = 22.0; /// Height of the rows table, and of either tab (so switching tabs doesn't resize the dialog). const TABLE_H: f32 = 182.0; const TAB_H: f32 = 400.0; @@ -971,7 +978,29 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value }); ui.add_space(8.0); let colors: Vec = active.iter().filter_map(|&i| to_color(&rows[i])).collect(); - let w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, base.and_then(|b| active.iter().position(|&i| i == b))); + let marked = base.and_then(|b| active.iter().position(|&i| i == b)); + let display = d.str("display"); + let mut w = widgets::WheelResponse::default(); + ui.horizontal(|ui| { + // The display buttons, beside the wheel so the tab keeps its height. + ui.vertical(|ui| { + for (id, icon, tip) in [ + ("smooth", "circle", tl!("Show smooth color wheel")), + ("segmented", "dc-polar-grid", tl!("Show segmented color wheel")), + ("bars", "dc-list-view", tl!("Show color bars")), + ] { + let on = display == id || (id == "smooth" && !matches!(display.as_str(), "segmented" | "bars")); + if widgets::icon_button(ui, icon, tip, on, 24.0).clicked() { + d.fields.insert("display".into(), json!(id)); + } + } + }); + ui.vertical(|ui| match display.as_str() { + "segmented" => w = widgets::segmented_wheel(ui, "recolor-wheel", WHEEL, &colors, marked), + "bars" => changed |= color_bars(ui, d, rows, &active, base), + _ => w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, marked), + }); + }); if let Some(k) = w.pressed { d.fields.insert("__sel".into(), json!([active[k]])); } @@ -1023,6 +1052,85 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value changed } +/// The Edit tab's color bars: a solid bar per row of `active` with its new color, in row order, the +/// base row's framed, scrolling past the wheel's height. A click on a bar selects its row (the +/// sliders under it edit that row's new color); a drag moves the bar's row to where the line under +/// the pointer shows, keeping every new color. Returns true when the rows moved. +fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize], base: Option) -> bool { + let t = Tokens::get(ui.ctx()); + let mut rects: Vec = Vec::with_capacity(active.len()); + let (mut dragging, mut released, mut dropped) = (None, None, None); + // The area is given its full height first: in the row beside the display buttons a scroll area + // alone is only as tall as the room the row has. + let area = vec2(ui.available_width(), BARS_H); + ui.allocate_ui_with_layout(area, egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(area); + egui::ScrollArea::vertical().id_salt("recolor-bars").max_height(BARS_H).show(ui, |ui| { + ui.set_min_height(BARS_H); + ui.set_width(ui.available_width()); + if active.is_empty() { + ui.add_space(8.0); + widgets::dim_label(ui, tl!("No colors to recolor (preserved colors are left out).")); + } + for (n, &i) in active.iter().enumerate() { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width() - 4.0, BAR_H), Sense::click_and_drag()); + chip(ui, r, to_color(&rows[i]).unwrap_or_default(), false); + if Some(i) == base { + ui.painter().rect_stroke(r, 2.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); + } + let name = format!("{} {}", tl!("Color"), i + 1); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &name)); + if resp.clicked() || resp.drag_started() { + d.fields.insert("__sel".into(), json!([i])); + } + if resp.dragged() { + dragging = Some(n); + } + if resp.drag_stopped() { + released = Some(n); + } + rects.push(r); + resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default()); + } + // The place a dragged bar goes: before the first bar whose middle is below the pointer. + let at = ui.input(|i| i.pointer.latest_pos()).map(|p| rects.iter().filter(|r| r.center().y < p.y).count()); + if let (Some(n), Some(to)) = (dragging, at) + && to != n + && to != n + 1 + { + let y = rects.get(to).map_or_else(|| rects.last().map_or(0.0, |r| r.bottom() + 1.5), |r| r.top() - 1.5); + let x = rects.first().map_or(ui.max_rect().x_range(), |r| r.x_range()); + ui.painter().hline(x, y, egui::Stroke::new(2.0, t.accent)); + } + dropped = released.zip(at); + }); + }); + let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return false }; + d.fields.insert("__sel".into(), json!([moved])); + // The slider values held are those of a row index that may now hold another row. + d.fields.remove(COMPS); + true +} + +/// Move the row of the `from`th active row (of `active`, ascending row indexes) to before the +/// `to`th, or after the last for `active.len()`; the rows between shift by one. Returns the row's +/// new index, or `None` when it stays where it is. +fn move_bar(rows: &mut [Value], active: &[usize], from: usize, to: usize) -> Option { + let &src = active.get(from)?; + if to == from || to == from + 1 || to > active.len() { + return None; + } + if to > from { + let dst = active[to - 1]; + rows[src..=dst].rotate_left(1); + Some(dst) + } else { + let dst = active[to]; + rows[dst..=src].rotate_right(1); + Some(dst) + } +} + /// Give the rows `active` the colours of `rule` from the base colour `b` of row `base` (the base row /// first, then the others in order, the rule's colours repeating), each in its row's model. A row /// whose new color changes loses its tint. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 073f577150..643a878e77 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1340,6 +1340,10 @@ font-technology Variable Променливи Hard Light Твърда светлина Hard Mix Твърдо смесване Harmony Rules: Правила за хармония: + Segmented color wheel Сегментирано цветово колело + Show smooth color wheel Показване на плавно цветово колело + Show segmented color wheel Показване на сегментирано цветово колело + Show color bars Показване на цветни ленти Harmony Sets Набори от хармонии Height Височина Height: Височина: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 80e02fbe46..3f58c09f93 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2625,6 +2625,10 @@ digits Malayalam Malajalam Current Colors Trenutne boje Current Colors (0) Trenutne boje (0) Harmony Rules: Pravila harmonije: + Segmented color wheel Segmentirani kotač boja + Show smooth color wheel Prikaži glatki kotač boja + Show segmented color wheel Prikaži segmentirani kotač boja + Show color bars Prikaži trake boja Harmony Rules Pravila harmonije Keep this row's colors (exclude) Zadrži boje ovog reda (isključi) Limit to Library: Ograniči na biblioteku: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b6985fb130..7cfebef474 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1804,6 +1804,10 @@ digits Malayalam Malaiàlam Hard Mix Mescla dura Harmony Rules Regles d’harmonia Harmony Rules: Regles d’harmonia: + Segmented color wheel Roda de color segmentada + Show smooth color wheel Mostra la roda de color contínua + Show segmented color wheel Mostra la roda de color segmentada + Show color bars Mostra les barres de color Harmony Sets Conjunts d’harmonia HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 367be32b2c..7e228a046c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2656,6 +2656,10 @@ digits Malayalam Malajálamské Current Colors Aktuální barvy Current Colors (0) Aktuální barvy (0) Harmony Rules: Pravidla harmonie: + Segmented color wheel Segmentované barevné kolo + Show smooth color wheel Zobrazit plynulé barevné kolo + Show segmented color wheel Zobrazit segmentované barevné kolo + Show color bars Zobrazit barevné pruhy Harmony Rules Pravidla harmonie Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit) Limit to Library: Omezit na knihovnu: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7b077a50ad..ded431751d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2443,6 +2443,10 @@ digits Malayalam Malayalam Current Colors Aktuelle farver Current Colors (0) Aktuelle farver (0) Harmony Rules: Harmoniregler: + Segmented color wheel Segmenteret farvehjul + Show smooth color wheel Vis glat farvehjul + Show segmented color wheel Vis segmenteret farvehjul + Show color bars Vis farvebjælker Harmony Rules Harmoniregler Keep this row's colors (exclude) Behold farverne i denne række (ekskludér) Limit to Library: Begræns til bibliotek: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c87b45d229..885b6b3d15 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1371,6 +1371,10 @@ file-filter Templates Vorlagen Hard Light Hartes Licht Hard Mix Hart mischen Harmony Rules: Harmonieregeln: + Segmented color wheel Segmentierter Farbkreis + Show smooth color wheel Stufenlosen Farbkreis anzeigen + Show segmented color wheel Segmentierten Farbkreis anzeigen + Show color bars Farbbalken anzeigen Harmony Sets Harmoniesätze Height Höhe Height: Höhe: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 615e0e6ee0..8b199fdf1e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1310,6 +1310,10 @@ font-technology Variable Μεταβλητές Hard Light Έντονο φως Hard Mix Έντονη ανάμειξη Harmony Rules: Κανόνες χρωματικής αρμονίας: + Segmented color wheel Τμηματοποιημένος χρωματικός τροχός + Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού + Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού + Show color bars Εμφάνιση χρωματικών ράβδων Harmony Sets Σύνολα χρωματικής αρμονίας Height Ύψος Height: Ύψος: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c4d4a196b6..464a253e7f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1389,6 +1389,10 @@ font-technology Variable Variables Hard Light Luz fuerte Hard Mix Mezcla definida Harmony Rules: Reglas de armonía: + Segmented color wheel Rueda de color segmentada + Show smooth color wheel Mostrar rueda de color continua + Show segmented color wheel Mostrar rueda de color segmentada + Show color bars Mostrar barras de color Harmony Sets Conjuntos de armonía Height Altura Height: Altura: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7d571168f5..ece9300775 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2600,6 +2600,10 @@ digits Malayalam Malajalam Current Colors Nykyiset värit Current Colors (0) Nykyiset värit (0) Harmony Rules: Harmoniasäännöt: + Segmented color wheel Segmentoitu väriympyrä + Show smooth color wheel Näytä liukuva väriympyrä + Show segmented color wheel Näytä segmentoitu väriympyrä + Show color bars Näytä väripalkit Harmony Rules Harmoniasäännöt Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois) Limit to Library: Rajoita kirjastoon: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4372280dbd..742efb538f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1382,6 +1382,10 @@ font-technology Variable Variables Handles Poignées Hard Light Lumière crue Hard Mix Mélange maximal + Segmented color wheel Roue chromatique segmentée + Show smooth color wheel Afficher la roue chromatique continue + Show segmented color wheel Afficher la roue chromatique segmentée + Show color bars Afficher les barres de couleur Harmony Rules: Règles d’harmonie : Harmony Sets Ensembles d’harmonies Height Hauteur diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9890ecf5a9..e45e377753 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1771,6 +1771,10 @@ file-filter Templates Sablonok Hard Mix Kemény keverés Harmony Rules Harmóniaszabályok Harmony Rules: Harmóniaszabályok: + Segmented color wheel Szegmentált színkör + Show smooth color wheel Folytonos színkör megjelenítése + Show segmented color wheel Szegmentált színkör megjelenítése + Show color bars Színsávok megjelenítése Harmony Sets Harmóniakészletek HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index d8ceeacad7..c7ec63e0b9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2443,6 +2443,10 @@ digits Malayalam Malayalam Current Colors Warna saat ini Current Colors (0) Warna saat ini (0) Harmony Rules: Aturan harmoni: + Segmented color wheel Roda warna bersegmen + Show smooth color wheel Tampilkan roda warna halus + Show segmented color wheel Tampilkan roda warna bersegmen + Show color bars Tampilkan bilah warna Harmony Rules Aturan harmoni Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan) Limit to Library: Batasi ke pustaka: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1f6ffb4cf5..152801c729 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1401,6 +1401,10 @@ file-filter Templates Modelli Hard Light Luce intensa Hard Mix Miscela intensa Harmony Rules: Regole di armonia: + Segmented color wheel Ruota dei colori segmentata + Show smooth color wheel Mostra ruota dei colori continua + Show segmented color wheel Mostra ruota dei colori segmentata + Show color bars Mostra barre di colore Harmony Sets Gruppi di armonia Height Altezza Height: Altezza: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3d6849e46c..980727883d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1725,6 +1725,10 @@ digits Malayalam マラヤーラム数字 Hard Light ハードライト Hard Mix ハードミックス Harmony Rules: ハーモニールール: + Segmented color wheel 分割カラーホイール + Show smooth color wheel 滑らかなカラーホイールを表示 + Show segmented color wheel 分割カラーホイールを表示 + Show color bars カラーバーを表示 Height 高さ Height: 高さ: Help › Search Commands… ヘルプ › コマンドを検索… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1a01580e2e..ac304ea5a4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2334,6 +2334,10 @@ digits Malayalam მალაიალამური Colors: ფერები: Current Colors ({total}) მიმდინარე ფერები ({total}) Harmony Rules: ჰარმონიის წესები: + Segmented color wheel სეგმენტირებული ფერთა წრე + Show smooth color wheel გლუვი ფერთა წრის ჩვენება + Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება + Show color bars ფერთა ზოლების ჩვენება Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა) Limit to Library: ბიბლიოთეკით შეზღუდვა: Link harmony colors ჰარმონიის ფერების დაკავშირება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5f24419728..2a2d4dc90c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1715,6 +1715,10 @@ digits Malayalam 말라얄람어 Hard Light 하드 라이트 Hard Mix 하드 믹스 Harmony Rules: 하모니 규칙: + Segmented color wheel 분할 색상환 + Show smooth color wheel 부드러운 색상환 표시 + Show segmented color wheel 분할 색상환 표시 + Show color bars 색상 막대 표시 Height 높이 Height: 높이: Help › Search Commands… 도움말 › 명령 검색… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d7ccca2114..65cb8331d5 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2457,6 +2457,10 @@ digits Malayalam Malayalam Current Colors Huidige kleuren Current Colors (0) Huidige kleuren (0) Harmony Rules: Harmonieregels: + Segmented color wheel Gesegmenteerd kleurenwiel + Show smooth color wheel Vloeiend kleurenwiel tonen + Show segmented color wheel Gesegmenteerd kleurenwiel tonen + Show color bars Kleurbalken tonen Harmony Rules Harmonieregels Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten) Limit to Library: Beperken tot bibliotheek: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index be0a2a24b4..43d40f88c1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2566,6 +2566,10 @@ digits Malayalam Malajalam Colors: Kolory: Current Colors ({total}) Bieżące kolory ({total}) Harmony Rules: Reguły harmonii: + Segmented color wheel Segmentowe koło kolorów + Show smooth color wheel Pokaż płynne koło kolorów + Show segmented color wheel Pokaż segmentowe koło kolorów + Show color bars Pokaż paski kolorów Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz) Limit to Library: Ogranicz do biblioteki: Link harmony colors Połącz kolory harmonii diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2f07e53096..c25bee4cd8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1215,6 +1215,10 @@ Hard Light Luz Forte Hard Mix Mistura definida Harmony Rules: Regras de Harmonia: + Segmented color wheel Roda de cores segmentada + Show smooth color wheel Mostrar roda de cores contínua + Show segmented color wheel Mostrar roda de cores segmentada + Show color bars Mostrar barras de cores Harmony Sets Conjuntos de Harmonia Height Altura Height: Altura: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cb6cbd10b9..d639566a7a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1398,6 +1398,10 @@ file-filter Templates Шаблоны Hard Light Жёсткий свет Hard Mix Жёсткое наложение Harmony Rules: Правила гармонии: + Segmented color wheel Сегментированный цветовой круг + Show smooth color wheel Показать плавный цветовой круг + Show segmented color wheel Показать сегментированный цветовой круг + Show color bars Показать цветовые полосы Harmony Sets Наборы гармонии Height Высота Height: Высота: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b8cc549339..e5a0720bcf 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1348,6 +1348,10 @@ font-technology Variable Variabla Hard Light Hårt ljus Hard Mix Hård blandning Harmony Rules: Harmoniregler: + Segmented color wheel Segmenterat färghjul + Show smooth color wheel Visa steglöst färghjul + Show segmented color wheel Visa segmenterat färghjul + Show color bars Visa färgstaplar Harmony Sets Harmoniuppsättningar Height Höjd Height: Höjd: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9009af8ae1..a10a72c993 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1311,6 +1311,10 @@ font-technology Variable Değişken Handles Kollar Hard Light Sert Işık Harmony Rules: Uyum Kuralları: + Segmented color wheel Bölümlü renk tekerleği + Show smooth color wheel Kesintisiz renk tekerleğini göster + Show segmented color wheel Bölümlü renk tekerleğini göster + Show color bars Renk çubuklarını göster Harmony Sets Armoni Setleri Height Yükseklik Height: Yükseklik: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7535b5357c..83484d9d4e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1395,6 +1395,10 @@ file-filter Templates Шаблони Hard Light Жорстке світло Hard Mix Жорстке накладання Harmony Rules: Правила гармонії: + Segmented color wheel Сегментоване колірне коло + Show smooth color wheel Показати плавне колірне коло + Show segmented color wheel Показати сегментоване колірне коло + Show color bars Показати колірні смуги Harmony Sets Набори гармонії Height Висота Height: Висота: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 07852ac9fd..dd00265586 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1610,6 +1610,10 @@ file-filter Templates Mẫu Hard Light Ánh sáng mạnh Hard Mix Trộn cứng Harmony Rules: Quy tắc hài hòa màu: + Segmented color wheel Bánh xe màu phân đoạn + Show smooth color wheel Hiện bánh xe màu liền mạch + Show segmented color wheel Hiện bánh xe màu phân đoạn + Show color bars Hiện các thanh màu Harmony Sets Bộ hài hòa màu Height Chiều cao Height: Chiều cao: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d609725c4e..56cccd8849 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1338,6 +1338,10 @@ file-filter Templates 模板 Hard Light 强光 Hard Mix 实色混合 Harmony Rules: 协调规则: + Segmented color wheel 分段色轮 + Show smooth color wheel 显示平滑色轮 + Show segmented color wheel 显示分段色轮 + Show color bars 显示颜色条 Harmony Sets 色彩调和组 Height 高度 Height: 高度: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 32dbb3ba2b..19e4baad32 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1366,6 +1366,10 @@ file-filter Templates 範本 Hard Light 實光 Hard Mix 實色混合 Harmony Rules: 色彩調和規則: + Segmented color wheel 分段色輪 + Show smooth color wheel 顯示平滑色輪 + Show segmented color wheel 顯示分段色輪 + Show color bars 顯示顏色條 Harmony Sets 色彩調和組 Height 高度 Height: 高度: diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 0e7fe849b2..cb44318cff 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -576,7 +576,10 @@ fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { ("sliderMode", json!("hsb")), ("sliderMode", json!("lab")), ("tab", json!("edit")), + ("display", json!("segmented")), + ("display", json!("bars")), ("sliderMode", json!("global")), + ("display", json!("smooth")), ("sliderMode", json!("rgb")), ("tab", json!("assign")), ] { @@ -939,3 +942,233 @@ fn the_last_edit_color_can_be_selected_edited_and_undone() { assert_eq!(h.state().session.doc().unwrap().doc, before); } } + +/// The height of the open Recolor Artwork dialog. +fn dialog_height(h: &egui_kittest::Harness<'_, VectorcraftApp>) -> f32 { + h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", "recolor")))).unwrap().height() +} + +/// Clicks the Edit tab's display button named `name` and lets the dialog settle. +fn show_display(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) { + h.get_by_role_and_label(egui::accesskit::Role::Button, name).click(); + h.run_steps(6); +} + +/// The Edit tab opens on the smooth color wheel and its buttons switch to the segmented wheel and to +/// the color bars and back: the dialog keeps its size, and the rows and the selected row stay. The +/// choice stays while the dialog is open; the next opening starts on the smooth wheel again. +#[test] +fn the_edit_tab_shows_a_smooth_or_segmented_wheel_or_color_bars() { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]); + set(h.state_mut(), "__sel", json!([1])); + h.run_steps(4); + let (rows, height) = (field(h.state(), "rows"), dialog_height(&h)); + let slider = |h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str| h.query_by_role_and_label(egui::accesskit::Role::Slider, name).is_some(); + let bar = |h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str| h.query_by_role_and_label(egui::accesskit::Role::Button, name).is_some(); + assert!(slider(&h, "Color wheel") && !slider(&h, "Segmented color wheel"), "the smooth wheel first"); + assert!(!bar(&h, "Color 1")); + show_display(&mut h, "Show segmented color wheel"); + assert_eq!(field(h.state(), "display"), json!("segmented")); + assert!(slider(&h, "Segmented color wheel") && !slider(&h, "Color wheel")); + assert_eq!(widget_of_size(&h, vec2(220.0, 220.0)).size(), vec2(220.0, 220.0), "the same size of wheel"); + assert!(slider(&h, "Brightness")); + show_display(&mut h, "Show color bars"); + assert_eq!(field(h.state(), "display"), json!("bars")); + assert!(!slider(&h, "Color wheel") && !slider(&h, "Segmented color wheel")); + assert!(["Color 1", "Color 2", "Color 3"].iter().all(|n| bar(&h, n)), "a bar per color"); + assert_eq!(dialog_height(&h), height, "the bars keep the dialog's height"); + show_display(&mut h, "Show smooth color wheel"); + assert!(slider(&h, "Color wheel")); + assert_eq!(dialog_height(&h), height); + assert_eq!(field(h.state(), "rows"), rows, "switching changes no color"); + assert_eq!(field(h.state(), "__sel"), json!([1]), "and keeps the selected row"); + show_display(&mut h, "Show color bars"); + set(h.state_mut(), "tab", json!("assign")); + h.run_steps(3); + set(h.state_mut(), "tab", json!("edit")); + h.run_steps(3); + assert!(bar(&h, "Color 1"), "the choice stays while the dialog is open"); + let app = h.state_mut(); + dialogs::cancel(app); + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + assert_eq!(field(app, "display"), Value::Null, "a new opening starts on the smooth wheel"); +} + +/// The segmented wheel's patches: 24 hues, centered on red, by 5 saturations, at the brightness asked. +#[test] +fn the_segmented_wheel_has_24_hues_by_5_saturations() { + let seg = |h, s, v| crate::widgets::segment_color(h, s, v).to_hsb(); + let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3); + assert!(near(seg(7.0, 0.95, 1.0), [0.0, 0.9, 1.0]), "{:?}", seg(7.0, 0.95, 1.0)); + assert!(near(seg(8.0, 0.0, 0.5), [15.0, 0.1, 0.5]), "{:?}", seg(8.0, 0.0, 0.5)); + assert!(near(seg(355.0, 1.0, 1.0), [0.0, 0.9, 1.0]), "{:?}", seg(355.0, 1.0, 1.0)); + assert!(near(seg(120.0, 0.5, 1.0), [120.0, 0.5, 1.0]), "{:?}", seg(120.0, 0.5, 1.0)); + let mut patches = std::collections::BTreeSet::new(); + for h in 0..360 { + for s in 0..=100 { + patches.insert(ColorKey::of(&crate::widgets::segment_color(h as f32, s as f32 / 100.0, 1.0)).to_string()); + } + } + assert_eq!(patches.len(), 24 * 5); +} + +/// On the segmented wheel a marker moves as freely as on the smooth one, past patch edges and +/// without snapping to a patch; linked colors turn with it from where the drag started, an excluded +/// row keeps its color, and the smooth wheel shows the result. Its Brightness slider works too. +#[test] +fn a_segmented_wheel_marker_moves_freely() { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200", "rgb 20 160 20"]); + let mut rows = field(h.state(), "rows"); + let green = (0..3).find(|i| rows[*i]["from"] == json!(["rgb 20 160 20"])).unwrap(); + let red = (0..3).find(|i| rows[*i]["from"] == json!(["rgb 200 100 100"])).unwrap(); + rows[green]["exclude"] = json!(true); + set(h.state_mut(), "rows", rows); + set(h.state_mut(), "__sel", json!([red])); + h.run_steps(4); + show_display(&mut h, "Show segmented color wheel"); + let start = new_hsb(h.state()); + let wheel = widget_of_size(&h, vec2(220.0, 220.0)); + let (c, r) = (wheel.center(), 100.0); + let at = |hue: f32, s: f32| c + vec2(hue.to_radians().cos(), -hue.to_radians().sin()) * r * s; + let [hue, s, _] = start[red]; + h.hover_at(at(hue, s)); + h.run_steps(1); + h.drag_at(at(hue, s)); + h.run_steps(1); + // 37° on in small steps, across two patch edges, ending inside a patch away from its center. + for k in 1..=10 { + h.hover_at(at(hue + 3.7 * k as f32, s)); + h.run_steps(1); + } + h.drop_at(at(hue + 37.0, s)); + h.run_steps(2); + let moved = new_hsb(h.state()); + let gap = |a: f32, b: f32| (a - b).rem_euclid(360.0).min((b - a).rem_euclid(360.0)); + let want = (hue + 37.0).rem_euclid(360.0); + assert!(gap(moved[red][0], want) < 1.0, "the marker follows the pointer: {} -> {}", hue, moved[red][0]); + assert!(gap(moved[red][0], (want / 15.0).round() * 15.0) > 2.0, "not snapped to a patch center: {}", moved[red][0]); + let other = 3 - red - green; + assert!((gap(moved[other][0], start[other][0]) - 37.0).abs() < 1.5, "linked: {:?} -> {:?}", start[other], moved[other]); + assert_eq!(field(h.state(), "rows")[green]["to"], json!("rgb 20 160 20"), "the excluded row stays"); + let rows = field(h.state(), "rows"); + show_display(&mut h, "Show smooth color wheel"); + assert_eq!(field(h.state(), "rows"), rows, "the smooth wheel shows the same colors"); + show_display(&mut h, "Show segmented color wheel"); + click_slider(&mut h, "Brightness", 0.25); + assert!((new_hsb(h.state())[red][2] - 0.25).abs() < 0.02, "the Brightness slider: {:?}", new_hsb(h.state())); +} + +/// The rows as `(current colors, new color)` pairs, sorted. +fn row_pairs(app: &VectorcraftApp) -> Vec { + let mut v: Vec = field(app, "rows").as_array().unwrap().iter().map(|r| format!("{} {}", r["from"], r["to"])).collect(); + v.sort(); + v +} + +/// The color bars: one per recolored row (none for an excluded row), the last one selected with a +/// click and edited with the H slider, then dragged to the top, which moves its row and changes no +/// color. Preview shows the edit, Cancel restores the art and OK keeps it as one undo step. +#[test] +fn color_bars_select_edit_and_reorder_the_rows() { + for confirm in [false, true] { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00", "#ffff00"]); + let before = h.state().session.doc().unwrap().doc.clone(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + let mut rows = field(h.state(), "rows"); + rows[1]["exclude"] = json!(true); + set(h.state_mut(), "rows", rows); + set(h.state_mut(), "linked", json!(false)); + set(h.state_mut(), "sliderMode", json!("hsb")); + show_display(&mut h, "Show color bars"); + let bar = |h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str| { + h.query_by_role_and_label(egui::accesskit::Role::Button, name).map(|n| n.rect()) + }; + assert!(bar(&h, "Color 2").is_none(), "no bar for the excluded row"); + let first = bar(&h, "Color 1").expect("a bar per recolored row"); + let last = bar(&h, "Color 4").expect("a bar per recolored row"); + assert!(bar(&h, "Color 3").is_some_and(|r| r.top() > first.bottom() && r.bottom() < last.top()), "in row order"); + h.input_mut().events.extend(press(last.center(), 1)); + h.run_steps(3); + assert_eq!(field(h.state(), "__sel"), json!([3]), "a click selects the bar's row"); + let unedited = field(h.state(), "rows"); + click_slider(&mut h, "H", 0.5); + let edited = field(h.state(), "rows"); + assert_ne!(edited[3]["to"], unedited[3]["to"], "the H slider edits the selected bar's color"); + assert_eq!(&edited.as_array().unwrap()[..3], &unedited.as_array().unwrap()[..3], "and only that one"); + let previewed = h.state().session.doc().unwrap().doc.clone(); + assert_ne!(previewed, before, "the art previews the edit"); + let pairs = row_pairs(h.state()); + let last = bar(&h, "Color 4").unwrap(); + h.hover_at(last.center()); + h.run_steps(1); + h.drag_at(last.center()); + h.run_steps(1); + let top = egui::pos2(last.center().x, first.top() + 2.0); + for k in 1..=8 { + h.hover_at(last.center().lerp(top, k as f32 / 8.0)); + h.run_steps(1); + } + h.drop_at(top); + h.run_steps(3); + let rows = field(h.state(), "rows"); + assert_eq!(rows[0], edited[3], "the dragged row moved to the top: {rows}"); + assert_eq!(rows.as_array().unwrap()[1..], [edited[0].clone(), edited[1].clone(), edited[2].clone()], "the others shift down"); + assert_eq!(row_pairs(h.state()), pairs, "moving a bar changes no color"); + assert_eq!(field(h.state(), "__sel"), json!([0]), "the moved row stays selected"); + assert_eq!(h.state().session.doc().unwrap().doc, previewed, "and the art keeps the same colors"); + h.get_by_label(if confirm { "OK" } else { "Cancel" }).click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + let app = h.state(); + if confirm { + assert_eq!(app.session.doc().unwrap().doc, previewed, "OK keeps the edit"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "as one undo step"); + } else { + assert_eq!(app.session.doc().unwrap().doc, before, "Cancel restores the art"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + } + } +} + +/// Many color bars scroll within the wheel's height, the dialog keeps its height, and the last bar +/// can be reached and selected; with every row excluded the bars area says there is nothing to +/// recolor. +#[test] +fn color_bars_scroll_and_show_when_nothing_is_recolored() { + let colors: Vec = (1..=40).map(|i| format!("#{:06x}", i * 9973)).collect(); + let refs: Vec<&str> = colors.iter().map(String::as_str).collect(); + let mut h = edit_harness(&refs); + let height = dialog_height(&h); + show_display(&mut h, "Show color bars"); + assert_eq!(dialog_height(&h), height, "40 bars keep the dialog's height"); + let first = h.get_by_role_and_label(egui::accesskit::Role::Button, "Color 1").rect(); + let wheel_bottom = first.top() + 251.0; + let last = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.get_by_role_and_label(egui::accesskit::Role::Button, "Color 40").rect(); + assert!(last(&h).top() > wheel_bottom, "the last bar starts out of view: {:?}", last(&h)); + h.input_mut().events.extend([ + Event::PointerMoved(first.center()), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -10000.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.run_steps(12); + let shown = last(&h); + assert!(shown.bottom() <= wheel_bottom + 1.0, "the last bar scrolls into view: {shown:?}"); + assert_eq!(dialog_height(&h), height); + h.input_mut().events.extend(press(shown.center(), 1)); + h.run_steps(3); + assert_eq!(field(h.state(), "__sel"), json!([39])); + let mut rows = field(h.state(), "rows"); + for r in rows.as_array_mut().unwrap() { + r["exclude"] = json!(true); + } + set(h.state_mut(), "rows", rows); + h.run_steps(4); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Color 1").is_none()); + let _ = h.get_by_label("No colors to recolor (preserved colors are left out)."); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b03788da31..e8da10df34 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -35,7 +35,8 @@ pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, pub(crate) use color::pointer_phase; pub use color::{ Live, SliderValue, WheelResponse, channel_slider, channel_slider_named, channel_slider_valued, color_field, color_mesh, color_slider, - color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, region_texture, stepped_area, + color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, region_texture, segment_color, + segmented_wheel, stepped_area, }; pub use drag::{ PanelDrag, RowClick, SwatchRows, apply_row_click, art_drop, doc_preview, drag_ghost, drag_source, drop_target_outline, ghost_row, row_click, diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 1433cbd4cc..bd40e174d8 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -486,6 +486,48 @@ fn wheel_shape(c: Pos2, r: f32, v: f32) -> egui::Shape { egui::Shape::mesh(mesh) } +/// Hue sectors and saturation rings of the [`segmented_wheel`]: patches 15° of hue by 20% +/// saturation wide, the sectors centered on red at 0°. +const WHEEL_SECTORS: u32 = 24; +const WHEEL_RINGS: u32 = 5; + +/// The color of the [`segmented_wheel`] patch that holds hue `h` (degrees) and saturation `s` (0 to +/// 1), at brightness `v`: the hue and saturation at the patch's center. +pub fn segment_color(h: f32, s: f32, v: f32) -> Color { + let step = 360.0 / WHEEL_SECTORS as f32; + let sector = (h.rem_euclid(360.0) / step).round() % WHEEL_SECTORS as f32; + let ring = (s.clamp(0.0, 1.0) * WHEEL_RINGS as f32).floor().min((WHEEL_RINGS - 1) as f32); + Color::from_hsb(sector * step, (ring + 0.5) / WHEEL_RINGS as f32, v) +} + +/// The segmented hue and saturation wheel at brightness `v`: a solid patch per hue sector and +/// saturation ring, in its [`segment_color`]. +fn segmented_wheel_shape(c: Pos2, r: f32, v: f32) -> egui::Shape { + // Points along each patch's arcs. + const ARC: u32 = 4; + let step = 360.0 / WHEEL_SECTORS as f32; + let mut mesh = egui::Mesh::default(); + for ring in 0..WHEEL_RINGS { + let (s0, s1) = (ring as f32 / WHEEL_RINGS as f32, (ring + 1) as f32 / WHEEL_RINGS as f32); + for k in 0..WHEEL_SECTORS { + let h = k as f32 * step; + let col = crate::panels::c32(&segment_color(h, (s0 + s1) / 2.0, v)); + let first = mesh.vertices.len() as u32; + for j in 0..=ARC { + let a = h - step / 2.0 + step * j as f32 / ARC as f32; + mesh.colored_vertex(wheel_pos(c, r, a, s0), col); + mesh.colored_vertex(wheel_pos(c, r, a, s1), col); + } + for j in 0..ARC { + let at = first + 2 * j; + mesh.add_triangle(at, at + 1, at + 3); + mesh.add_triangle(at, at + 3, at + 2); + } + } + } + egui::Shape::mesh(mesh) +} + /// What a [`harmony_wheel`] did this frame. #[derive(Default)] pub struct WheelResponse { @@ -501,6 +543,18 @@ pub struct WheelResponse { /// marker per colour joined to the centre (the selected colour, `base`, larger) and a Brightness /// slider for the selected colour below it. pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { + wheel(ui, id, size, colors, base, false) +} + +/// [`harmony_wheel`] drawn as solid patches (24 hues by 5 saturations, each in its +/// [`segment_color`]). The markers sit at their colors' own hue and +/// saturation, and a drag moves them as freely as on the smooth wheel. +pub fn segmented_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { + wheel(ui, id, size, colors, base, true) +} + +/// [`harmony_wheel`], or with `segmented` [`segmented_wheel`]. +fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option, segmented: bool) -> WheelResponse { let t = Tokens::get(ui.ctx()); let mut out = WheelResponse::default(); let base_hsb = base.and_then(|b| colors.get(b)).map(Color::to_hsb); @@ -510,7 +564,7 @@ pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: O let (rect, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click_and_drag()); let (c, r) = (rect.center(), size / 2.0 - 10.0); let painter = ui.painter_at(rect); - painter.add(wheel_shape(c, r, v.max(0.15))); + painter.add(if segmented { segmented_wheel_shape(c, r, v.max(0.15)) } else { wheel_shape(c, r, v.max(0.15)) }); painter.circle_stroke(c, r, Stroke::new(1.0, t.border)); let at = |col: &Color| { let [h, s, _] = col.to_hsb(); @@ -539,7 +593,8 @@ pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: O let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0); out.moved = Some((i, [Some(h), Some((dv.length() / r).clamp(0.0, 1.0)), None])); } - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), tl!("Color wheel"))); + let name = if segmented { tl!("Segmented color wheel") } else { tl!("Color wheel") }; + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), name)); }); ui.add_space(6.0); ui.horizontal(|ui| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 720bfeed37..3da08ad0f9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -264,7 +264,10 @@ same sliders under the wheel, and its mode menu also has Global Adjust (`sliderM Brightness, Temperature and Luminosity sliders that set `globalAdjust` (`{saturation, brightness, temperature, luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-zero `globalAdjust` as `recolor.apply`'s `globalAdjust` in every slider mode, so one slider changes every recolored color at once and the rows keep their new -colors; colors opened alone are saved as a group with the change. Setting +colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new +colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches, +24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click +selects its row for the sliders and a drag moves the row without changing a color). Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..878c1d4558 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -984,6 +984,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. + - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html): "Select a smooth color wheel, a segmented color wheel, or color bars to display and edit colors"). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. From 52d180910dada87cffa898a168fc0f4bdaa405a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 05:04:46 -0800 Subject: [PATCH 259/674] PDF export: spot inks named All or None print as spot inks In a Separation color space, the colorant name All marks every plate and None marks no plate (ISO 32000-1:2008, 8.6.6.4). A spot swatch with one of those names was written under its own name, so its paint printed on every plate or on none. PDF export now writes such an ink as All Spot or None Spot, numbered All Spot 2, All Spot 3 and on when a spot swatch already has that name, the same rule EPS export uses. The new name is used for fills and strokes, tint shadings, DeviceN gradients, colorized images and the Lab alternates. Registration still writes All. --- crates/pdf/src/export/paint.rs | 40 +++++++++++++++------ crates/pdf/src/tests/output.rs | 64 ++++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 95 insertions(+), 10 deletions(-) diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 06c08bc2dc..e8dfd4a07d 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -36,18 +36,37 @@ impl Exporter<'_> { Some(SeparationSpace::new(SeparationColorant::Custom(ink), alt)) } - /// The ink name of spot swatch `name` and its CMYK equivalent at 100% (a Lab spot color is - /// noted for [`crate::lab_spot`]); `None` when `name` isn't a spot color. + /// The ink name of spot swatch `name` ([`Self::colorant_name`]) and its CMYK equivalent at + /// 100% (a Lab spot color is noted for [`crate::lab_spot`]); `None` when `name` isn't a spot + /// color. pub(super) fn spot_ink(&mut self, name: &str) -> Option<(String, [f32; 4])> { let doc = self.doc; let sw = doc.swatch(name).filter(|s| s.spot)?; let color = doc.linked_color(sw.paint.color()?, true); + let ink = self.colorant_name(&sw.name); if let Color::Lab { l, a, b } = color - && !self.lab_spots.iter().any(|(n, _)| n == name) + && !self.lab_spots.iter().any(|(n, _)| *n == ink) { - self.lab_spots.push((name.to_string(), vectorcraft_color::cms::Lab::new(l, a, b))); + self.lab_spots.push((ink.clone(), vectorcraft_color::cms::Lab::new(l, a, b))); } - Some((sw.name.clone(), self.out.cmyk(&color, self.intent))) + Some((ink, self.out.cmyk(&color, self.intent))) + } + + /// The colorant name spot swatch `name` is written under: its own name, except that `All` + /// (every plate in PDF) and `None` (no plate) become `All Spot` and `None Spot`, numbered + /// `All Spot 2`, `All Spot 3`, … past the names of the document's spot swatches. + fn colorant_name(&self, name: &str) -> String { + if name != "All" && name != "None" { + return name.to_string(); + } + let taken = |c: &str| self.doc.swatches_iter().any(|s| s.spot && s.name == c); + let mut colorant = format!("{name} Spot"); + let mut n = 2; + while taken(&colorant) { + colorant = format!("{name} Spot {n}"); + n += 1; + } + colorant } /// A solid paint, in the Separation colour space at its tint when it's linked to a spot swatch @@ -109,12 +128,13 @@ impl Exporter<'_> { fn spot_of<'s>(doc: &vectorcraft_doc::Document, s: &'s vectorcraft_color::GradientStop) -> Option<&'s str> { s.swatch.as_deref().filter(|n| doc.swatch(n).is_some_and(|w| w.spot)) } - let mut spots: Vec<(String, [f32; 4])> = Vec::new(); + // Each spot ink: its swatch's name, then its colorant name and CMYK equivalent. + let mut spots: Vec<(&str, (String, [f32; 4]))> = Vec::new(); for s in &g.stops { if let Some(n) = spot_of(doc, s) - && !spots.iter().any(|(m, _)| m == n) + && !spots.iter().any(|(m, _)| *m == n) { - spots.push(self.spot_ink(n)?); + spots.push((n, self.spot_ink(n)?)); } } // Each stop's ink coverage: the four process inks, then one tint per spot ink. @@ -123,7 +143,7 @@ impl Exporter<'_> { let mut v = vec![0.0; 4 + spots.len()]; match spot_of(doc, s) { Some(n) => { - let i = spots.iter().position(|(m, _)| m == n)?; + let i = spots.iter().position(|(m, _)| *m == n)?; v[4 + i] = s.tint; } None if self.paper_stop(s) => {} @@ -142,7 +162,7 @@ impl Exporter<'_> { let colorants = process .iter() .map(|&i| Colorant::Process(Process::ALL[i])) - .chain(spots.iter().map(|(name, f)| Colorant::Spot { name: name.clone(), alternate: cmyk::Color::new_f32(f[0], f[1], f[2], f[3]) })); + .chain(spots.iter().map(|(_, (name, f))| Colorant::Spot { name: name.clone(), alternate: cmyk::Color::new_f32(f[0], f[1], f[2], f[3]) })); let Some(space) = DeviceNSpace::new(colorants) else { self.warn("gradients whose spot inks can't share a DeviceN color space are exported without the spot inks"); return None; diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index 36eb939ffd..f7732821c1 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -161,6 +161,70 @@ fn spot_alternates_and_device_n_gradient_inks_are_written_as_the_document_holds_ assert!(text.contains("/C0[0 0 0.75]/C1[0.75 0.04 0]"), "the stops' C75, K4 and 75% Gold are written as they are"); } +/// A spot swatch's Separation space with alternate C0 M20 Y80 K10 under `colorant` (a PDF name). +fn gold_separation(colorant: &str) -> String { + format!("[/Separation{colorant}/DeviceCMYK<>]") +} + +#[test] +fn spot_inks_named_all_or_none_are_written_under_names_of_their_own() { + let solid = |name: &str, color: Color| Paint::Solid { color, swatch: Some(name.into()), tint: 0.5 }; + let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1); + let rect = |d: &mut Document, i: usize, y: f64, paint: Paint, stroke: Paint| { + let l = d.layers[0].id; + let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, y, 140.0, y + 20.0)), Appearance::basic(paint, stroke, 1.0)); + d.insert(Some(l), i, n).unwrap(); + }; + let stop = |offset: f32, ink: &str, tint: f32| { + let mut s = GradientStop::new(offset, gold.tinted(tint)); + s.swatch = Some(ink.into()); + s.tint = tint; + s + }; + let gradient = |stops| Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + for (name, colorant) in [("All", "/All#20Spot"), ("None", "/None#20Spot")] { + let mut d = doc(ColorMode::Cmyk, &[]); + for ink in [name, "Gold"] { + d.swatches.push(Swatch { name: ink.into(), paint: Paint::solid(gold), global: true, spot: true }); + } + // A fill of the spot ink with a Registration stroke, a gradient of the spot ink's tints, + // and a gradient from Gold to the spot ink. + let registration = solid(vectorcraft_color::swatch::REGISTRATION, Color::cmyk(1.0, 1.0, 1.0, 1.0)); + rect(&mut d, 0, 10.0, solid(name, gold), registration); + rect(&mut d, 1, 40.0, gradient(vec![stop(0.0, name, 1.0), stop(1.0, name, 0.25)]), Paint::None); + rect(&mut d, 2, 70.0, gradient(vec![stop(0.0, "Gold", 1.0), stop(1.0, name, 1.0)]), Paint::None); + let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned(); + let spaces = text.matches(&format!("[/Separation{colorant}/")).count(); + assert!(spaces > 0 && text.matches(&gold_separation(colorant)).count() == spaces, "{name}: {text}"); + assert!(!text.contains(&gold_separation(&format!("/{name}"))), "{name} is not the colorant: {text}"); + assert!(text.contains("[/Separation/All/DeviceCMYK<<"), "Registration prints on every plate: {text}"); + assert!(text.contains(&format!("[/DeviceN[/Gold{colorant}]")), "{name}: {text}"); + } + + // A spot swatch already named All Spot keeps its name, and All is numbered past it. + let mut d = doc(ColorMode::Cmyk, &[]); + for name in ["All", "All Spot"] { + d.swatches.push(Swatch { name: name.into(), paint: Paint::solid(gold), global: true, spot: true }); + } + rect(&mut d, 0, 10.0, solid("All", gold), solid("All Spot", gold)); + let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned(); + assert!(text.contains(&gold_separation("/All#20Spot#202")) && text.contains(&gold_separation("/All#20Spot")), "{text}"); +} + +#[test] +fn a_lab_spot_ink_named_all_keeps_its_lab_alternate() { + let mut d = doc(ColorMode::Cmyk, &[]); + let lab = Color::Lab { l: 60.0, a: 40.0, b: 50.0 }; + d.swatches.push(Swatch { name: "All".into(), paint: Paint::solid(lab), global: true, spot: true }); + let fill = Paint::Solid { color: lab, swatch: Some("All".into()), tint: 1.0 }; + let l = d.layers[0].id; + let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Appearance::basic(fill, Paint::None, 0.0)); + d.insert(Some(l), 0, n).unwrap(); + let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned(); + assert!(text.contains("[/Separation/All#20Spot[/Lab<<"), "{text}"); + assert!(!text.contains("[/Separation/All/") && !text.contains("[/Separation/All["), "{text}"); +} + /// The uncompressed PDF of a CMYK document whose rectangle is filled with gradient `stops` /// (Perceptual when `perceptual`), with spot swatch "Gold" (C0 M20 Y80 K10). fn gold_gradient_pdf(stops: Vec, perceptual: bool) -> String { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..23cc1efa36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,6 +1066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning, and a gradient with the Perceptual method is written as an image, without the spot ink. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). + PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). A name returned by the desktop save panel with the extension of a format the save does not write has it replaced with the saved format's: Save As of a new document saves `card.ait` and `card.png` as `card.vectorcraft`, and Save as Template saves `card.pdf` as `card.vctemplate`. An extension that names no format stays part of the name (`notes.v2` is saved as `notes.v2.vectorcraft`). From 8b249f8275dd5f78ffd87197a085817bbecc376b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 05:06:38 -0800 Subject: [PATCH 260/674] Document Info: Objects counts each object once An object with a gradient or a pattern on both its fill and its stroke counted twice in Objects. It now counts once for each paint kind it uses. With Selection Only, a selection that holds a group and an object inside it walked that object twice, so the object counts, the paths' total length and Repeat Objects counted it twice. The walk now visits each object once. --- crates/engine/src/cmd/docinfo.rs | 47 +++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 7131dd9d4d..776b4af979 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -293,8 +293,13 @@ fn info(s: &mut Session, p: &Value) -> Result { // `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order. let mut repeats: Vec = vec![]; let mut repeat_rows: Vec<(String, String)> = vec![]; + // The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once. + let mut seen: BTreeSet = BTreeSet::new(); for r in roots { r.walk(&mut |n| { + if !seen.insert(n.id) { + return; + } let k = match &n.kind { NodeKind::Layer { .. } => None, NodeKind::Group { clip: true, .. } => Some("clipGroups"), @@ -337,13 +342,15 @@ fn info(s: &mut Session, p: &Value) -> Result { if let Some(k) = k { *counts.entry(k).or_default() += 1; } + // The paint kinds this object's fills and strokes use, each once. + let mut kinds = BTreeSet::new(); for item in &n.appearance.items { let paint = match item { vectorcraft_doc::AppearanceItem::Fill(f) => &f.paint, vectorcraft_doc::AppearanceItem::Stroke(s) => &s.paint, }; if let Some(k) = paint_kind(paint) { - *counts.entry(k).or_default() += 1; + kinds.insert(k); } if let Paint::Pattern { pattern, .. } = paint { patterns.insert(pattern.clone()); @@ -354,6 +361,9 @@ fn info(s: &mut Session, p: &Value) -> Result { spot.insert(name.clone()); } } + for k in kinds { + *counts.entry(k).or_default() += 1; + } if n.extras().mask.is_some() { *counts.entry("opacityMasks").or_default() += 1; } @@ -618,6 +628,41 @@ mod tests { assert_eq!(i["sections"][0]["rows"][0], json!(["", "Grid Repeat, 500 rows × 500 columns, 125000 instances"])); } + /// Document Info › Objects counts an object with a gradient or a pattern on both its fill and + /// its stroke once, and with Selection Only a selection that holds a group and an object inside + /// it counts that object once. + #[test] + fn info_counts_each_object_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let square = + |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let tile = square(&mut s, 0.0); + s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap(); + let (g, p) = (square(&mut s, 100.0), square(&mut s, 200.0)); + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"ids": [g], "gradient": gradient})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [g], "gradient": gradient})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots"})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!((i["objects"]["gradients"].as_u64(), i["objects"]["patterns"].as_u64()), (Some(1), Some(1)), "{}", i["objects"]); + // A group of the two squares, selected together with one of them. + s.execute("select.set", &json!({"ids": [g, p]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + for ids in [json!([group, p]), json!([p, group])] { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap(); + let o = &i["objects"]; + assert_eq!( + (o["paths"].as_u64(), o["groups"].as_u64(), o["gradients"].as_u64(), o["patterns"].as_u64()), + (Some(2), Some(1), Some(1), Some(1)), + "{ids}: {o}" + ); + assert!((i["pathLength"].as_f64().unwrap() - 80.0).abs() < 1e-6, "{ids}: {}", i["pathLength"]); + } + } + #[test] fn embedding_permissions_read_from_fs_type() { assert_eq!(embedding_label(0), "embedding allowed"); From 588ff039a94c29aab82f6af4a125f56d1e66fab0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 06:32:52 -0800 Subject: [PATCH 261/674] Type: Tate-chu-yoko offsets in character style definitions stay in range A character style whose Up/Down or Left/Right offset lies past MAX_COORD either way now opens with the nearer end, as text runs already do, so text that takes the style no longer gets the out-of-range offset. An offset within range is not rewritten. --- crates/doc/src/text/object.rs | 4 ++++ crates/engine/src/tests/typescale.rs | 24 ++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 29 insertions(+) diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5ba5669e62..c6a22a29c4 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -435,12 +435,16 @@ impl crate::Document { st.h_scale = num("h_scale").unwrap_or(st.h_scale); st.v_scale = num("v_scale").unwrap_or(st.v_scale); st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift); + st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down); + st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right); st.keep_dimensions_in_range(); let kept = [ ("size", Some(st.size)), ("h_scale", Some(st.h_scale)), ("v_scale", Some(st.v_scale)), ("baseline_shift", Some(st.baseline_shift)), + ("tcyUpDown", Some(st.tcy_up_down)), + ("tcyLeftRight", Some(st.tcy_left_right)), ("leading", st.leading), ]; for (k, v) in kept { diff --git a/crates/engine/src/tests/typescale.rs b/crates/engine/src/tests/typescale.rs index bdfb27f2f9..5bc09827b9 100644 --- a/crates/engine/src/tests/typescale.rs +++ b/crates/engine/src/tests/typescale.rs @@ -271,6 +271,30 @@ fn a_file_with_type_sizes_out_of_range_opens_with_them_in_range() { assert!(b.width().is_finite() && b.height().is_finite(), "{b:?}"); } +/// A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past +/// `MAX_COORD` either way opens with the nearer end, and text that takes the style gets it. An +/// offset within range stays as saved. +#[test] +fn a_file_with_tate_chu_yoko_offsets_out_of_range_in_a_character_style_opens_with_them_in_range() { + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 40, "y": 60, "size": 20, "text": "12"})).unwrap()["id"].as_u64().unwrap()); + let mut d = (*s.doc().unwrap().doc).clone(); + let attrs = json!({"tateChuYoko": true, "tcyUpDown": 1e12, "tcyLeftRight": -1e12}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Far".into(), attrs: attrs.as_object().unwrap().clone() }); + let attrs = json!({"tcyUpDown": 5000, "tcyLeftRight": -3.5}); + d.char_styles.push(vectorcraft_doc::TextStyleDef { name: "Near".into(), attrs: attrs.as_object().unwrap().clone() }); + let data = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)); + s.execute("document.open", &json!({"name": "tcy.vectorcraft", "dataBase64": data})).unwrap(); + let max = vectorcraft_doc::MAX_COORD; + let doc = &s.doc().unwrap().doc; + let fixed = json!({"tateChuYoko": true, "tcyUpDown": max, "tcyLeftRight": -max}); + assert_eq!(doc.char_styles[0].attrs, *fixed.as_object().unwrap()); + assert_eq!(doc.char_styles[1].attrs, *json!({"tcyUpDown": 5000, "tcyLeftRight": -3.5}).as_object().unwrap()); + s.execute("charStyle.apply", &json!({"name": "Far", "id": id.0})).unwrap(); + let t = text(&s, id); + assert_eq!(t.runs.iter().map(|r| (r.style.tcy_up_down, r.style.tcy_left_right)).collect::>(), [(max, -max)]); +} + /// SVG import keeps type sizes outside the Character panel's 0.1 to 1296 pt, and it gives a line /// aligned differently from the one before it an indent, here past the Paragraph panel's 1296 pt. /// A native file of the result opens with the same type. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..31c39ffc71 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -917,6 +917,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. + A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. The Character panel's All Caps, Underline and Strikethrough buttons and its menu's All Caps, Underline, Strikethrough, Proportional Metrics, Tate-chu-yoko and No Break show off while only some of the selected characters have the attribute, and choosing one then turns it on for all of them, as `type.underline` (Cmd+Shift+U) does for underlining; the Character Alignment and Digits submenus check no item while the selected characters differ. `text.setFormat` refuses a value that is not true or false for its on/off attributes, as `text.setRangeStyle` does. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). Isolation mode and opacity mask editing exclude each other ([transparency and blending modes](https://web.archive.org/web/20230102045151/https://helpx.adobe.com/illustrator/using/transparency-blending-modes.html)): in isolation mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Enter Isolation Mode and Object › Perspective › Edit Text are off, the Contextual Task Bar leaves out Isolate, and Quick Actions leave out Isolate Group. From e365c09141f52255495a2cff8dac1ca1c404547a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 07:10:04 -0800 Subject: [PATCH 262/674] Geometry: a projective map's horizon and invertibility checks do not depend on its scale A homography means the same map at any nonzero uniform scale of its entries, but `apply`, `is_invertible` and `inverse` compared w and the determinant with absolute thresholds. A map stored with small entries refused every point and could not be inverted, and a map with large entries drew points past its horizon. - `apply` refuses a point when w is at most 1e-9 times the largest magnitude in the w row. - A map counts as invertible when its determinant is more than 1e-15 times the largest of the six products the determinant sums, taken on a copy rescaled by a power of two. An inverse whose determinant overflows or underflows is taken on that copy. --- crates/geom/src/projective.rs | 116 +++++++++++++++++++++++----------- docs/target-app-parity.md | 1 + 2 files changed, 80 insertions(+), 37 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 80758d3bab..a5ae446a52 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -50,14 +50,16 @@ impl Homography { [m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]] } - /// Map a point; `None` when it lands on or beyond the horizon (w ≤ 0), or when it does not map - /// to a finite page point. + /// Map a point; `None` when it lands on or beyond the horizon (w at most 1e-9 times the largest + /// magnitude in the map's `w` row, so the answer is the same at any scale of the map), or when + /// it does not map to a finite page point. pub fn apply(&self, p: Point) -> Option { let m = &self.0; let x = m[0][0] * p.x + m[0][1] * p.y + m[0][2]; let y = m[1][0] * p.x + m[1][1] * p.y + m[1][2]; let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; - if w <= 1e-9 || !x.is_finite() || !y.is_finite() { + let k = m[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + if w <= 1e-9 * k || !x.is_finite() || !y.is_finite() { return None; } let q = Point::new(x / w, y / w); @@ -70,16 +72,34 @@ impl Homography { + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) } - /// Whether the map is invertible: the magnitude of its determinant is above 1e-15, or, when the + /// Whether the map is invertible: [`Self::scaled_det`] gives a determinant, or, when the /// determinant is not finite, [`Self::inverse`] gives one. fn is_invertible(&self) -> bool { - let d = self.det(); - if d.is_finite() { - return d.abs() > 1e-15; + if self.det().is_finite() { + return self.scaled_det().is_some(); } self.inverse().is_some() } + /// [`Self::scaled`] and its determinant; `None` when the magnitude of that determinant is at + /// most 1e-15 times that of the largest of the six products it sums (a test that gives the + /// same answer at any scale of the map). + fn scaled_det(&self) -> Option<(Self, f64)> { + let s = self.scaled()?; + let m = &s.0; + let terms = [ + m[0][0] * m[1][1] * m[2][2], + m[0][0] * m[1][2] * m[2][1], + m[0][1] * m[1][0] * m[2][2], + m[0][1] * m[1][2] * m[2][0], + m[0][2] * m[1][0] * m[2][1], + m[0][2] * m[1][1] * m[2][0], + ]; + let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); + let d = s.det(); + (d.abs() > 1e-15 * largest).then_some((s, d)) + } + /// The same map with every entry divided by one power of two, chosen so that the largest of the /// six products its determinant sums is at least 1/8 and below 4. `None` when every one of /// those products is 0 or an entry is not finite. @@ -100,36 +120,14 @@ impl Homography { Some(Self(self.0.map(|row| row.map(|v| ldexp(v, -e))))) } - /// Inverse; `None` when the map is not invertible or its inverse has an entry that is not - /// finite. When the determinant is not finite, this is the inverse of [`Self::scaled`] (the - /// exact inverse multiplied by one power of two, which is the same map), and that copy counts - /// as not invertible when the magnitude of its determinant is at most 1e-15 times that of the largest - /// of the six products the determinant sums. + /// Inverse; `None` when [`Self::scaled_det`] counts the map as not invertible or its inverse + /// has an entry that is not finite. When the determinant is not finite or is below the normal + /// range, this is the inverse of [`Self::scaled`] (the exact inverse multiplied by one power of + /// two, which is the same map). pub fn inverse(&self) -> Option { + let (s, sd) = self.scaled_det()?; let d = self.det(); - let (h, d) = if d.is_finite() { - if d.abs() < 1e-15 { - return None; - } - (*self, d) - } else { - let s = self.scaled()?; - let m = &s.0; - let terms = [ - m[0][0] * m[1][1] * m[2][2], - m[0][0] * m[1][2] * m[2][1], - m[0][1] * m[1][0] * m[2][2], - m[0][1] * m[1][2] * m[2][0], - m[0][2] * m[1][0] * m[2][1], - m[0][2] * m[1][1] * m[2][0], - ]; - let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); - let d = s.det(); - if d.abs() <= 1e-15 * largest { - return None; - } - (s, d) - }; + let (h, d) = if d.is_finite() && d.abs() >= f64::MIN_POSITIVE { (*self, d) } else { (s, sd) }; let m = &h.0; let c = |r0: usize, c0: usize, r1: usize, c1: usize| m[r0][c0] * m[r1][c1] - m[r0][c1] * m[r1][c0]; let adj = [ @@ -397,12 +395,56 @@ mod tests { let want = t * far.apply(p).unwrap(); assert!(c.apply(t * p).unwrap().distance(want) <= 1e-9 * want.to_vec2().hypot(), "{c:?}"); } - // A determinant that does not overflow is judged as it is. - assert!(Homography::from_array([1e-6, 0.0, 0.0, 0.0, 1e-6, 0.0, 0.0, 0.0, 1e-6]).is_none()); + // A determinant that does not overflow is judged against the size of the map's entries: + // the identity with every entry 1e-6 is the identity, and two equal rows are not invertible. + let small = [1e-6, 0.0, 0.0, 0.0, 1e-6, 0.0, 0.0, 0.0, 1e-6]; + let q = Homography::from_array(small).unwrap().apply(Point::new(2.0, 3.0)).unwrap(); + assert!(q.distance(Point::new(2.0, 3.0)) < 1e-12); + assert!(Homography::from_array([1e-6, 2e-6, 0.0, 1e-6, 2e-6, 0.0, 0.0, 0.0, 1e-6]).is_none()); assert!(Homography::from_array([f64::NAN; 9]).is_none()); assert!(Homography::from_array([0.0; 9]).is_none()); } + #[test] + fn the_checks_do_not_depend_on_the_scale_of_the_map() { + let times = |h: Homography, f: f64| Homography(h.0.map(|row| row.map(|v| v * f))); + // The same map with its w row's largest entry 1. + let unit = |h: Homography| { + let k = h.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs())); + Homography(h.0.map(|row| row.map(|v| v / k))) + }; + // The horizon of h() is 0.001x + 0.002y + 1 = 0: two points in front of it, one with w of + // about 5e-10 (too close to it to draw), and two beyond it. + let pts = + [Point::new(30.0, -12.0), Point::new(-999.99, 0.0), Point::new(-999.9999995, 0.0), Point::new(-2000.0, 0.0), Point::new(0.0, -600.0)]; + let at_unit: Vec<_> = pts.iter().map(|&p| h().apply(p)).collect(); + assert!(at_unit[0].is_some() && at_unit[1].is_some()); + assert!(at_unit[2..].iter().all(Option::is_none)); + let inv = h().inverse().unwrap(); + // Two equal rows (up to a factor of 2), with entries that are exact in binary. + let flat = Homography([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.25, 0.5, 1.0]]); + assert!(!flat.is_invertible()); + assert_eq!(flat.inverse(), None); + for f in [1e-200, 1e-12, 1e12, 1e200] { + let s = times(h(), f); + for (&p, want) in pts.iter().zip(&at_unit) { + match (s.apply(p), want) { + (Some(q), Some(w)) => assert!(q.distance(*w) <= 1e-6 * w.to_vec2().hypot(), "{f} {p:?}"), + (None, None) => {} + (got, _) => panic!("{f} {p:?}: {got:?}"), + } + } + assert!(s.is_invertible(), "{f}"); + let si = unit(s.inverse().unwrap_or_else(|| panic!("{f}"))); + for (a, b) in si.to_array().iter().zip(unit(inv).to_array()) { + assert!((a - b).abs() <= 1e-9 * b.abs().max(1.0), "{f}: {si:?}"); + } + let sf = times(flat, f); + assert!(!sf.is_invertible(), "{f}"); + assert_eq!(sf.inverse(), None, "{f}"); + } + } + #[test] fn a_product_that_overflows_is_none() { // Each factor is finite and invertible, but the product's first entry is 1e400. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..68ef6787b5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1045,6 +1045,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Move in Perspective (its copy, perpendicular and Snap to Grid choices), Transform in Perspective (its copy), Nudge in Perspective (its ×10 and copy), Draw in Perspective (Snap to Grid), Define Perspective Grid (its reproject choice), Show Perspective Grid, Width Point (Adjust Adjoining Width Points), Liquify (its pen pressure, Simplify and Affect choices) and Puppet Warp (its pins' rest shape) refuse a value other than true, false or null, such as "true", and leave the document and its undo history as they were. Moves and transforms in perspective and Define Perspective Grid with reproject return an error, and leave the document and its undo history as they were, when the projection they would give type or a symbol instance in perspective has a number too large to store. Object › Perspective › Edit Text returns an error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn: when part of it crosses the horizon, or when that view's projection has a number too large to store. Regressions: `a_product_that_overflows_is_none` in `crates/geom/src/projective.rs`, and `moving_type_whose_projection_would_overflow_is_refused` and `edit_text_whose_flat_view_would_overflow_is_refused` in `crates/engine/src/tests/persp_text.rs`. A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens as the same map at a smaller scale (divided by the largest number in its bottom row), so points that overflowed at the stored scale draw, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. + A projection gives the same answers when every one of its numbers is multiplied by the same factor: a point is past its horizon when its w is at most 1e-9 times the largest number in the bottom row, and the projection is invertible when its determinant is more than 1e-15 times the largest of the six products the determinant sums, so a stored projection with very small numbers draws and inverts, and one that cannot be inverted is refused at every scale. Regression: `the_checks_do_not_depend_on_the_scale_of_the_map` in `crates/geom/src/projective.rs`. Create Object Mosaic (its columns and rows), Transform Each (its reference point and Random seed) and Rearrange All Artboards (its columns) refuse a fraction, a negative number or a string, such as 2.5, -1 or "4"; 4.0 counts as 4. Move, Rotate, Scale, Reflect, Shear, Transform Again, Nudge and the Transform panel's values (their copy, Scale Strokes & Effects, Scale Corners, Transform Patterns, Transform Objects and area type options), Align, Distribute and Distribute Spacing (Transform Patterns), Object Properties (visible, locked, Isolate Blending and Opacity & Mask Define Knockout Shape) and Live Shape Properties (Invert Pie, Make Sides Equal and relative rounding) refuse a value other than true, false or null, such as "false", and leave the document as it was. Object Properties (its opacity), Live Shape Properties (corner radius and polygon sides), the Transform panel's reference point and Align, Distribute and Distribute Spacing to an artboard (the artboard's number) refuse a value other than a number or null, such as "50", and leave the document as it was. From bffb4e6e87ce8363d5c4755ca2c25e7dc8035afc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 07:21:32 -0800 Subject: [PATCH 263/674] Geometry: a projective map with entries of very different sizes stays invertible The scale-free determinant test no longer builds a rescaled copy of the map. It forms each of the six determinant products as a mantissa product and an exponent sum and compares their sum with the largest of them, so a map such as diag(1e307, 1e-157, 1e-157), whose rescaled copy overflows, is still invertible and loads from a document. The rescaled copy is built only to invert a map whose determinant is not finite or is below the normal range. --- crates/geom/src/projective.rs | 71 +++++++++++++++++++++++------------ 1 file changed, 46 insertions(+), 25 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index a5ae446a52..73805baf1a 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -72,32 +72,38 @@ impl Homography { + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) } - /// Whether the map is invertible: [`Self::scaled_det`] gives a determinant, or, when the - /// determinant is not finite, [`Self::inverse`] gives one. + /// Whether the map is invertible: [`Self::has_significant_det`], or, when the determinant is + /// not finite, [`Self::inverse`] gives one. fn is_invertible(&self) -> bool { if self.det().is_finite() { - return self.scaled_det().is_some(); + return self.has_significant_det(); } self.inverse().is_some() } - /// [`Self::scaled`] and its determinant; `None` when the magnitude of that determinant is at - /// most 1e-15 times that of the largest of the six products it sums (a test that gives the - /// same answer at any scale of the map). - fn scaled_det(&self) -> Option<(Self, f64)> { - let s = self.scaled()?; - let m = &s.0; - let terms = [ - m[0][0] * m[1][1] * m[2][2], - m[0][0] * m[1][2] * m[2][1], - m[0][1] * m[1][0] * m[2][2], - m[0][1] * m[1][2] * m[2][0], - m[0][2] * m[1][0] * m[2][1], - m[0][2] * m[1][1] * m[2][0], - ]; + /// Whether every entry is finite and the determinant's magnitude is more than 1e-15 times that + /// of the largest of the six products it sums (a test that gives the same answer at any scale + /// of the map). Each product is formed as a mantissa product and an exponent sum, and all six + /// are divided by the power of two of the largest before they are summed, so the largest is at + /// least 1/8 and below 1 and none of them overflows. + fn has_significant_det(&self) -> bool { + if !self.is_finite() { + return false; + } + let f = self.0.map(|row| row.map(frexp)); + // The columns each of the six products takes from rows 0, 1 and 2, and its sign. + let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)]; + let terms = cols.map(|(a, b, c, sign)| { + let (a, b, c) = (f[0][a], f[1][b], f[2][c]); + (sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1) + }); + let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else { + return false; + }; + let terms = terms.map(|(m, x)| ldexp(m, x - e)); let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs())); - let d = s.det(); - (d.abs() > 1e-15 * largest).then_some((s, d)) + let d: f64 = terms.iter().sum(); + d.abs() > 1e-15 * largest } /// The same map with every entry divided by one power of two, chosen so that the largest of the @@ -120,14 +126,17 @@ impl Homography { Some(Self(self.0.map(|row| row.map(|v| ldexp(v, -e))))) } - /// Inverse; `None` when [`Self::scaled_det`] counts the map as not invertible or its inverse - /// has an entry that is not finite. When the determinant is not finite or is below the normal - /// range, this is the inverse of [`Self::scaled`] (the exact inverse multiplied by one power of - /// two, which is the same map). + /// Inverse; `None` when [`Self::has_significant_det`] counts the map as not invertible or its + /// inverse has an entry that is not finite. When the determinant is not finite or is below the + /// normal range, this is the inverse of [`Self::scaled`] (the exact inverse multiplied by one + /// power of two, which is the same map). pub fn inverse(&self) -> Option { - let (s, sd) = self.scaled_det()?; + if !self.has_significant_det() { + return None; + } let d = self.det(); - let (h, d) = if d.is_finite() && d.abs() >= f64::MIN_POSITIVE { (*self, d) } else { (s, sd) }; + let h = if d.is_finite() && d.abs() >= f64::MIN_POSITIVE { *self } else { self.scaled()? }; + let d = h.det(); let m = &h.0; let c = |r0: usize, c0: usize, r1: usize, c1: usize| m[r0][c0] * m[r1][c1] - m[r0][c1] * m[r1][c0]; let adj = [ @@ -443,6 +452,18 @@ mod tests { assert!(!sf.is_invertible(), "{f}"); assert_eq!(sf.inverse(), None, "{f}"); } + // Entries of very different sizes: the determinant is about 1e-7 and every entry of the + // inverse is finite, though one power of two that brings the products near 1 takes the + // first entry past the largest finite number. + let uneven = Homography([[1e307, 0.0, 0.0], [0.0, 1e-157, 0.0], [0.0, 0.0, 1e-157]]); + assert!(uneven.det().is_finite()); + assert_eq!(Homography::from_array(uneven.to_array()), Some(uneven)); + let inv = uneven.inverse().unwrap(); + for p in [Point::new(1e-300, 2.0), Point::new(-3e-299, -0.5)] { + let q = uneven.apply(p).unwrap(); + let back = inv.apply(q).unwrap(); + assert!((back.x - p.x).abs() <= 1e-9 * p.x.abs() && (back.y - p.y).abs() <= 1e-9 * p.y.abs(), "{p:?} {back:?}"); + } } #[test] From b22912b25a237de9f915794a5d297be4b8e14927 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 07:37:37 -0800 Subject: [PATCH 264/674] Geometry: the inverse of a projective map with a tiny determinant keeps its w row When a cofactor of a map with a normal but very small determinant underflows to 0, the inverse formed from the map itself can have a w row of 0, so every point mapped through it is refused. The inverse is now kept only when it is itself invertible, and is otherwise formed from the map divided by a power of two that brings its determinant's products near 1. --- crates/geom/src/projective.rs | 43 ++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 73805baf1a..6fe0cfdce6 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -126,18 +126,31 @@ impl Homography { Some(Self(self.0.map(|row| row.map(|v| ldexp(v, -e))))) } - /// Inverse; `None` when [`Self::has_significant_det`] counts the map as not invertible or its - /// inverse has an entry that is not finite. When the determinant is not finite or is below the - /// normal range, this is the inverse of [`Self::scaled`] (the exact inverse multiplied by one - /// power of two, which is the same map). + /// Inverse; `None` when [`Self::has_significant_det`] counts the map as not invertible. The + /// inverse is formed from the map itself when its determinant is finite and in the normal + /// range, and is kept when every entry is finite and it passes [`Self::has_significant_det`]. + /// Otherwise it is the inverse of [`Self::scaled`] (the exact inverse multiplied by one power + /// of two, which is the same map), and `None` when that one fails the same checks. pub fn inverse(&self) -> Option { if !self.has_significant_det() { return None; } let d = self.det(); - let h = if d.is_finite() && d.abs() >= f64::MIN_POSITIVE { *self } else { self.scaled()? }; - let d = h.det(); - let m = &h.0; + if d.is_finite() + && d.abs() >= f64::MIN_POSITIVE + && let Some(inv) = self.adjugate_inverse() + { + return Some(inv); + } + self.scaled()?.adjugate_inverse() + } + + /// The adjugate divided by the determinant; `None` when an entry is not finite or the result + /// fails [`Self::has_significant_det`] (a cofactor that underflows to 0 can leave a whole row + /// at 0). + fn adjugate_inverse(&self) -> Option { + let d = self.det(); + let m = &self.0; let c = |r0: usize, c0: usize, r1: usize, c1: usize| m[r0][c0] * m[r1][c1] - m[r0][c1] * m[r1][c0]; let adj = [ [c(1, 1, 2, 2), -c(0, 1, 2, 2), c(0, 1, 1, 2)], @@ -150,11 +163,9 @@ impl Homography { out[r][k] = v / d; } } - if out.iter().flatten().any(|v| !v.is_finite()) { - return None; - } + let out = Self(out); // H⁻¹·(x, y, 1) = (u, v, 1)/w_H, so points in front of the camera keep w > 0. - Some(Self(out)) + out.has_significant_det().then_some(out) } /// `self ∘ other`: `other` first. @@ -464,6 +475,16 @@ mod tests { let back = inv.apply(q).unwrap(); assert!((back.x - p.x).abs() <= 1e-9 * p.x.abs() && (back.y - p.y).abs() <= 1e-9 * p.y.abs(), "{p:?} {back:?}"); } + // A normal determinant (1e-200) whose cofactor 1e-200 · 1e-200 is below the smallest + // positive f64: the inverse still has a w row that is not 0. + let tiny = Homography([[1e-200, 0.0, 0.0], [0.0, 1e-200, 0.0], [0.0, 0.0, 1e200]]); + assert_eq!(Homography::from_array(tiny.to_array()), Some(tiny)); + let inv = tiny.inverse().unwrap(); + for p in [Point::new(1e300, -2e299), Point::new(-4e299, 5e300)] { + let q = tiny.apply(p).unwrap(); + let back = inv.apply(q).unwrap(); + assert!((back.x - p.x).abs() <= 1e-9 * p.x.abs() && (back.y - p.y).abs() <= 1e-9 * p.y.abs(), "{p:?} {back:?}"); + } } #[test] From d1fb8e540cfc176685eaa025db24d2041d866fcc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 07:45:10 -0800 Subject: [PATCH 265/674] Geometry: a projective map with entries far apart in size keeps its inverse The inverse holds every cofactor and the determinant as a mantissa and a power of two, and forms each entry from their quotient. A map such as diag(1e-300, 1e300, 1e-300), which counts as invertible, now gets its inverse diag(1e300, 1e-300, 1e300) instead of none. --- crates/geom/src/projective.rs | 68 +++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 18 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 6fe0cfdce6..baf0570651 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -127,17 +127,15 @@ impl Homography { } /// Inverse; `None` when [`Self::has_significant_det`] counts the map as not invertible. The - /// inverse is formed from the map itself when its determinant is finite and in the normal - /// range, and is kept when every entry is finite and it passes [`Self::has_significant_det`]. - /// Otherwise it is the inverse of [`Self::scaled`] (the exact inverse multiplied by one power - /// of two, which is the same map), and `None` when that one fails the same checks. + /// inverse is formed from the map itself when its determinant is finite, and is kept when every + /// entry is finite and it passes [`Self::has_significant_det`]. Otherwise it is the inverse of + /// [`Self::scaled`] (the exact inverse multiplied by one power of two, which is the same map), + /// and `None` when that one fails the same checks. pub fn inverse(&self) -> Option { if !self.has_significant_det() { return None; } - let d = self.det(); - if d.is_finite() - && d.abs() >= f64::MIN_POSITIVE + if self.det().is_finite() && let Some(inv) = self.adjugate_inverse() { return Some(inv); @@ -145,22 +143,35 @@ impl Homography { self.scaled()?.adjugate_inverse() } - /// The adjugate divided by the determinant; `None` when an entry is not finite or the result - /// fails [`Self::has_significant_det`] (a cofactor that underflows to 0 can leave a whole row - /// at 0). + /// The adjugate divided by the determinant; `None` when an entry is not finite, the + /// determinant is 0, or the result fails [`Self::has_significant_det`]. Every cofactor and the + /// determinant are held as a mantissa and a power of two, so an entry of the result is lost + /// only when that entry itself is beyond the range of `f64`. fn adjugate_inverse(&self) -> Option { - let d = self.det(); - let m = &self.0; - let c = |r0: usize, c0: usize, r1: usize, c1: usize| m[r0][c0] * m[r1][c1] - m[r0][c1] * m[r1][c0]; + if !self.is_finite() { + return None; + } + let f = self.0.map(|row| row.map(frexp)); + let mul = |a: (f64, i32), b: (f64, i32)| (a.0 * b.0, a.1 + b.1); + let c = |r0: usize, c0: usize, r1: usize, c1: usize| { + let (a, b) = (mul(f[r0][c0], f[r1][c1]), mul(f[r0][c1], f[r1][c0])); + split_sum(&[a, (-b.0, b.1)]) + }; + let neg = |(m, e): (f64, i32)| (-m, e); let adj = [ - [c(1, 1, 2, 2), -c(0, 1, 2, 2), c(0, 1, 1, 2)], - [-c(1, 0, 2, 2), c(0, 0, 2, 2), -c(0, 0, 1, 2)], - [c(1, 0, 2, 1), -c(0, 0, 2, 1), c(0, 0, 1, 1)], + [c(1, 1, 2, 2), neg(c(0, 1, 2, 2)), c(0, 1, 1, 2)], + [neg(c(1, 0, 2, 2)), c(0, 0, 2, 2), neg(c(0, 0, 1, 2))], + [c(1, 0, 2, 1), neg(c(0, 0, 2, 1)), c(0, 0, 1, 1)], ]; + // The determinant expanded along the first row, as `det` sums it. + let (dm, de) = split_sum(&[mul(f[0][0], adj[0][0]), mul(f[0][1], adj[1][0]), mul(f[0][2], adj[2][0])]); + if dm == 0.0 { + return None; + } let mut out = [[0.0; 3]; 3]; for (r, row) in adj.iter().enumerate() { - for (k, v) in row.iter().enumerate() { - out[r][k] = v / d; + for (k, (m, e)) in row.iter().enumerate() { + out[r][k] = ldexp(m / dm, e - de); } } let out = Self(out); @@ -269,6 +280,17 @@ fn frexp(v: f64) -> (f64, i32) { (f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e + bias) } +/// The sum of `m·2^e` over `terms`, in order, as a mantissa `0.5 ≤ |m| < 1` (or 0) and a power of +/// two. Every term is first divided by the power of two of the largest nonzero one, so none of +/// them overflows. +fn split_sum(terms: &[(f64, i32)]) -> (f64, i32) { + let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else { + return (0.0, 0); + }; + let (m, x) = frexp(terms.iter().map(|&(m, x)| ldexp(m, x - e)).sum()); + (m, e + x) +} + /// `m·2^e`, multiplied in steps of powers of two that are each within the normal range. fn ldexp(mut m: f64, mut e: i32) -> f64 { while e > 1023 && m.is_finite() { @@ -485,6 +507,16 @@ mod tests { let back = inv.apply(q).unwrap(); assert!((back.x - p.x).abs() <= 1e-9 * p.x.abs() && (back.y - p.y).abs() <= 1e-9 * p.y.abs(), "{p:?} {back:?}"); } + // A normal determinant (1e-300) whose cofactor 1e-300 · 1e-300 is below the smallest + // positive f64, and where one power of two that brings the products near 1 takes 1e300 past + // the largest finite number: the inverse is still diag(1e300, 1e-300, 1e300). + let spread = Homography([[1e-300, 0.0, 0.0], [0.0, 1e300, 0.0], [0.0, 0.0, 1e-300]]); + assert_eq!(Homography::from_array(spread.to_array()), Some(spread)); + let inv = spread.inverse().unwrap(); + let want = [1e300, 0.0, 0.0, 0.0, 1e-300, 0.0, 0.0, 0.0, 1e300]; + for (v, w) in inv.to_array().iter().zip(want) { + assert!((v - w).abs() <= 1e-12 * w.abs(), "{inv:?}"); + } } #[test] From 4494d40c333474ad3b7ff33ccd697405e236561e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 07:55:19 -0800 Subject: [PATCH 266/674] Geometry: the inverse of an invertible projective map is kept however small its relative determinant adjugate_inverse no longer applies the relative determinant test to its result. That test is not symmetric between a map and its inverse: a map whose determinant is 1e-8 of its largest product can have a finite, accurate inverse whose own ratio is near 1e-16, so inverse() was None while is_invertible() was true. The result is now kept when every entry is finite and its determinant, summed from the six products in split form, is not 0. --- crates/geom/src/projective.rs | 59 ++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index baf0570651..2a9ff9093e 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -90,13 +90,7 @@ impl Homography { if !self.is_finite() { return false; } - let f = self.0.map(|row| row.map(frexp)); - // The columns each of the six products takes from rows 0, 1 and 2, and its sign. - let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)]; - let terms = cols.map(|(a, b, c, sign)| { - let (a, b, c) = (f[0][a], f[1][b], f[2][c]); - (sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1) - }); + let terms = self.det_terms(); let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else { return false; }; @@ -106,6 +100,18 @@ impl Homography { d.abs() > 1e-15 * largest } + /// The six signed products the determinant sums, each as a mantissa product and an exponent + /// sum. + fn det_terms(&self) -> [(f64, i32); 6] { + let f = self.0.map(|row| row.map(frexp)); + // The columns each of the six products takes from rows 0, 1 and 2, and its sign. + let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)]; + cols.map(|(a, b, c, sign)| { + let (a, b, c) = (f[0][a], f[1][b], f[2][c]); + (sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1) + }) + } + /// The same map with every entry divided by one power of two, chosen so that the largest of the /// six products its determinant sums is at least 1/8 and below 4. `None` when every one of /// those products is 0 or an entry is not finite. @@ -128,7 +134,7 @@ impl Homography { /// Inverse; `None` when [`Self::has_significant_det`] counts the map as not invertible. The /// inverse is formed from the map itself when its determinant is finite, and is kept when every - /// entry is finite and it passes [`Self::has_significant_det`]. Otherwise it is the inverse of + /// entry is finite and its own determinant is not 0. Otherwise it is the inverse of /// [`Self::scaled`] (the exact inverse multiplied by one power of two, which is the same map), /// and `None` when that one fails the same checks. pub fn inverse(&self) -> Option { @@ -144,9 +150,10 @@ impl Homography { } /// The adjugate divided by the determinant; `None` when an entry is not finite, the - /// determinant is 0, or the result fails [`Self::has_significant_det`]. Every cofactor and the - /// determinant are held as a mantissa and a power of two, so an entry of the result is lost - /// only when that entry itself is beyond the range of `f64`. + /// determinant is 0, or the result has an entry that is not finite or a determinant of 0 (its + /// six products, each held as a mantissa and a power of two, sum to 0, as when a row underflows + /// to 0). Every cofactor and the determinant are held as a mantissa and a power of two, so an + /// entry of the result is lost only when that entry itself is beyond the range of `f64`. fn adjugate_inverse(&self) -> Option { if !self.is_finite() { return None; @@ -176,7 +183,7 @@ impl Homography { } let out = Self(out); // H⁻¹·(x, y, 1) = (u, v, 1)/w_H, so points in front of the camera keep w > 0. - out.has_significant_det().then_some(out) + (out.is_finite() && split_sum(&out.det_terms()).0 != 0.0).then_some(out) } /// `self ∘ other`: `other` first. @@ -519,6 +526,34 @@ mod tests { } } + #[test] + fn an_invertible_map_has_an_inverse_at_any_scale() { + let times = |h: Homography, f: f64| Homography(h.0.map(|row| row.map(|v| v * f))); + // Determinant 1e-17 against a largest product of 1e-9 (and 1e-8 at 1e3 times the map): its + // inverse is finite, though that inverse's own determinant is near 1e-16 of its largest + // product. + let skew = Homography([[-1000.0, -1e-8, -1e-5], [0.0, 1e-4, -1e7], [1e-8, 0.0, 1e-8]]); + let exact = [1e5, 10.0, 1e16 + 1e8, -1e16, -1e12 + 1e4, -1e27, -1e5, -10.0, -1e16]; + for f in [1.0, 1e3] { + let s = times(skew, f); + assert_eq!(Homography::from_array(s.to_array()), Some(s), "{f}"); + let inv = s.inverse().unwrap_or_else(|| panic!("{f}")); + for (v, w) in inv.to_array().iter().zip(exact) { + assert!((v * f - w).abs() <= 1e-9 * w.abs(), "{f}: {inv:?}"); + } + // The map times its inverse is the identity, to within the rounding of the products + // each entry sums (they cancel by up to 1e23 in the second row). + let id = s.then_after(&inv); + for (r, row) in id.0.iter().enumerate() { + for (k, v) in row.iter().enumerate() { + let size: f64 = (0..3).map(|i| (s.0[r][i] * inv.0[i][k]).abs()).sum(); + let want = if r == k { 1.0 } else { 0.0 }; + assert!((v - want).abs() <= 1e-12 * size, "{f}: {id:?}"); + } + } + } + } + #[test] fn a_product_that_overflows_is_none() { // Each factor is finite and invertible, but the product's first entry is 1e400. From ce9002008b9cc0dcb0dc43a6f8aab705056a76db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 08:10:43 -0800 Subject: [PATCH 267/674] Docs: file-format-parity keeps one .ai editing-data paragraph The editing-data paragraph appeared twelve times, each copy holding one feature's change. The copies are merged into one paragraph. --- docs/file-format-parity.md | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 450872215b..92d6f79d22 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -111,18 +111,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow, Offset Path, Outline Object or Outline Stroke comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or a graphic after the text object of a legacy wraparound group (`*w` … `*W`), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow or Convert to Shape comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format From 0f48ba21e9d8c260e756c61fc7ceec421b903c1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 08:15:21 -0800 Subject: [PATCH 268/674] Geometry: a projective map at a tiny scale maps points and derivatives as at unit scale apply and affine_at multiply every entry by the power of two that brings the largest to at least 1/2 when all entries are below 1/2, so products that would be subnormal keep their precision. The identity times 5e-324 mapped (0.5, 0.5) to (0, 0) before. Maps with an entry of 1/2 or more are unchanged. --- crates/geom/src/projective.rs | 36 ++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 2a9ff9093e..9d4800626c 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -52,9 +52,9 @@ impl Homography { /// Map a point; `None` when it lands on or beyond the horizon (w at most 1e-9 times the largest /// magnitude in the map's `w` row, so the answer is the same at any scale of the map), or when - /// it does not map to a finite page point. + /// it does not map to a finite page point. The point is mapped through [`Self::upscaled`]. pub fn apply(&self, p: Point) -> Option { - let m = &self.0; + let m = self.upscaled(); let x = m[0][0] * p.x + m[0][1] * p.y + m[0][2]; let y = m[1][0] * p.x + m[1][1] * p.y + m[1][2]; let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; @@ -66,6 +66,15 @@ impl Homography { q.is_finite().then_some(q) } + /// The entries, multiplied by the power of two that brings the largest magnitude to at least + /// 1/2 and below 1 when every entry is below 1/2 in magnitude (an exact step that keeps a map + /// at a tiny scale from losing precision to subnormal products), and unchanged otherwise. + fn upscaled(&self) -> [[f64; 3]; 3] { + let largest = self.0.iter().flatten().fold(0.0_f64, |k, v| k.max(v.abs())); + let e = frexp(largest).1.min(0); + self.0.map(|row| row.map(|v| ldexp(v, -e))) + } + pub fn det(&self) -> f64 { let m = &self.0; m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) @@ -252,7 +261,7 @@ impl Homography { /// The affine map that matches `self` to first order at `p` (its derivative there), `None` /// beyond the horizon or when the derivative is not finite. pub fn affine_at(&self, p: Point) -> Option { - let m = &self.0; + let m = self.upscaled(); let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; let q = self.apply(p)?; // d(x/w) = (dx − (x/w)·dw) / w, and the same for y. @@ -554,6 +563,27 @@ mod tests { } } + #[test] + fn a_map_at_a_tiny_scale_maps_points_as_at_unit_scale() { + for f in [5e-324, 1e-300] { + let h = Homography(Homography::IDENTITY.0.map(|row| row.map(|v| v * f))); + assert_eq!(Homography::from_array(h.to_array()), Some(h), "{f}"); + for p in [Point::new(0.5, 0.5), Point::new(1e-20, 1e-20)] { + let q = h.apply(p).unwrap_or_else(|| panic!("{f}: {p:?}")); + assert!((q.x - p.x).abs() <= 1e-12 * p.x && (q.y - p.y).abs() <= 1e-12 * p.y, "{f}: {p:?} -> {q:?}"); + } + } + // A perspective map whose entries are exact at 2^-1060 times their size, so the scaled + // copy holds the same map. + let unit = Homography([[1.0, 0.0, 2.0], [0.0, 1.0, 3.0], [0.5, 0.25, 1.0]]); + let tiny = Homography(unit.0.map(|row| row.map(|v| v * pow2(-1022) * pow2(-38)))); + let p = Point::new(0.3, 0.7); + let (a, b) = (tiny.affine_at(p).unwrap(), unit.affine_at(p).unwrap()); + for (u, v) in a.as_coeffs().iter().zip(b.as_coeffs()) { + assert!((u - v).abs() <= 1e-12 * v.abs().max(1.0), "{a:?} {b:?}"); + } + } + #[test] fn a_product_that_overflows_is_none() { // Each factor is finite and invertible, but the product's first entry is 1e400. From b5885e35fa7461b5036ff7ac9fc64dfc05dd88c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 08:24:29 -0800 Subject: [PATCH 269/674] Geometry: a projective map at a small scale maps a far point without overflowing The power of two that brings a small map's entries up before a point is mapped is now reduced by the power of two of the point's larger coordinate, so no product of an entry and a coordinate reaches 1. A map that mapped a point before the scaling step does so again, and affine_at uses the same entries. --- crates/geom/src/projective.rs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/crates/geom/src/projective.rs b/crates/geom/src/projective.rs index 9d4800626c..070048f38c 100644 --- a/crates/geom/src/projective.rs +++ b/crates/geom/src/projective.rs @@ -54,7 +54,7 @@ impl Homography { /// magnitude in the map's `w` row, so the answer is the same at any scale of the map), or when /// it does not map to a finite page point. The point is mapped through [`Self::upscaled`]. pub fn apply(&self, p: Point) -> Option { - let m = self.upscaled(); + let m = self.upscaled(p); let x = m[0][0] * p.x + m[0][1] * p.y + m[0][2]; let y = m[1][0] * p.x + m[1][1] * p.y + m[1][2]; let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; @@ -66,12 +66,15 @@ impl Homography { q.is_finite().then_some(q) } - /// The entries, multiplied by the power of two that brings the largest magnitude to at least - /// 1/2 and below 1 when every entry is below 1/2 in magnitude (an exact step that keeps a map - /// at a tiny scale from losing precision to subnormal products), and unchanged otherwise. - fn upscaled(&self) -> [[f64; 3]; 3] { + /// The entries for mapping `p`, multiplied by a power of two of at least 1 (an exact step that + /// keeps a map at a tiny scale from losing precision to subnormal products). When every entry + /// is below 1/2 in magnitude, the power brings the largest to at least 1/2 and below 1, divided + /// by the power of two of `p`'s larger coordinate magnitude when that is 1 or more, so that no + /// product of an entry and a coordinate reaches 1. Otherwise the entries are unchanged. + fn upscaled(&self, p: Point) -> [[f64; 3]; 3] { let largest = self.0.iter().flatten().fold(0.0_f64, |k, v| k.max(v.abs())); - let e = frexp(largest).1.min(0); + let e_p = frexp(p.x.abs().max(p.y.abs())).1.max(0); + let e = (frexp(largest).1.min(0) + e_p).min(0); self.0.map(|row| row.map(|v| ldexp(v, -e))) } @@ -261,7 +264,7 @@ impl Homography { /// The affine map that matches `self` to first order at `p` (its derivative there), `None` /// beyond the horizon or when the derivative is not finite. pub fn affine_at(&self, p: Point) -> Option { - let m = self.upscaled(); + let m = self.upscaled(p); let w = m[2][0] * p.x + m[2][1] * p.y + m[2][2]; let q = self.apply(p)?; // d(x/w) = (dx − (x/w)·dw) / w, and the same for y. @@ -584,6 +587,17 @@ mod tests { } } + #[test] + fn a_map_at_a_small_scale_maps_a_far_point() { + // Every product of an entry and a coordinate is finite, but the entries brought to 1/2 or + // more would overflow against this point. + let h = Homography([[1e-6, 1e-6, 0.0], [0.0, 1e-6, 0.0], [1e-6, 0.0, 1e-6]]); + let p = Point::new(1.75e308, 1.75e308); + let q = h.apply(p).unwrap_or_else(|| panic!("{p:?}")); + assert!((q.x - 2.0).abs() <= 1e-12 && (q.y - 1.0).abs() <= 1e-12, "{q:?}"); + assert!(h.affine_at(p).is_some()); + } + #[test] fn a_product_that_overflows_is_none() { // Each factor is finite and invertible, but the product's first entry is 1e400. From 5f20bbc3e838aa13b07c89053ebbee53323a4233 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 08:25:02 -0800 Subject: [PATCH 270/674] Document Info: test that a Repeat object in a selected group is listed once With Selection Only, a selection that holds a group and the Repeat object inside it, in either order, lists that Repeat object once. --- crates/engine/src/cmd/docinfo.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 776b4af979..0fafdf7dcb 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -562,7 +562,7 @@ mod tests { /// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number /// of instances it makes (for a grid, its rows and columns, followed by the number it draws when /// that is fewer), one in a group included. With Selection Only it lists the Repeat objects in - /// the selection. + /// the selection, each once when the selection holds a group and a Repeat object inside it. #[test] fn info_lists_the_repeat_objects() { let mut s = Session::new(); @@ -600,6 +600,11 @@ mod tests { }; s.execute("select.set", &json!({"ids": [grid, group]})).unwrap(); assert_eq!(names(&mut s), ["Tiles", ""]); + // A selection that holds the group and the Repeat object inside it lists that object once. + for ids in [json!([group, mirror]), json!([mirror, group])] { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert_eq!(names(&mut s), [""], "{ids}"); + } s.execute("select.set", &json!({"ids": [radial]})).unwrap(); assert_eq!(names(&mut s), [""]); s.execute("select.set", &json!({"ids": [d]})).unwrap(); From 2d0fa32d303ee77d8ed2c55709c5bf2efa44d054 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 08:53:47 -0800 Subject: [PATCH 271/674] Docs: the projection checks compare absolute values The horizon test compares a point's signed w with the largest absolute value in the bottom row, and the invertibility test compares the absolute value of the determinant with the largest absolute value among its six products, so a negative determinant counts as invertible. A stored projection that overflows is divided by the largest absolute value in its bottom row. --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 68ef6787b5..043058ec0d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1044,8 +1044,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur All Artwork Above and Other Layers (Object › Lock and Object › Hide), Transform Each, Rearrange All Artboards, the width point and width profile commands, Liquify, Puppet Warp, Define Perspective Grid, Attach to Active Plane, Release with Perspective, moves and transforms in perspective, Move Plane and Move Plane to Match Object record no undo step when they change nothing. Move in Perspective (its copy, perpendicular and Snap to Grid choices), Transform in Perspective (its copy), Nudge in Perspective (its ×10 and copy), Draw in Perspective (Snap to Grid), Define Perspective Grid (its reproject choice), Show Perspective Grid, Width Point (Adjust Adjoining Width Points), Liquify (its pen pressure, Simplify and Affect choices) and Puppet Warp (its pins' rest shape) refuse a value other than true, false or null, such as "true", and leave the document and its undo history as they were. Moves and transforms in perspective and Define Perspective Grid with reproject return an error, and leave the document and its undo history as they were, when the projection they would give type or a symbol instance in perspective has a number too large to store. Object › Perspective › Edit Text returns an error, and does not enter isolation mode, when the type cannot be shown flat where it is drawn: when part of it crosses the horizon, or when that view's projection has a number too large to store. Regressions: `a_product_that_overflows_is_none` in `crates/geom/src/projective.rs`, and `moving_type_whose_projection_would_overflow_is_refused` and `edit_text_whose_flat_view_would_overflow_is_refused` in `crates/engine/src/tests/persp_text.rs`. - A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens as the same map at a smaller scale (divided by the largest number in its bottom row), so points that overflowed at the stored scale draw, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. - A projection gives the same answers when every one of its numbers is multiplied by the same factor: a point is past its horizon when its w is at most 1e-9 times the largest number in the bottom row, and the projection is invertible when its determinant is more than 1e-15 times the largest of the six products the determinant sums, so a stored projection with very small numbers draws and inverts, and one that cannot be inverted is refused at every scale. Regression: `the_checks_do_not_depend_on_the_scale_of_the_map` in `crates/geom/src/projective.rs`. + A stored projection with numbers so large that its determinant overflows is judged on a copy divided by a power of two: an invertible one is read back when the document opens as the same map at a smaller scale (divided by the largest absolute value in its bottom row), so points that overflowed at the stored scale draw, and one that cannot be inverted, such as one whose bottom row is 0 at that scale, is not. Regression: `a_determinant_that_overflows_is_taken_at_a_smaller_scale` in `crates/geom/src/projective.rs`. + A projection gives the same answers when every one of its numbers is multiplied by the same factor. A point is on or past its horizon when its w is at most 1e-9 times the largest absolute value in the bottom row, so a point with a negative w is past it. The projection is invertible when the absolute value of its determinant is more than 1e-15 times the largest absolute value among the six products the determinant sums, so a negative determinant counts the same as a positive one. A stored projection with very small numbers draws and inverts, and one that cannot be inverted is refused at every scale. Regression: `the_checks_do_not_depend_on_the_scale_of_the_map` in `crates/geom/src/projective.rs`. Create Object Mosaic (its columns and rows), Transform Each (its reference point and Random seed) and Rearrange All Artboards (its columns) refuse a fraction, a negative number or a string, such as 2.5, -1 or "4"; 4.0 counts as 4. Move, Rotate, Scale, Reflect, Shear, Transform Again, Nudge and the Transform panel's values (their copy, Scale Strokes & Effects, Scale Corners, Transform Patterns, Transform Objects and area type options), Align, Distribute and Distribute Spacing (Transform Patterns), Object Properties (visible, locked, Isolate Blending and Opacity & Mask Define Knockout Shape) and Live Shape Properties (Invert Pie, Make Sides Equal and relative rounding) refuse a value other than true, false or null, such as "false", and leave the document as it was. Object Properties (its opacity), Live Shape Properties (corner radius and polygon sides), the Transform panel's reference point and Align, Distribute and Distribute Spacing to an artboard (the artboard's number) refuse a value other than a number or null, such as "50", and leave the document as it was. From 931e94cdeac3d4bd8c0fdb4cf6be73e13b0e80d9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 12:38:33 -0800 Subject: [PATCH 272/674] Symbols: 9-slice guides are shown and dragged on the canvas while editing a symbol While a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide sets it through `symbol.options`'s `nineSliceGuides` as one undo step; Escape during the drag puts it back. A guide within 4 screen pixels takes the press before the art and the bounding box. A dragged guide stays within the art's box and stops short of the opposite guide; positions outside the art are not supported yet. --- crates/doc/src/lib.rs | 5 +- crates/doc/src/symbol_nine_slice.rs | 157 ++++++++++++++ crates/tools/src/lib.rs | 1 + crates/tools/src/nineslice.rs | 229 +++++++++++++++++++++ crates/tools/src/select.rs | 54 ++++- crates/ui-egui/src/canvas.rs | 5 +- crates/ui-egui/src/canvas/tests.rs | 59 ++++++ crates/ui-egui/src/canvas/tool_overlays.rs | 17 ++ docs/gaps.md | 5 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 12 files changed, 529 insertions(+), 9 deletions(-) create mode 100644 crates/tools/src/nineslice.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c836390e19..b59f661c21 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -29,7 +29,10 @@ mod symbol_registration; pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; -pub use symbol_nine_slice::{MAX_SLICE_GROWTH, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, charge_symbol_art}; +pub use symbol_nine_slice::{ + EditedNineSlice, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice, + charge_symbol_art, +}; pub use symbol_overrides::SymbolOverride; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; pub mod links; diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index a37b92eef6..4e0f7ac51c 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -71,6 +71,78 @@ impl SymbolNineSlice { } } +/// One of the four 9-slice guides. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NineSliceGuide { + Left, + Top, + Right, + Bottom, +} + +impl NineSliceGuide { + pub const ALL: [Self; 4] = [Self::Left, Self::Top, Self::Right, Self::Bottom]; +} + +/// The narrowest center band a guide dragged toward the opposite guide leaves, as a fraction of +/// the art's width or height (VectorCraft's own rule). +pub const MIN_CENTER_BAND: f64 = 0.001; + +/// The 9-slice guides of the symbol edited in symbol editing mode, over its art on the editing +/// layer ([`Document::edited_nine_slice`]). +#[derive(Clone, Debug, PartialEq)] +pub struct EditedNineSlice { + /// The symbol's name. + pub symbol: String, + pub guides: SymbolNineSlice, + /// The art's geometric box at its natural size. + art: Rect, + /// The art at its natural size → the document. + to_doc: Affine, +} + +impl EditedNineSlice { + /// Guide `g` as a line across the art's box, from one edge to the other, in the document. + pub fn line(&self, g: NineSliceGuide) -> (Point, Point) { + let (b, s) = (self.art, self.guides); + let (a, c) = match g { + NineSliceGuide::Left | NineSliceGuide::Right => { + let x = if g == NineSliceGuide::Left { b.x0 + s.left * b.width() } else { b.x1 - s.right * b.width() }; + (Point::new(x, b.y0), Point::new(x, b.y1)) + } + NineSliceGuide::Top | NineSliceGuide::Bottom => { + let y = if g == NineSliceGuide::Top { b.y0 + s.top * b.height() } else { b.y1 - s.bottom * b.height() }; + (Point::new(b.x0, y), Point::new(b.x1, y)) + } + }; + (self.to_doc * a, self.to_doc * c) + } + + /// The four guides' lines: left, top, right, bottom. + pub fn lines(&self) -> [(NineSliceGuide, Point, Point); 4] { + NineSliceGuide::ALL.map(|g| { + let (a, b) = self.line(g); + (g, a, b) + }) + } + + /// The guides with guide `g` moved across its axis to document point `p`. The guide stays + /// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide. A point that is + /// not finite leaves the guides as they are. + pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice { + let (b, mut out) = (self.art, self.guides); + let q = self.to_doc.inverse() * p; + let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(0.0)) } else { now }; + match g { + NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left), + NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right), + NineSliceGuide::Top => out.top = fit((q.y - b.y0) / b.height(), out.bottom, out.top), + NineSliceGuide::Bottom => out.bottom = fit((b.y1 - q.y) / b.height(), out.top, out.bottom), + } + out + } +} + /// The most objects [`NineSliceMap::place`] makes for each object of the art it places: an /// object drawn in nine cells becomes a group of nine clip groups, each a clip path and a copy. pub const MAX_SLICE_GROWTH: u64 = 28; @@ -638,6 +710,25 @@ impl Document { } } + /// The 9-slice guides of the symbol being edited in symbol editing mode, over its art on the + /// editing layer: `None` outside the mode, when the symbol has no guides, or when its art has + /// no width or height. + pub fn edited_nine_slice(&self) -> Option { + let se = self.symbol_edit.as_ref()?; + let guides = self.symbol_nine_slice(&se.symbol)?; + let sym = self.symbols.iter().find(|s| s.name == se.symbol)?; + let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?; + let natural = self.symbol_natural_xf(&se.symbol); + let b = natural.transform_rect_bbox(art); + if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 { + return None; + } + let to_doc = se.xf * natural.inverse(); + let det = to_doc.determinant(); + let usable = to_doc.as_coeffs().into_iter().all(f64::is_finite) && det.is_finite() && det.abs() > 1e-18; + usable.then(|| EditedNineSlice { symbol: se.symbol.clone(), guides, art: b, to_doc }) + } + /// [`Self::place_symbol_art`] for writers that do not apply clipping /// ([`NineSliceMap::place_unclipped`]). pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option { @@ -1279,4 +1370,70 @@ mod tests { let v = inst.visual_bounds_with(&d.symbol_boxes()); assert!(v.is_some_and(|b| near(b, whole)), "{v:?}"); } + + /// Symbol "S" of [`markers`] edited in symbol editing mode, its art placed by `xf`. + fn editing(guides: Option, xf: Affine) -> Document { + let mut d = markers(guides); + let layer = d.layers[0].id; + d.symbol_edit = Some(crate::SymbolEdit { + symbol: "S".into(), + layer, + instance: None, + xf, + group: true, + changed: false, + back_isolation: None, + back_layer: None, + }); + d + } + + fn near_point(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-9 + } + + /// While a symbol with guides is edited, its four guides cross its art's box from edge to edge + /// where the art shows on the editing layer: here at 25 % in, the art doubled and moved. + #[test] + fn the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it() { + let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0); + let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap(); + assert_eq!(e.symbol, "S"); + let want = [ + (NineSliceGuide::Left, Point::new(60.0, 20.0), Point::new(60.0, 220.0)), + (NineSliceGuide::Top, Point::new(10.0, 70.0), Point::new(210.0, 70.0)), + (NineSliceGuide::Right, Point::new(160.0, 20.0), Point::new(160.0, 220.0)), + (NineSliceGuide::Bottom, Point::new(10.0, 170.0), Point::new(210.0, 170.0)), + ]; + for ((g, a, b), (wg, wa, wb)) in e.lines().into_iter().zip(want) { + assert!(g == wg && near_point(a, wa) && near_point(b, wb), "{g:?} {a:?} {b:?}"); + } + // Outside the mode, without guides, or for a symbol that is gone: no guides. + assert!(markers(Some(SymbolNineSlice::default())).edited_nine_slice().is_none()); + assert!(editing(None, xf).edited_nine_slice().is_none()); + let mut d = editing(Some(SymbolNineSlice::default()), xf); + d.symbols.clear(); + assert!(d.edited_nine_slice().is_none()); + } + + /// Moving a guide changes that guide alone, follows the pointer across its axis only, stays + /// within the art's box and stops short of the opposite guide. + #[test] + fn a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide() { + let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0); + let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap(); + let q = SymbolNineSlice { left: 0.25, top: 0.25, right: 0.25, bottom: 0.25 }; + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(30.0, 999.0)), SymbolNineSlice { left: 0.1, ..q }); + assert_eq!(e.moved(NineSliceGuide::Bottom, Point::new(-50.0, 180.0)), SymbolNineSlice { bottom: 0.2, ..q }); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: 0.0, ..q }); + assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: 0.0, ..q }); + let crossed = e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)); + assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}"); + assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some()); + assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q); + // A mirrored placement measures along the symbol's own axes. + let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap(); + assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0))); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-10.0, 0.0)), SymbolNineSlice { left: 0.1, ..q }); + } } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 1ca8df7c01..1a6a1b6f80 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -24,6 +24,7 @@ pub mod intertwine; pub mod meshblend; pub mod meshedit; pub mod mirror; +pub mod nineslice; pub mod objects_on_path; pub mod params; pub mod pathtype; diff --git a/crates/tools/src/nineslice.rs b/crates/tools/src/nineslice.rs new file mode 100644 index 0000000000..61de9e9580 --- /dev/null +++ b/crates/tools/src/nineslice.rs @@ -0,0 +1,229 @@ +//! The 9-slice guides of a symbol edited in symbol editing mode: two horizontal and two vertical +//! guides over its art +//! ([helpx: maintain proportions while scaling symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)). +//! The canvas draws them, dotted, with any tool. With the Selection tool, the pointer near a guide +//! takes the Move cursor, and dragging the guide moves it (`symbol.options`'s +//! `nineSliceGuides`), in one undo step. +//! +//! VectorCraft's own rules: a guide stays within the art's box and stops short of the opposite +//! guide; the drag does not snap and its modifiers change nothing; a guide within reach takes the +//! press before the art and the bounding box, and of two guides within reach the nearer one, else +//! the first of left, top, right and bottom; Escape during the drag puts the guide back. + +use serde_json::json; +use vectorcraft_doc::{EditedNineSlice, NineSliceGuide}; +use vectorcraft_geom::Point; + +use crate::{Action, PointerEvent, ToolContext}; + +/// How near (screen px) the pointer must come to a guide to take it. +const HIT_PX: f64 = 4.0; + +/// The distance from `p` to the segment from `a` to `b`. +fn to_segment(p: Point, a: Point, b: Point) -> f64 { + let d = b - a; + let len2 = d.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(d) / len2).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(a + d * t) +} + +/// The edited symbol's guides and the one within reach of `p`, the nearest first. +pub fn guide_at(cx: &ToolContext, p: Point) -> Option<(EditedNineSlice, NineSliceGuide)> { + if !(p.x.is_finite() && p.y.is_finite()) { + return None; + } + let e = cx.doc.edited_nine_slice()?; + let reach = cx.tol(HIT_PX); + let near = e + .lines() + .into_iter() + .map(|(g, a, b)| (g, to_segment(p, a, b))) + .filter(|(_, d)| *d <= reach) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(g, _)| g)?; + Some((e, near)) +} + +/// Is `p` over a guide of the edited symbol? +pub fn over_guide(cx: &ToolContext, p: Point) -> bool { + guide_at(cx, p).is_some() +} + +/// Dragging a 9-slice guide. +#[derive(Clone, Debug)] +pub struct GuideDrag { + frame: EditedNineSlice, + guide: NineSliceGuide, + start: Point, + began: bool, +} + +impl GuideDrag { + /// Start a drag when the press `ev` is on a guide of the edited symbol. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let (frame, guide) = guide_at(cx, ev.pos)?; + Some(Self { frame, guide, start: ev.pos, began: false }) + } + + /// The drag has left the click: the guide is moving. + pub fn adjusting(&self) -> bool { + self.began + } + + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !(p.x.is_finite() && p.y.is_finite()) || (!self.began && p.distance(self.start) < cx.tol(3.0)) { + return vec![]; + } + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin("Symbol Options".into())); + } + let guides = self.frame.moved(self.guide, p); + out.push(Action::Preview("symbol.options".into(), json!({ "name": self.frame.symbol, "nineSliceGuides": guides.to_value() }))); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + pub fn cancel(self) -> Vec { + if self.began { vec![Action::Cancel] } else { vec![] } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::select::SelectionTool; + use crate::testutil::*; + use crate::{Cursor, Mods, PointerKind, Tool, ToolKey}; + use vectorcraft_doc::{Appearance, Document, Node, Selection, Symbol, SymbolEdit, SymbolNineSlice}; + use vectorcraft_geom::{Affine, Rect, shapes}; + + /// A 100 × 100 symbol "S" with 9-slice guides `guides`, edited in symbol editing mode with its + /// art, a filled square, at (100, 100) on the editing layer: its guides lie at x and y = 125 + /// and 175. + fn editing(guides: Option) -> Document { + let mut d = Document::new(500.0, 500.0); + let square = |d: &mut Document, r: Rect| Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + let art = square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0)); + d.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + d.set_symbol_nine_slice("S", guides); + let layer = d.add_layer(Some("S")); + let copy = square(&mut d, Rect::new(100.0, 100.0, 200.0, 200.0)); + d.insert(Some(layer), 0, copy).unwrap(); + d.symbol_edit = Some(SymbolEdit { + symbol: "S".into(), + layer, + instance: None, + xf: Affine::translate((100.0, 100.0)), + group: false, + changed: false, + back_isolation: None, + back_layer: None, + }); + d + } + + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent::new(kind, x, y) + } + + fn preview(a: &Action) -> (String, serde_json::Value) { + match a { + Action::Preview(cmd, v) => (cmd.clone(), v.clone()), + other => panic!("{other:?}"), + } + } + + /// The pointer within 4 screen px of a guide takes it at any zoom, the nearer of two where + /// they cross, and nothing is taken outside symbol editing mode or without guides. + #[test] + fn a_guide_is_taken_within_a_few_screen_pixels_at_any_zoom() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + for zoom in [0.25, 1.0, 8.0] { + let c = ToolContext { zoom, ..cx(&d, &s, &p) }; + let at = |x: f64, y: f64| guide_at(&c, Point::new(x, y)).map(|(_, g)| g); + assert_eq!(at(125.0 + 3.5 / zoom, 150.0), Some(NineSliceGuide::Left), "{zoom}"); + assert_eq!(at(125.0 + 5.0 / zoom, 150.0), None, "{zoom}"); + assert_eq!(at(150.0, 175.0 - 2.0 / zoom), Some(NineSliceGuide::Bottom), "{zoom}"); + // Past the art's box the guides end. + assert_eq!(at(125.0, 100.0 - 6.0 / zoom), None, "{zoom}"); + } + let c = cx(&d, &s, &p); + assert_eq!(guide_at(&c, Point::new(176.0, 173.0)).map(|(_, g)| g), Some(NineSliceGuide::Right)); + assert_eq!(guide_at(&c, Point::new(173.0, 176.0)).map(|(_, g)| g), Some(NineSliceGuide::Bottom)); + assert_eq!(guide_at(&c, Point::new(125.0, 125.0)).map(|(_, g)| g), Some(NineSliceGuide::Left), "left before top"); + assert!(guide_at(&c, Point::new(f64::NAN, 150.0)).is_none()); + let off = editing(None); + assert!(!over_guide(&cx(&off, &s, &p), Point::new(125.0, 150.0))); + let mut out = editing(Some(SymbolNineSlice::default())); + out.symbol_edit = None; + assert!(!over_guide(&cx(&out, &s, &p), Point::new(125.0, 150.0))); + } + + /// With the Selection tool, a press on a guide over the art takes the guide, not the art: the + /// pointer shows the Move cursor, the drag previews that guide alone, and the release commits + /// it as one step. A click without a drag sends nothing. + #[test] + fn dragging_a_guide_moves_that_guide_in_one_step() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, Point::new(126.0, 150.0), Mods::default()), Cursor::Move); + assert_ne!(t.cursor(&c, Point::new(150.0, 150.0), Mods::default()), Cursor::Move, "the art between the guides"); + assert!(t.pointer(&c, &ev(PointerKind::Down, 126.0, 150.0)).is_empty(), "the art is not selected"); + assert!(t.busy()); + assert_eq!(t.cursor(&c, Point::new(300.0, 300.0), Mods::default()), Cursor::Move, "kept during the drag"); + let a = t.pointer(&c, &ev(PointerKind::Drag, 110.0, 400.0)); + assert_eq!(a[0], Action::Begin("Symbol Options".into())); + let (cmd, v) = preview(&a[1]); + assert_eq!(cmd, "symbol.options"); + assert_eq!(v, json!({ "name": "S", "nineSliceGuides": [0.1, 0.25, 0.25, 0.25] })); + // Past the opposite guide it stops short of it; modifiers change nothing. + let shifted = PointerEvent { mods: Mods { shift: true, alt: true, ..Mods::default() }, ..ev(PointerKind::Drag, 190.0, 150.0) }; + let (_, v) = preview(&t.pointer(&c, &shifted)[0]); + let left = v["nineSliceGuides"][0].as_f64().unwrap(); + assert!((left - (0.75 - vectorcraft_doc::MIN_CENTER_BAND)).abs() < 1e-12, "{v}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 190.0, 150.0)), vec![Action::Commit]); + assert!(!t.busy()); + // A click on a guide without moving. + assert!(t.pointer(&c, &ev(PointerKind::Down, 175.0, 150.0)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, 176.0, 150.0)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 176.0, 150.0)).is_empty()); + // The top guide moves up and down only. + t.pointer(&c, &ev(PointerKind::Down, 150.0, 125.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 10.0, 140.0)); + assert_eq!(preview(&a[1]).1["nineSliceGuides"], json!([0.25, 0.4, 0.25, 0.25])); + } + + /// Escape during a guide drag cancels it and is the tool's; the release after it commits + /// nothing. A double-click on a guide neither edits the art nor leaves the mode. + #[test] + fn escape_cancels_a_guide_drag_and_a_double_click_stays_on_the_guide() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { isolation: d.symbol_edit.as_ref().map(|e| e.layer), ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 175.0, 150.0)); + assert_eq!(t.pointer(&c, &ev(PointerKind::Drag, 160.0, 150.0))[0], Action::Begin("Symbol Options".into())); + assert!(t.claims_key(&c, ToolKey::Escape)); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy() && !t.claims_key(&c, ToolKey::Escape)); + assert!(t.pointer(&c, &ev(PointerKind::Up, 160.0, 150.0)).is_empty()); + // Escape after a click that did not move cancels nothing. + t.pointer(&c, &ev(PointerKind::Down, 175.0, 150.0)); + assert!(t.key(&c, ToolKey::Escape, Mods::default()).is_empty()); + for k in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + assert!(t.pointer(&c, &ev(k, 175.0, 150.0)).is_empty(), "{k:?}"); + } + // Away from the guides a double-click outside the art still leaves isolation. + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, 400.0, 400.0)), vec![Action::Exec("object.exitIsolation".into(), json!({}))]); + } +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e6fa43602f..f51af25c30 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -11,7 +11,8 @@ //! a guide path to release it ([`release_guide_at`]), drag the brackets of type on a path //! ([`crate::pathtype`]), double-click the type widget to convert point type to area type and back //! ([`crate::typewidget`]), click a Shaper Group's mode widget to switch between Face Selection and -//! Construction mode ([`crate::shaperwidget`]). +//! Construction mode ([`crate::shaperwidget`]), drag the 9-slice guides of the symbol being edited +//! in symbol editing mode ([`crate::nineslice`]). //! The bounding box stands at the selection's own angle after a rotation, so its handles scale //! along the objects' axes. A handle drag resizes area type's frame (the type area) instead of //! scaling its type: the text reflows at its size. @@ -105,6 +106,8 @@ enum State { GridRepeat(crate::repeat_grid::GridDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), + /// Dragging a 9-slice guide of the symbol being edited. + NineSlice(crate::nineslice::GuideDrag), /// Loaded with the text of area type or type on a path `from` by a click on its out port, or /// on its in port (`before`: the frame it goes into comes before `from` in its thread); /// `press`: where the next press went down and where the pointer is now. @@ -639,6 +642,12 @@ impl Tool for SelectionTool { { return d.cancel(); } + if key == ToolKey::Escape + && matches!(self.state, State::NineSlice(_)) + && let State::NineSlice(d) = std::mem::take(&mut self.state) + { + return d.cancel(); + } if key == ToolKey::Escape && matches!(self.state, State::Loaded { .. }) { self.state = State::Idle; return vec![]; @@ -657,7 +666,7 @@ impl Tool for SelectionTool { match self.state { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) => key == ToolKey::Escape, + State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, _ => false, } } @@ -695,6 +704,10 @@ impl Tool for SelectionTool { { return out; } + // The edited symbol's 9-slice guides take precedence over every other control and the art. + if let Some(out) = self.nine_slice_guides(cx, ev) { + return out; + } // Mirror and grid repeat controls take precedence over art and ruler guides; the mirror // axis line and the grid's controls yield to the bounding-box handles they overlap. if let Some(out) = self.repeat_controls(cx, ev) { @@ -923,6 +936,9 @@ impl Tool for SelectionTool { if let State::GridRepeat(d) = &self.state { return d.cursor(cx); } + if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { + return Cursor::Move; + } if matches!(self.state, State::Idle) && !m.cmd && !m.ctrl @@ -1113,6 +1129,40 @@ impl SelectionTool { } } + /// A press on a 9-slice guide of the edited symbol starts dragging it; the drag and the + /// release go to it. + fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + if let State::NineSlice(mut d) = self.state.clone() { + return Some(match ev.kind { + PointerKind::Drag => { + let out = d.drag(cx, ev.pos); + self.state = State::NineSlice(d); + out + } + PointerKind::Up => { + self.state = State::Idle; + d.finish() + } + _ => vec![], + }); + } + if !matches!(self.state, State::Idle) { + return None; + } + match ev.kind { + PointerKind::Down => { + let d = crate::nineslice::GuideDrag::hit(cx, ev)?; + self.state = State::NineSlice(d); + self.hover = None; + Some(vec![]) + } + // The clicks of a double-click on a guide belong to it: it neither edits the art nor + // leaves symbol editing mode. + PointerKind::DoubleClick if crate::nineslice::over_guide(cx, ev.pos) => Some(vec![]), + _ => None, + } + } + fn repeat_controls(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { if let State::Mirror(mut d) = self.state.clone() { match ev.kind { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e501273d59..afcd2c37b7 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -70,8 +70,8 @@ pub use tool_overlays::HiddenChars; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; use tool_overlays::{ - grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, original_path_overlay, print_tiling_overlay, - rotate_view_dial, shaper_widget_overlay, slice_overlay, thread_overlays, + grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, + print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, thread_overlays, }; pub(crate) use view::animated_zoom; pub use view::fit; @@ -325,6 +325,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.view.guides { guide_lines(app, &painter, &xf, rect, &t); } + nine_slice_overlay(app, &painter, &xf); if !app.session.slices_hidden() { slice_overlay(app, &painter, &xf); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 836049278c..499ff8a7e3 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3159,6 +3159,65 @@ fn grid_repeat_handles_set_rows_and_spacing_in_one_undo_step_each() { assert_eq!((grid(&app).0, grid(&app).2), (5, 10.0), "the spacing's own undo step"); } +/// While a symbol with 9-slice guides is edited, the canvas draws its four guides dotted across +/// its art, with ruler guides hidden too, and none once the mode ends. Dragging the left guide in +/// a zoomed view moves that guide alone, as one undo step. +#[test] +fn the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("symbol.new", json!({"name": "Box", "nineSlice": true})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.view_mut().unwrap().zoom = 1.5; + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // The dots drawn along the guide from document point `a` to `b`. + let dots = |app: &mut VectorcraftApp, a: Point, b: Point| { + let (a, b) = (xf.to_screen(a), xf.to_screen(b)); + let on = |q: Pos2| { + let (d, len) = (b - a, (b - a).length()); + let t = (q - a).dot(d) / (len * len); + (-0.01..=1.01).contains(&t) && (a + d * t).distance(q) < 0.01 + }; + shapes(app, &ctx).into_iter().filter(|s| matches!(s, Shape::LineSegment { points: [p, q], .. } if on(*p) && on(*q))).count() + }; + let guides = [ + (Point::new(125.0, 100.0), Point::new(125.0, 200.0)), + (Point::new(100.0, 125.0), Point::new(200.0, 125.0)), + (Point::new(175.0, 100.0), Point::new(175.0, 200.0)), + (Point::new(100.0, 175.0), Point::new(200.0, 175.0)), + ]; + assert_eq!(dots(&mut app, guides[0].0, guides[0].1), 0, "not while the instance is only selected"); + app.run("symbol.edit", json!({})).unwrap(); + app.ui.view.guides = false; + for (a, b) in guides { + assert!(dots(&mut app, a, b) > 10, "a dotted guide from {a:?} to {b:?}"); + } + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let from = xf.to_screen(Point::new(125.0, 150.0)); + let to = xf.to_screen(Point::new(110.0, 160.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + for k in 1..=4 { + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + frame(&mut app, &ctx, vec![button(to, false)]); + let guides_now = |app: &VectorcraftApp| app.session.active().unwrap().doc.symbol_nine_slice("Box").unwrap(); + let g = guides_now(&app); + assert!((g.left - 0.1).abs() < 1e-3 && (g.top, g.right, g.bottom) == (0.25, 0.25, 0.25), "{g:?}"); + assert!(app.session.active().unwrap().doc.symbol_edit.is_some(), "still editing the symbol"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(guides_now(&app).left, 0.25, "one undo step"); + app.run("edit.redo", json!({})).unwrap(); + assert!((guides_now(&app).left - 0.1).abs() < 1e-3); + app.run("symbol.exitEditing", json!({})).unwrap(); + assert_eq!(dots(&mut app, Point::new(110.0, 100.0), Point::new(110.0, 200.0)), 0, "none outside the mode"); +} + #[test] fn top_bounding_box_handle_scales_a_default_mirror_repeat() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index bbb8bf5f0f..7b88244f68 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -166,6 +166,23 @@ pub(super) fn original_path_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: } } +/// The 9-slice guides of the symbol edited in symbol editing mode: four thin dotted lines across +/// its art's box, with any tool, whether ruler guides are shown or hidden. The Selection tool drags +/// them ([`vectorcraft_tools::nineslice`]) at the places drawn here. +pub(super) fn nine_slice_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { + let Some(e) = app.session.active().and_then(|st| st.doc.edited_nine_slice()) else { return }; + let color = Tokens::get(p.ctx()).selection; + for (_, a, b) in e.lines() { + let (a, b) = (xf.to_screen(a), xf.to_screen(b)); + if !a.is_finite() || !b.is_finite() { + continue; + } + if let Some((a, b)) = clip_segment(a, b, xf.rect) { + p.extend(Shape::dashed_line(&[a, b], Stroke::new(1.0, color), 2.0, 2.0)); + } + } +} + /// The slices (unless View → Hide Slices): user and object slices outlined in the Slices /// preferences' line colour, auto slices dashed and dimmer, each numbered at its top left (Show /// Slice Numbers); selected slices have a bolder outline. The layout is cached per revision. diff --git a/docs/gaps.md b/docs/gaps.md index 8a305fb7ee..d7276abeab 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -529,7 +529,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall Export Type (Graphic or Movie Clip; default Movie Clip; `symbol.new` / `symbol.options` / Symbols panel; canvas placement unchanged; Animate / Flash handoff metadata); Symbol Options › Enable Guides for 9-Slice Scaling (four guides as fractions of the symbol size, `nineSlice` / `nineSliceGuides` on `symbol.new` / - `symbol.options`, stored per symbol; handoff metadata, not drawn on the canvas, #2342); Brush Options › Key + `symbol.options`, stored per symbol; handoff metadata, #2342; drawn dotted over the art in symbol editing + mode, where the Selection tool drags them); Brush Options › Key Color eyedropper for scatter, art and pattern brushes (Hue Shift colorization; samples canvas art); Select › Start Global Edit (#3521) on paths, compound paths and symbol instances: the objects of the same shape at any place and size, narrowed by Appearance, Size and the artboards to search, take an edit of any one of @@ -565,7 +566,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall dynamic instance, with the Fill/Stroke controls and Appearance panel then setting its change) and their `.ai` read and write; Global Edit of groups holding type or images, rotated copies as matches, Shift-click to leave a match out and highlighting matches before the start; - drawing the 9-slice guides on the canvas in symbol edit mode. + 9-slice guides outside the symbol's art (a dragged guide stops at the art's edge). - **Estimate:** 14–24 h. ## G3 3D and Materials diff --git a/docs/mcp.md b/docs/mcp.md index 07fbd7b556..b07cc9be7d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1570,7 +1570,8 @@ already walks Image Trace. Short agent entry points: `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions 0..1 of the symbol size, a quarter each when none are given; rows of `symbol.list` carry `nineSlice`: the guides or `null`; a scaled instance of - a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; `type` is + a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a + guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}`, `symbol.replace`, `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e32418659..50984b1792 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -622,6 +622,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html): "When you scale the symbol, the parts of the symbol that don't lie within the guides are not scaled."): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), "Use 9-slice scaling": "guides are placed at 25% (or 1/4)"); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a ``, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Guides are not drawn in symbol edit mode yet. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - Symbol editing mode keeps every instance in step: instances of a dynamic symbol inside other symbols' art, pattern tiles, graph designs, stored brushes and opacity masks keep their appearance changes on the objects an edit reorders and drop the changes to objects it deletes. The view does not draw the instance the edit was entered from. Area type in the symbol's art takes the text wrap that moving a wrap object gives it. Editing another symbol at a place that fails keeps the current edit open, and only the editing layer or art on it can be isolated. Tests: `crates/engine/src/tests/symboledit.rs`, `isolation::symbol_editing_does_not_draw_the_instance_it_was_entered_from`, `panels::symbols::tests::double_clicking_a_symbol_in_the_panel_edits_it_in_either_view`, `the_panel_menus_edit_symbol_edits_the_instances_symbol_or_the_panels`, `the_control_bars_edit_symbol_edits_the_selected_instances_symbol`, `chrome::tests::the_control_bar_exits_symbol_editing_mode`. + - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it stays within the art's box (guides outside the art are not supported yet) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol. A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 51e5f7ac31..ade964e871 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -313,7 +313,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; only one built-in library (original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Calligraphic Nibs, Pattern Borders, Scatter Shapes, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; four built-in libraries (original, generated in code) | -| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; guides not drawn in symbol edit mode); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | +| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; on-canvas Direct Selection of a part inside an instance (with the Fill/Stroke controls then setting its change) remains | | Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | | Pathfinder panel on one group selected alone; a greyed-out button says what it needs | partial | #1450; the group's members are combined; one plain path selected alone stays disabled (the public documentation doesn't say what the operations do to a single path) | From 537511ae65a46a9afee224fabb5fb1942ce4be0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 13:03:45 -0800 Subject: [PATCH 273/674] Symbols: a dragged 9-slice guide moves with Real-time Drawing off With Performance > Real-time Drawing and Editing off, tool previews are applied only on release. A ruler guide being dragged was already exempt; a symbol's 9-slice guide, a symbol.options preview that sets only nineSliceGuides, now is too, so the dotted guide follows the pointer while it is dragged. The release still leaves one Symbol Options step. --- crates/engine/src/tests/prefs.rs | 24 ++++++++++++++++++++++++ crates/engine/src/tooling.rs | 12 ++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 5727e9db13..b590e3c289 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1658,6 +1658,30 @@ fn real_time_drawing_off_still_shows_a_dragged_guide() { assert_eq!((s.doc().unwrap().doc.guides[0].pos, s.doc().unwrap().history.undo.last().map(|e| e.label.as_str())), (150.0, Some("Move Guide"))); } +/// With Real-time Drawing off, a 9-slice guide of the edited symbol moved with the Selection tool +/// still moves while it is dragged, and the release leaves one Symbol Options undo step. +#[test] +fn real_time_drawing_off_still_shows_a_dragged_nine_slice_guide() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + s.execute("symbol.new", &json!({"name": "Box", "nineSlice": true})).unwrap(); + s.execute("symbol.edit", &json!({})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + set_pref(&mut s, "realTimeDrawing", json!(false)); + let left = |s: &Session| s.doc().unwrap().doc.symbol_nine_slice("Box").unwrap().left; + assert_eq!(left(&s), 0.25); + let steps = s.doc().unwrap().history.undo.len(); + s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 110.0, 150.0), v).unwrap(); + assert!((left(&s) - 0.1).abs() < 1e-9, "the guide moves while dragged: {}", left(&s)); + s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 150.0), v).unwrap(); + let d = s.doc().unwrap(); + assert!((left(&s) - 0.1).abs() < 1e-9); + assert_eq!((d.history.undo.len(), d.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Symbol Options"))); +} + /// Real-time Drawing turned on mid-drag still applies the deferred preview on commit. #[test] fn real_time_drawing_turned_on_mid_drag_still_commits_deferred_preview() { diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index efaef7d642..c53383ddd4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -65,6 +65,13 @@ fn rgb(hex: &str, fallback: [u8; 3]) -> [u8; 3] { }) } +/// Whether a tool preview of `cmd` with params `p` sets only a symbol's 9-slice guides: a +/// `symbol.options` whose params hold `nineSliceGuides` and nothing besides `name`. +fn nine_slice_guide_preview(cmd: &str, p: &Value) -> bool { + cmd == "symbol.options" + && p.as_object().is_some_and(|m| m.contains_key("nineSliceGuides") && m.keys().all(|k| k == "name" || k == "nineSliceGuides")) +} + /// Requests from tools that only the frontend can fulfil. #[derive(Clone, Debug, PartialEq)] pub enum UiRequest { @@ -784,8 +791,9 @@ impl Session { Action::Preview(cmd, p) => { // Performance › Real-time Drawing and Editing (#394): off, remember the latest // params and apply them once on Commit instead of every move. A ruler guide - // being dragged still shows: the guide is all there is to see (#4646). - if !self.prefs.real_time_drawing && !matches!(cmd.as_str(), "guide.add" | "guide.move") { + // being dragged still shows: the guide is all there is to see (#4646). So does a + // symbol's 9-slice guide being dragged. + if !self.prefs.real_time_drawing && !matches!(cmd.as_str(), "guide.add" | "guide.move") && !nine_slice_guide_preview(&cmd, &p) { self.clear_deferred_overlay_cache(); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { From b63517df7f079299ce42dc04d612cce385e64f48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 13:16:49 -0800 Subject: [PATCH 274/674] Symbols: a dragged 9-slice guide keeps its place when saved guides are closer than the minimum band A guide whose saved position leaves a center band narrower than the minimum no longer jumps to the art's edge when a drag does not move it closer to the opposite guide. The 9-slice scaling line in docs/target-app-parity.md no longer says guides are not drawn in symbol editing mode. --- crates/doc/src/symbol_nine_slice.rs | 13 ++++++++++--- docs/target-app-parity.md | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 4e0f7ac51c..fae10bdc1a 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -127,12 +127,13 @@ impl EditedNineSlice { } /// The guides with guide `g` moved across its axis to document point `p`. The guide stays - /// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide. A point that is - /// not finite leaves the guides as they are. + /// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide, or where it is + /// when the guides are already closer than that. A point that is not finite leaves the guides + /// as they are. pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice { let (b, mut out) = (self.art, self.guides); let q = self.to_doc.inverse() * p; - let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(0.0)) } else { now }; + let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(now)) } else { now }; match g { NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left), NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right), @@ -1431,6 +1432,12 @@ mod tests { assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}"); assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some()); assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q); + // Saved guides closer than the minimum center band keep their place when a drag does not + // move them closer. + let narrow = SymbolNineSlice::new(0.00005, 0.25, 0.9999, 0.25).unwrap(); + let e = editing(Some(narrow), xf).edited_nine_slice().unwrap(); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)), narrow); + assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: 0.0, ..narrow }); // A mirrored placement measures along the symbol's own axes. let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap(); assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0))); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50984b1792..3c5885bcf5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -619,7 +619,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in library, Basic Shapes, is original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html): "When you scale the symbol, the parts of the symbol that don't lie within the guides are not scaled."): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), "Use 9-slice scaling": "guides are placed at 25% (or 1/4)"); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a ``, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Guides are not drawn in symbol edit mode yet. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). + - **9-slice scaling** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html): "When you scale the symbol, the parts of the symbol that don't lie within the guides are not scaled."): a scaled instance of a symbol with Enable Guides for 9-Slice Scaling on stays an instance and keeps the parts of its art outside the guides at their size. New guides sit a quarter of the symbol's width and height in from each edge ([reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), "Use 9-slice scaling": "guides are placed at 25% (or 1/4)"); saved guides keep their values. The rest is VectorCraft's own rule: the corners keep both sizes, the top and bottom edges stretch in width, the left and right edges in height and the center in both; an instance smaller than its two outer cells on an axis shrinks them in proportion and leaves the center empty; the cells are sized along the symbol's axes before the instance's rotation, shear or reflection. A path with solid paint that crosses a guide is cut there and stays one path, its stroke at its weight with Scale Strokes & Effects on or off; type, images, live objects and gradient or pattern paint that cross a guide are drawn in each cell they reach, clipped to it, except those that draw symbol art (a nested instance, type with an inline graphic, a placed document, a brushed stroke, or a pattern whose tile draws one of these), which are placed by the cell their center is in; an object in one cell is placed by that cell and stays as it is. The canvas, bounds, the Eyedropper, Break Link to Symbol and the PDF, EPS, DXF, EMF/WMF and SVG exports place the art the same way; SVG writes such an instance as its placed art instead of a ``, and DXF and WMF, which do not clip, cut every path that crosses a guide and place other such objects by the cell their center is in. Tests: `symbol_nine_slice::tests` in `crates/doc`, `crates/engine/src/tests/symbol_nine_slice.rs`, `a_scaled_nine_slice_instance_keeps_its_corners` (PDF), `a_scaled_nine_slice_instance_is_written_as_the_canvas_draws_it` (SVG), `a_scaled_nine_slice_instance_is_sampled_as_it_is_drawn` (Eyedropper). - **Symbol editing mode** ([Edit symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a double-click on a symbol instance, the Control bar's Edit Symbol button, a double-click on a symbol in the Symbols panel and the panel menu's Edit Symbol (`symbol.edit`) open the symbol's art on a temporary isolated layer, where the instance shows it (from the panel: centered on the active artboard, or in the view in a document without artboards), with the rest of the document dimmed. Each edit there changes every instance at once; the instances keep their own transforms and stay linked (Break Link to Symbol still expands one), and a dynamic symbol's instances keep their appearance changes to the objects the art still has. Escape, the isolation bar's back button, the Control bar's Exit Symbol Editing Mode and a double-click outside the art leave the mode (`symbol.exitEditing`); leaving without an edit adds no undo step. Saving leaves the editing layer out. Tests: `crates/engine/src/tests/symboledit.rs`, `select::tests::a_double_click_on_a_symbol_instance_edits_its_symbol`, `panels::symbols::tests::edit_symbol_from_the_panel_centers_the_art_on_the_active_artboard_or_the_view`. - Symbol editing mode keeps every instance in step: instances of a dynamic symbol inside other symbols' art, pattern tiles, graph designs, stored brushes and opacity masks keep their appearance changes on the objects an edit reorders and drop the changes to objects it deletes. The view does not draw the instance the edit was entered from. Area type in the symbol's art takes the text wrap that moving a wrap object gives it. Editing another symbol at a place that fails keeps the current edit open, and only the editing layer or art on it can be isolated. Tests: `crates/engine/src/tests/symboledit.rs`, `isolation::symbol_editing_does_not_draw_the_instance_it_was_entered_from`, `panels::symbols::tests::double_clicking_a_symbol_in_the_panel_edits_it_in_either_view`, `the_panel_menus_edit_symbol_edits_the_instances_symbol_or_the_panels`, `the_control_bars_edit_symbol_edits_the_selected_instances_symbol`, `chrome::tests::the_control_bar_exits_symbol_editing_mode`. - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it stays within the art's box (guides outside the art are not supported yet) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. From e2b6903a3a56da3341b438a7d6496cf731737c62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 13:41:39 -0800 Subject: [PATCH 275/674] Symbols: test that a guide dragged on the canvas changes how a scaled instance draws A 200 x 150 instance of a 9-slice symbol draws its 10 pt corner square about 17.14 pt wide once the left guide is dragged from 25% to 5% in symbol editing mode, as the square then reaches into the stretched center band. --- crates/engine/src/tests/symbol_nine_slice.rs | 45 +++++++++++++++++++- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/symbol_nine_slice.rs b/crates/engine/src/tests/symbol_nine_slice.rs index 127af65c74..fba17f11ee 100644 --- a/crates/engine/src/tests/symbol_nine_slice.rs +++ b/crates/engine/src/tests/symbol_nine_slice.rs @@ -2,8 +2,9 @@ //! their size; Break Link to Symbol gives the art as it draws, in one step. use serde_json::json; -use vectorcraft_doc::{Node, NodeKind}; -use vectorcraft_geom::Rect; +use vectorcraft_doc::{EditedNineSlice, NineSliceGuide, Node, NodeKind}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::{PointerEvent, PointerKind}; use crate::*; @@ -209,3 +210,43 @@ fn a_dynamic_instance_keeps_its_changes_through_the_guides() { assert_eq!(fills.last().cloned().flatten().as_deref(), Some("#ff0000"), "{fills:?}"); assert_ne!(fills[0].as_deref(), Some("#ff0000"), "only the changed object"); } + +/// The boxes of the paths a symbol instance `id` draws, placed through its symbol's guides. +fn placed_boxes(s: &Session, id: NodeId) -> Vec { + let d = &s.doc().unwrap().doc; + let NodeKind::SymbolInstance { symbol, xf } = &d.node(id).unwrap().kind else { panic!("still an instance") }; + let art = d.symbols.iter().find(|s| &s.name == symbol).unwrap().art.clone(); + path_boxes(&d.place_symbol_art(symbol, &art, *xf).unwrap()) +} + +/// Dragging the left guide on the canvas while editing the symbol changes how a scaled instance +/// draws: with the guide moved from 25% to 5%, the corner square of the 200 × 150 instance reaches +/// past the left cell into the stretched center band, so it draws about 17.14 pt wide instead of 10. +#[test] +fn a_guide_dragged_on_the_canvas_changes_how_a_scaled_instance_draws() { + let (mut s, id) = panel(); + assert_sliced(&placed_boxes(&s, id)); + s.execute("symbol.edit", &json!({"name": "Panel"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let mid = |e: &EditedNineSlice, g| { + let (a, b) = e.line(g); + Point::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0) + }; + let e = s.doc().unwrap().doc.edited_nine_slice().unwrap(); + // The left guide sits at 25% of the art's width and the right one at 75%: 5% lies 0.4 of + // that span to the left of the left guide. + let (from, right) = (mid(&e, NineSliceGuide::Left), mid(&e, NineSliceGuide::Right)); + let to = from + (from - right) * 0.4; + s.pointer(&PointerEvent::new(PointerKind::Down, from.x + 1.0, from.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to.x, to.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to.x, to.y), v).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let boxes = placed_boxes(&s, id); + assert_eq!(boxes.len(), 3, "{boxes:?}"); + // 5 pt of the square in the left cell, then 5 pt of the 70 pt center band stretched to 170 pt. + let want = 5.0 + 5.0 * 170.0 / 70.0; + assert!(close(boxes[1], Rect::new(50.0, 50.0, 50.0 + want, 60.0)), "{boxes:?}"); + let left = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap().left; + assert!((left - 0.05).abs() < 1e-9, "{left}"); +} From 6ecf286f6b8da0948befdf3a350e082820b7f833 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:42:27 +0000 Subject: [PATCH 276/674] Drop invalid XML characters from SVG link URLs and aria-labels Found while testing crates/svg/src/export/nodes.rs:492 (Writer::node, `xlink:href` built with xml_escape) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/svg/src/export/nodes.rs | 7 +++++-- crates/svg/src/export/output.rs | 6 ++++++ crates/svg/src/export/text.rs | 4 ++-- crates/svg/tests/it/data_attributes.rs | 14 ++++++++++++++ 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index d2b18c39b2..7be7483919 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1,4 +1,4 @@ -use super::output::{sanitize_id, valid_xml_value, xml_attr_escape}; +use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_valid}; use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ @@ -489,7 +489,10 @@ impl Writer<'_> { self.layer_nest += layer; match n.url().filter(|_| n.visible && !self.anonymous) { Some(url) => { - self.line(&format!("", xml_escape(url))); + if !valid_xml_value(url) { + self.warn("Link URLs containing invalid XML characters had those characters removed"); + } + self.line(&format!("", xml_attr_valid(url))); self.depth += 1; self.node_body(n); self.depth -= 1; diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index cc7680e902..01d33c833b 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -19,6 +19,12 @@ pub(super) fn xml_text(s: &str) -> String { xml_escape(&s) } +/// `s` without the characters XML 1.0 does not allow, ready for a double-quoted attribute. +pub(super) fn xml_attr_valid(s: &str) -> String { + let s: String = s.chars().filter(|c| valid_xml_value(c.encode_utf8(&mut [0; 4]))).collect(); + xml_attr_escape(&s) +} + pub(super) fn valid_xml_value(s: &str) -> bool { s.chars().all(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}')) } diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index bab0cf3270..5fc015039f 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -1,4 +1,4 @@ -use super::output::xml_text; +use super::output::{xml_attr_valid, xml_text}; use super::{ Affine, AppearanceItem, Arc, BTreeSet, BezPath, BlendMode, CharStyle, FillRule, FontDb, FontFace, GradientKind, HashMap, Justify, Node, NodeId, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, Styling, TextKind, TextObject, Writer, base64_encode, css, css_string, fmt_num, @@ -163,7 +163,7 @@ impl Writer<'_> { // Glyphs bent along a path (joined scripts on a curve) can only be outlines: the group // names its text for screen readers and search. let label = if lay.glyphs.iter().any(|g| g.bend.is_some()) { - format!(" role=\"img\" aria-label=\"{}\"", xml_escape(&t.plain_text())) + format!(" role=\"img\" aria-label=\"{}\"", xml_attr_valid(&t.plain_text())) } else { String::new() }; diff --git a/crates/svg/tests/it/data_attributes.rs b/crates/svg/tests/it/data_attributes.rs index 752b8f1c3a..d652b9665f 100644 --- a/crates/svg/tests/it/data_attributes.rs +++ b/crates/svg/tests/it/data_attributes.rs @@ -277,3 +277,17 @@ fn invalid_symbol_name_alias_does_not_break_xml() { } } } + +#[test] +fn link_url_with_invalid_xml_characters_does_not_break_export() { + let mut doc = import(&svg(r#""#)).unwrap(); + let id = named(&doc, "shape").id; + doc.node_mut(id).unwrap().edit_attrs(|a| a.url = "http://a/\u{1}b\u{ffff}".into()); + for styling in styles() { + let out = export_full(&doc, &ExportOptions { styling, ..Default::default() }, None); + let parsed = xml(&out.svg); + let a = parsed.descendants().find(|n| n.has_tag_name("a")).unwrap(); + assert_eq!(a.attribute(("http://www.w3.org/1999/xlink", "href")), Some("http://a/b")); + assert!(out.warnings.iter().any(|w| w.contains("invalid XML characters"))); + } +} From 11862f61198c8f62c0b22b6c9a331cc5950ac98d Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 2 Nov 2026 19:27:35 -0500 Subject: [PATCH 277/674] Release 0.21.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 56 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 72b06a51a6..0b55428494 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6072,7 +6072,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.20.0" +version = "0.21.0" dependencies = [ "arboard", "block2 0.6.2", @@ -6117,7 +6117,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.20.0" +version = "0.21.0" dependencies = [ "crc32fast", "flate2", @@ -6128,7 +6128,7 @@ dependencies = [ [[package]] name = "vectorcraft-brush" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "serde", @@ -6140,7 +6140,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6156,7 +6156,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.20.0" +version = "0.21.0" dependencies = [ "log", "objc2-core-foundation", @@ -6178,7 +6178,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -6190,7 +6190,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.20.0" +version = "0.21.0" dependencies = [ "chrono", "hayro-ccitt", @@ -6209,7 +6209,7 @@ dependencies = [ [[package]] name = "vectorcraft-effects" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6225,7 +6225,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.20.0" +version = "0.21.0" dependencies = [ "cfb", "chrono", @@ -6267,7 +6267,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.20.0" +version = "0.21.0" dependencies = [ "fax", "flate2", @@ -6291,7 +6291,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.20.0" +version = "0.21.0" dependencies = [ "craft-vectorcraft-format", "flate2", @@ -6307,7 +6307,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -6319,7 +6319,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "log", @@ -6338,7 +6338,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6352,7 +6352,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.20.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -6364,7 +6364,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.20.0" +version = "0.21.0" dependencies = [ "aes", "chrono", @@ -6396,7 +6396,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.20.0" +version = "0.21.0" dependencies = [ "serde", "serde_json", @@ -6410,7 +6410,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.20.0" +version = "0.21.0" dependencies = [ "flate2", "gif 0.14.2", @@ -6440,14 +6440,14 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.20.0" +version = "0.21.0" dependencies = [ "proptest", ] [[package]] name = "vectorcraft-svg" -version = "0.20.0" +version = "0.21.0" dependencies = [ "craft-docpath", "flate2", @@ -6472,7 +6472,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.20.0" +version = "0.21.0" dependencies = [ "fax", "image", @@ -6490,7 +6490,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.20.0" +version = "0.21.0" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.20.0" +version = "0.21.0" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -6519,7 +6519,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6536,7 +6536,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.20.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6548,7 +6548,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.20.0" +version = "0.21.0" dependencies = [ "bytemuck", "craft-keymap", @@ -6586,7 +6586,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.20.0" +version = "0.21.0" dependencies = [ "eframe", "egui", @@ -7717,7 +7717,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.0" +version = "0.21.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index fe54598299..35be6fd24b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.20.0" +version = "0.21.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From eaab849f42da45362c4b9c53ffb48aab790c11ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 17:01:29 -0800 Subject: [PATCH 278/674] Document Info: count objects that share an id as separate objects The walk that skips objects it has already visited keys them by address instead of id, so two objects that share an id in a damaged file are both counted. An object reached through a selected group and again on its own still counts once. --- crates/engine/src/cmd/docinfo.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 0fafdf7dcb..260b981d27 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -1,7 +1,7 @@ //! Document Info panel data, its categories and the text report (Document Info › Save…, File → //! Package), and Object → Make Pixel Perfect. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -294,10 +294,11 @@ fn info(s: &mut Session, p: &Value) -> Result { let mut repeats: Vec = vec![]; let mut repeat_rows: Vec<(String, String)> = vec![]; // The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once. - let mut seen: BTreeSet = BTreeSet::new(); + // The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two. + let mut seen: HashSet<*const Node> = HashSet::new(); for r in roots { r.walk(&mut |n| { - if !seen.insert(n.id) { + if !seen.insert(std::ptr::from_ref(n)) { return; } let k = match &n.kind { @@ -668,6 +669,29 @@ mod tests { } } + /// Document Info › Objects counts two objects that share an id (as a damaged file can hold) as + /// two, in the whole document and in a selected group that holds both. + #[test] + fn info_counts_objects_that_share_an_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let square = |s: &mut Session, x: f64| { + s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (square(&mut s, 0.0), square(&mut s, 100.0)); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(NodeId(b)).unwrap().id = NodeId(a); + for p in [json!({}), json!({"selectionOnly": true})] { + let i = s.execute("document.info", &p).unwrap(); + let o = &i["objects"]; + assert_eq!((o["paths"].as_u64(), o["groups"].as_u64()), (Some(2), Some(1)), "{p}: {o}"); + assert!((i["pathLength"].as_f64().unwrap() - 80.0).abs() < 1e-6, "{p}: {}", i["pathLength"]); + } + } + #[test] fn embedding_permissions_read_from_fs_type() { assert_eq!(embedding_label(0), "embedding allowed"); From 653f178b289720a7be60a5baa0481adcc4abddaf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:33:10 -0500 Subject: [PATCH 279/674] Affinity import: count path segments and masks in master page copies Master page copies were charged one unit per shape whatever its number of segments, and nothing for attached vector or pixel masks, so a master holding one huge curve or mask could be rebuilt on thousands of pages within the copy allowance. Copy costs now count every subpath and segment of a shape's path and its vector mask, and a pixel mask's pixels. A node's vector mask also skipped the document range check the node's own art passes; its control points are now checked as mapped into the document (non-finite ones included) and an object whose mask reaches beyond the range is left out, as one whose art does. --- .../src/cmd/fileio/affinity/master_copies.rs | 59 ++++++++++++++++++- .../engine/src/cmd/fileio/affinity/nodes.rs | 37 ++++++++++++ 2 files changed, 93 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/affinity/master_copies.rs b/crates/engine/src/cmd/fileio/affinity/master_copies.rs index 91b0ce53ce..789f3c774e 100644 --- a/crates/engine/src/cmd/fileio/affinity/master_copies.rs +++ b/crates/engine/src/cmd/fileio/affinity/master_copies.rs @@ -1,7 +1,8 @@ use super::nodes::MAX_DEPTH; use super::{Kind, af}; -/// What copying a subtree takes: its nodes, characters and table cells (`work`), and its pixels. +/// What copying a subtree takes: its nodes, characters, table cells and path segments (`work`), +/// and its pixels. #[derive(Clone, Copy, Debug, Default)] pub(super) struct CopyCost { pub(super) work: u64, @@ -40,8 +41,60 @@ pub(super) fn copy_cost(n: &af::Node, depth: usize) -> CopyCost { let own = match &n.kind { Kind::Text(t) => CopyCost { work: 1 + len(&t.runs), pixels: 0 }, Kind::Table(t) => CopyCost { work: 1 + t.cells.iter().map(|c| 1 + len(&c.runs)).sum::(), pixels: 0 }, - Kind::Image(img) => CopyCost { work: 1, pixels: u64::from(img.width) * u64::from(img.height) }, + Kind::Image(img) => CopyCost { work: 1, pixels: pixels(img) }, + // Each copy builds its own path: a curve of many segments costs them all. + Kind::Shape { path, .. } | Kind::Artboard { path, .. } => CopyCost { work: 1 + segments(path), pixels: 0 }, _ => CopyCost { work: 1, pixels: 0 }, }; - n.children.iter().fold(own, |c, ch| c.plus(copy_cost(ch, depth + 1))) + // A vector mask is a path of its own, and a pixel mask an image of its own, in every copy. + let mask = CopyCost { + work: n.mask.as_ref().map_or(0, segments) + u64::from(n.pixel_mask.is_some()), + pixels: n.pixel_mask.as_ref().map_or(0, pixels), + }; + n.children.iter().fold(own.plus(mask), |c, ch| c.plus(copy_cost(ch, depth + 1))) +} + +/// The subpaths and segments of `p`. +fn segments(p: &af::Path) -> u64 { + p.subpaths.iter().map(|s| 1 + s.segments.len() as u64).sum() +} + +fn pixels(img: &af::Image) -> u64 { + u64::from(img.width) * u64::from(img.height) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn node(kind: Kind, mask: Option) -> af::Node { + af::Node { + class: vectorcraft_affinity::stream::Tag::of(b"ShpN"), + name: String::new(), + visible: true, + locked: false, + opacity: 1.0, + blend: af::Blend::Normal, + kind, + mask, + pixel_mask: None, + effects: vec![], + children: vec![], + } + } + + fn path(n: usize) -> af::Path { + let p = af::Point { x: 0.0, y: 0.0 }; + af::Path { subpaths: vec![af::SubPath { start: p, segments: vec![[p; 3]; n], closed: false }] } + } + + /// A curve, and a vector mask, cost every segment each copy rebuilds: a shape of a million + /// segments shown on many pages can't pass as one object. + #[test] + fn paths_and_masks_cost_their_segments() { + let shape = |n| Kind::Shape { path: path(n), fills: vec![], strokes: vec![], even_odd: false }; + assert!(copy_cost(&node(shape(1_000_000), None), 0).work > 1_000_000); + assert!(copy_cost(&node(Kind::Group, Some(path(1_000_000))), 0).work > 1_000_000); + assert!(copy_cost(&node(shape(3), None), 0).work < 10); + } } diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs index 2e93342279..36734dbe39 100644 --- a/crates/engine/src/cmd/fileio/affinity/nodes.rs +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -11,6 +11,15 @@ pub(super) fn affine(a: af::Affine) -> Affine { Affine::new(a.0) } +/// Are all of `p`'s points, mapped by `to_doc`, finite and within `MAX_COORD` of the origin? +pub(super) fn path_in_range(p: &af::Path, to_doc: Affine) -> bool { + let ok = |q: &af::Point| { + let d = to_doc * kurbo::Point::new(q.x, q.y); + [d.x, d.y].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD) + }; + p.subpaths.iter().all(|s| ok(&s.start) && s.segments.iter().flatten().all(ok)) +} + impl Builder { pub(super) fn layer_with(&mut self, name: Option<&str>, children: Vec>) -> Arc { let id = self.doc.alloc_id(); @@ -107,6 +116,12 @@ impl Builder { return None; } } + // So must its vector mask, which becomes a clipping path: every control point, not just + // the finite ones a bounding box takes. + if n.mask.as_ref().is_some_and(|m| !path_in_range(m, to_doc)) { + self.warn("objects beyond the document range VectorCraft supports (left out)"); + return None; + } let n = &*self.overlaid(n); // Register before descending so nested artboards keep their document order. Inside an // embedded document an artboard is just its content's frame. @@ -252,3 +267,25 @@ impl Builder { Some(Arc::new(out)) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn path(points: &[(f64, f64)]) -> af::Path { + let p = |&(x, y): &(f64, f64)| af::Point { x, y }; + let start = p(&points[0]); + let segments = points[1..].iter().map(|q| [start, p(q), p(q)]).collect(); + af::Path { subpaths: vec![af::SubPath { start, segments, closed: true }] } + } + + /// A mask's control points are checked as mapped into the document, NaN ones included. + #[test] + fn mask_paths_must_stay_in_the_document_range() { + let k = Affine::scale(0.75); + assert!(path_in_range(&path(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]), k)); + assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0e7, 0.0)]), k)); + assert!(!path_in_range(&path(&[(0.0, 0.0), (f64::NAN, 0.0)]), k)); + assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0, 1.0)]), Affine::scale(1.0e9))); + } +} From f20444511985834202adb87eaabce54fc915b9b6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:33:27 -0500 Subject: [PATCH 280/674] Repeat: the instance budget counts opacity-mask art and the nodes each copy holds A Repeat kept up to 250 000 instances whatever its source held, and the nested-instance count skipped the art of opacity masks. Expanding copied the whole source for every kept instance, and a Repeat inside an enabled mask was evaluated again for each outer copy. The budget now counts the Repeats inside enabled opacity masks, and keeps a second bound, MAX_REPEAT_COPIES, on the nodes and path anchors copied in all (nested Repeats included). --- crates/doc/src/pattern.rs | 103 +++++++++++++++++++++++++++++++------- 1 file changed, 84 insertions(+), 19 deletions(-) diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index a0b19b844c..c0ac821700 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -522,7 +522,28 @@ pub struct RepeatSpec { /// many as one 500 × 500 grid, the budget [`PatternDef::offsets_covering`] also keeps. const MAX_REPEAT_INSTANCES: usize = 250_000; -/// Counts the instances Repeats make in all, following symbol instances into their symbol's art +/// Most nodes and anchors a Repeat copies in all, those of the Repeats nested in its source and +/// of the opacity masks in it included: each instance copies the whole source, so a large source +/// keeps fewer instances than [`MAX_REPEAT_INSTANCES`] allows (a 500 × 500 grid of a shape of up +/// to 39 anchors keeps them all). +const MAX_REPEAT_COPIES: usize = 10_000_000; + +/// What the Repeats in some art make in all ([`NestedCount::nodes`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Cost { + /// Instances the Repeats make (0 when there are none). + instances: usize, + /// Nodes and path anchors drawn, each Repeat's source counted once per instance it keeps. + copies: usize, +} + +impl Cost { + fn plus(self, o: Cost) -> Cost { + Cost { instances: self.instances.saturating_add(o.instances), copies: self.copies.saturating_add(o.copies) } + } +} + +/// Counts the instances Repeats make, and the nodes they copy, in all, following symbol instances into their symbol's art /// in `doc`: each symbol's art is counted once, and a missing symbol, or an instance of a symbol /// inside its own art, counts as none. /// @@ -549,21 +570,27 @@ impl<'a> NestedCount<'a> { } let Some(sym) = self.doc.and_then(|d| d.symbols.iter().find(|s| s.name == name)) else { return 0 }; self.symbols.borrow_mut().insert(name.to_owned(), None); - let n = self.nodes(std::slice::from_ref(&sym.art)); + let n = self.nodes(std::slice::from_ref(&sym.art)).instances; self.symbols.borrow_mut().insert(name.to_owned(), Some(n)); n } - /// Instances the Repeats in `nodes` make in all (0 when there are none). - fn nodes(&self, nodes: &[Arc]) -> usize { - let mut sum = 0usize; + /// What the Repeats in `nodes` make in all, in the art of their enabled opacity masks too + /// (drawn again with each copy of the object they mask). + fn nodes(&self, nodes: &[Arc]) -> Cost { + let mut sum = Cost::default(); for n in nodes { - sum = sum.saturating_add(match (&n.kind, n.children()) { - (NodeKind::Repeat(r), _) => r.instances_in_all(self), - (NodeKind::SymbolInstance { symbol, .. }, _) => self.symbol(symbol), - (_, Some(c)) => self.nodes(c), - _ => 0, - }); + let own = match (&n.kind, n.children()) { + (NodeKind::Repeat(r), _) => r.in_all(self), + (NodeKind::SymbolInstance { symbol, .. }, _) => Cost { instances: self.symbol(symbol), copies: 1 }, + (NodeKind::Path { path, .. }, _) => Cost { instances: 0, copies: path.anchor_count().saturating_add(1) }, + (_, Some(c)) => self.nodes(c).plus(Cost { instances: 0, copies: 1 }), + _ => Cost { instances: 0, copies: 1 }, + }; + sum = sum.plus(own); + if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) { + sum = sum.plus(self.nodes(std::slice::from_ref(&m.art))); + } } sum } @@ -643,21 +670,22 @@ impl RepeatSpec { v.truncate(self.kept(NestedCount::new(doc).nodes(&self.source))); v } - /// How many of its instances this Repeat keeps when each makes `nested` instances of the - /// Repeats in its source: as many as fit in [`MAX_REPEAT_INSTANCES`], at least one. - fn kept(&self, nested: usize) -> usize { - self.kind.count().min(MAX_REPEAT_INSTANCES / nested.max(1)).max(1) + /// How many of its instances this Repeat keeps when its source costs `nested`: as many as fit + /// in [`MAX_REPEAT_INSTANCES`] and [`MAX_REPEAT_COPIES`], at least one. + fn kept(&self, nested: Cost) -> usize { + self.kind.count().min(MAX_REPEAT_INSTANCES / nested.instances.max(1)).min(MAX_REPEAT_COPIES / nested.copies.max(1)).max(1) } /// How many instances this Repeat draws ([`Self::transforms`] for `doc`): as many as its /// options make, fewer when the Repeats in its source would take it past - /// [`MAX_REPEAT_INSTANCES`]. + /// [`MAX_REPEAT_INSTANCES`], or the copies of its source past [`MAX_REPEAT_COPIES`]. pub fn instances(&self, doc: Option<&Document>) -> usize { self.kept(NestedCount::new(doc).nodes(&self.source)) } - /// Instances made in all, those of the Repeats nested in the source included. - fn instances_in_all(&self, count: &NestedCount) -> usize { + /// Instances made and nodes copied in all, those of the Repeats nested in the source included. + fn in_all(&self, count: &NestedCount) -> Cost { let nested = count.nodes(&self.source); - self.kept(nested).saturating_mul(nested.max(1)) + let kept = self.kept(nested); + Cost { instances: kept.saturating_mul(nested.instances.max(1)), copies: kept.saturating_mul(nested.copies).saturating_add(1) } } /// Evaluated instances: one group of the (transformed) source per instance (ids 0), as many /// as [`Self::transforms`] keeps for `doc`. @@ -1005,6 +1033,43 @@ mod tests { assert_eq!(made(&small), 18); } + #[test] + fn repeats_in_opacity_masks_share_the_instance_budget() { + let grid = |source: Arc| { + let mut g = RepeatSpec::grid(vec![source], 0.0, 0.0); + if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind { + *rows = 500; + *cols = 500; + } + g + }; + // A shape masked by a 500 × 500 grid draws the grid again for each copy. + let inner = Node::new(NodeId(3), NodeKind::Repeat(grid(sq(0.0, 0.0, 1.0)))); + let mut masked = (*sq(0.0, 0.0, 1.0)).clone(); + masked.extras_mut().mask = Some(Box::new(crate::node::OpacityMask::new(inner, true))); + let outer = grid(Arc::new(masked.clone())); + assert_eq!(outer.transforms(None).len(), 1); + // A disabled mask is not drawn, so it costs nothing. + if let Some(m) = &mut masked.extras_mut().mask { + m.disabled = true; + } + assert_eq!(grid(Arc::new(masked)).transforms(None).len(), 250_000); + } + + #[test] + fn a_large_source_keeps_fewer_copies() { + let mut g = RepeatSpec::grid((0..1000).map(|i| sq(i as f64, 0.0, 1.0)).collect(), 0.0, 0.0); + if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind { + *rows = 500; + *cols = 500; + } + // Each copy is 1000 paths of 4 anchors: far fewer than 250 000 of them fit. + let kept = g.transforms(None).len(); + assert!(kept.saturating_mul(5000) <= MAX_REPEAT_COPIES, "{kept} copies kept"); + assert!(kept > 1); + assert_eq!(g.expand(None).len(), kept); + } + #[test] fn serde_roundtrip() { let mut def = PatternDef::new("Dots", vec![sq(0.0, 0.0, 10.0)]); From 09d8872f15cb14a87563f6a1f6e972dc49e8cbf9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:33:29 -0500 Subject: [PATCH 281/674] Depth limit: merge containers at the cap in one pass over the siblings limit() replaced each too-deep container by its children with Vec::splice in the middle of the sibling list, moving every later sibling each time: a wide list of such containers took quadratic time to load. The list is now rebuilt in order from a worklist, so each node moves a bounded number of times. --- crates/doc/src/depth.rs | 45 ++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index 6f10da9b7a..5abba9c63b 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -107,15 +107,21 @@ fn nested_deeper(now: &[Arc], depth: usize) -> bool { /// an opacity mask too deep are left out); what it held stays hidden or locked as it was. Returns /// whether anything changed. Recurses no deeper than the cap. fn limit(nodes: &mut Vec>, depth: usize) -> bool { - let mut changed = false; - let mut i = 0; - while let Some(n) = nodes.get_mut(i) { - if !nested_deeper(std::slice::from_ref(n), depth) { - i += 1; + if !nested_deeper(nodes, depth) { + return false; + } + // The list is rebuilt in order rather than spliced in place: replacing one container of many + // by what it holds would move all the siblings after it each time. + let mut out = Vec::with_capacity(nodes.len()); + // What is left to look at, the next one last. + let mut left: Vec> = std::mem::take(nodes); + left.reverse(); + while let Some(mut a) = left.pop() { + if !nested_deeper(std::slice::from_ref(&a), depth) { + out.push(a); continue; } - changed = true; - let n = Arc::make_mut(n); + let n = Arc::make_mut(&mut a); if n.extras().mask.as_ref().is_some_and(|m| nested_deeper(std::slice::from_ref(&m.art), depth + 1)) { n.extras_mut().mask = None; } @@ -123,7 +129,7 @@ fn limit(nodes: &mut Vec>, depth: usize) -> bool { if let Some(ch) = n.children_mut() { limit(ch, depth + 1); } - i += 1; + out.push(a); continue; } let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }); @@ -140,9 +146,10 @@ fn limit(nodes: &mut Vec>, depth: usize) -> bool { } } // What it held takes its place, and is looked at in its turn. - nodes.splice(i..=i, held); + left.extend(held.into_iter().rev()); } - changed + *nodes = out; + true } /// A symbol (`false`) or a pattern (`true`) of the document, by name: what art draws by name, an @@ -439,6 +446,24 @@ mod tests { } } + #[test] + fn many_containers_at_the_cap_are_merged_in_order() { + // A group just above the cap holding many groups of two paths each: every group is + // replaced by its two paths, in order (in time linear in their number). + const PAIRS: u64 = 50_000; + let path = |id| Arc::new(Node::path(NodeId(id), Default::default(), Default::default())); + let pairs = (0..PAIRS).map(|i| Arc::new(Node::group(NodeId(1_000_000 + i), vec![path(2 * i + 1), path(2 * i + 2)]))).collect(); + let mut art = Arc::new(Node::group(NodeId(500_000), pairs)); + for i in 0..MAX_DEPTH - 3 { + art = Arc::new(Node::group(NodeId(600_000 + i as u64), vec![art])); + } + let mut d = doc(art); + assert!(d.limit_depth()); + assert!(!d.too_deep(None)); + let holder = d.node(NodeId(500_000)).and_then(Node::children).map(|c| c.iter().map(|c| c.id.0).collect::>()); + assert_eq!(holder, Some((1..=2 * PAIRS).collect())); + } + #[test] fn a_clipping_path_and_a_mask_too_deep_are_left_out_and_hidden_art_stays_hidden() { let mut inner = Node::new(NodeId(9000), NodeKind::Group { children: vec![nested(0), nested(0)], clip: true }); From 1ad42338465c6b94c0ca1cbb4b7c9884068b54ac Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:33:30 -0500 Subject: [PATCH 282/674] Page ranges: overlapping intervals skip indices already picked parse_range walked every index of every interval, so a range that names the same pages many times ("1-,1-,1-,...") cost the number of parts times the page count. Picked indices now link to the next unpicked one, so each page is visited about once whatever the overlap. --- crates/doc/src/range.rs | 46 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/range.rs b/crates/doc/src/range.rs index 87db16f206..7162709bc8 100644 --- a/crates/doc/src/range.rs +++ b/crates/doc/src/range.rs @@ -17,7 +17,9 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { .ok_or_else(|| format!("range `{s}`: `{t}` is not a number from 1 to {count}")) }; let mut out = vec![]; - let mut seen = std::collections::HashSet::new(); + // Past each run of indices picked so far, the index after it: an interval skips the runs it + // overlaps instead of walking them again, so repeating `1-` costs no more than writing it once. + let mut next = std::collections::HashMap::new(); for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) { let (a, b) = match part.replace('\u{2013}', "-").split_once('-') { Some((a, b)) if a.trim().is_empty() && b.trim().is_empty() => return Err(format!("range `{s}`: `{part}` names no number")), @@ -30,10 +32,11 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { if a > b { return Err(format!("range `{s}`: `{part}` runs backwards")); } - for i in a - 1..b { - if seen.insert(i) { - out.push(i); - } + let mut i = unpicked(&mut next, a - 1); + while i < b { + out.push(i); + next.insert(i, i + 1); + i = unpicked(&mut next, i + 1); } } if out.is_empty() { @@ -42,6 +45,23 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { Ok(out) } +/// The first index from `i` on not picked yet, `next` linking each picked index onward (the links +/// followed are then pointed straight at it). +fn unpicked(next: &mut std::collections::HashMap, i: usize) -> usize { + let mut end = i; + while let Some(&j) = next.get(&end) { + end = j; + } + let mut at = i; + while at != end { + match next.insert(at, end) { + Some(j) => at = j, + None => break, + } + } + end +} + #[cfg(test)] mod tests { use super::parse_range; @@ -53,4 +73,20 @@ mod tests { assert!(parse_range("-+2", 5).is_err()); assert_eq!(parse_range("1-3, 5", 5), Ok(vec![0, 1, 2, 4])); } + + #[test] + fn repeats_and_overlaps_are_dropped_in_order() { + assert_eq!(parse_range("3-5, 1-4, 2, 6-, -1", 7), Ok(vec![2, 3, 4, 0, 1, 5, 6])); + assert_eq!(parse_range("2,2,1-2", 4), Ok(vec![1, 0])); + assert_eq!(parse_range("4, 2, 1-", 5), Ok(vec![3, 1, 0, 2, 4])); + } + + #[test] + fn a_range_repeated_many_times_is_read_once() { + // 100 000 pages named 50 000 times: walking the pages for each would take billions of steps. + let s = "1-,".repeat(50_000); + let pages = parse_range(&s, 100_000).unwrap(); + assert_eq!(pages.len(), 100_000); + assert!(pages.iter().enumerate().all(|(i, p)| i == *p)); + } } From 1d7c8f93ab975c5860548f483999c1fe4541dcf3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:35:58 -0500 Subject: [PATCH 283/674] Export for Screens: name patterns and taken names take linear work The file name pattern searched the rest of the pattern for a closing bracket at every opening bracket, so a pattern of many unmatched brackets took quadratic time to render, in the export and its live preview. A token's name never holds a bracket, so the search now stops at the next opening one. Output naming tried -2, -3 and so on from the start for every file given a taken name, so one name pattern over many artboards rebuilt and looked up every number used before for each file. It now goes on from the last number given for that name, and remembers which file got a name from it. --- crates/engine/src/cmd/fileio/naming.rs | 16 +++++++++-- crates/engine/src/cmd/fileio/screens.rs | 36 +++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/fileio/naming.rs b/crates/engine/src/cmd/fileio/naming.rs index e701a03d05..12cf26ca0b 100644 --- a/crates/engine/src/cmd/fileio/naming.rs +++ b/crates/engine/src/cmd/fileio/naming.rs @@ -70,9 +70,11 @@ pub fn render(template: &str, p: &NameParts<'_>) -> String { let mut out = String::with_capacity(t.len() + 16); let mut rest = t; while let Some(c) = rest.chars().next() { - // Bracketed tokens; an unknown one stays as written, with `-` for its brackets. + // Bracketed tokens; an unknown one stays as written, with `-` for its brackets. A token's + // name has no `<`, so the search for its `>` stops at the next `<`: each part of the + // pattern is searched once, not once for every `<` before it. if c == '<' - && let Some(end) = rest.find('>') + && let Some(end) = rest.get(1..).and_then(|r| r.find(['<', '>'])).map(|i| i + 1).filter(|&i| rest.as_bytes().get(i) == Some(&b'>')) && let Some(value) = rest.get(1..end).and_then(|name| token(name, p)) { out.push_str(&value); @@ -155,6 +157,16 @@ mod tests { assert_eq!(render("#", &NameParts { counter: 12345, ..parts() }), "12345"); } + /// Many `<` without a `>`, or before one far away, are each looked at once. + #[test] + fn unmatched_brackets_are_read_in_one_pass() { + let p = parts(); + let n = 200_000; + assert_eq!(render(&"<".repeat(n), &p), "-".repeat(n)); + assert_eq!(render(&format!("{}", "<".repeat(n)), &p), format!("{}Dark", "-".repeat(n))); + assert_eq!(render(">", &p), "-aDark-"); + } + #[test] fn dates_are_strict_about_hyphens_and_days() { for bad in ["2026-1-011", "2-0-2-6-1-0-1-6", "2026--10--16", "2026-02-31", "2026-10-16-", "202610-16"] { diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 384f731aa3..19381709ab 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -521,6 +521,11 @@ struct Output { folders: std::collections::HashMap, /// Sub-folders already made, by their [`fold`]ed names. made: HashSet, + /// For each [`fold`]ed name asked for, the number to try next: many files given one name + /// would otherwise try `-2`, `-3`… from the start each time. + next: std::collections::HashMap, + /// Each [`fold`]ed name asked for with the file (`key`) that got a name from it. + claimed: HashSet<(String, String)>, /// `(relative name, bytes)` kept to return or zip (empty when written to a folder). kept: Vec<(String, Vec)>, /// The paths written. @@ -540,8 +545,14 @@ impl Output { } None => name.to_string(), }; + let asked = (fold(&name), key.to_string()); + // The same file under the same name again: it has its name already. + if self.claimed.contains(&asked) { + return None; + } let (base, ext) = name.rsplit_once('.').map_or((name.as_str(), ""), |(b, e)| (b, e)); - for n in 1.. { + let start = self.next.get(&asked.0).copied().unwrap_or(1); + for n in start.. { let candidate = if n == 1 { name.to_string() } else if ext.is_empty() { @@ -554,6 +565,8 @@ impl Output { Some(_) => continue, None => { self.taken.insert(fold(&candidate), key.to_string()); + self.next.insert(asked.0.clone(), n + 1); + self.claimed.insert(asked); return Some(candidate); } } @@ -1280,7 +1293,26 @@ pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod tests { - use super::{ScreenSize, safe_file_name}; + use super::{Output, ScreenSize, safe_file_name}; + + /// Files given one name are numbered in turn, each numbering going on from the last one (so + /// thousands of them don't each try every number used before), and a file asking again for + /// the name it got is told it has it. + #[test] + fn taken_names_are_numbered_from_the_last_number() { + let mut out = Output::default(); + assert_eq!(out.claim("a.png", "1").as_deref(), Some("a.png")); + assert_eq!(out.claim("A.png", "2").as_deref(), Some("A-2.png")); + assert_eq!(out.claim("a-3.png", "x").as_deref(), Some("a-3.png")); + assert_eq!(out.claim("a.png", "3").as_deref(), Some("a-4.png")); + assert_eq!(out.claim("a.png", "2"), None); + assert_eq!(out.claim("a.png", "1"), None); + assert_eq!(out.claim("sub/a.png", "1").as_deref(), Some("sub/a.png")); + for k in 0..20_000 { + assert!(out.claim("same.png", &k.to_string()).is_some()); + } + assert_eq!(out.claim("same.png", "last").as_deref(), Some("same-20001.png")); + } #[test] fn size_parse_refuses_signs_and_exponents() { From 9a1ac9dad32dbb7a5a48a977080a26abb60b0c01 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:38:22 -0500 Subject: [PATCH 284/674] Brush and symbol libraries: look definitions up by name Making a brush or symbol library, and gathering the resources copied art uses, found each referenced swatch, symbol, pattern, graphic style, text style and brush by scanning all the definitions of its kind, and checked library membership and panel order by scanning the lists again, so a library or document of N definitions cost N squared comparisons. Each kind is now indexed by name the first time a reference to it is followed, and the library code looks names up in sets and maps built once. --- crates/engine/src/cmd/brushlib.rs | 11 +++- crates/engine/src/cmd/clipboard.rs | 13 +++- crates/engine/src/cmd/clipboard/resources.rs | 68 ++++++++++++++++---- crates/engine/src/cmd/symbollib.rs | 41 ++++++++++-- 4 files changed, 111 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 04498111c9..8f36e16f61 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -107,10 +107,14 @@ impl BrushLibrary { /// `name`: the brushes and every resource their art uses. pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result { let all = brush::library(src); - if let Some(n) = names.iter().find(|n| !all.iter().any(|b| b.name == **n)) { + // Names looked up in sets: scanning the lists for each brush made a library of N brushes + // cost N² comparisons. + let have: HashSet<&str> = all.iter().map(|b| b.name.as_str()).collect(); + if let Some(n) = names.iter().find(|n| !have.contains(n.as_str())) { return Err(format!("no brush `{n}`")); } - let picked = all.iter().filter(|b| names.is_empty() || names.contains(&b.name)); + let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); + let picked = all.iter().filter(|b| names.is_empty() || wanted.contains(b.name.as_str())); let clip = Clipboard::gather(src, picked.map(|b| stroke(&b.name)).collect()); let mut doc = clip.to_document(); for l in &mut doc.layers { @@ -120,7 +124,8 @@ impl BrushLibrary { } // The brushes picked and those their art paints with, in the panel order of the document // they came from. - let brushes: Vec = all.into_iter().filter(|b| clip.brushes.iter().any(|c| c.name == b.name)).collect(); + let kept: HashSet<&str> = clip.brushes.iter().map(|c| c.name.as_str()).collect(); + let brushes: Vec = all.iter().filter(|b| kept.contains(b.name.as_str())).cloned().collect(); brush::store(&mut doc, &brushes); doc.title = name.clone(); Ok(Self { name, brushes, doc }) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index ec2722197d..29933309e9 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -161,10 +161,19 @@ impl Clipboard { d.para_styles = self.para_styles.clone().into(); if !self.brushes.is_empty() { let mut lib = vectorcraft_brush::library(&d); + // Each brush's place in the library by name: finding it by scanning the growing list + // made a library of N brushes cost N² comparisons. + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for (i, b) in lib.iter().enumerate() { + at.entry(b.name.clone()).or_insert(i); + } for b in &self.brushes { - match lib.iter_mut().find(|x| x.name == b.name) { + match at.get(&b.name).and_then(|&i| lib.get_mut(i)) { Some(x) => *x = b.clone(), - None => lib.push(b.clone()), + None => { + at.insert(b.name.clone(), lib.len()); + lib.push(b.clone()); + } } } vectorcraft_brush::store(&mut d, &lib); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index e6bd96371b..6a436ab31d 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -14,7 +14,7 @@ //! uses its resources as they are now. use std::cell::OnceCell; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Map, Value, json}; @@ -149,6 +149,39 @@ struct Defs<'a> { char_styles: &'a [TextStyleDef], para_styles: &'a [TextStyleDef], brushes: Brushes<'a>, + /// Where each name is defined, built the first time a kind is followed. + index: DefIndex, +} + +/// The positions of a kind's definitions by name. +type NameIndex = HashMap>; + +/// [`Defs`]' definitions by name (graphic styles by id), each kind indexed the first time a +/// reference to it is followed: finding a name's definitions by scanning them all made a +/// document or library of N definitions that use each other cost N² comparisons. +#[derive(Default)] +struct DefIndex { + swatches: OnceCell, + symbols: OnceCell, + patterns: OnceCell, + styles: OnceCell>>, + char_styles: OnceCell, + para_styles: OnceCell, + brushes: OnceCell, +} + +/// The items of `list` named `name`, in order, `index` holding their positions (built from +/// `list` the first time). +fn named<'l, T>(index: &OnceCell, list: &'l [T], name_of: impl Fn(&T) -> &str, name: &str) -> impl Iterator { + let index = index.get_or_init(|| { + let mut by: NameIndex = HashMap::new(); + for (i, item) in list.iter().enumerate() { + by.entry(name_of(item).to_string()).or_default().push(i); + } + by + }); + let at: &[usize] = index.get(name).map_or(&[], Vec::as_slice); + at.iter().filter_map(move |&i| list.get(i)) } /// The brushes references lead to: a document's library, read the first time a brush is used @@ -178,6 +211,7 @@ impl<'a> Defs<'a> { char_styles: &d.char_styles, para_styles: &d.para_styles, brushes: Brushes::Lazy(d, brushes), + index: DefIndex::default(), } } } @@ -219,8 +253,16 @@ impl Used { fn note<'a>(&mut self, defs: &Defs<'a>, r: Ref<'_>, todo: &mut Vec>) { let (res, name) = match r { Ref::Style(id) => { - if self.styles.insert(id) { - todo.extend(defs.styles.iter().filter(|g| g.id != 0 && g.id == id).map(|g| Source::Appearance(&g.appearance))); + if self.styles.insert(id) && id != 0 { + let index = defs.index.styles.get_or_init(|| { + let mut by: HashMap> = HashMap::new(); + for (i, g) in defs.styles.iter().enumerate() { + by.entry(g.id).or_default().push(i); + } + by + }); + let at = index.get(&id).map_or(&[][..], Vec::as_slice); + todo.extend(at.iter().filter_map(|&i| defs.styles.get(i)).map(|g| Source::Appearance(&g.appearance))); } return; } @@ -237,15 +279,16 @@ impl Used { return; } set.insert(name.to_string()); + let ix = &defs.index; match res { // A tint swatch's base, a gradient swatch's linked stops. - Res::Swatch => todo.extend(defs.swatches.iter().filter(|w| w.name == name).map(|w| Source::Paint(&w.paint))), - Res::Symbol => todo.extend(defs.symbols.iter().filter(|s| s.name == name).map(|s| Source::Node(&s.art))), - Res::Pattern => todo.extend(defs.patterns.iter().filter(|p| p.name == name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))), - Res::CharStyle => todo.extend(defs.char_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))), - Res::ParaStyle => todo.extend(defs.para_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))), + Res::Swatch => todo.extend(named(&ix.swatches, &defs.swatches, |w| &w.name, name).map(|w| Source::Paint(&w.paint))), + Res::Symbol => todo.extend(named(&ix.symbols, defs.symbols, |s| &s.name, name).map(|s| Source::Node(&s.art))), + Res::Pattern => todo.extend(named(&ix.patterns, defs.patterns, |p| &p.name, name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))), + Res::CharStyle => todo.extend(named(&ix.char_styles, defs.char_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), + Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), // A scatter or art brush's art, a pattern brush's tiles. - Res::Brush => todo.extend(defs.brushes.get().iter().filter(|b| b.name == name).flat_map(|b| b.art().into_iter().map(Source::Node))), + Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))), _ => {} } } @@ -649,6 +692,7 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), + index: DefIndex::default(), }; Used::of(&defs, &self.nodes) } @@ -671,7 +715,7 @@ impl Clipboard { self.import_swatches(d, &used, choices, same_doc, &mut out); // Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art // they may brush; the others once those are in. - let mut added_brushes = self.import_brushes(d, &used, same_doc, false, &mut out); + let mut added_brushes: HashSet = self.import_brushes(d, &used, same_doc, false, &mut out).into_iter().collect(); // Character and paragraph styles (their colours relinked first). for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] { for def in mine.iter().filter(|s| used.has(r, &s.name)) { @@ -683,14 +727,14 @@ impl Clipboard { } // Symbols and patterns, compared once relinked. Those added are relinked at the end, when // every new name and graphic style id is known. - let mut added_symbols = vec![]; + let mut added_symbols = HashSet::new(); for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) { let r = &out.relink; let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))); added_symbols.extend(p.new_name(&def.name)); out.placed(Res::Symbol, &def.name, &p); } - let mut added_patterns = vec![]; + let mut added_patterns = HashSet::new(); for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) { // Tile options alike, and the art once relinked. let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 49e9f5a614..e5f2ccfe24 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -7,7 +7,7 @@ //! document VectorCraft opens. `symbol.addFromLibrary` copies symbols into the document; //! `symbol.saveLibrary` writes the document's. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::{Arc, LazyLock}; use serde_json::{Value, json}; @@ -104,10 +104,17 @@ impl SymbolLibrary { /// `name`: the symbols, the symbols they nest and every other resource they use, with their /// Symbol Options. pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result { - if let Some(n) = names.iter().find(|n| !src.symbols.iter().any(|s| s.name == **n)) { + // Each name's first place in the panel, looked up rather than scanned for: scanning the + // symbols for each one made a library of N symbols cost N² comparisons. + let mut order: HashMap<&str, usize> = HashMap::new(); + for (i, s) in src.symbols.iter().enumerate() { + order.entry(s.name.as_str()).or_insert(i); + } + if let Some(n) = names.iter().find(|n| !order.contains_key(n.as_str())) { return Err(format!("no symbol `{n}`")); } - let picked = src.symbols.iter().filter(|s| names.is_empty() || names.contains(&s.name)); + let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); + let picked = src.symbols.iter().filter(|s| names.is_empty() || wanted.contains(s.name.as_str())); let clip = Clipboard::gather(src, picked.map(|s| instance(&s.name)).collect()); let mut doc = clip.to_document(); for l in &mut doc.layers { @@ -116,8 +123,7 @@ impl SymbolLibrary { } } // The panel order of the document they came from. - let order = |n: &str| src.symbols.iter().position(|s| s.name == n); - doc.symbols.sort_by_key(|s| order(&s.name)); + doc.symbols.sort_by_key(|s| order.get(s.name.as_str()).copied()); for s in &doc.symbols.clone() { copy_options(src, &s.name, &mut doc, &s.name); } @@ -344,3 +350,28 @@ fn load(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({"library": info.id, "name": info.name, "count": lib.len()})) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A library made from thousands of symbols holds them all, once each, in the panel order of + /// the document they came from, a name given twice kept at its first place. + #[test] + fn many_symbols_keep_their_panel_order() { + let mut src = Document::new(100.0, 100.0); + let n = 4000; + // Names out of alphabetical order, so the order kept is the panel's. + src.symbols = (0..n).map(|i| Symbol { name: format!("s{}", (i * 7919) % n), art: Arc::new(Node::group(NodeId(i as u64 + 1), vec![])), dynamic: false }).collect(); + let lib = SymbolLibrary::from_document(&src, &[], "Many".into()).unwrap(); + let names = |d: &Document| d.symbols.iter().map(|s| s.name.clone()).collect::>(); + assert_eq!(names(&lib.doc), names(&src)); + let picked = ["s3".to_string(), "s1".to_string()]; + let lib = SymbolLibrary::from_document(&src, &picked, "Two".into()).unwrap(); + let order = |name: &str| src.symbols.iter().position(|s| s.name == name); + let mut want = vec!["s3", "s1"]; + want.sort_by_key(|n| order(n)); + assert_eq!(names(&lib.doc), want); + assert!(SymbolLibrary::from_document(&src, &["nope".to_string()], "None".into()).is_err()); + } +} From 67ef83f1555d9de204d24d74c486f9371dcfdfb1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:39:15 -0500 Subject: [PATCH 285/674] Gradients: midpoints and freeform points find their stops by binary search A gradient whose stops are not strictly increasing (repeated offsets, or a file's unsorted stops) sampled each Classic off-centre midpoint, and each freeform point when recoloring, by scanning the stops from the start, so many stops and points cost their product. Such stops now get an index of the furthest offset reached so far, which never decreases, and each sample finds the pair of stops sample() would pick by binary search, giving the same colour for any order of offsets. --- crates/color/src/gradient.rs | 48 ++++++++++++++++++++++++++++-- crates/color/src/gradient/tests.rs | 38 +++++++++++++++++++++++ 2 files changed, 83 insertions(+), 3 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 402cf3ae26..8441ebcc52 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -175,6 +175,40 @@ fn between(a: &GradientStop, b: &GradientStop, t: f32, mix: &impl Fn(&Color, &Co (mix(&a.color, &b.color, v), a.opacity + (b.opacity - a.opacity) * v) } +/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset among stops `1..=k + 1`. +/// [`Gradient::sample_with`] picks the first pair whose end offset `t` doesn't pass; that is the +/// first pair whose reach `t` doesn't pass, and the reaches never decrease, so the pair is found by +/// binary search whether or not the stops are in order. +struct StopReach(Vec); + +impl StopReach { + fn new(stops: &[GradientStop]) -> Self { + // `f32::max` skips a NaN offset, which `t <= offset` never chooses either. + let reach = stops.iter().skip(1).scan(f32::NEG_INFINITY, |m, s| { + *m = m.max(s.offset); + Some(*m) + }); + Self(reach.collect()) + } + + /// What [`Gradient::sample_with`] gives at `t` for `stops`, the stops this was built from. + fn sample_with(&self, stops: &[GradientStop], t: f32, mix: &impl Fn(&Color, &Color, f32) -> Color) -> (Color, f32) { + let Some(first) = stops.first() else { return (Color::BLACK, 1.0) }; + if t <= first.offset { + return (first.color, first.opacity); + } + let last = || stops.last().map_or((Color::BLACK, 1.0), |l| (l.color, l.opacity)); + if t.is_nan() { + return last(); + } + let k = self.0.partition_point(|r| *r < t); + match (stops.get(k), stops.get(k + 1)) { + (Some(a), Some(b)) => between(a, b, t, mix), + _ => last(), + } + } +} + fn one() -> f32 { 1.0 } @@ -245,9 +279,11 @@ impl Gradient { /// the one before it stopped, so the work is the samples plus the stops, not their product. pub fn sample_increasing_with(&self, ts: impl IntoIterator, mix: impl Fn(&Color, &Color, f32) -> Color) -> Vec<(Color, f32)> { let stops = &self.stops; - // The shared index assumes ordered stops; others (a file's, unsorted) sample one by one. + // The shared cursor assumes ordered stops; others (a file's, unsorted) look each sample up + // in a [`StopReach`], so they cost a binary search each rather than a scan of the stops. if stops.windows(2).any(|w| w[1].offset < w[0].offset) { - return ts.into_iter().map(|t| self.sample_with(t, &mix)).collect(); + let reach = StopReach::new(stops); + return ts.into_iter().map(|t| reach.sample_with(stops, t, &mix)).collect(); } let mut j = 0; ts.into_iter() @@ -284,6 +320,9 @@ impl Gradient { fn expanded_with_stops(&self) -> impl Iterator, Option)> + '_ { // Direct interpolation matches `sample` only for strictly increasing offsets. let increasing = self.stops.windows(2).all(|w| w[0].offset < w[1].offset); + // Otherwise (repeated or unsorted offsets) each midpoint is looked up as `sample` would + // find it, but by binary search: a scan of all the stops per midpoint cost their square. + let reach = if increasing || !self.method.is_classic() { None } else { Some(StopReach::new(&self.stops)) }; self.stops.iter().enumerate().flat_map(move |(i, s)| { let next = self.stops.get(i + 1); let off_centre = (s.midpoint - 0.5).abs() > 1e-3; @@ -293,7 +332,10 @@ impl Gradient { // Mixed from the two stops it lies between, as `sample` would: searching all the // stops again for each midpoint made many stops cost their square. let mix = |a: &Color, b: &Color, v| self.method.mix(a, b, v); - let (c, o) = if increasing { between(s, n, t, &mix) } else { self.sample_with(t, mix) }; + let (c, o) = match &reach { + Some(reach) => reach.sample_with(&self.stops, t, &mix), + None => between(s, n, t, &mix), + }; (t, c, o, Some(s.midpoint), None) }); // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 2248030758..7084be18cc 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -23,6 +23,44 @@ fn increasing_samples_match_single_samples() { assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one); } +/// Looking stops up by their reach finds what scanning them does, for any order of offsets, +/// repeated, out-of-order and NaN ones included, and for positions outside and between them. +#[test] +fn stop_reach_matches_scanning_the_stops() { + let colors = ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#00ffff", "#000000"]; + let offsets: [&[f32]; 5] = [ + &[0.1, 0.4, 0.4, 0.2, 0.9, 0.5], + &[0.5, 0.5, 0.5, 0.5], + &[0.9, 0.1, 0.8, 0.2, 0.7, 0.3], + &[0.2, f32::NAN, 0.6, 0.1, f32::NAN, 1.0], + &[f32::NAN, 0.3, 0.3, 0.8], + ]; + for offsets in offsets { + let stops: Vec = + offsets.iter().zip(colors.iter().cycle()).map(|(&o, hex)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::from_hex(hex).unwrap()) }).collect(); + let g = Gradient::new(GradientKind::Linear, stops); + let reach = StopReach::new(&g.stops); + for t in (-4..=44).map(|k| k as f32 / 40.0).chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]) { + assert_eq!(reach.sample_with(&g.stops, t, &Color::lerp_keep_model), g.sample_with(t, Color::lerp_keep_model), "{offsets:?} at {t}"); + } + } +} + +/// Repeated offsets turn off the direct midpoint mix, and the midpoints still come out as +/// `sample` gives them, with work that stays near linear in the stops (thousands of stops at one +/// offset used to scan them all for each midpoint). +#[test] +fn expanded_with_repeated_offsets_samples_midpoints() { + let stop = |offset: f32, hex: &str| GradientStop { midpoint: 0.25, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) }; + let g = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000"), stop(0.5, "#00ff00"), stop(0.5, "#0000ff"), stop(1.0, "#000000")]); + for (t, c, o, mid) in g.expanded().filter(|e| e.3.is_some()) { + assert_eq!(mid, Some(0.25)); + assert_eq!((c, o), g.sample(t), "midpoint at {t}"); + } + let many = Gradient::new(GradientKind::Linear, (0..200_000).map(|i| stop(if i == 0 { 0.0 } else { 0.5 }, "#808080")).collect()); + assert_eq!(many.expanded().count(), 2 * 200_000 - 1); +} + #[test] fn midpoint_shifts() { let mut g = Gradient::default(); From f1d4969864f1db89110855414efbb94d5d08d211 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:43:17 -0500 Subject: [PATCH 286/674] DXF export: bound curve flattening work and expanded symbol art Flattening a path for DXF capped the points it kept but kept flattening every remaining curve after the cap, each curve at a fixed tolerance however large it was. Symbol instances placed inside symbols were cloned and walked once per instance with only the nesting depth bounded, so a small symbol graph of empty symbols could fan out into billions of visits that write nothing. - Flatten through vectorcraft_geom::flatten (a bounded number of segments per curve) and stop at the first curve past the point or segment budget. - Charge each symbol instance's art to MAX_SYMBOL_NODES with charge_symbol_art before placing it, as the document does elsewhere; once spent, no further instances are expanded. --- crates/cad/src/scene.rs | 83 +++++++++++++++++++++++++++++++++++------ crates/cad/src/tests.rs | 18 +++++++++ 2 files changed, 90 insertions(+), 11 deletions(-) diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index b7aeb5c6c2..a82a891d1d 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -271,7 +271,11 @@ const MAX_ENTITIES: u32 = 10_000_000; /// The largest x or y a path may have to be flattened, and the most points its polygons keep. const MAX_COORD: f64 = 1e9; -const MAX_POINTS: usize = 4_000_000; +const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 4_000_000 }; +/// The most segments flattening one path makes, kept or not (repeats of a point are dropped). +const MAX_FLATTEN_SEGMENTS: usize = 4 * MAX_POINTS; + +const SYMBOLS_LEFT_OUT: &str = "symbols placed inside symbols hold too many objects for DXF: the instances past that were left out"; /// Do the dashes of `d` start at the start of their pattern, as a linetype's do? A pattern of /// odd length repeats twice in its linetype. @@ -296,14 +300,19 @@ fn polygons(bp: &BezPath) -> Vec> { } let mut out: Vec> = vec![]; let mut cur: Vec = vec![]; - let mut points = 0usize; - let mut push = |p: Point, cur: &mut Vec| { - if points < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) { - points += 1; + // Points kept, and segments made: once either budget is spent, no further curve is flattened. + let points = std::cell::Cell::new(0usize); + let segments = std::cell::Cell::new(0usize); + let push = |p: Point, cur: &mut Vec| { + segments.set(segments.get() + 1); + if points.get() < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) { + points.set(points.get() + 1); cur.push(p); } }; - kurbo::flatten(bp.iter(), FLATNESS, |el| match el { + let elements = bp.iter().take_while(|_| points.get() < MAX_POINTS && segments.get() < MAX_FLATTEN_SEGMENTS); + // Each curve is flattened into a bounded number of segments, however large it is. + vectorcraft_geom::flatten(elements, FLATNESS, |el| match el { PathEl::MoveTo(p) => { out.push(std::mem::take(&mut cur)); push(p, &mut cur); @@ -412,6 +421,9 @@ pub(crate) struct Scene<'a> { opacity: f32, /// Symbols and brush art being written inside one another. nest: u32, + /// Objects the symbol instances written held, together + /// ([`vectorcraft_doc::MAX_SYMBOL_NODES`]). + symbol_nodes: u64, } impl<'a> Scene<'a> { @@ -441,6 +453,8 @@ impl<'a> Scene<'a> { extents: None, opacity: 1.0, nest: 0, + // Tests spend all but a million of it up front. + symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 }, } } @@ -542,13 +556,35 @@ impl<'a> Scene<'a> { NodeKind::Text(t) => self.text(n, t), NodeKind::Image(im) => self.image(im), NodeKind::SymbolInstance { symbol, xf } => { - if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) + let doc = self.doc; + if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES { + // Spent: no more instances are looked at, so what's left costs nothing. + self.warn(SYMBOLS_LEFT_OUT); + } else if let Some(sym) = doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST - && let Some(art) = self.doc.place_symbol_art_unclipped(symbol, &vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n), *xf) { - self.nest += 1; - self.node(&art, true); - self.nest -= 1; + // Symbols holding instances of symbols are written in full for each instance, + // empty or not: every instance's art counts against one budget for the export. + let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); + let count = art.count_with_masks() as u64; + let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed(&art, doc)); + let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || { + let placed = doc.place_symbol_art_unclipped(symbol, &art, *xf); + let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64); + (placed, n) + }); + match placed { + Some(Some(art)) => { + self.nest += 1; + self.node(&art, true); + self.nest -= 1; + } + Some(None) => {} + None => { + self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; + self.warn(SYMBOLS_LEFT_OUT); + } + } } } // Live blends, envelopes, meshes and repeats are written as their evaluated art. @@ -1262,3 +1298,28 @@ fn first_solid(n: &Node) -> Option { }); own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c))) } + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn flattening_a_path_of_huge_curves_stops_at_its_budget() { + // Each curve, a hundred million points across, flattens to thousands of segments at + // FLATNESS; a small square after them is past the budget and left out. + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for i in 0..20_000 { + let y = if i % 2 == 0 { 1e8 } else { -1e8 }; + bp.curve_to((1e8, y), (-1e8, y), (0.0, 0.0)); + } + bp.move_to((10.0, 10.0)); + bp.line_to((20.0, 10.0)); + bp.line_to((20.0, 20.0)); + bp.close_path(); + let polys = polygons(&bp); + let points: usize = polys.iter().map(Vec::len).sum(); + assert!(points <= MAX_POINTS, "{points} points"); + assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out"); + } +} diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index f1b537b70b..b09a8f0800 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1007,3 +1007,21 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { let o = DxfOptions { crop: true, ..opts(&d) }; assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); } + +#[test] +fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { + // Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty + // instances, which write no entities, past the million objects tests export with. + let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "L5".into(), xf: Affine::IDENTITY })]); + let empty = Node::group(d.alloc_id(), vec![]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "L0".into(), art: Arc::new(empty) }); + for level in 1..=5 { + let below = format!("L{}", level - 1); + let children = (0..100).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: below.clone(), xf: Affine::IDENTITY }))).collect(); + let art = Node::group(d.alloc_id(), children); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) }); + } + let out = export(&d, &opts(&d)).unwrap(); + assert!(entities(&out).is_empty()); + assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings); +} From 572a51894f6cb6faa3afc31caae6566efe6b8b52 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:46:58 -0500 Subject: [PATCH 287/674] Affinity import: index the fields of large objects and read four rectangle corners Object::get scanned every field for each lookup, and a shared object is looked up again on every visit. Objects with more than 16 fields now keep a sorted tag index (first and last position), so get and get_last are binary searches with the same first/last- occurrence results. Rectangle corner types and radii read at most the four entries that can matter instead of converting the whole arrays. --- crates/affinity/src/shapes.rs | 12 ++--- crates/affinity/src/stream.rs | 97 ++++++++++++++++++++++++++++++++--- 2 files changed, 97 insertions(+), 12 deletions(-) diff --git a/crates/affinity/src/shapes.rs b/crates/affinity/src/shapes.rs index c5d1b31e0e..a2503539f4 100644 --- a/crates/affinity/src/shapes.rs +++ b/crates/affinity/src/shapes.rs @@ -13,8 +13,7 @@ const MAX_SIDES: i64 = 10_000; /// The last value of a tag: a shape changed from one kind to another keeps a stale first block. fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> { - let t = Tag::of(tag); - r.s.object(id)?.fields.iter().rev().find(|(k, _)| *k == t).map(|(_, v)| v) + r.s.object(id)?.get_last(Tag::of(tag)) } fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option { @@ -51,12 +50,13 @@ pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> let class = r.s.class(shape)?; let sub = match &class.0.to_be_bytes() { b"ShNR" | b"ShRR" => { - let types = match last(r, shape, b"CTyp") { - Some(Value::Array(a)) => a.iter().map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(), + // Only the four corners' entries can matter: longer arrays are read no further. + let types: Vec> = match last(r, shape, b"CTyp") { + Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(), _ => Vec::new(), }; - let radii = match last(r, shape, b"ShCR") { - Some(Value::Floats(v)) => v.iter().map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(), + let radii: Vec = match last(r, shape, b"ShCR") { + Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(), _ => Vec::new(), }; // Corners follow the first one (top left) unless they were unlocked; then each has diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs index 7a3010251f..9d31f35e70 100644 --- a/crates/affinity/src/stream.rs +++ b/crates/affinity/src/stream.rs @@ -73,11 +73,67 @@ pub struct Object { pub chain: Vec, /// Fields in stream order; positional fields have tag 0. pub fields: Vec<(Tag, Value)>, + /// For objects with many fields: each tag with the positions of its first and last field, + /// sorted by tag, so a lookup isn't a scan of every field (a shared object is looked up + /// again on every visit). Built by [`Object::index`]; empty for small objects. + index: Vec<(Tag, u32, u32)>, } +/// Objects with more fields than this get an [`Object::index`]; fewer are scanned. +const INDEXED_FIELDS: usize = 16; + impl Object { + pub fn new(class: Tag, kind: Kind, chain: Vec, fields: Vec<(Tag, Value)>) -> Self { + let mut o = Self { class, kind, chain, fields, index: Vec::new() }; + o.index(); + o + } + + /// (Re)build the tag index after `fields` changed. + fn index(&mut self) { + self.index.clear(); + if self.fields.len() <= INDEXED_FIELDS { + return; + } + let mut index: Vec<(Tag, u32, u32)> = Vec::new(); + if index.try_reserve_exact(self.fields.len()).is_err() { + return; + } + // Fields beyond u32 positions are impossible: a stream holds at most MAX_VALUES values. + index.extend(self.fields.iter().enumerate().filter_map(|(i, (t, _))| u32::try_from(i).ok().map(|i| (*t, i, i)))); + // Stable: equal tags stay in stream order, so the run of a tag starts at its first field. + index.sort_by_key(|(t, _, _)| *t); + index.dedup_by(|later, first| { + if later.0 == first.0 { + first.2 = later.2; + true + } else { + false + } + }); + index.shrink_to_fit(); + self.index = index; + } + + fn position(&self, tag: Tag, last: bool) -> Option { + if self.index.is_empty() { + let mut fields = self.fields.iter().enumerate(); + let hit = if last { fields.rev().find(|(_, (t, _))| *t == tag) } else { fields.find(|(_, (t, _))| *t == tag) }; + return hit.map(|(i, _)| i); + } + let at = self.index.binary_search_by_key(&tag, |(t, _, _)| *t).ok()?; + let (_, first, end) = self.index.get(at)?; + usize::try_from(if last { *end } else { *first }).ok() + } + + /// The first field tagged `tag`. pub fn get(&self, tag: Tag) -> Option<&Value> { - self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v) + self.fields.get(self.position(tag, false)?).map(|(_, v)| v) + } + + /// The last field tagged `tag` (a shape changed from one kind to another keeps a stale first one). + pub fn get_last(&self, tag: Tag) -> Option<&Value> { + self.fields.get(self.position(tag, true)?).map(|(_, v)| v) } } @@ -124,10 +180,11 @@ pub fn parse(bytes: &[u8]) -> Result { c.u32()?; } let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 }; - let root = p.push(Object { class, kind: Kind::Root, chain: vec![class], fields: Vec::new() })?; + let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?; let fields = p.fields(true, class)?; if let Some(o) = p.objects.get_mut(root) { o.fields = fields; + o.index(); } Ok(Stream { root, objects: p.objects }) } @@ -252,7 +309,7 @@ impl Parser<'_> { } 0x30 => { let fields = self.fields(false, class)?; - let id = self.push(Object { class, kind: Kind::Positional, chain: Vec::new(), fields })?; + let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?; Value::Obj(Some(id)) } 0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")), @@ -354,7 +411,7 @@ impl Parser<'_> { } }; let fields = self.fields(true, class)?; - let id = self.push(Object { class, kind: Kind::Inline, chain: vec![class], fields })?; + let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?; Ok(Value::Obj(Some(id))) } @@ -373,7 +430,7 @@ impl Parser<'_> { return Err(Error::Malformed("object defined twice")); } // Register before the fields: an object's own fields may refer back to it. - let id = self.push(Object { class: Tag(0), kind: Kind::Shared, chain: Vec::new(), fields: Vec::new() })?; + let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?; self.shared.insert(key, id); let mut chain = Vec::new(); let mut fields = Vec::new(); @@ -399,8 +456,36 @@ impl Parser<'_> { let class = chain.first().copied().unwrap_or(Tag(0)); fields.extend(self.fields(true, class)?); if let Some(o) = self.objects.get_mut(id) { - *o = Object { class, kind: Kind::Shared, chain, fields }; + *o = Object::new(class, Kind::Shared, chain, fields); } Ok(Value::Obj(Some(id))) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lookups_in_a_large_object_find_the_first_and_last_fields_of_a_tag() { + let tag = |i: u32| Tag(0x4100_0000 + i); + let mut fields: Vec<(Tag, Value)> = (0..1000).map(|i| (tag(i % 300), Value::UInt(u64::from(i)))).collect(); + fields.push((tag(7), Value::Str("last".into()))); + let o = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), fields.clone()); + assert!(!o.index.is_empty()); + // The index has one entry per distinct tag, not per field. + assert_eq!(o.index.len(), 300); + for t in 0..300 { + let first = fields.iter().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); + let last = fields.iter().rev().find(|(k, _)| *k == tag(t)).map(|(_, v)| v); + assert_eq!(o.get(tag(t)), first); + assert_eq!(o.get_last(tag(t)), last); + } + assert_eq!(o.get(tag(300)), None); + assert_eq!(o.get_last(tag(7)), Some(&Value::Str("last".into()))); + let small = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), vec![(tag(1), Value::Bool(true)), (tag(1), Value::Bool(false))]); + assert!(small.index.is_empty()); + assert_eq!(small.get(tag(1)), Some(&Value::Bool(true))); + assert_eq!(small.get_last(tag(1)), Some(&Value::Bool(false))); + } +} From 1f80c018c7c149ecba6f625fe6775d0777b8067a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:03:30 -0500 Subject: [PATCH 288/674] Gradients: compare NaN samples as printed in the stop lookup test --- crates/color/src/gradient/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 7084be18cc..6c9a08a9d7 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -41,7 +41,9 @@ fn stop_reach_matches_scanning_the_stops() { let g = Gradient::new(GradientKind::Linear, stops); let reach = StopReach::new(&g.stops); for t in (-4..=44).map(|k| k as f32 / 40.0).chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]) { - assert_eq!(reach.sample_with(&g.stops, t, &Color::lerp_keep_model), g.sample_with(t, Color::lerp_keep_model), "{offsets:?} at {t}"); + // Compared as printed: a NaN offset mixes NaN colours, which are equal only so. + let (got, want) = (reach.sample_with(&g.stops, t, &Color::lerp_keep_model), g.sample_with(t, Color::lerp_keep_model)); + assert_eq!(format!("{got:?}"), format!("{want:?}"), "{offsets:?} at {t}"); } } } From f8f9280d75d114b019536647a19322502875b578 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:31:03 -0500 Subject: [PATCH 289/674] Repeat test: drop the full-budget expand from the large-source test --- crates/doc/src/pattern.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index c0ac821700..2a98df62ce 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -1067,7 +1067,6 @@ mod tests { let kept = g.transforms(None).len(); assert!(kept.saturating_mul(5000) <= MAX_REPEAT_COPIES, "{kept} copies kept"); assert!(kept > 1); - assert_eq!(g.expand(None).len(), kept); } #[test] From aaca80c961048161a3c7ab3ed8079727ac82b020 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:36:16 -0500 Subject: [PATCH 290/674] Affinity import: bound archive index names and charge failed entry extraction (#5291) The table chain's records and entry names now have a whole-archive allowance, only the first name of an id is decoded and kept (no clone into the entry map), and an entry's size is charged before it is decompressed and stays charged when it fails, with the failure remembered so a broken entry is not decompressed again. --- crates/affinity/src/container.rs | 91 +++++++++++++++++++++++--------- crates/affinity/src/tests.rs | 28 ++++++++++ 2 files changed, 93 insertions(+), 26 deletions(-) diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs index 6b1df95103..f26948e919 100644 --- a/crates/affinity/src/container.rs +++ b/crates/affinity/src/container.rs @@ -15,6 +15,13 @@ const DOCUMENT_KIND: &[u8; 4] = b"nsrP"; /// A save appends one table; real files have one to a few hundred. const MAX_TABLES: usize = 4096; +/// Allocation records read over the whole table chain. Each save lists every entry again, so a +/// document with a few hundred saves of a few thousand entries stays far below; tables whose +/// record regions overlap (or a table chain of thousands of huge tables) can't multiply the work. +const MAX_INDEX_RECORDS: usize = 1 << 22; +/// Bytes of entry names kept by the index (after lossy UTF-8 decoding, which can triple a name). +/// Real names (`doc.dat`, `d/12`) are a few bytes each. +const MAX_INDEX_NAME_BYTES: usize = 16 << 20; /// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes. const MAX_ZSTD_WINDOW: u64 = 64 << 20; @@ -75,6 +82,9 @@ pub struct Archive<'a> { pub revisions: usize, extracted: usize, limits: Limits, + /// Entries whose extraction failed after their size was charged: asked again, they fail + /// again without being decompressed again. + failed: HashMap, } pub(crate) struct Cursor<'a> { @@ -157,7 +167,15 @@ pub fn header(bytes: &[u8]) -> Result { impl<'a> Archive<'a> { pub fn open(bytes: &'a [u8], limits: Limits) -> Result { + Self::open_within(bytes, limits, MAX_INDEX_RECORDS, MAX_INDEX_NAME_BYTES) + } + + /// [`Archive::open`] reading at most `max_records` allocation records and keeping at most + /// `max_name_bytes` bytes of entry names, both over the whole table chain. + pub(crate) fn open_within(bytes: &'a [u8], limits: Limits, max_records: usize, max_name_bytes: usize) -> Result { let header = header(bytes)?; + let mut records_left = max_records; + let mut name_bytes_left = max_name_bytes; // Newest record per id: (table date, table index, record). let mut latest: HashMap)> = HashMap::new(); let mut names: HashMap = HashMap::new(); @@ -189,6 +207,7 @@ impl<'a> Archive<'a> { let dirs = c.u16()?; c.take(1)?; for _ in 0..files { + records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; let id = c.u32()?; let flag = c.u8()?; let mut record = None; @@ -224,8 +243,13 @@ impl<'a> Archive<'a> { } if flag == 0 { let len = usize::from(c.u16()?); - let name = String::from_utf8_lossy(c.take(len)?).into_owned(); - names.entry(id).or_insert(name); + let raw = c.take(len)?; + // Only the first name of an id is kept: later ones are not even decoded. + if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) { + let name = String::from_utf8_lossy(raw); + name_bytes_left = name_bytes_left.checked_sub(name.len()).ok_or(Error::Limit("archive entry names too long"))?; + slot.insert(name.into_owned()); + } } // Equal dates: the first table in the chain (the newest) wins, as in afread. let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d); @@ -234,6 +258,7 @@ impl<'a> Archive<'a> { } } for _ in 0..dirs { + records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?; let len = usize::from(c.u16()?); c.take(10)?; c.take(len)?; @@ -241,12 +266,12 @@ impl<'a> Archive<'a> { } let mut entries = HashMap::new(); for (id, (_, _, record)) in latest { - if let (Some(mut e), Some(name)) = (record, names.get(&id)) { - e.name = name.clone(); + if let (Some(mut e), Some(name)) = (record, names.remove(&id)) { + e.name = name; entries.insert(e.name.clone(), e); } } - Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits }) + Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits, failed: HashMap::new() }) } pub fn entry(&self, name: &str) -> Option<&Entry> { @@ -279,7 +304,10 @@ impl<'a> Archive<'a> { } pub fn read(&mut self, name: &str) -> Result, Error> { - let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone(); + if let Some(e) = self.failed.get(name) { + return Err(*e); + } + let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?; let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?; if size > self.limits.max_entry { return Err(Error::Limit("archive entry too large")); @@ -288,30 +316,41 @@ impl<'a> Archive<'a> { if total > self.limits.max_total { return Err(Error::Limit("document too large")); } - let mut c = Cursor::new(self.bytes, offset(e.offset)?); - if c.take(4)? != b"#Fil" { - return Err(Error::Malformed("archive entry has no data block")); - } - let method = e.compression & 3; - let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size }; - let data = c.take(offset(stored_len)?)?; - let mut out = match method { - 1 => inflate(data, size)?, - 2 => unzstd(data, size)?, - _ => data.to_vec(), - }; - if out.len() != size { - return Err(Error::Malformed("archive entry size mismatch")); - } - unpredict(&mut out, e.compression)?; - if crc32fast::hash(&out) != e.crc { - return Err(Error::Malformed("archive entry checksum mismatch")); - } + // Charged before the work, and kept when it fails: an entry that fails its checksum + // can't be decompressed over and over for free. self.extracted = total; - Ok(out) + let result = extract(self.bytes, e, size); + if let Err(err) = result { + self.failed.insert(name.to_owned(), err); + } + result } } +/// Decompress entry `e` of `bytes` (declared `size` bytes), undo its predictor and check its CRC. +fn extract(bytes: &[u8], e: &Entry, size: usize) -> Result, Error> { + let mut c = Cursor::new(bytes, offset(e.offset)?); + if c.take(4)? != b"#Fil" { + return Err(Error::Malformed("archive entry has no data block")); + } + let method = e.compression & 3; + let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size }; + let data = c.take(offset(stored_len)?)?; + let mut out = match method { + 1 => inflate(data, size)?, + 2 => unzstd(data, size)?, + _ => data.to_vec(), + }; + if out.len() != size { + return Err(Error::Malformed("archive entry size mismatch")); + } + unpredict(&mut out, e.compression)?; + if crc32fast::hash(&out) != e.crc { + return Err(Error::Malformed("archive entry checksum mismatch")); + } + Ok(out) +} + /// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught /// without unbounded allocation. fn read_bounded(mut r: impl Read, size: usize) -> Result, Error> { diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index eeb709d34d..75b6b7b146 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -261,6 +261,34 @@ mod archive { assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); } + #[test] + fn an_entry_that_fails_its_checksum_is_charged_once_and_not_decompressed_again() { + let d = doc(); + let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None); + let mut broken = file.clone(); + broken[90] ^= 0x55; + let mut a = Archive::open(&broken, Limits::default()).unwrap(); + let first = a.read("doc.dat").unwrap_err(); + // The work was done, so it counts against the import even though it failed. + assert_eq!(a.extracted(), d.len()); + assert_eq!(a.read("doc.dat").unwrap_err(), first); + assert_eq!(a.extracted(), d.len()); + // A budget that only covers one attempt is not exceeded by asking again. + let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len() }).unwrap(); + assert!(a.read("doc.dat").is_err()); + assert_eq!(a.read("doc.dat").unwrap_err(), first); + } + + #[test] + fn the_table_index_has_a_budget_for_records_and_names() { + let d = doc(); + let long = "n".repeat(300); + let file = synth::container(&[("doc.dat", &d, Method::Stored), (&long, b"tile", Method::Stored)], None); + Archive::open_within(&file, Limits::default(), 2, 307).unwrap(); + assert_eq!(Archive::open_within(&file, Limits::default(), 1, 1 << 20).unwrap_err(), Error::Limit("too many archive entries")); + assert_eq!(Archive::open_within(&file, Limits::default(), 2, 306).unwrap_err(), Error::Limit("archive entry names too long")); + } + // Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's // window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than // the format permits for a block. 0.9.1 refuses it. From 029661cf78fb1db0854d35417396953aa981a835 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 18:55:11 -0800 Subject: [PATCH 291/674] .ai save: the editing copy places symbol instances through their 9-slice guides A scaled instance of a symbol with 9-slice guides was written with its art stretched as a whole. The editing copy now places it as the canvas draws it, and leaves the instance out when placing it would pass the symbol art limit. --- crates/eps/src/ai_editing/tests.rs | 26 ++++++++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 18 ++++++++++-------- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 915cda084d..4f533193d6 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -721,6 +721,32 @@ fn inline_graphics_in_type_are_written_as_their_art() { assert!(at(&blue) < at(&red), "the stroke above the characters is over the inline graphic"); } +/// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it: the corner +/// keeps its size while the rest stretches. +#[test] +fn a_scaled_nine_slice_symbol_instance_keeps_its_corner_size() { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + let square = |doc: &mut Document, r: Rect| { + Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0)) + }; + let frame = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0))); + let corner = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0))); + let art = Node::group(doc.alloc_id(), vec![frame, corner]); + doc.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + doc.set_symbol_nine_slice("S", Some(vectorcraft_doc::SymbolNineSlice::default())); + let xf = Affine::scale_non_uniform(2.0, 1.5); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let sizes: Vec<(i64, i64)> = + all.iter().filter_map(|p| p.geometric_bounds()).map(|b| (b.width().round() as i64, b.height().round() as i64)).collect(); + assert!(sizes.contains(&(10, 10)), "the corner keeps its size: {sizes:?}"); + assert!(sizes.contains(&(200, 150)), "the frame is scaled: {sizes:?}"); +} + /// Nested symbols whose instances multiply stop at [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects of /// symbol art in all, with a warning. #[test] diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 1cf0390ca4..cd5f80ced6 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -254,14 +254,16 @@ impl<'a> Writer<'a> { && self.take_symbol(&sym.art) { // Stained by the instance's fill, as the canvas draws it. - let mut art = vectorcraft_brush::instance_art(&sym.art, n); - art.transform(*xf, false); - art.visible = true; - art.locked = false; - art.name = None; - self.nest += 1; - self.node(&art); - self.nest -= 1; + let stained = vectorcraft_brush::instance_art(&sym.art, n); + // Through the symbol's 9-slice guides when it has them, as the canvas draws it. + if let Some(mut art) = self.doc.place_symbol_art(symbol, &stained, *xf) { + art.visible = true; + art.locked = false; + art.name = None; + self.nest += 1; + self.node(&art); + self.nest -= 1; + } } self.line("U"); } From 5df9b2d1e093d909dacc6caa5b82a8c87beb88a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 18:59:11 -0800 Subject: [PATCH 292/674] .ai save: nine-slice symbol placement counts toward the symbol art limit --- crates/eps/src/ai_editing/writer.rs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index cd5f80ced6..3252031886 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -249,20 +249,38 @@ impl<'a> Writer<'a> { NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); self.line("u"); - if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) + let doc = self.doc; + if let Some(sym) = doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST - && self.take_symbol(&sym.art) { // Stained by the instance's fill, as the canvas draws it. let stained = vectorcraft_brush::instance_art(&sym.art, n); - // Through the symbol's 9-slice guides when it has them, as the canvas draws it. - if let Some(mut art) = self.doc.place_symbol_art(symbol, &stained, *xf) { + // Through the symbol's 9-slice guides when it has them, as the canvas draws it; + // placing through them needs room for the most objects it can make, and the + // objects it makes count. + let map = doc.symbol_slice_map(symbol, *xf); + let most = map.map_or(stained.count() as u64, |m| m.most_placed(&stained, doc)); + let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || { + let art = match map { + Some(m) => m.place(&stained, doc), + None => { + let mut a = stained.clone(); + a.transform(*xf, false); + a + } + }; + let count = if map.is_some() { art.count_with_masks() } else { art.count() } as u64; + (art, count) + }); + if let Some(mut art) = placed { art.visible = true; art.locked = false; art.name = None; self.nest += 1; self.node(&art); self.nest -= 1; + } else { + self.warn(SYMBOL_LIMIT); } } self.line("U"); From ed4a663986ab739711058ac80b9dc813d11e5690 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 22:33:39 -0500 Subject: [PATCH 293/674] DXF export: charge symbol art as it is placed unclipped, test the segment budget Count nine-slice symbol art with clips off, as place_symbol_art_unclipped places it, so art crossing the guides is not over-charged; add a test that the flattening segment budget stops a path independently of the point budget; format. --- crates/cad/src/scene.rs | 22 +++++++++++++++++++++- crates/cad/src/tests.rs | 3 ++- crates/doc/src/symbol_nine_slice.rs | 13 +++++++++---- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index a82a891d1d..d7e20654a1 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -567,7 +567,8 @@ impl<'a> Scene<'a> { // empty or not: every instance's art counts against one budget for the export. let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); let count = art.count_with_masks() as u64; - let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed(&art, doc)); + // Counted as `place_symbol_art_unclipped` places it: no clip groups. + let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed_unclipped(&art, doc)); let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || { let placed = doc.place_symbol_art_unclipped(symbol, &art, *xf); let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64); @@ -1322,4 +1323,23 @@ mod budget_tests { assert!(points <= MAX_POINTS, "{points} points"); assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out"); } + + #[test] + fn flattening_a_path_of_repeated_points_stops_at_its_segment_budget() { + // Repeats of a point are dropped, so these keep one point but still count as segments: + // the segment budget, not the point budget, leaves out the square after them. + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for _ in 0..MAX_FLATTEN_SEGMENTS { + bp.line_to((0.0, 0.0)); + } + bp.move_to((10.0, 10.0)); + bp.line_to((20.0, 10.0)); + bp.line_to((20.0, 20.0)); + bp.close_path(); + let polys = polygons(&bp); + let points: usize = polys.iter().map(Vec::len).sum(); + assert!(points < MAX_POINTS, "{points} points"); + assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out"); + } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index b09a8f0800..e4984c3332 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1017,7 +1017,8 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "L0".into(), art: Arc::new(empty) }); for level in 1..=5 { let below = format!("L{}", level - 1); - let children = (0..100).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: below.clone(), xf: Affine::IDENTITY }))).collect(); + let children = + (0..100).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: below.clone(), xf: Affine::IDENTITY }))).collect(); let art = Node::group(d.alloc_id(), children); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) }); } diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index a37b92eef6..faa9afe6fb 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -364,6 +364,11 @@ impl NineSliceMap { self.most_at(art, &boxes, 0) } + /// [`Self::most_placed`] for [`Self::place_unclipped`]: the most objects it makes of `art`. + pub fn most_placed_unclipped(&self, art: &Node, doc: &Document) -> u64 { + Self { clips: false, ..*self }.most_placed(art, doc) + } + /// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`]. fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 { let whole = n.count_with_masks() as u64; @@ -642,10 +647,7 @@ impl Document { /// ([`NineSliceMap::place_unclipped`]). pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option { match self.symbol_slice_map(name, xf) { - Some(m) => { - let m = NineSliceMap { clips: false, ..m }; - (m.most_placed(art, self) <= MAX_SYMBOL_NODES).then(|| m.place(art, self)) - } + Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)), None => Some(transformed(art, xf)), } } @@ -1072,6 +1074,9 @@ mod tests { let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 100.0, 60.0)), Appearance::basic(gradient, Paint::None, 0.0)); assert_eq!(m.most_placed(&bar, &d), 10); assert_eq!(m.place(&bar, &d).count(), 10); + // Unclipped, as DXF writes it, the bar is cut at the guides and stays one path. + assert_eq!(m.most_placed_unclipped(&bar, &d), 1); + assert_eq!(m.place_unclipped(&bar, &d).count(), 1); // Art nested past the depth limit, clipped in all nine cells. let mut deep = square(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); for _ in 0..=MAX_SLICE_DEPTH { From e44f5a1b7767045658187715fab327fb22f30bcf Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 01:07:29 -0300 Subject: [PATCH 294/674] Fix #5312: EPS files written by Ghostscript's eps2write open `gcheck` and `scheck` answered false for every operand. The PLRM (3rd ed., `gcheck`) says they are true for a simple object, and false only for a composite one in local VM. The eps2write prolog copies its initial graphics state into global VM and leaves a value alone only when `gcheck` is true. So the integers in the `currenthalftone` dictionary took the copy path, left the stack one item off, and the next `put` failed with a typecheck in `cp2g`. Simple objects now answer true. Composites still answer false, since every composite here is in local VM. --- crates/eps/src/import/interp.rs | 7 +++++-- crates/eps/src/import/obj.rs | 5 +++++ crates/eps/src/import/tests_generators.rs | 15 +++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 12232624f8..6126b4b324 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -1135,9 +1135,12 @@ impl<'a> Interp<'a> { PdfMark => { self.pop_to_mark()?; } + // True for a simple object, and for a composite one in global VM (PLRM 3rd ed., `gcheck`); + // every composite here is in local VM. Procsets that copy values into global VM leave + // alone those whose `gcheck` is true, such as a halftone's numbers. Gcheck | Scheck => { - self.pop()?; - self.push(Obj::Bool(false))?; + let simple = !self.pop()?.is_composite(); + self.push(Obj::Bool(simple))?; } CurrentShared => self.push(Obj::Bool(false))?, SetShared | SetVmThreshold | VmReclaim | Echo => { diff --git a/crates/eps/src/import/obj.rs b/crates/eps/src/import/obj.rs index b4dc34364a..4f07678a71 100644 --- a/crates/eps/src/import/obj.rs +++ b/crates/eps/src/import/obj.rs @@ -286,6 +286,11 @@ impl Obj { Self::GState(_) => "gstatetype", } } + + /// A composite object, whose value lives in VM; the others are simple (PLRM 3rd ed., §3.3.1). + pub fn is_composite(&self) -> bool { + matches!(self, Self::Str(_) | Self::ExecStr(_) | Self::Array { .. } | Self::Dict(_) | Self::File { .. } | Self::Save(_) | Self::GState(_)) + } } /// The values of a string or an array: a run of storage that other strings or arrays may share diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 2fe6ba324c..4337b9474c 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -592,6 +592,21 @@ showpage"##; assert!(near(bounds(&meshes[1]), Rect::new(150.0, 90.0, 190.0, 140.0)), "{:?}", bounds(&meshes[1])); } +/// Ghostscript 9's `eps2write` copies the initial graphics state (`currenthalftone`, +/// `currentcolortransfer`) into global VM before it draws, with a copier for each composite type. +/// It copies only what `gcheck` says is in local VM: `gcheck` is true for every simple object +/// (PLRM 3rd ed., `gcheck`), so the halftone's numbers stay as they are. Written from the PLRM. +#[test] +fn gcheck_is_true_for_simple_objects() { + super::tests::check("1 gcheck 2.5 gcheck and /n gcheck and true gcheck and null gcheck and /add load gcheck and mark gcheck and"); + super::tests::check("(s) gcheck not 1 dict gcheck not and {} gcheck not and 1 scheck and (s) scheck not and"); + super::tests::check( + "/copiers << /dicttype { << exch { cp2g } forall >> } /arraytype { [ exch { cp2g } forall ] } >> def \ + /cp2g { dup gcheck not { copiers 1 index type get exec } if } bind def \ + currenthalftone cp2g /Frequency get 60 eq [ currentcolortransfer ] cp2g length 4 eq and", + ); +} + /// A procset written as the PostScript Language Reference (3rd ed.) describes the Level 2 and 3 /// facilities programs probe before drawing: a resource category made from `Generic` and /// resources defined and found in it (§3.9), local and global VM (`currentglobal`, `setglobal`, From 5e3d35c0e02eb703caff71436fb068d3b1672801 Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 01:07:42 -0300 Subject: [PATCH 295/674] contributors: add my name for the About window --- contributors/people.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index f3c8629b71..db94e2a890 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -189,3 +189,7 @@ sync_github_name = false [people.WadahBadawi] display_name = "Wadah Badawi" sync_github_name = true + +[people.JonRC] +real_name = "Jonathan Cardoso" +display_name = "Jonathan Cardoso" From fb67e28954ae13a2deaebc59957553c67d1505ca Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:31:54 +0000 Subject: [PATCH 296/674] Format with rustfmt --- crates/color/src/gradient/tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 6c9a08a9d7..da9a3f2cce 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -36,8 +36,11 @@ fn stop_reach_matches_scanning_the_stops() { &[f32::NAN, 0.3, 0.3, 0.8], ]; for offsets in offsets { - let stops: Vec = - offsets.iter().zip(colors.iter().cycle()).map(|(&o, hex)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::from_hex(hex).unwrap()) }).collect(); + let stops: Vec = offsets + .iter() + .zip(colors.iter().cycle()) + .map(|(&o, hex)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::from_hex(hex).unwrap()) }) + .collect(); let g = Gradient::new(GradientKind::Linear, stops); let reach = StopReach::new(&g.stops); for t in (-4..=44).map(|k| k as f32 / 40.0).chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]) { From 9086842f4b1ecfc456e646d790a98a946dfa8686 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:31:56 +0000 Subject: [PATCH 297/674] Format with rustfmt --- crates/engine/src/cmd/fileio/affinity/master_copies.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/fileio/affinity/master_copies.rs b/crates/engine/src/cmd/fileio/affinity/master_copies.rs index 789f3c774e..f0ab8bd404 100644 --- a/crates/engine/src/cmd/fileio/affinity/master_copies.rs +++ b/crates/engine/src/cmd/fileio/affinity/master_copies.rs @@ -47,10 +47,8 @@ pub(super) fn copy_cost(n: &af::Node, depth: usize) -> CopyCost { _ => CopyCost { work: 1, pixels: 0 }, }; // A vector mask is a path of its own, and a pixel mask an image of its own, in every copy. - let mask = CopyCost { - work: n.mask.as_ref().map_or(0, segments) + u64::from(n.pixel_mask.is_some()), - pixels: n.pixel_mask.as_ref().map_or(0, pixels), - }; + let mask = + CopyCost { work: n.mask.as_ref().map_or(0, segments) + u64::from(n.pixel_mask.is_some()), pixels: n.pixel_mask.as_ref().map_or(0, pixels) }; n.children.iter().fold(own.plus(mask), |c, ch| c.plus(copy_cost(ch, depth + 1))) } From 14d617f1d4528f2d1d0e3b46bccc0726f24a6a90 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 2 Nov 2026 23:44:01 -0500 Subject: [PATCH 298/674] Format the symbol library test (rustfmt) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/symbollib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index e5f2ccfe24..a2c4b0bdb8 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -362,7 +362,9 @@ mod tests { let mut src = Document::new(100.0, 100.0); let n = 4000; // Names out of alphabetical order, so the order kept is the panel's. - src.symbols = (0..n).map(|i| Symbol { name: format!("s{}", (i * 7919) % n), art: Arc::new(Node::group(NodeId(i as u64 + 1), vec![])), dynamic: false }).collect(); + src.symbols = (0..n) + .map(|i| Symbol { name: format!("s{}", (i * 7919) % n), art: Arc::new(Node::group(NodeId(i as u64 + 1), vec![])), dynamic: false }) + .collect(); let lib = SymbolLibrary::from_document(&src, &[], "Many".into()).unwrap(); let names = |d: &Document| d.symbols.iter().map(|s| s.name.clone()).collect::>(); assert_eq!(names(&lib.doc), names(&src)); From 32d59f72392adb5fdcb561cb27d9b319d1b20474 Mon Sep 17 00:00:00 2001 From: Rahul Date: Tue, 3 Nov 2026 10:18:51 +0530 Subject: [PATCH 299/674] i18n(ru): drop the rows MENU_KEEP_AS_IS forbids (gate fix) The gate failed kept_menu_names_are_menu_labels_left_in_english: ru is in KEEPS_MENU_NAMES, so the MENU_KEEP_AS_IS names (VectorCraft, OpenType, the workspace names, the perspective-grid presets) must stay in English. The coverage report had listed them as missing; the 20 rows are removed so the names fall back to English again. The 110 genuinely-missing strings stay. Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- crates/ui-egui/src/i18n/ru.tsv | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 11ced1266c..867860d0e7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6234,7 +6234,6 @@ breakText Glyphs Глифы Art and Bright Colors Художественные и яркие цвета Artboard Options: edit with the Artboard tool Параметры монтажной области: измените их инструментом «Монтажная область» Automate Автоматизация - Automation Автоматизация B4 B4 B5 B5 CRLF (Windows) CRLF (Windows) @@ -6248,8 +6247,6 @@ breakText Glyphs Глифы Dimension Text Размерный текст Dot Gain 15% Растискивание 15 % Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Перетащите сюда объекты, цвета и стили текста, чтобы использовать их в разных документах. Библиотеки хранятся на этом компьютере — учётная запись не нужна. - Essentials Основные - Essentials Classic Основные (классические) Expand 1 Selected Разбить 1 объект Extension Lines Выносные линии Extension: Выносная линия: @@ -6268,24 +6265,20 @@ breakText Glyphs Глифы Kaku #2 Каку №2 Kaku #3 Каку №3 LF (macOS, Linux) LF (macOS, Linux) - Layout Макет Legal Legal Line Type: Тип линии: Line Weight: Толщина линии: Load Variable Library Загрузить библиотеку переменных - OpenType OpenType PDF 1.7 PDF 1.7 PDF/X-1a:2001 PDF/X-1a:2001 PDF/X-3:2002 PDF/X-3:2002 PDF/X-4:2010 PDF/X-4:2010 - Painting Рисование Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Часть ArtCraft. MIT OR Apache-2.0. Шрифты: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Значки: Lucide (ISC) + VectorCraft. Phone 375×812 Телефон 375×812 Photo Low Fidelity Фото (низкое качество) Preparing the image… Подготовка изображения… Print & Proof Печать и цветопроба Printing & Proofing Печать и цветопроба - Printing and Proofing Печать и цветопроба RECENT (1) НЕДАВНИЕ (1) RGB RGB Reset Automation Сбросить «Автоматизация» @@ -6310,28 +6303,15 @@ breakText Glyphs Глифы Spot Colors (0) Плашечные цвета (0) Tablet 1024×768 Планшет 1024×768 Tabloid Tabloid - Touch Сенсорный - Tracing Трассировка Tracing the colors… Трассировка цветов… - Typography Типографика UTF-16 (Unicode) UTF-16 (Unicode) Units & Scale Единицы и масштаб - VectorCraft VectorCraft VectorCraft Updates Обновления VectorCraft Video 1920×1080 Видео 1920×1080 Video 3840×2160 Видео 3840×2160 - Web Веб Web 1280×720 Веб 1280×720 WebP WebP Yonroku-ban Ёнроку-бан - [1P-High View] [1P — высокое качество] - [1P-Low View] [1P — низкое качество] - [1P-Normal View] [1P — обычное качество] - [2P-High View] [2P — высокое качество] - [2P-Low View] [2P — низкое качество] - [2P-Normal View] [2P — обычное качество] - [3P-Low View] [3P — низкое качество] - [3P-Normal View] [3P — обычное качество] [High Quality Print] [Высококачественная печать] [High Resolution] [Высокое разрешение] [Low Resolution] [Низкое разрешение] From b191900855e95753cffc2c1fcd176f5623cd7520 Mon Sep 17 00:00:00 2001 From: Rahul Date: Tue, 3 Nov 2026 10:18:58 +0530 Subject: [PATCH 300/674] i18n(sv): drop the rows MENU_KEEP_AS_IS forbids (gate fix) The gate failed kept_menu_names_are_menu_labels_left_in_english: sv is in KEEPS_MENU_NAMES, so the MENU_KEEP_AS_IS names (VectorCraft, OpenType, the workspace names, the perspective-grid presets) must stay in English. The coverage report had listed them as missing; the 20 rows are removed so the names fall back to English again. The two genuinely-missing strings (Font Size:, digits Hindi) stay. Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- crates/ui-egui/src/i18n/sv.tsv | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 0e7b5d75c9..0cb4ac6123 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6297,25 +6297,5 @@ breakText Glyphs Glyfer HEX HEX # The strings the report listed as missing for sv. - Automation Automation - Essentials Grundläggande - Essentials Classic Grundläggande (klassiska) Font Size: Teckenstorlek: - Layout Layout - OpenType OpenType - Painting Målning - Printing and Proofing Utskrift och korrektur - Touch Pek - Tracing Spårning - Typography Typografi - VectorCraft VectorCraft - Web Webb - [1P-High View] [1P — hög kvalitet] - [1P-Low View] [1P — låg kvalitet] - [1P-Normal View] [1P — normal kvalitet] - [2P-High View] [2P — hög kvalitet] - [2P-Low View] [2P — låg kvalitet] - [2P-Normal View] [2P — normal kvalitet] - [3P-Low View] [3P — låg kvalitet] - [3P-Normal View] [3P — normal kvalitet] digits Hindi Hindi From 4a0a3701b0b85a86583b68d62a44ceb5ccf85487 Mon Sep 17 00:00:00 2001 From: Maxwell Wang <99717069+cybermaxwel@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:55:01 +0800 Subject: [PATCH 301/674] Fix Simplified Chinese translation of Luminosity --- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 040c49a7fb..1e6bdda750 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1743,7 +1743,7 @@ file-filter Templates 模板 Lossy: 有损: Low 低 lowercase 小写 - Luminosity 亮度 + Luminosity 明度 LZW Compression LZW 压缩 Mac Mac Magenta 洋红 From d9e3df23b1cb16735d18df81a41e15b711fcd305 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:18:28 -0500 Subject: [PATCH 302/674] Brushes: leave out an opacity mask whose root symbol draws a brushed stroke The filter that keeps brush pieces from drawing a brush again walked a mask's art but never looked at the mask's root itself. A symbol instance at the root of a mask, whose symbol draws a stroke with the brush, then survived and re-entered the brush while the mask was rendered, without end. The mask goes now, as such an instance goes among the children. --- crates/brush/src/lib.rs | 11 ++++++++++- crates/brush/src/tests.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 60e8a0234d..bc75f09cf1 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -884,7 +884,16 @@ fn leave_out_brushed(doc: &Document, nodes: &mut Vec, known: &mut Known) { walk(doc, Arc::make_mut(c), known); } } - if n.extras().mask.is_some() + // A mask's art is drawn too. Its root is filtered like any other node: a symbol instance + // there that draws a brushed stroke would run the brush again from inside the mask, so the + // mask goes, as such an instance goes from the pieces and their children. + let rejected_root = matches!( + n.extras().mask.as_ref().map(|m| &m.art.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if draws_brushed(doc, (false, symbol.as_str()), known) + ); + if rejected_root { + n.extras_mut().mask = None; + } else if n.extras().mask.is_some() && let Some(mask) = n.extras_mut().mask.as_mut() { walk(doc, Arc::make_mut(&mut mask.art), known); diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 6e8113f14a..eb7bd8865e 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1316,6 +1316,42 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { } } +/// A symbol instance at the root of an opacity mask is filtered like one among the children: when +/// its symbol draws a brushed stroke the mask goes (it would run the brush again from inside the +/// mask, without end), and a mask whose root symbol is plain stays. +#[test] +fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() { + use vectorcraft_doc::{OpacityMask, Symbol}; + let mut doc = Document::new(100.0, 100.0); + let mut brushed = rect_art(10.0, 4.0); + brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) })); + for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] { + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) }); + } + let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let masked = |symbol: &str| { + let mut n = rect_art(10.0, 4.0); + n.extras_mut().mask = Some(Box::new(OpacityMask::new(instance(symbol), true))); + n + }; + let art = Node::group(NodeId(0), [masked("plain"), masked("brushed")].map(std::sync::Arc::new).into()); + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }; + let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty()); + for piece in &out { + let roots: Vec> = piece + .children() + .unwrap() + .iter() + .map(|c| match c.extras().mask.as_ref().map(|m| &m.art.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.as_str()), + _ => None, + }) + .collect(); + assert_eq!(roots, [Some("plain"), None], "the plain mask stays and the brushed one goes"); + } +} + /// Anchors a brushed stroke emitted, which is what the output budget counts. fn anchors(nodes: &[Node]) -> usize { nodes From a4aa1960cf7ea9ee0a91f5a6455fb877967b821e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:34:19 -0500 Subject: [PATCH 303/674] Threaded text: a frame listed twice flows the story once Reflow copied each listed frame's text into its thread's story, so a document that listed one frame several times in a thread, or in several threads, repeated that text in the story and wrote the grown story back for the next thread to copy again, growing the text with every repetition while the document opened. Reflow now keeps each frame at its first place in the thread list only. --- crates/engine/src/cmd/threads.rs | 7 ++++++- crates/engine/src/cmd/threads/tests.rs | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 3bb35b979a..db7082f054 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -93,7 +93,12 @@ thread_local! { /// makes "changed" a pointer comparison). Deleted frames' text flows into the remaining ones; a /// frame that is now point type leaves its thread with the text it holds. pub(crate) fn reflow(before: &Document, doc: &mut Document) { - let threads = std::mem::take(&mut doc.text_threads); + // A frame is in one thread, once: a file that lists it again (in its thread or another) would + // copy its text into the story each time, and write the grown story back for the next thread + // to copy again. Only its first place counts. + let mut seen = std::collections::HashSet::new(); + let threads: Vec> = + std::mem::take(&mut doc.text_threads).into_iter().map(|t| t.into_iter().filter(|id| seen.insert(*id)).collect()).collect(); let mut kept = vec![]; for thread in threads { let changed = thread.iter().any(|id| match (before.node(*id), doc.node(*id)) { diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 07531d4edd..2dfb119fec 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -40,6 +40,24 @@ fn thread_flows_reflows_on_edit_and_survives_delete() { assert_eq!(s.doc().unwrap().doc.text_threads.len(), 1); } +/// A file that lists a frame more than once, in its own thread or in another, flows the story +/// through each frame once: repeated places would copy its text again and again. +#[test] +fn frames_listed_twice_flow_the_story_once() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + let mut d = (*s.doc().unwrap().doc).clone(); + let (fa, fb) = (NodeId(a), NodeId(b)); + d.text_threads = vec![vec![fa, fb, fa, fb, fa], vec![fb, fa], vec![fa, fb]]; + reflow(&Document::new(1.0, 1.0), &mut d); + assert_eq!(d.text_threads, vec![vec![fa, fb]]); + let plain = |id: NodeId| match &d.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert_eq!(format!("{}{}", plain(fa), plain(fb)), TEXT.repeat(4)); +} + #[test] fn edits_copy_only_the_stories_of_threads_whose_frames_changed() { let (mut s, a, b) = setup(); From 2fec613353624a248d65030154584b2ebd4d88e5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:42:43 -0500 Subject: [PATCH 304/674] Place: the place cursor reads its files within the roots it was loaded in An agent confined to automation roots could load the place cursor, with file.place.queue or tool.setOption, and the files were placed later, by a click of the person at the keyboard, outside any roots. tool.setOption checked a queued path but not files given inline, whose linked files (an SVG's referenced images) were then read with the keyboard user's unrestricted access. The session now keeps the automation roots in force when the cursor's queue is loaded, and both the engine's own placement and the desktop app's background placement read the queued file within them. A queue loaded outside any roots places as before. --- crates/engine/src/lib.rs | 5 ++++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/place.rs | 33 ++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 26 ++++++++++++++++++++ crates/ui-egui/src/place.rs | 17 ++++++++----- 5 files changed, 76 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0eed45b343..177697839e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -163,6 +163,11 @@ pub struct Session { /// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which /// the command loads the place cursor with instead of reading them; `None` otherwise. pub(crate) queue_hand_off: Option, + /// The automation roots in force when the place cursor was last loaded (`None`: none were). + /// The cursor places its files later, on a click that may come from the person at the + /// keyboard: those files, and the files they link to, are read under these roots, so a queue + /// an agent loaded never reads beyond what it was given. + pub(crate) place_queue_roots: Option>, /// While [`Session::import_image_read`] runs `clipboard.importImage`: the image read for it, /// which the command loads instead of reading `dataBase64`; `None` otherwise. pub(crate) image_hand_off: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 71233cea6e..51b5b57769 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -79,6 +79,7 @@ impl Session { batch_steps: None, place_hand_off: None, queue_hand_off: None, + place_queue_roots: None, image_hand_off: None, trace_hand_off: None, place_cursor_requests: false, diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 7c3ff56ab1..3c86e513e6 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -722,6 +722,39 @@ fn a_queue_of_3_with_click_drag_and_esc_places_2() { assert_eq!(s.doc().unwrap().history.undo.len(), 2, "one undo step per placement"); } +/// A place cursor loaded within automation roots places its files within them, even on a later +/// click outside any roots (the person at the keyboard's): a queued file outside the roots, or +/// one it links to, is not read then. One loaded outside any roots places as before. +#[test] +fn the_place_cursor_places_within_the_roots_it_was_loaded_in() { + let base = std::env::temp_dir().join(format!("vectorcraft-place-roots-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("in")).unwrap(); + let outside = base.join("outside.png"); + std::fs::write(&outside, png(40, 20, [9, 9, 9, 255], None)).unwrap(); + let entry = json!({"params": {"path": outside.to_string_lossy()}, "name": "outside.png", "width": 40, "height": 20}); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("in")], &[]).unwrap().unwrap(); + let view = ViewInfo::default(); + let click = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), view)?; + s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view) + }; + let mut s = session(); + s.select_tool("place", view).unwrap(); + // Loaded within the roots (as a tool option, past the check tool.setOption makes of paths). + crate::file_access::confine(Some(&roots), || s.set_tool_option("queue", &json!({"entries": [entry]}))); + assert!(s.place_queue_roots().is_some()); + let placed = crate::file_access::unconfined(|| click(&mut s)); + assert!(top_children(&s).is_empty(), "{placed:?}"); + // Loaded outside any roots: the click places it. + s.select_tool("place", view).unwrap(); + crate::file_access::unconfined(|| s.set_tool_option("queue", &json!({"entries": [entry]}))); + assert!(s.place_queue_roots().is_none()); + crate::file_access::unconfined(|| click(&mut s)).unwrap(); + assert_eq!(top_children(&s).len(), 1); + let _ = std::fs::remove_dir_all(base); +} + /// With [`Session::place_cursor_requests`] set, a click of the place cursor asks the frontend to /// place its file ([`UiRequest::Place`]) and places nothing itself; the params it asks with place /// the file as the click places it without the flag. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ecbc459643..d5c03a651f 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -658,11 +658,27 @@ impl Session { self.tool.options() } pub fn set_tool_option(&mut self, key: &str, v: &Value) { + if key == "queue" && self.tool.id() == "place" { + self.note_place_queue_roots(); + } self.tool.set_option(key, v); self.tool_set_since_reset = true; self.keep_tool_settings(); } + /// Keep the automation roots in force now as those the place cursor's queue, being loaded, + /// is placed under ([`Session::place_queue_roots`]). + fn note_place_queue_roots(&mut self) { + self.place_queue_roots = crate::file_access::current(); + } + + /// The automation roots the place cursor's files are placed under: those in force when it + /// was loaded. A frontend that places them itself ([`UiRequest::Place`]) reads them within + /// these roots ([`crate::file_access::confine`]). + pub fn place_queue_roots(&self) -> Option> { + self.place_queue_roots.clone() + } + /// The options of tool `id`: the active tool's, or those it would have if chosen now. pub fn tool_options_of(&self, id: &str) -> Value { if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() } @@ -673,6 +689,9 @@ impl Session { /// Liquify tools' Global Brush Dimensions, the Smooth tool's Fidelity for Pencil, Paintbrush /// and Blob Brush Alt smoothing). Returns the tool's options. pub fn set_tool_options(&mut self, id: Option<&str>, values: &Map) -> Value { + if values.contains_key("queue") && id.unwrap_or(self.tool.id()) == "place" { + self.note_place_queue_roots(); + } let active = id.is_none_or(|id| id == self.tool.id()); self.tool_set_since_reset |= active; let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default())); @@ -842,6 +861,13 @@ impl Session { } // The place cursor's file, placed by the frontend that asked for it. Action::Exec(cmd, p) if cmd == "file.place" && self.place_cursor_requests => ui.push(UiRequest::Place(p)), + // The place cursor's file, read within the roots of whoever loaded the cursor. + Action::Exec(cmd, p) if cmd == "file.place" => { + let roots = self.place_queue_roots.clone(); + if let Some(w) = crate::file_access::confine(roots.as_ref(), || self.execute(&cmd, &p))?.get("warning").and_then(Value::as_str) { + ui.push(UiRequest::Status(w.to_string())); + } + } Action::Exec(cmd, p) => { // A command's warning (Crop Image's when the image couldn't be decoded) goes to the // status bar too. diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index c2b920b837..d4f4412ec0 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -376,13 +376,18 @@ fn queue_files(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result Date: Tue, 3 Nov 2026 01:27:06 -0300 Subject: [PATCH 305/674] Fix #5316: StandardEncoding and ISOLatin1Encoding are Encoding resources The standard encodings were names in systemdict only, and the Encoding category was empty, so `/StandardEncoding /Encoding findresource` failed with undefinedresource. The PLRM (3rd ed.) has both as instances of the Encoding category, the same arrays as the names. Ghostscript's eps2write prolog takes StandardEncoding that way for a font whose encoding is a Differences dictionary with no BaseEncoding, so files with its Type 3 text stopped there. --- crates/eps/src/import/interp.rs | 8 +++++++- crates/eps/src/import/tests.rs | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 6126b4b324..98a4a4e774 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -105,13 +105,18 @@ impl<'a> Interp<'a> { pub fn new(src: &'a [u8], g: GState, out: Out) -> Self { let made = super::obj::track(); let system = new_dict(); + // The standard encodings are also instances of the Encoding category, the same arrays + // (PLRM 3rd ed., `findencoding` and §3.9.2). + let encodings = new_dict(); { let mut d = system.borrow_mut(); for (op, name) in Op::ALL { d.insert(Key::name(name), Obj::Op(*op)); } for name in ["StandardEncoding", "ISOLatin1Encoding"] { - d.insert(Key::name(name), encoding()); + let e = encoding(); + d.insert(Key::name(name), e.clone()); + encodings.borrow_mut().insert(Key::name(name), e); } // An integer, as interpreters have it (`systemdict /languagelevel get 2 ge`): run, the // name pushes it all the same. @@ -122,6 +127,7 @@ impl<'a> Interp<'a> { CATEGORIES.split_whitespace().map(|c| (Key::name(c), Obj::dict(Dict::from([(Key::name("Category"), Obj::name(c))])))).collect(); let resources = new_dict(); resources.borrow_mut().insert(Key::name("Category"), Obj::dict(categories)); + resources.borrow_mut().insert(Key::name("Encoding"), Obj::Dict(encodings)); let fonts = new_dict(); system.borrow_mut().insert(Key::name("FontDirectory"), Obj::Dict(fonts.clone())); for name in ["GlobalFontDirectory", "SharedFontDirectory"] { diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index aa97f32cb5..3f734fef9a 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -892,6 +892,17 @@ fn the_generic_category_defines_new_categories() { check("{ /X 5 /Category defineresource } stopped"); } +/// The standard encodings are instances of the Encoding category, the same arrays as the names in +/// `systemdict` (PLRM 3rd ed., `findencoding` and §3.9.2). Ghostscript's `eps2write` finds +/// `StandardEncoding` that way for the fonts it embeds. +#[test] +fn the_standard_encodings_are_encoding_resources() { + check("/StandardEncoding /Encoding findresource StandardEncoding eq"); + check("/ISOLatin1Encoding /Encoding findresource ISOLatin1Encoding eq"); + check("/StandardEncoding /Encoding resourcestatus { pop pop true } { false } ifelse"); + check("{ /Nope /Encoding findresource } stopped"); +} + #[test] fn clipsave_and_cliprestore_bring_the_clip_back() { // #234. From eca414044bebdc497f55264b0196230638ef7b2d Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 02:26:12 -0300 Subject: [PATCH 306/674] Cite the PostScript Language Reference by its public URL --- crates/eps/src/import/interp.rs | 2 +- crates/eps/src/import/tests.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 98a4a4e774..cf7c5495ad 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -106,7 +106,7 @@ impl<'a> Interp<'a> { let made = super::obj::track(); let system = new_dict(); // The standard encodings are also instances of the Encoding category, the same arrays - // (PLRM 3rd ed., `findencoding` and §3.9.2). + // (PLRM 3rd ed., §3.9.2 and `findencoding`, ). let encodings = new_dict(); { let mut d = system.borrow_mut(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 3f734fef9a..f249ebf316 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -893,8 +893,8 @@ fn the_generic_category_defines_new_categories() { } /// The standard encodings are instances of the Encoding category, the same arrays as the names in -/// `systemdict` (PLRM 3rd ed., `findencoding` and §3.9.2). Ghostscript's `eps2write` finds -/// `StandardEncoding` that way for the fonts it embeds. +/// `systemdict` (PLRM 3rd ed., §3.9.2 and `findencoding`, ). +/// Ghostscript's `eps2write` finds `StandardEncoding` that way for the fonts it embeds. #[test] fn the_standard_encodings_are_encoding_resources() { check("/StandardEncoding /Encoding findresource StandardEncoding eq"); From 8fb394ca16da8a68674994fd93d13b9512c31c6d Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 01:42:14 -0300 Subject: [PATCH 307/674] Fix #5318: `known` answers false for keys no dictionary holds `known` raised a typecheck for any key that can't be a key here (an array, a dictionary, a real with a fraction). The PLRM allows any object but null as a key, and since `put` refuses such keys, no dictionary holds one: `known` now answers false, and null still raises the typecheck. Ghostscript's eps2write prolog looks each inline-image value up in a dictionary of abbreviations, and an image with two filters has an array there. --- crates/eps/src/import/interp.rs | 16 +++++++++++++--- crates/eps/src/import/tests.rs | 11 +++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index cf7c5495ad..3908bd41b5 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -1050,10 +1050,10 @@ impl<'a> Interp<'a> { self.insert(&d, k, Some(v))?; } Known => { - let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?; + let k = self.pop()?; let d = self.pop_dict()?; - let known = d.borrow().contains_key(&k); - self.push(Obj::Bool(known))?; + let found = known(&d, &k)?; + self.push(Obj::Bool(found))?; } Where => { let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?; @@ -1418,6 +1418,16 @@ fn index(k: &Obj) -> Res { } } +/// `known`: a key may be any object but null (PLRM 3rd ed.), and one that can't be a key here (an +/// array, a dictionary, a real with a fraction) is in no dictionary, since `put` refuses it. +fn known(d: &DictRef, k: &Obj) -> Res { + match k.key() { + Some(key) => Ok(d.borrow().contains_key(&key)), + None if matches!(k, Obj::Null) => ps_err("typecheck", "known"), + None => Ok(false), + } +} + /// `eq`: numbers by value, strings and names by text, composites by identity. fn equal(a: &Obj, b: &Obj) -> bool { match (a, b) { diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index f249ebf316..7435fc8b2b 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -996,6 +996,17 @@ fn the_standard_dictionaries_are_dictionaries_in_systemdict() { check("SharedFontDirectory type /dicttype eq"); } +/// A key may be any object but null (PLRM 3rd ed.), so `known` answers for every other key. +/// Ghostscript's `eps2write` looks an inline image's filter up in a dictionary of abbreviations, +/// and the filter may be an array of them. +#[test] +fn known_answers_false_for_keys_no_dictionary_holds() { + check("<< /A85 /ASCII85Decode >> [ /A85 /LZW ] known not"); + check("1 dict 1 dict known not 1 dict 1.5 known not and 1 dict mark known not and"); + check("<< /A85 /ASCII85Decode >> /A85 known << 1 2 >> 1.0 known and"); + check("{ 1 dict null known } stopped"); +} + #[test] fn dictstack_and_internaldict_answer() { check("10 array dictstack length countdictstack eq"); From d627a776de768177cb696d0154855b41db28d90e Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 02:26:55 -0300 Subject: [PATCH 308/674] Cite the PostScript Language Reference by its public URL --- crates/eps/src/import/interp.rs | 5 +++-- crates/eps/src/import/tests.rs | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 3908bd41b5..f44bf71325 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -1418,8 +1418,9 @@ fn index(k: &Obj) -> Res { } } -/// `known`: a key may be any object but null (PLRM 3rd ed.), and one that can't be a key here (an -/// array, a dictionary, a real with a fraction) is in no dictionary, since `put` refuses it. +/// `known`: a key may be any object but null (PLRM 3rd ed., §3.3.9, ), +/// and one that can't be a key here (an array, a dictionary, a real with a fraction) is in no +/// dictionary, since `put` here refuses it. fn known(d: &DictRef, k: &Obj) -> Res { match k.key() { Some(key) => Ok(d.borrow().contains_key(&key)), diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 7435fc8b2b..20593f0e6e 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -996,7 +996,8 @@ fn the_standard_dictionaries_are_dictionaries_in_systemdict() { check("SharedFontDirectory type /dicttype eq"); } -/// A key may be any object but null (PLRM 3rd ed.), so `known` answers for every other key. +/// A key may be any object but null (PLRM 3rd ed., §3.3.9, ), +/// so `known` answers for every other key. /// Ghostscript's `eps2write` looks an inline image's filter up in a dictionary of abbreviations, /// and the filter may be an array of them. #[test] From 6fc82a141fb9ea09d3f4f72908315024eb8a619d Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 02:13:31 -0300 Subject: [PATCH 309/674] Fix #5321: `currentfile` in a file being run is that file A file run with `cvx exec` was read whole and run as a separate program, while `currentfile` stayed the outer EPS. The PLRM has `currentfile` return the topmost file being run, positioned after the last token read. Ghostscript's eps2write runs each page's content and each Type 3 glyph from a SubFileDecode filter, and its `ID` reads the inline image's samples through `currentfile`, so they were read from the outer file and then ran as program. A file being run is now read object by object from its own data, and while it runs it is `currentfile`. A filter made over it waits to read, as one over the program's own file does, so it starts where the program is when the filter is first read. --- crates/eps/src/import/data/ops.rs | 75 ++++++++++++++++----------- crates/eps/src/import/interp.rs | 41 +++++++++++++-- crates/eps/src/import/tests_images.rs | 29 +++++++++++ 3 files changed, 111 insertions(+), 34 deletions(-) diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 3b4046de91..fbac566d05 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -29,7 +29,10 @@ impl Interp<'_> { pub fn data_op(&mut self, op: Op) -> Res { use Op::*; match op { - CurrentFile => self.push(Obj::File { stream: Rc::new(RefCell::new(Stream::Current)), exec: false })?, + CurrentFile => { + let stream = self.running.last().cloned().unwrap_or_else(|| Rc::new(RefCell::new(Stream::Current))); + self.push(Obj::File { stream, exec: false })?; + } Filter => self.filter()?, ReadHexString | ReadString => { let s = self.pop_str()?; @@ -163,18 +166,7 @@ impl Interp<'_> { self.push(o)?; } Obj::File { stream: f, .. } => { - self.materialize(&f)?; - let (o, immediate) = match &mut *f.borrow_mut() { - Stream::Current => (self.lex.next()?, self.lex.immediate), - Stream::Buf { data, pos, .. } => { - let rest = data.get(*pos..).unwrap_or_default(); - let mut lex = Lexer::new(rest); - let o = lex.next()?; - *pos += rest.len() - lex.data().len(); - (o, lex.immediate) - } - Stream::Pending(_) => (None, false), - }; + let (o, immediate) = self.next_in(&f)?; let Some(o) = o else { return self.push(Obj::Bool(false)) }; let o = self.scanned(o, immediate)?; self.push(o)?; @@ -184,6 +176,23 @@ impl Interp<'_> { self.push(Obj::Bool(true)) } + /// The next object in file `f` (`token`, and a file being run), read with the whitespace + /// after it, and whether it has `//name`s in it. + pub(in super::super) fn next_in(&mut self, f: &Rc>) -> Res<(Option, bool)> { + self.materialize(f)?; + Ok(match &mut *f.borrow_mut() { + Stream::Current => (self.lex.next()?, self.lex.immediate), + Stream::Buf { data, pos, .. } => { + let rest = data.get(*pos..).unwrap_or_default(); + let mut lex = Lexer::new(rest); + let o = lex.next()?; + *pos += rest.len() - lex.data().len(); + (o, lex.immediate) + } + Stream::Pending(_) => (None, false), + }) + } + /// Up to `n` bytes of file `f`. fn read(&mut self, f: &Rc>, n: usize) -> Res> { self.materialize(f)?; @@ -275,11 +284,16 @@ impl Interp<'_> { let spec = Filter { name, sub, predictor, fax }; let stream = match self.pop()? { Obj::File { stream: f, .. } => { - if let Stream::Buf { data, pos, .. } = &*f.borrow() { - self.alloc(data.len().saturating_sub(*pos))?; + // A filter over the file being run reads it, as one over the program's own file + // does, from where the program is when the filter is first read. + let running = self.running.last().is_some_and(|r| Rc::ptr_eq(r, &f)); + match &*f.borrow() { + Stream::Buf { data, pos, .. } if !running => self.alloc(data.len().saturating_sub(*pos))?, + _ => {} } let chain = match &*f.borrow() { Stream::Current => Some(vec![]), + Stream::Buf { .. } if running => Some(vec![]), Stream::Pending(c) => Some(c.clone()), Stream::Buf { .. } => None, }; @@ -325,15 +339,6 @@ impl Interp<'_> { self.push(Obj::File { stream, exec: false }) } - /// The data an executable file runs as a program: what is left of it. `None` for the - /// program's own file, which is being run already. - pub(in super::super) fn program_of(&mut self, f: &Rc>) -> Res>> { - if matches!(&*f.borrow(), Stream::Current) { - return Ok(None); - } - self.read(f, MAX_DATA).map(Some) - } - /// The decoded data left in file `f`, without reading it (a shading's or function's data). pub(in super::super) fn peek_all(&mut self, f: &Rc>) -> Res> { self.materialize(f)?; @@ -343,8 +348,9 @@ impl Interp<'_> { }) } - /// Decode the filters a file waits to run over the program's data, from where it is now. - fn materialize(&mut self, f: &Rc>) -> Res { + /// Decode the filters a file waits to run over the program's data, from where it is now: the + /// file being run, or the program's own file. + pub(in super::super) fn materialize(&mut self, f: &Rc>) -> Res { let chain = match &*f.borrow() { Stream::Pending(c) => c.clone(), _ => return Ok(()), @@ -353,10 +359,21 @@ impl Interp<'_> { for spec in &chain { buf = Some(match buf.take() { None => { - let raw = self.lex.data(); - let (data, used, rgb) = decode(spec, raw)?; + let (data, rgb) = match self.running.last() { + Some(r) => { + let mut b = r.borrow_mut(); + let Stream::Buf { data, pos, .. } = &mut *b else { return io("filter") }; + let (out, used, rgb) = decode(spec, data.get(*pos..).unwrap_or_default())?; + *pos = pos.saturating_add(used); + (out, rgb) + } + None => { + let (out, used, rgb) = decode(spec, self.lex.data())?; + self.lex.advance(used); + (out, rgb) + } + }; self.charge_decoded(data.len())?; - self.lex.advance(used); (data, rgb) } Some((prev, was)) => { diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index f44bf71325..f4c210b9cd 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -4,10 +4,12 @@ //! Every operation counts against a budget and procedures nest only so deep, so a looping or //! recursing program ends with [`PsError::Limit`] instead of hanging. +use std::cell::RefCell; use std::rc::Rc; use vectorcraft_geom::Affine; +use super::data::Stream; use super::graphics::{GState, Out}; use super::lex::{IMMEDIATE, Lexer}; use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err}; @@ -32,6 +34,9 @@ pub(crate) struct Interp<'a> { /// The list of the arrays and dictionaries made since this started ([`super::obj::track`]). made: u64, pub lex: Lexer<'a>, + /// The files being run (`cvx exec`), innermost last: the program reads from the last one, and + /// it is `currentfile` while it runs. + pub running: Vec>>, pub stack: Vec, pub dicts: Vec, system: DictRef, @@ -151,6 +156,7 @@ impl<'a> Interp<'a> { Self { made, lex: Lexer::new(src), + running: vec![], stack: vec![], dicts: vec![system.clone(), global.clone(), user.clone()], system, @@ -388,10 +394,7 @@ impl<'a> Interp<'a> { pub fn call(&mut self, v: Obj) -> Res { match v { Obj::Array { items, exec: true } => self.run_proc(&items), - Obj::File { stream, exec: true } => match self.program_of(&stream)? { - Some(program) => self.run_program(&program), - None => Ok(()), - }, + Obj::File { stream, exec: true } => self.run_file(&stream), Obj::ExecStr(s) => self.run_program(&s.to_vec()), // Through the depth guard: `stopped` and the like call back into here. Obj::Op(op) => { @@ -428,7 +431,35 @@ impl<'a> Interp<'a> { r } - /// Run `program` (what is left of an executable file, an executable string), token by token. + /// Run file `f` (`cvx exec`), reading its objects from it as it goes. While it runs it is + /// `currentfile`, the topmost file being run (PLRM 3rd ed., `currentfile`, ), + /// so data the program reads from there (an inline image's samples) comes from `f`, after the + /// object that reads it. The program's own file is being run already. + fn run_file(&mut self, f: &Rc>) -> Res { + if matches!(&*f.borrow(), Stream::Current) { + return Ok(()); + } + // Its data, decoded from the program it was made over, before it becomes the program. + self.materialize(f)?; + self.enter()?; + self.running.push(f.clone()); + let r = loop { + match self.next_in(f) { + Ok((Some(o), immediate)) => { + if let Err(e) = self.scanned(o, immediate).and_then(|o| self.exec_token(o)) { + break Err(e); + } + } + Ok((None, _)) => break Ok(()), + Err(e) => break Err(e), + } + }; + self.running.pop(); + self.depth -= 1; + r + } + + /// Run `program` (an executable string), token by token. fn run_program(&mut self, program: &[u8]) -> Res { self.enter()?; let mut lex = Lexer::new(program); diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 199a6ed7ab..76dc84670e 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -77,6 +77,35 @@ fn separate_sources_keep_their_planes() { assert_eq!(pixels(&r, 3, 2), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [16, 64, 112, 255], [32, 80, 128, 255], [48, 96, 144, 255]]); } +/// A program run from a file (`filter cvx exec`, as Ghostscript's `eps2write` runs each page's +/// content) reads data through `currentfile` from that file, right after the operator that reads +/// it (PLRM 3rd ed., `currentfile`, ): an image's +/// samples, kept after it as an inline image keeps them, plain or up to `~>` through +/// `SubFileDecode` and `ASCII85Decode`. +#[test] +fn image_data_comes_from_the_file_being_run() { + let r = read( + "currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\ + 30 20 scale 3 2 8 [3 0 0 -2 0 2] currentfile /ASCIIHexDecode filter false 3 colorimage\n\ + ff0000 00ff00 0000ff 102030 405060 708090>\n\ + endstream\n", + ); + assert_eq!(pixels(&r, 3, 2), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [16, 32, 48, 255], [64, 80, 96, 255], [112, 128, 144, 255]]); + let r = read( + "/ID { 3 1 8 [3 0 0 -1 0 1] currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter false 3 colorimage } def\n\ + currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\ + 30 20 scale ID\n\ + rr<$!rr<$!rr~>\n\ + endstream\n", + ); + assert_eq!(pixels(&r, 3, 1), [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]]); + super::tests::check( + "/ok false def currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\ + currentfile 4 string readstring WXYZ pop (WXYZ) eq /ok exch def\n\ + endstream\nok", + ); +} + /// CMYK samples keep their ink amounts in a CMYK TIFF: in the operand and dictionary forms, from /// hex and binary data, from one source or one a component, at 4, 8 and 16 bits, read through /// the Decode array. Gray and RGB images stay PNGs. From 400a49666a3b806ff3ecedcfee3dedfb07149649 Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 03:43:13 -0300 Subject: [PATCH 310/674] Pending filters read the file they were made over A filter over `currentfile` waits until it is first read, and it took its data from whichever file was running by then. One made over the program's own file and first read inside a file run with `cvx exec` read that file instead, and one made over a file being run, first read in a file that one runs, read the inner file. The pending stream now records the file it was made over (a chained filter inherits it), and `materialize` decodes from that file. --- crates/eps/src/import/data/filters.rs | 12 +++++--- crates/eps/src/import/data/ops.rs | 40 +++++++++++++-------------- crates/eps/src/import/tests_images.rs | 25 +++++++++++++++++ 3 files changed, 53 insertions(+), 24 deletions(-) diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index d049e39a9d..e3268b240a 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,15 +1,19 @@ use super::ops::MAX_DATA; use super::{ - DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, Res, find, hex_decode, jpeg_components, ps, - ps_err, + DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, + jpeg_components, ps, ps_err, }; /// A file object: the program itself, or data a filter decoded. #[derive(Debug)] pub(crate) enum Stream { Current, - /// Filters over the program's own data, decoded when first read. - Pending(Vec), + /// Filters over the data the program reads, decoded when first read, from the file they were + /// made over: a file being run (`from`), or else the program's own file. + Pending { + chain: Vec, + from: Option>>, + }, Buf { data: Vec, pos: usize, diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index fbac566d05..a39d56081f 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -97,7 +97,7 @@ impl Interp<'_> { let n = match &*f.borrow() { Stream::Current => self.lex.rest().len(), Stream::Buf { data, pos, .. } => data.len().saturating_sub(*pos), - Stream::Pending(_) => 0, + Stream::Pending { .. } => 0, }; self.push(Obj::Int(n as i64))?; } @@ -189,7 +189,7 @@ impl Interp<'_> { *pos += rest.len() - lex.data().len(); (o, lex.immediate) } - Stream::Pending(_) => (None, false), + Stream::Pending { .. } => (None, false), }) } @@ -210,7 +210,7 @@ impl Interp<'_> { *pos = end; data.get(start..end).unwrap_or_default().to_vec() } - Stream::Pending(_) => vec![], + Stream::Pending { .. } => vec![], }) } @@ -229,7 +229,7 @@ impl Interp<'_> { *pos += 1; } } - Stream::Pending(_) => {} + Stream::Pending { .. } => {} } } @@ -284,28 +284,28 @@ impl Interp<'_> { let spec = Filter { name, sub, predictor, fax }; let stream = match self.pop()? { Obj::File { stream: f, .. } => { - // A filter over the file being run reads it, as one over the program's own file - // does, from where the program is when the filter is first read. + // A filter over the program's own file or the file being run waits until it is + // first read, and keeps which of them it reads, wherever the program runs by then. let running = self.running.last().is_some_and(|r| Rc::ptr_eq(r, &f)); match &*f.borrow() { Stream::Buf { data, pos, .. } if !running => self.alloc(data.len().saturating_sub(*pos))?, _ => {} } - let chain = match &*f.borrow() { - Stream::Current => Some(vec![]), - Stream::Buf { .. } if running => Some(vec![]), - Stream::Pending(c) => Some(c.clone()), + let pending = match &*f.borrow() { + Stream::Current => Some((vec![], None)), + Stream::Buf { .. } if running => Some((vec![], Some(f.clone()))), + Stream::Pending { chain, from } => Some((chain.clone(), from.clone())), Stream::Buf { .. } => None, }; - match chain { - Some(mut c) => { + match pending { + Some((mut chain, from)) => { // The new filter reads a pending one's data: it has none left of its own // (`flushfile` on it skips nothing more). - if !c.is_empty() { + if !chain.is_empty() { *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; } - c.push(spec); - Stream::Pending(c) + chain.push(spec); + Stream::Pending { chain, from } } None => { let mut b = f.borrow_mut(); @@ -348,18 +348,18 @@ impl Interp<'_> { }) } - /// Decode the filters a file waits to run over the program's data, from where it is now: the - /// file being run, or the program's own file. + /// Decode the filters a file waits to run over the data the program reads, from where it is + /// now in the file they were made over: a file being run, or the program's own file. pub(in super::super) fn materialize(&mut self, f: &Rc>) -> Res { - let chain = match &*f.borrow() { - Stream::Pending(c) => c.clone(), + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), _ => return Ok(()), }; let mut buf: Option<(Vec, Option)> = None; for spec in &chain { buf = Some(match buf.take() { None => { - let (data, rgb) = match self.running.last() { + let (data, rgb) = match &from { Some(r) => { let mut b = r.borrow_mut(); let Stream::Buf { data, pos, .. } = &mut *b else { return io("filter") }; diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 76dc84670e..1600742300 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -106,6 +106,31 @@ fn image_data_comes_from_the_file_being_run() { ); } +/// A filter waits until it is first read, then reads the file it was made over, wherever the +/// program runs by then: one over the program's own file, read in a file being run, and one over +/// a file being run, read in a file that one runs. +#[test] +fn filters_read_the_file_they_were_made_over() { + super::tests::check( + "/f currentfile /ASCIIHexDecode filter def\n\ + currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\ + /s f 3 string readstring pop def\n\ + endstream\n\ + 616263>\n\ + s (abc) eq", + ); + super::tests::check( + "currentfile 0 (endstream) /SubFileDecode filter cvx exec\n\ + /g currentfile /ASCIIHexDecode filter def\n\ + currentfile 0 (endinner) /SubFileDecode filter cvx exec\n\ + /t g 3 string readstring pop def\n\ + endinner\n\ + 78797A>\n\ + endstream\n\ + t (xyz) eq", + ); +} + /// CMYK samples keep their ink amounts in a CMYK TIFF: in the operand and dictionary forms, from /// hex and binary data, from one source or one a component, at 4, 8 and 16 bits, read through /// the Decode array. Gray and RGB images stay PNGs. From 15cd642be80a4abbed14fbbdb4afe14a05ce66f1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:31:28 -0500 Subject: [PATCH 311/674] Clipboard: leave out the PNG of art too large to scale to 4096 pixels Copy scaled its PNG down to fit 4096 pixels a side but never below 0.01 pixels a point, so art over 409,600 pt across produced a PNG far past that side, up to the general raster export limit of a gigabyte of pixels, on an ordinary copy. Such art now gets no PNG flavour. --- crates/engine/src/cmd/clipboard/flavours.rs | 14 ++++++++++++-- crates/engine/src/tests/clipflavours.rs | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 8d9fe0b3fd..1a088cf3ed 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -125,6 +125,8 @@ pub struct Flavour { /// Longest side (px) of the PNG Copy offers: larger art is scaled down to fit. const COPY_PNG_SIDE: f64 = 4096.0; +/// The smallest scale (pixels a point) the PNG encoder renders at. +const MIN_COPY_PNG_SCALE: f64 = 0.01; /// Most bytes of text `clipboard.importText` takes. const MAX_TEXT: usize = 1 << 20; /// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the @@ -293,7 +295,8 @@ impl Clipboard { /// What Copy offers other apps, best first, with Include SVG Code (`svg`) and On Copy: PDF /// (`pdf`) as given (see `clipboard.flavours`). A [`Flavour`] that can't be made (art too large - /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side. + /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side, and + /// left out when even [`MIN_COPY_PNG_SCALE`] can't bring it that small. pub fn flavours(&self, svg: bool, pdf: bool) -> Vec { self.flavours_with_warnings(svg, pdf).0 } @@ -320,7 +323,14 @@ impl Clipboard { PDF => self.pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten().map(&mut keep), _ => { let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); - let scale = (COPY_PNG_SIDE / side).clamp(0.01, 1.0); + let scale = (COPY_PNG_SIDE / side).min(1.0); + // The encoder renders at no fewer than MIN_COPY_PNG_SCALE pixels a point: art + // too large to fit COPY_PNG_SIDE at that scale gets no PNG, rather than one + // of up to a gigabyte of pixels. + if !(scale >= MIN_COPY_PNG_SCALE) { + log::warn!("clipboard PNG: art {side} pt across is too large to copy as a picture"); + continue; + } self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, _, _, notes)| keep((png, notes))) } }; diff --git a/crates/engine/src/tests/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index fd72f2980d..c490c2684f 100644 --- a/crates/engine/src/tests/clipflavours.rs +++ b/crates/engine/src/tests/clipflavours.rs @@ -350,6 +350,25 @@ fn type_only_copies_offer_their_text() { assert!(run(&mut s, "clipboard.exportText", json!({}))["text"].is_null()); } +/// Art too large to fit the clipboard's PNG side at the encoder's smallest scale gets no PNG, +/// instead of a picture hundreds of megabytes large. +#[test] +fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() { + let mut s = session(); + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 1_000_000, "height": 1_000_000}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "edit.copy", json!({})); + assert!(s.clipboard.flavour_types(false, false).contains(&PNG)); + assert!(s.clipboard.flavours(false, false).iter().all(|f| f.mime != PNG)); + // Art that fits at that scale still gets its PNG, at most 4096 pixels a side. + let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 200_000, "height": 100}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "edit.copy", json!({})); + let png = s.clipboard.flavours(false, false).into_iter().find(|f| f.mime == PNG).expect("a PNG"); + let img = image::load_from_memory(&png.data).unwrap(); + assert!(img.width() <= 4096 && img.height() <= 4096, "{}x{}", img.width(), img.height()); +} + #[test] fn copy_offers_flavours_by_the_preferences() { let mut s = session(); From 4ab16b7760beda28aaba60fd021991ba8c9c1899 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 15:57:51 +0700 Subject: [PATCH 312/674] Clipboard: compare the PNG scale directly (clippy neg_cmp_op_on_partial_ord) --- crates/engine/src/cmd/clipboard/flavours.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 1a088cf3ed..8e4c57d065 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -327,7 +327,7 @@ impl Clipboard { // The encoder renders at no fewer than MIN_COPY_PNG_SCALE pixels a point: art // too large to fit COPY_PNG_SIDE at that scale gets no PNG, rather than one // of up to a gigabyte of pixels. - if !(scale >= MIN_COPY_PNG_SCALE) { + if scale < MIN_COPY_PNG_SCALE { log::warn!("clipboard PNG: art {side} pt across is too large to copy as a picture"); continue; } From b032766a6635c1b604f1ebfe68ef089da82c53cb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:46:31 -0500 Subject: [PATCH 313/674] Flatten Transparency: group overlapping objects without comparing every open pair The overlap grouping swept left to right comparing each object's bounds with every box still open at its left edge, so many objects sharing a horizontal extent (stacked in a column) cost a comparison per pair before any of the flattener's geometry limits applied, and the grouping could not be cancelled. Open boxes are now kept in a tree by their tops that knows the lowest bottom below each branch, so each box meets only the open boxes it overlaps; an open box inside a later box of its group, ending no further right, is closed early. The grouping checks for cancellation as it goes. Groups are unchanged: a test compares them with every-pair grouping. --- crates/engine/src/cmd/flatten/analysis.rs | 170 ++++++++++++++++++++-- crates/engine/src/cmd/flatten/apply.rs | 2 +- 2 files changed, 157 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 4bdbb8b723..7236499403 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -112,8 +112,16 @@ pub(super) fn reach(n: &Node) -> Option { Some(b.inflate(fx + 1.0, fx + 1.0)) } -/// Indices of `bounds` grouped by overlap (transitively), each group in index order. -pub(super) fn overlapping(bounds: &[Option]) -> Vec> { +/// Indices of `bounds` grouped by overlap (transitively), each group in index order. Boxes that +/// only touch overlap; a box with a coordinate that isn't finite overlaps none. +/// +/// A sweep left to right keeps the boxes still open at the current left edge in a tree by their +/// tops that knows the lowest bottom below each of its branches, so each box meets only the open +/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their +/// horizontal extent, would otherwise compare every pair). An open box inside a later box of +/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box. +/// Fails only when cancelled ([`vectorcraft_doc::cancel`]). +pub(super) fn overlapping(bounds: &[Option]) -> Result>, vectorcraft_doc::cancel::Cancelled> { fn find(p: &mut [usize], mut i: usize) -> usize { while p[i] != i { p[i] = p[p[i]]; @@ -122,19 +130,75 @@ pub(super) fn overlapping(bounds: &[Option]) -> Vec> { i } let mut parent: Vec = (0..bounds.len()).collect(); - let mut order: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.map(|b| (i, b))).collect(); - order.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0)); - // Sweep left to right, comparing each box with those still open at its left edge. - let mut open: Vec<(usize, Rect)> = vec![]; - for (i, b) in order { - open.retain(|(_, o)| o.x1 >= b.x0); - for (j, o) in &open { - if o.y0 <= b.y1 && b.y0 <= o.y1 { - let (a, c) = (find(&mut parent, i), find(&mut parent, *j)); - parent[a.max(c)] = a.min(c); + let finite = |b: &Rect| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.x0 <= b.x1 && b.y0 <= b.y1; + let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect(); + let n = boxes.len(); + // Each box's place in the tree: by top (then index). + let mut by_top: Vec = (0..n).collect(); + by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b))); + let tops: Vec = by_top.iter().map(|&k| boxes[k].1.y0).collect(); + let mut leaf = vec![0usize; n]; + for (pos, &k) in by_top.iter().enumerate() { + leaf[k] = pos; + } + // The lowest bottom of the open boxes below each node (−∞: none open). + let size = n.next_power_of_two().max(1); + let mut low = vec![f64::NEG_INFINITY; 2 * size]; + let set = |low: &mut [f64], pos: usize, v: f64| { + let mut i = pos + size; + low[i] = v; + while i > 1 { + i /= 2; + low[i] = low[2 * i].max(low[2 * i + 1]); + } + }; + let mut by_left: Vec = (0..n).collect(); + by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0)); + let mut by_right: Vec = (0..n).collect(); + by_right.sort_by(|&a, &b| boxes[a].1.x1.total_cmp(&boxes[b].1.x1)); + let mut closing = 0; + let mut stack: Vec<(usize, usize, usize)> = vec![]; + let mut met = vec![]; + let mut work = 0usize; + for &k in &by_left { + let b = boxes[k].1; + // Close the boxes that end left of this one. + while let Some(&c) = by_right.get(closing) + && boxes[c].1.x1 < b.x0 + { + set(&mut low, leaf[c], f64::NEG_INFINITY); + closing += 1; + } + // The open boxes with their top at most this bottom and their bottom at least this top. + let below = tops.partition_point(|t| *t <= b.y1); + met.clear(); + stack.clear(); + stack.push((1, 0, size)); + while let Some((node, lo, hi)) = stack.pop() { + work += 1; + if work % 4096 == 0 { + vectorcraft_doc::cancel::check()?; + } + if lo >= below || low[node] < b.y0 { + continue; + } + if hi - lo == 1 { + met.push(by_top[lo]); + continue; + } + let mid = (lo + hi) / 2; + stack.push((2 * node + 1, mid, hi)); + stack.push((2 * node, lo, mid)); + } + for &o in &met { + let (a, c) = (find(&mut parent, boxes[k].0), find(&mut parent, boxes[o].0)); + parent[a.max(c)] = a.min(c); + let ob = boxes[o].1; + if ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 { + set(&mut low, leaf[o], f64::NEG_INFINITY); } } - open.push((i, b)); + set(&mut low, leaf[k], b.y1); } let mut groups: Vec> = vec![]; let mut slot: Vec> = vec![None; bounds.len()]; @@ -148,5 +212,83 @@ pub(super) fn overlapping(bounds: &[Option]) -> Vec> { } } } - groups + Ok(groups) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What [`overlapping`] gives, comparing every pair. + fn every_pair(bounds: &[Option]) -> Vec> { + let n = bounds.len(); + let mut group: Vec = (0..n).collect(); + let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1; + loop { + let mut changed = false; + for i in 0..n { + for j in 0..n { + if let (Some(a), Some(b)) = (bounds[i], bounds[j]) + && hit(&a, &b) + && group[j] < group[i] + { + group[i] = group[j]; + changed = true; + } + } + } + if !changed { + break; + } + } + let mut out: Vec> = vec![]; + let mut seen = std::collections::HashMap::new(); + for i in 0..n { + let g = *seen.entry(group[i]).or_insert_with(|| { + out.push(vec![]); + out.len() - 1 + }); + out[g].push(i); + } + out + } + + /// Boxes of many sizes, nested, touching and apart, group as comparing every pair groups them. + #[test] + fn groups_match_comparing_every_pair() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |m: f64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f64 / 1000.0 * m + }; + for round in 0..40 { + let n = 5 + round * 4; + let bounds: Vec> = (0..n) + .map(|i| { + if i % 11 == 3 { + return None; + } + let (x, y) = (next(100.0).round(), next(100.0).round()); + Some(Rect::new(x, y, x + next(30.0).round(), y + next(30.0).round())) + }) + .collect(); + assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}"); + } + } + + /// A column of many boxes sharing their horizontal extent: each one meets only its + /// neighbours, so they group (here, touching in pairs) without comparing every pair. + #[test] + fn a_tall_column_groups_by_its_neighbours() { + let n = 200_000; + let bounds: Vec> = (0..n).map(|i| Some(Rect::new(0.0, 3.0 * f64::from(i), 100.0, 3.0 * f64::from(i) + if i % 2 == 0 { 3.0 } else { 1.0 }))).collect(); + let groups = overlapping(&bounds).unwrap(); + assert_eq!(groups.len(), n as usize / 2); + assert!(groups.iter().enumerate().all(|(g, ids)| ids == &[2 * g, 2 * g + 1])); + // Boxes that aren't finite overlap nothing. + let odd = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(f64::NAN, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 20.0, 20.0))]; + assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]); + } } diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index d229f1bbb8..cccd82ecc8 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -79,7 +79,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). vectorcraft_doc::cancel::check()?; - for g in overlapping(&reaches) { + for g in overlapping(&reaches)? { vectorcraft_doc::cancel::check()?; let ids: Vec = g.iter().map(|&i| roots[i]).collect(); let group = g.iter().any(|&i| see_through[i]).then(|| { From e505bccd5e55b60a62c48884bb5d1d5ad35965f1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 04:31:57 +0000 Subject: [PATCH 314/674] Format with rustfmt --- crates/engine/src/cmd/flatten/analysis.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index 7236499403..a5443fc71a 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -283,7 +283,8 @@ mod tests { #[test] fn a_tall_column_groups_by_its_neighbours() { let n = 200_000; - let bounds: Vec> = (0..n).map(|i| Some(Rect::new(0.0, 3.0 * f64::from(i), 100.0, 3.0 * f64::from(i) + if i % 2 == 0 { 3.0 } else { 1.0 }))).collect(); + let bounds: Vec> = + (0..n).map(|i| Some(Rect::new(0.0, 3.0 * f64::from(i), 100.0, 3.0 * f64::from(i) + if i % 2 == 0 { 3.0 } else { 1.0 }))).collect(); let groups = overlapping(&bounds).unwrap(); assert_eq!(groups.len(), n as usize / 2); assert!(groups.iter().enumerate().all(|(g, ids)| ids == &[2 * g, 2 * g + 1])); From 6b30867eba8079bc3c512f542f84d12bcba8f4b3 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 15:57:57 +0700 Subject: [PATCH 315/674] Flatten Transparency: use is_multiple_of (clippy) --- crates/engine/src/cmd/flatten/analysis.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index a5443fc71a..e7879ec156 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -176,7 +176,7 @@ pub(super) fn overlapping(bounds: &[Option]) -> Result>, ve stack.push((1, 0, size)); while let Some((node, lo, hi)) = stack.pop() { work += 1; - if work % 4096 == 0 { + if work.is_multiple_of(4096) { vectorcraft_doc::cancel::check()?; } if lo >= below || low[node] < b.y0 { From 2d6cf9020b9185c5d188fb10667038cd11b06e64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 20:13:42 -0800 Subject: [PATCH 316/674] Canvas: a dropped press cancels the tool's drag instead of ending it A long touch, a canceled touch or a second finger drops the tool press in progress. The tool used to get a plain mouse-up, which it cannot tell from a release: the options the drag changed (the Polygon tool's sides set with the arrow keys) were stored, and a shape tool pressed and held still opened its size dialog. Session::drop_tool_press undoes the press's interaction, sends the tool Escape as during a drag, and then a release that returns it to rest without storing the tool's options. What the tool asks of the UI along the way is dropped. --- crates/engine/src/tests/toolsettings.rs | 30 ++++++++++++++++++++++++ crates/engine/src/tooling.rs | 20 +++++++++++++++- crates/ui-egui/src/canvas/drag.rs | 14 ++++------- crates/ui-egui/src/canvas/tests.rs | 31 +++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 5 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index d1224e05da..34f85f8227 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -1,6 +1,7 @@ //! Tool options that persist across tool switches, documents and launches (`Prefs::tool_settings`). use serde_json::json; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; use crate::*; @@ -90,6 +91,35 @@ fn a_gesture_keeps_what_it_changed_and_a_document_switch_keeps_options() { assert_eq!(s.tool_options()["segments"], json!(14)); } +/// A dropped press (a long touch, a cancelled touch, a second finger) keeps nothing it began: the +/// tool takes Escape and ends at rest, and the options the drag changed are not stored. A release +/// stores them. +#[test] +fn a_dropped_press_does_not_store_what_its_drag_changed() { + let mut s = session(); + select(&mut s, "polygon"); + let v = ViewInfo::default(); + let drag_with_one_more_side = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + }; + let before = s.tool_options()["sides"].clone(); + drag_with_one_more_side(&mut s); + assert_eq!(s.tool_options()["sides"], json!(7)); + s.drop_tool_press(v).unwrap(); + assert!(!s.tool_busy(), "the tool is at rest"); + let st = s.active().unwrap(); + assert!(st.interaction.is_none() && st.doc.art_bounds().is_none(), "the polygon is not drawn"); + // A tool whose Escape puts back the options the drag changed stores those; nothing else is stored. + let stored = s.prefs.tool_settings.get("polygon").and_then(|o| o.get("sides")); + assert!(stored.is_none_or(|v| *v == before), "the dropped drag's sides are not stored: {stored:?}"); + drag_with_one_more_side(&mut s); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert!(s.active().unwrap().doc.art_bounds().is_some(), "a release draws the polygon"); + assert_eq!(s.prefs.tool_settings["polygon"]["sides"], s.tool_options()["sides"], "and stores its sides"); +} + #[test] fn options_are_saved_with_the_preferences() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index d5c03a651f..f8eb5c1f6a 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -358,6 +358,24 @@ impl Session { /// Feed a pointer event to the active tool. Returns requests for the UI. pub fn pointer(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result> { + self.pointer_event(ev, view, true) + } + + /// Drop the press in progress (a long touch, a cancelled touch, a second finger): nothing it + /// began is kept. Its interaction is undone, the tool takes Escape as it does during a drag, + /// and then a release that returns it to rest. The options the press changed are not stored, + /// and what the tool asks of the UI along the way (a size dialog for a click) is dropped. + pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> { + // Nothing to roll back without a document; the tool still takes Escape and the release. + let _ = self.cancel_interaction(); + let esc = self.tool_key(ToolKey::Escape, Mods::default(), view); + let up = PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote: false, pressure: 1.0, pen: None }; + let up = self.pointer_event(&up, view, false); + esc.and(up).map(drop) + } + + /// [`Self::pointer`]; a release stores the tool's options only with `keep`. + fn pointer_event(&mut self, ev: &PointerEvent, view: ViewInfo, keep: bool) -> Result> { self.last_view = view; match ev.kind { PointerKind::Down | PointerKind::Drag => self.pointer_held = true, @@ -373,7 +391,7 @@ impl Session { let acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); let r = self.take_tool_panic().and_then(|()| { // A gesture may change options (Alt-drag sizes a Liquify brush): keep them. - if ev.kind == PointerKind::Up { + if keep && ev.kind == PointerKind::Up { self.keep_tool_settings(); } self.apply_actions(acts) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 88293880a8..ef4cc2ad25 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -230,15 +230,11 @@ pub fn mods(m: egui::Modifiers, space: bool) -> Mods { pub(super) fn drop_press(app: &mut VectorcraftApp, ui: &Ui, view: vectorcraft_engine::ViewInfo) { match ui.data(|d| d.get_temp::(drag_id())) { Some(Drag::Tool | Drag::Art) => { - // The tool's mouse-up returns it to rest. A move waiting over a panel is still live - // and would otherwise outlive the drag that owns it (#2826). - // Nothing to roll back without a document; the tool still gets its mouse-up. - let _ = app.session.cancel_interaction(); - dispatch( - app, - &PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote: false, pressure: 1.0, pen: None }, - view, - ); + // The tool takes Escape, as during a drag, and then a mouse-up that returns it to rest. + // A move waiting over a panel is still live and would otherwise outlive the drag that + // owns it (#2826). + let r = app.session.drop_tool_press(view); + apply_requests(app, r.map(|()| vec![])); egui::DragAndDrop::clear_payload(ui.ctx()); } Some(_) => {} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3e184bef45..f0a594f2a1 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6723,10 +6723,41 @@ fn long_touch_drops_a_tool_press_without_committing_art() { tick(&mut app, 1.5, vec![]); assert!(matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Gesture)), "long touch drops the tool drag"); assert!(app.session.active().unwrap().interaction.is_none()); + assert!(app.ui.dialog.is_none(), "the dropped press is not a click that opens the size dialog"); tick(&mut app, 1.6, pen(egui::TouchPhase::End, pos, 0.5)); assert!(app.session.active().unwrap().doc.art_bounds().is_none(), "releasing cannot commit the cancelled press"); } +/// A cancelled touch drops the tool's drag as Escape does: the options the drag changed (the +/// Polygon tool's sides) are not stored, and nothing is drawn. +#[test] +fn a_cancelled_touch_drops_the_drag_without_storing_its_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.touch_gestures = true; + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.select_tool("polygon"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let start = xf.to_screen(Point::new(200.0, 200.0)); + frame(&mut app, &ctx, pen(egui::TouchPhase::Start, start, 0.5)); + frame(&mut app, &ctx, pen(egui::TouchPhase::Move, start + vec2(60.0, 40.0), 0.5)); + assert!(matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Tool))); + assert!(app.session.active().unwrap().interaction.is_some(), "the drag previews the polygon"); + let view = app.view_info(); + let before = app.session.tool_options()["sides"].clone(); + app.session.tool_key(vectorcraft_tools::ToolKey::Up, Mods::default(), view).unwrap(); + assert_eq!(app.session.tool_options()["sides"], json!(7)); + frame(&mut app, &ctx, pen(egui::TouchPhase::Cancel, start + vec2(60.0, 40.0), 0.5)); + assert!(!app.session.tool_busy(), "the tool is at rest"); + let st = app.session.active().unwrap(); + assert!(st.interaction.is_none() && st.doc.art_bounds().is_none(), "nothing is drawn"); + assert!(app.ui.dialog.is_none()); + // A tool whose Escape puts back the options the drag changed stores those; nothing else is stored. + let stored = app.session.prefs.tool_settings.get("polygon").and_then(|o| o.get("sides")); + assert!(stored.is_none_or(|v| *v == before), "the dropped drag's sides are not stored: {stored:?}"); +} + /// #2826: a second finger drops a move waiting over a panel, so its interaction doesn't /// outlive the drag that began it. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b9c9ad6df2..1ce35dbe36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -840,6 +840,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the view rotated, a second Escape less than a second after the first resets the rotation, as Reset Rotate View does. The first Escape may end something else, such as isolation mode or a path being drawn. The second resets the view only when it has nothing else to end, and an Escape that closes a menu does not count. After a click, or a press of another key that is not a modifier (Shift, Control, Alt/Option or Command), the next Escape counts as the first. With the Rotate View tool chosen, one Escape resets the view. A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5° (Preferences › General › Trackpad Gesture to Rotate View, on by default). On a touch screen a second finger cancels the tool press the first finger began, in the frame it lands or later: the Pencil's stroke or a Selection move is rolled back with no undo entry, and a finger that lands while another is down presses nothing, so a pinch or two-finger pan only zooms and pans (#4198; canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`). + A tool press dropped by a second finger, a long touch or a cancelled touch reaches the tool as Escape does during a drag, followed by a release: the options the drag changed (the Polygon tool's sides, set with ↑ and ↓) are not stored, and a press held still opens no size dialog (canvas tests `a_cancelled_touch_drops_the_drag_without_storing_its_options` and `long_touch_drops_a_tool_press_without_committing_art`). The status bar navigator's field shows the active artboard's number and name, and its drop-down lists every artboard by number and name, as the Artboards panel does. Choosing an artboard in the list makes it the active artboard and fits it in the window (`view.goToArtboard`). The list opens on the active artboard's row and lays out only the rows in view and at most one more. - **Geometry and effects:** - **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged. From 06139d00117a1994022a1ff28ef8121c92101f99 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:36:46 -0500 Subject: [PATCH 317/674] Export for Screens: keep PDF passwords out of remembered settings A successful Export for Screens stored its params in the document's export settings, which native saves write, PDF security passwords included, although the PDF settings themselves are saved without them. Saved export presets kept them in the preferences the same way. Both now drop openPassword and permissionsPassword wherever they appear in the settings, keeping the other security choices. --- crates/engine/src/cmd/fileio/screens.rs | 46 ++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 19381709ab..b6fe4d85a2 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -698,6 +698,8 @@ fn preset_settings(s: &Session, cmd: &str, given: &Map) -> Result // Refuse what an export would refuse, now rather than when the preset is used. check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(cmd, e.to_string()))?; Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(cmd, e.to_string()))?; + let mut settings = settings; + remove_passwords(&mut settings); Ok(settings) } @@ -1275,9 +1277,33 @@ fn remember(s: &mut Session, p: &Value) { let _ = store_settings(s, settings); } +/// The PDF passwords an export may be given (`security` of a PDF row or of `settings.pdf`). +const PASSWORD_KEYS: [&str; 2] = ["openPassword", "permissionsPassword"]; + +/// `settings` without the PDF passwords anywhere in them: settings kept in the document (which +/// native saves write) or in the preferences hold the export's choices, never its secrets, as +/// the PDF settings themselves are saved without them. +fn remove_passwords(settings: &mut Map) { + for key in PASSWORD_KEYS { + settings.remove(key); + } + for v in settings.values_mut() { + remove_passwords_in(v); + } +} + +fn remove_passwords_in(v: &mut Value) { + match v { + Value::Object(m) => remove_passwords(m), + Value::Array(items) => items.iter_mut().for_each(remove_passwords_in), + _ => {} + } +} + /// Make `settings` the document's export settings. Not an undo step (like the settings of any /// export); the document has changed only if they differ. -pub(crate) fn store_settings(s: &mut Session, settings: Map) -> Result<()> { +pub(crate) fn store_settings(s: &mut Session, mut settings: Map) -> Result<()> { + remove_passwords(&mut settings); let st = s.doc_mut()?; if st.doc.export_settings != settings { Arc::make_mut(&mut st.doc).export_settings = settings; @@ -1314,6 +1340,7 @@ mod tests { assert_eq!(out.claim("same.png", "last").as_deref(), Some("same-20001.png")); } + #[test] fn size_parse_refuses_signs_and_exponents() { for s in ["+2x", "+2", "+100w", "+100h", "+72ppi", "-2x", "1e2", "2e0w"] { @@ -1334,4 +1361,21 @@ mod tests { assert_eq!(safe_file_name("lpt9 .png"), "lpt9-.png"); assert_eq!(safe_file_name("My CON .png"), "My CON .png"); } + + /// The settings an export leaves in the document keep its PDF security choices but not its + /// passwords, in a row or in `settings.pdf`. + #[test] + fn stored_settings_leave_out_pdf_passwords() { + let mut s = crate::Session::new(); + s.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); + let given = serde_json::json!({ + "formats": [{"format": "pdf", "security": {"openPassword": "open sesame", "permissionsPassword": "owner", "printing": "low"}}], + "settings": {"pdf": {"security": {"openPassword": "open sesame", "copy": false}}}, + }); + super::store_settings(&mut s, given.as_object().unwrap().clone()).unwrap(); + let kept = serde_json::Value::Object(s.doc().unwrap().doc.export_settings.clone()); + assert!(!kept.to_string().contains("Password"), "{kept}"); + assert_eq!(kept["formats"][0]["security"]["printing"], "low"); + assert_eq!(kept["settings"]["pdf"]["security"]["copy"], false); + } } From 8e692d83ed1464a61b935e59e0b65c67672ccac0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:29:45 -0500 Subject: [PATCH 318/674] ICC: refuse a profile whose tag table lists a tag twice moxcms parses every entry of the tag table, so a profile listing one description, copyright or table tag thousands of times, each pointing at the same large data, made it decode and copy that data once per entry. The ICC specification allows each tag signature once; such a table is now refused before parsing. --- crates/color/src/cms/icc.rs | 20 ++++++++++++++++++++ crates/color/src/cms/tests_icc.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 64f42f25b9..2599956ce7 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -106,6 +106,9 @@ impl IccProfile { if !localized_text_fits(bytes) { return Err(CmsError::BadProfile(format!("its localized names take more than {} KB", MAX_LOCALIZED_TEXT >> 10))); } + if let Some(tag) = repeated_tag(bytes) { + return Err(CmsError::BadProfile(format!("its tag table lists the `{}` tag more than once", String::from_utf8_lossy(&tag.to_be_bytes())))); + } let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?; Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? }) } @@ -417,6 +420,23 @@ pub(super) fn gray_profile(name: &str) -> ColorProfile { labelled(p, name) } +/// The first tag signature the tag table of ICC `bytes` lists twice, which the ICC +/// specification forbids. moxcms parses every entry of the table, so a profile listing one +/// description, copyright or table tag thousands of times, each pointing at the same large data, +/// would decode and copy that data once per entry. A table it can't read is left to moxcms. +pub(crate) fn repeated_tag(bytes: &[u8]) -> Option { + let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]])); + let tags = be32(128)? as usize; + let mut seen = std::collections::HashSet::new(); + for i in 0..tags { + let sig = be32(i.checked_mul(12)?.checked_add(132)?)?; + if !seen.insert(sig) { + return Some(sig); + } + } + None +} + /// Most bytes of UTF-16 the localized names (`mluc` tags) of a profile may take together. const MAX_LOCALIZED_TEXT: usize = 1 << 20; diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index 46e44cd760..1d312c09c3 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -181,6 +181,32 @@ fn aliased_localized_names_are_refused() { assert!(!super::icc::localized_text_fits(&profile(4096, 64 << 10))); } +/// A tag table that lists one tag many times, every entry pointing at the same long text, is +/// refused before moxcms decodes the text once per entry; distinct tags pass. +#[test] +fn repeated_tags_are_refused() { + let profile = |sigs: &[&[u8; 4]], text: usize| { + let mut b = vec![0u8; 128]; + b.extend((sigs.len() as u32).to_be_bytes()); + let tag_at = 128 + 4 + 12 * sigs.len(); + let size = 8 + text; + for sig in sigs { + b.extend(*sig); + b.extend((tag_at as u32).to_be_bytes()); + b.extend((size as u32).to_be_bytes()); + } + b.extend(b"text"); + b.extend([0; 4]); + b.extend(vec![b'a'; text]); + b + }; + assert_eq!(super::icc::repeated_tag(&profile(&[b"desc", b"cprt", b"dmdd"], 64)), None); + let many: Vec<&[u8; 4]> = std::iter::repeat_n(b"desc", 4096).collect(); + let bytes = profile(&many, 256 << 10); + assert_eq!(super::icc::repeated_tag(&bytes), Some(u32::from_be_bytes(*b"desc"))); + assert!(matches!(super::icc::IccProfile::from_bytes(None, &bytes), Err(super::CmsError::BadProfile(_)))); +} + /// Reloading an RGB profile under the name it had (a new file for "My RGB") changes what CMYK /// converts to in it: the direct CMYK → RGB transform isn't kept from the old file. #[test] From cd1afaf1cffa82968804d6df277eb59efc283688 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 20:21:58 -0500 Subject: [PATCH 319/674] DXF import: budget dash lengths, copied text and names, and block items looked at A drawing could make the importer keep far more than its own size: every dashed path held its own copy of its linetype, every text object and symbol instance of an array copied its text, font family or block name, and each placement of a block looked at all of its items, hidden or not, without charging the work budget. - Dash lengths kept across the import are capped; past the cap lines are drawn solid. - Text, font family and block-name bytes copied into objects share one 64 MB budget, and a font family longer than 256 bytes falls back to the default. - Each block placement charges one visit per item it looks at, and stops once the budget is spent. --- crates/cad/src/import/build.rs | 79 ++++++++++++++++++++++----- crates/cad/src/import/tests.rs | 97 ++++++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 13 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 6857c2a175..ee14e81f5c 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -23,10 +23,19 @@ const PT_PER_MM: f64 = 72.0 / 25.4; const THINNEST: f64 = 0.25; /// The most objects an import makes. const MAX_NODES: usize = 2_000_000; -/// The most block visits (one per insert copy) an import makes, whatever they produce. -const MAX_VISITS: usize = 10_000_000; +/// The most block work an import does, whatever it produces: one per insert copy drawn, and one +/// per item of the block looked at for it (art on hidden layers too). +const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; /// The most path elements an import makes (blocks drawn as art are copied for every placement). const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; +/// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern). +const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 }; +/// The most bytes of text, font names and symbol names an import copies into objects (a block's +/// text and name are copied for every placement). +const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 }; +/// The longest font family a text style may name; a longer one is not a font, and is set in the +/// default. +const MAX_FAMILY_BYTES: usize = 256; /// How far from the origin art may lie (points): the canvas. pub(crate) const MAX_EXTENT: f64 = 4.0e6; @@ -34,6 +43,8 @@ const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are const XREFS: &str = "blocks referencing other drawings (external references) are left out"; const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out"; const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out"; +const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; +const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; /// What a block's art takes from the insert that places it: its colour, lineweight, linetype /// and opacity where the art says "by block", and its layer for art on layer 0. @@ -71,6 +82,9 @@ pub(crate) struct Build<'d, 'a> { visits: usize, /// Path elements made so far. elements: usize, + /// Dash lengths and text bytes kept so far. + dash_values: usize, + text_bytes: usize, warnings: Vec, } @@ -128,6 +142,8 @@ impl<'d, 'a> Build<'d, 'a> { nodes: 0, visits: 0, elements: 0, + dash_values: 0, + text_bytes: 0, warnings: vec![], } } @@ -138,6 +154,20 @@ impl<'d, 'a> Build<'d, 'a> { } } + /// Take `bytes` of text from [`MAX_TEXT_BYTES`]; false (with a warning) when they don't fit. + fn charge_text(&mut self, bytes: usize) -> bool { + match self.text_bytes.checked_add(bytes).filter(|t| *t <= MAX_TEXT_BYTES) { + Some(t) => { + self.text_bytes = t; + true + } + None => { + self.warn(TOO_MUCH_TEXT); + false + } + } + } + /// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own /// unit and at the scale asked for (fitting computes its own). pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec), String> { @@ -484,9 +514,15 @@ impl<'d, 'a> Build<'d, 'a> { if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() && let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale) { - s.dash = Some(dash); - if dots { - s.cap = LineCap::Round; + match self.dash_values.checked_add(dash.pattern.len()).filter(|n| *n <= MAX_DASH_VALUES) { + Some(n) => { + self.dash_values = n; + s.dash = Some(dash); + if dots { + s.cap = LineCap::Round; + } + } + None => self.warn(TOO_MANY_DASHES), } } ap @@ -527,10 +563,15 @@ impl<'d, 'a> Build<'d, 'a> { if !(s > 1e-12 && s.is_finite()) { return None; } - let family = t.family.clone().or_else(|| self.d.styles.get(&t.style).filter(|f| !f.is_empty()).cloned()); + let d = self.d; + let family = t.family.as_deref().or_else(|| d.styles.get(&t.style).map(String::as_str).filter(|f| !f.is_empty())); + let family = family.filter(|f| f.len() <= MAX_FAMILY_BYTES); + if !self.charge_text(t.text.len().saturating_add(family.map_or(0, str::len))) { + return None; + } let default = CharStyle::default(); let style = CharStyle { - font_family: family.unwrap_or(default.font_family.clone()), + font_family: family.map_or_else(|| default.font_family.clone(), str::to_string), size: t.height / CAP_HEIGHT * s, h_scale: t.width * 100.0, leading: t.leading.map(|l| l * s), @@ -558,6 +599,13 @@ impl<'d, 'a> Build<'d, 'a> { for cell in &ins.cells { let node = match &symbol { Some(name) => { + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + if !self.charge_text(name.len()) { + break; + } let xf = map * *cell * self.symbol_map.inverse(); self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) @@ -581,14 +629,19 @@ impl<'d, 'a> Build<'d, 'a> { /// The art of block `name` drawn by `map`, as one object. fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option { - self.visits += 1; - if self.visits > MAX_VISITS { - if self.visits == MAX_VISITS + 1 { - self.warn(TOO_MANY); - } + if self.visits >= MAX_VISITS { + self.warn(TOO_MANY); return None; } - let items = self.block(name)?; + let items = self.block(name); + // Each placement looks at every item of the block, drawn or not (art on a hidden layer + // makes nothing, so the node budget doesn't bound it). + self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len())); + if self.visits > MAX_VISITS { + self.warn(TOO_MANY); + return None; + } + let items = items?; if !self.enter(name, depth) { return None; } diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 6bd3d1c106..4ecba52f5d 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -1177,3 +1177,100 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() { assert!(total <= 2_000_000 + 3000, "total cells materialised: {total}"); assert!(conv.warnings.iter().any(|w| w.contains("array inserts")), "{:?}", conv.warnings); } + +#[test] +fn dashed_lines_past_the_dash_budget_are_drawn_solid() { + // 600 lines of a two-length linetype: 1,200 dash lengths, past the 1,000 tests import with. + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + let line = [(0, "LINE"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")]; + let e: Vec<(i32, &str)> = (0..600).flat_map(|_| line).collect(); + let r = open(&drawing(&[], &tables, &[], &e), &points()); + let (mut dashed, mut solid, mut kept) = (0, 0, 0); + r.document.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + match n.appearance.stroke().and_then(|s| s.dash.as_ref()) { + Some(d) => { + dashed += 1; + kept += d.pattern.len(); + } + None => solid += 1, + } + } + }); + assert_eq!(dashed + solid, 600); + assert!(dashed > 0 && solid > 0, "{dashed} dashed, {solid} solid"); + assert!(kept <= 1_000, "{kept} dash lengths kept"); + assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings); +} + +/// The bytes of text in the document's text objects. +fn text_bytes(doc: &Document) -> usize { + let mut bytes = 0; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + bytes += t.runs.iter().map(|r| r.text.len()).sum::(); + } + }); + bytes +} + +#[test] +fn text_copied_into_array_cells_stops_at_the_text_budget() { + // 1,000 characters of text in an anonymous block placed 10 × 10: 100 KB of copies, past the + // 64 KB tests import with. + let long = "x".repeat(1000); + let blocks = [(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")]; + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "1"), (45, "1")]; + let r = open(&drawing(&[], &[], &blocks, &insert), &points()); + let bytes = text_bytes(&r.document); + assert!(bytes > 0, "some copies are kept"); + assert!(bytes <= 64 << 10, "{bytes} bytes of text"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); +} + +#[test] +fn a_text_style_naming_an_overlong_font_family_takes_the_default() { + let family = "F".repeat(10_000); + let tables = [(0, "TABLE"), (2, "STYLE"), (0, "STYLE"), (2, "Big"), (3, "x.ttf"), (1001, "ACAD"), (1000, family.as_str()), (0, "ENDTAB")]; + let e = [(0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, "Hi"), (7, "Big")]; + let doc = open(&drawing(&[], &tables, &[], &e), &points()).document; + let mut families = vec![]; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + families.extend(t.runs.iter().map(|r| r.style.font_family.clone())); + } + }); + assert_eq!(families, [vectorcraft_doc::CharStyle::default().font_family]); +} + +#[test] +fn symbol_instances_of_a_long_block_name_stop_at_the_text_budget() { + // A 1,000-byte block name placed 10 × 10: each instance keeps its own copy of the name. + let name = "N".repeat(1000); + let blocks = [(0, "BLOCK"), (2, name.as_str()), (10, "0"), (20, "0"), (0, "LINE"), (10, "0"), (20, "0"), (11, "1"), (21, "0"), (0, "ENDBLK")]; + let insert = [(0, "INSERT"), (2, name.as_str()), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "2"), (45, "2")]; + let r = open(&drawing(&[], &[], &blocks, &insert), &points()); + let mut instances = 0; + r.document.walk(|n| { + if let NodeKind::SymbolInstance { .. } = n.kind { + instances += 1; + } + }); + assert!(instances > 0 && instances < 100, "{instances} instances"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); +} + +#[test] +fn arrays_of_blocks_of_hidden_art_stop_at_the_work_budget() { + // 500 lines on a hidden layer in an anonymous block placed 50 × 50: they make nothing, but + // each placement looks at all of them (1,250,000 items, past the 1,000,000 tests import with). + let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")]; + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + for _ in 0..500 { + blocks.extend([(0, "LINE"), (8, "Off"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + } + blocks.push((0, "ENDBLK")); + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "50"), (71, "50"), (44, "1"), (45, "1")]; + let r = open(&drawing(&[], &tables, &blocks, &insert), &points()); + assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings); +} From b1dc20b811f7adba2059391a770b55b25f450aa5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 05:54:15 -0800 Subject: [PATCH 320/674] Type: text.setStyle sets the text's stroke as well as its fill text.setStyle takes stroke (a color or "none") and strokeWidth (the character stroke's weight in document points, as stroke.set gives it), with keepModel for both colors. They apply to all the text or to the start..end range, and to graph label styles, in the same undo step as the command's other keys. A stroke key was ignored before. --- crates/engine/src/cmd/typecmd.rs | 36 +++++++++++++++++++++++++---- crates/engine/src/tests/textedit.rs | 36 +++++++++++++++++++++++++++++ docs/mcp.md | 7 ++++-- docs/target-app-parity.md | 1 + 4 files changed, 73 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 84221ced1c..9ee14708ac 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -123,7 +123,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, keepModel?: bool (as paint.setFill), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -785,11 +785,21 @@ fn set_style(s: &mut Session, p: &Value) -> Result { None => None, }; super::paint::check_keep_model(p, C)?; - let fill = match p.get("fill") { - None | Some(Value::Null) => None, - Some(Value::String(n)) if n.eq_ignore_ascii_case("none") => Some(vectorcraft_color::Paint::None), - Some(v) => Some(vectorcraft_color::Paint::solid(super::paint::new_color(s, p, color_value(v).ok_or_else(|| bad(C, "bad fill colour"))?))), + let paint = |k: &str| -> Result> { + Ok(match p.get(k) { + None | Some(Value::Null) => None, + Some(Value::String(n)) if n.eq_ignore_ascii_case("none") => Some(vectorcraft_color::Paint::None), + Some(v) => { + Some(vectorcraft_color::Paint::solid(super::paint::new_color(s, p, color_value(v).ok_or_else(|| bad(C, format!("bad {k} colour")))?))) + } + }) }; + let fill = paint("fill")?; + let stroke = paint("stroke")?; + check_numbers(p, &["strokeWidth"], C)?; + // The weight of the character stroke. + let mut stroke_weight = super::stroke::StrokeChange::default(); + stroke_weight.weight = p.get("strokeWidth").and_then(Value::as_f64).map(|w| w.clamp(0.0, 1000.0)); let features = super::textedit::features_param(p, C)?; let feature_changes = super::textedit::feature_changes_param(p, C)?; if font.is_none() @@ -799,6 +809,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result { && tracking.is_none() && justify.is_none() && fill.is_none() + && stroke.is_none() + && stroke_weight.is_empty() && features.is_none() && feature_changes.is_none() { @@ -814,6 +826,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; let size = size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, C)).transpose()?; let leading = leading.map(|v| v.map(|v| local_type_value(t, v, (0.1, 5000.0), false, C)).transpose()).transpose()?; + // The stroke weight is in document points, as stroke.set gives it; the character stroke is drawn in text space. + let k = vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0); let before = protect.then(|| t.runs.clone()); style_chars(t, range, |st| { if let Some(f) = &font { @@ -843,6 +857,12 @@ fn set_style(s: &mut Session, p: &Value) -> Result { if let Some(f) = &fill { st.fill = f.clone(); } + if let Some(f) = &stroke { + st.stroke = f.clone(); + } + if !stroke_weight.is_empty() { + stroke_weight.apply_char_scaled(st, k); + } if let Some(f) = &features { st.features = f.clone(); } @@ -899,6 +919,12 @@ fn set_style(s: &mut Session, p: &Value) -> Result { if let Some(f) = &fill { st.fill = f.clone(); } + if let Some(f) = &stroke { + st.stroke = f.clone(); + } + if !stroke_weight.is_empty() { + stroke_weight.apply_char(st); + } if let Some(f) = &features { st.features = f.clone(); } diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index a3e8f7c66e..ea5b38ca47 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -139,6 +139,42 @@ fn feature_changes_keep_each_runs_other_features() { assert_eq!(features(&s), [vec!["smcp", "numr", "liga", "dnom"], vec!["swsh", "numr", "liga", "dnom"], vec!["-onum", "swsh", "dnom"]]); } +/// `text.setStyle {stroke, strokeWidth}` sets the character stroke of all the text or of a range, as +/// `text.setRangeStyle` does, and a call with `fill` and `stroke` sets both in one undo step. +#[test] +fn set_style_sets_the_character_stroke() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let id = text(&mut s, "Hello world"); + let paints = + |s: &Session| obj(s, id).runs.iter().map(|r| (r.style.fill.color(), r.style.stroke.color(), r.style.stroke_width)).collect::>(); + let red = Some(Color::rgb8(255, 0, 0)); + let blue = Some(Color::rgb8(0, 0, 255)); + let fill = obj(&s, id).runs[0].style.fill.color(); + s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "#ff0000", "strokeWidth": 2})).unwrap(); + assert_eq!(paints(&s), [(fill, red, 2.0)], "all the text"); + s.execute("text.setStyle", &json!({"ids": [id.0], "start": 6, "end": 11, "stroke": "#0000ff"})).unwrap(); + assert_eq!(paints(&s), [(fill, red, 2.0), (fill, blue, 2.0)], "a range"); + let before = paints(&s); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("text.setStyle", &json!({"ids": [id.0], "fill": "#0000ff", "stroke": "none", "strokeWidth": 0})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!( + obj(&s, id).runs.iter().all(|r| r.style.fill.color() == blue && r.style.stroke == Paint::None && r.style.stroke_width == 0.0), + "{:?}", + paints(&s) + ); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paints(&s), before, "undo restores the fill and the stroke"); + let e = s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "nope"})).unwrap_err().to_string(); + assert!(e.contains("bad stroke colour"), "{e}"); + assert!(s.execute("text.setStyle", &json!({"ids": [id.0], "strokeWidth": "x"})).is_err(), "strokeWidth must be a number"); + // The weight is in document points, as stroke.set gives it: type scaled 200% keeps half of it in text space. + s.execute("object.scale", &json!({"ids": [id.0], "sx": 200, "sy": 200})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id.0], "strokeWidth": 2})).unwrap(); + assert!(obj(&s, id).runs.iter().all(|r| (r.style.stroke_width - 1.0).abs() < 1e-9), "{:?}", paints(&s)); +} + #[test] fn optical_command_manual_pair_undo_redo_and_native_reopen() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 3d8e999b5c..24f8a17808 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -548,7 +548,7 @@ Brushes of different types, or a `type` other than theirs, are refused with "bru Document colour mode: `file.new {colorMode: "cmyk"}` starts a CMYK document with CMYK default swatches, and RGB colors applied to it (`paint.setFill`/`setStroke` colors, gradient stops and freeform points, `paint.editGradient` stops, `paint.freeform.addPoint`/`setPoint`, `paint.sampleColor`, `object.mesh.setPointColor`/`addLine`, the -`text.create` and `text.createInPath` color, the `text.setStyle` fill, `text.setRangeStyle` fills and strokes, a +`text.create` and `text.createInPath` color, `text.setStyle` and `text.setRangeStyle` fills and strokes, a `shapeBuilder.merge` hex fill (its `fill: {color, keepModel: true}` form keeps RGB), the `symbol.adjust` stain color, `swatch.new {color}` and `{colors}`, `swatch.newGroup`, `swatch.editGroup` and `swatch.edit`) are stored as CMYK, converted through the color settings (`edit.colorSettings`: the CMYK @@ -2358,7 +2358,10 @@ dash options go to every run (the object keeps no stroke of its own); an `item` with `appearance.addStroke`, which takes every stroke option (dashes, profile, opacity, blend) like a path's and paints under or over the characters as its place relative to the Characters row says. To stroke some characters, use `text.setRangeStyle {id, start, end, strokeOptions: {weight?, cap?, join?, miterLimit?, align?, -dash?, dashOffset?, alignDashes?}}`. `align: "inside"|"outside"` keeps the characters' stroke on that side of the +dash?, dashOffset?, alignDashes?}}`. `text.setStyle {ids?, stroke?, strokeWidth?, start?, end?}` sets the stroke color +and weight of the characters of each object given (without `start` and `end`: all of its text), with its other keys in +one undo step; `strokeWidth` is in document points, as `stroke.set` gives the weight of scaled type. +`align: "inside"|"outside"` keeps the characters' stroke on that side of the glyph outlines, drawn at twice the weight and clipped, while the type stays editable (beyond Illustrator); SVG export writes the text live and that stroke as glyph outlines over it. `inspect_document` reports each object's stroke as `strokeOptions` (type: its first run's) in `stroke.set` terms. `stroke.set` on a group leaves the images and symbol instances in it alone. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3f95343c96..b9c9ad6df2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -885,6 +885,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. + `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. From df61ee2f848882477c479038681e58f5059aa1ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 07:44:39 -0800 Subject: [PATCH 321/674] Canvas: moves after the button-up do not join a stroke A Pencil or brush stroke takes every pointer move of a frame. In the frame that releases the button, the moves that came after the button-up were sent as drags before the release, so the stroke ran out to them and back. The moves now stop at the primary button-up, and the pen pose for the end of the stroke is the one kept for the last move before it. --- crates/ui-egui/src/canvas/drag.rs | 23 +++++++--- crates/ui-egui/src/canvas/input.rs | 7 +-- crates/ui-egui/src/canvas/tests.rs | 71 +++++++++++++++++++++++++++--- 3 files changed, 87 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 1c14379e28..871af252f6 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -149,10 +149,17 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// move (empty when the pen read neither), if any. The last move is the pointer's position; the /// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no /// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, -/// too few for a low Fidelity to follow the hand (#3328). -pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> (Vec, Option) { +/// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that +/// button's button-up in this frame, if it came: the moves after it are hover, and the last move +/// before it is the pointer's position. +pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option) -> (Vec, Option) { let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { + // How many of the frame's moves came before the button-up, if it came. + let before_up = release.and_then(|b| { + let up = i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button, pressed: false, .. } if *button == b))?; + Some(i.events.iter().take(up).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()) + }); let mut moves = vec![]; if i.events.iter().any(|e| matches!(e, egui::Event::Touch { .. })) { let mut force = None; @@ -173,6 +180,10 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> (Vec) -> (Vec (Vec, Option) { - let (moves, last_pose) = frame_moves(ui, app.services.stylus.as_ref()); +/// position come second, for every tool. With `released`, only the moves before the primary +/// button-up count. +pub(super) fn tool_frame_moves(ui: &Ui, app: &VectorcraftApp, released: bool) -> (Vec, Option) { + let release = released.then_some(egui::PointerButton::Primary); + let (moves, last_pose) = frame_moves(ui, app.services.stylus.as_ref(), release); (if app.session.tool_wants_samples() { moves } else { vec![] }, last_pose) } diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 87b35a7c93..3775edeb86 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -382,7 +382,7 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) // or the web, a finger) and a macOS pen's moves carry their own pressure; a // mouse's, a pen's on X11 among them, take the host's latest. Other tools get // the last position only, so a costly drag preview runs once a frame. - let (moves, last_pose) = tool_frame_moves(ui, app); + let (moves, last_pose) = tool_frame_moves(ui, app, false); // A frame whose pointer ends where the last one did still moved in between. let backquote = ui.input(|i| i.key_down(egui::Key::Backtick)); let mods_changed = tool_drag_mods_changed(ui, mods(m, space), backquote); @@ -467,8 +467,9 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po // tools commit the last preview, which should be where the pointer let go // (#834). Only once the press has dragged, so a click's jitter stays a click // (the Pen's corner anchor, no nudge with Direct Selection). A tool that builds a - // stroke from the drag's samples gets the frame's other moves before it. - let (moves, last_pose) = tool_frame_moves(ui, app); + // stroke from the drag's samples gets the frame's other moves before it, up to the + // button-up: the moves after it are hover. + let (moves, last_pose) = tool_frame_moves(ui, app, true); let pen = move_pose(app, &xf, last_pose); if let Some(last) = last_drag { let backquote = ui.input(|i| i.key_down(egui::Key::Backtick)); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 499ff8a7e3..79954a6b0a 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6578,6 +6578,64 @@ fn a_drag_ends_where_the_button_went_up_in_its_frame() { assert!(app.session.active().unwrap().interaction.is_none(), "committed"); } +/// The moves that come after the button-up in the release's frame are hover: a stroke built from +/// the drag's samples does not take them. +#[test] +fn moves_after_the_button_up_do_not_join_the_stroke() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let center = app.canvas_rect.unwrap().center(); + app.select_tool("pencil"); + let a = center - vec2(100.0, 0.0); + let end = a + vec2(120.0, 0.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(a)]); + frame(&mut app, &ctx, vec![button(a, true)]); + for x in [20.0, 40.0, 60.0] { + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(x, 0.0))]); + } + let hover = [end + vec2(30.0, 100.0), end + vec2(60.0, 120.0), end + vec2(90.0, 140.0)]; + let mut events = vec![Event::PointerMoved(a + vec2(90.0, 0.0)), Event::PointerMoved(end), button(end, false)]; + events.extend(hover.map(Event::PointerMoved)); + frame(&mut app, &ctx, events); + let st = app.session.active().unwrap(); + let r = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap(); + let (left, right) = (xf.to_doc(a), xf.to_doc(end)); + assert!((r.x0 - left.x).abs() < 1.0 && (r.x1 - right.x).abs() < 1.0 && r.height() < 1.0, "the stroke stops at the release: {r:?}"); +} + +/// [`frame_moves`] with a release keeps the moves before the button-up, and the pose the feed kept +/// for the last of them. +#[test] +fn frame_moves_stop_at_the_button_up() { + let ctx = egui::Context::default(); + let (a, b, c, d) = (pos2(10.0, 20.0), pos2(20.0, 30.0), pos2(30.0, 40.0), pos2(40.0, 50.0)); + let up = egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c), egui::Event::PointerMoved(d)]; + let feed = StylusFeed::default(); + let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; + let after = PenPose { tilt: Some([50.0, 0.0]), rotation: None }; + for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, after), (0.8, after)] { + feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); + } + let (mut moves, mut last) = (vec![], None); + let release = Some(egui::PointerButton::Primary); + let mut out = + ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| (moves, last) = frame_moves(ui, Some(&feed), release)); + out.textures_delta.clear(); + assert_eq!(moves, [(a, Some(0.4), Some(PenPose::default()))], "the moves after the button-up are left out"); + assert_eq!(last, Some(at_b), "the pose is the last move's before the button-up"); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| moves = frame_moves(ui, None, None).0); + out.textures_delta.clear(); + assert_eq!(moves, [(a, None, None), (b, None, None), (c, None, None)], "without a release every move counts"); +} + #[test] fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { let ctx = egui::Context::default(); @@ -6586,7 +6644,7 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { let c = pos2(30.0, 40.0); let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), egui::Event::PointerMoved(c)]; let mut mouse = vec![]; - let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| mouse = frame_moves(ui, None).0); + let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| mouse = frame_moves(ui, None, None).0); out.textures_delta.clear(); // A mouse keeps its moves too, without a pressure or a pose. assert_eq!(mouse, [(a, None, None), (b, None, None)], "the last move follows the normal pointer path"); @@ -6597,7 +6655,8 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } let (mut samples, mut last) = (vec![], None); - let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed))); + let mut out = + ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed), None)); out.textures_delta.clear(); assert_eq!( samples, @@ -6605,17 +6664,17 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { "paired from the end, each with its own pose; a lift's 0 is no pressure" ); assert_eq!(last, Some(leaning), "the last move's pose comes with the moves"); - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed))); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (samples, last) = frame_moves(ui, Some(&feed), None)); out.textures_delta.clear(); assert_eq!(samples, [(a, None, None), (b, None, None)], "the moves were taken: a mouse's moves again"); assert_eq!(last, None); let events = [pen(egui::TouchPhase::Move, a, 0.2), pen(egui::TouchPhase::Move, b, 0.8), pen(egui::TouchPhase::Move, c, 0.6)].concat(); let mut samples = vec![]; - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None).0); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None, None).0); out.textures_delta.clear(); assert_eq!(samples, [(a, Some(0.2), None), (b, Some(0.8), None)], "the last sample follows the normal pointer path"); let events = (0..200).flat_map(|n| pen(egui::TouchPhase::Move, pos2(n as f32, 0.0), 0.5)).collect(); - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None).0); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None, None).0); out.textures_delta.clear(); assert!(samples.len() <= 64, "a stalled frame stays bounded"); } @@ -7200,7 +7259,7 @@ fn only_the_freehand_tools_get_every_move_of_a_frame() { { app.select_tool(tool); let mut moves = vec![]; - let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| moves = tool_frame_moves(ui, &app).0); + let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| moves = tool_frame_moves(ui, &app, false).0); out.textures_delta.clear(); assert_eq!(moves.len(), if every { 19 } else { 0 }, "{tool}"); } From 641ac7e301289f7a250be26a51b0ae1c5a51639d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 00:10:25 -0800 Subject: [PATCH 322/674] Canvas: a dropped press puts back the tool's options and keeps the path being drawn A dropped press (a long touch, a canceled touch, a second finger) now goes to the tool through Tool::drop_press, which takes Escape as during a drag by default. The Pen, Smart Pen and Curvature tools override it so the path being drawn goes on: they forget the press, and a Curvature point the press dragged goes back where it was. The release that follows runs only the tool's Cancel and Notify actions, so a Selection marquee selects nothing and a Shift-drag Artboard marquee toggles nothing. The engine puts back the persistent options the tool had at the press (the Polygon tool's sides changed with the arrow keys), and stores none of them. --- crates/engine/src/lib.rs | 3 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/toolsettings.rs | 98 ++++++++++++++++++++--- crates/engine/src/tooling.rs | 52 +++++++++--- crates/tools/src/addons/smart_pen.rs | 9 +++ crates/tools/src/draw2/curvature.rs | 18 ++++- crates/tools/src/draw2/curvature/tests.rs | 28 +++++++ crates/tools/src/lib.rs | 6 ++ crates/tools/src/pen.rs | 9 +++ crates/ui-egui/src/canvas/drag.rs | 4 +- crates/ui-egui/src/canvas/tests.rs | 12 +-- docs/target-app-parity.md | 2 +- 12 files changed, 213 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 177697839e..f0b7f4b603 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -203,6 +203,9 @@ pub struct Session { /// The pointer button is held: the last pointer event was a press or a drag, not a release or /// a move ([`Session::pointer_held`]). pub(crate) pointer_held: bool, + /// The id and persistent options of the tool when the press under way began, which a dropped + /// press puts back ([`Session::drop_tool_press`]). + pub(crate) press_options: Option<(String, serde_json::Map)>, /// A guide being dragged out of a ruler ([`Session::ruler_guide`]). pub(crate) ruler_guide: Option, /// Which selected type overflows its frame, for the ports every tool but the Type tools shows. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 51b5b57769..da2c659882 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -92,6 +92,7 @@ impl Session { liquify_stroke: None, plane_widget_press: false, pointer_held: false, + press_options: None, ruler_guide: None, port_marks: Default::default(), font_search: None, diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 34f85f8227..3e522a5529 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -91,11 +91,11 @@ fn a_gesture_keeps_what_it_changed_and_a_document_switch_keeps_options() { assert_eq!(s.tool_options()["segments"], json!(14)); } -/// A dropped press (a long touch, a cancelled touch, a second finger) keeps nothing it began: the -/// tool takes Escape and ends at rest, and the options the drag changed are not stored. A release -/// stores them. +/// A dropped press (a long touch, a canceled touch, a second finger) keeps nothing it began: the +/// tool ends at rest with the options it had before the press, and the options the drag changed +/// are not stored. A release stores them. #[test] -fn a_dropped_press_does_not_store_what_its_drag_changed() { +fn a_dropped_press_does_not_keep_what_its_drag_changed() { let mut s = session(); select(&mut s, "polygon"); let v = ViewInfo::default(); @@ -104,20 +104,100 @@ fn a_dropped_press_does_not_store_what_its_drag_changed() { s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); }; - let before = s.tool_options()["sides"].clone(); + assert_eq!(s.tool_options()["sides"], json!(6)); drag_with_one_more_side(&mut s); assert_eq!(s.tool_options()["sides"], json!(7)); s.drop_tool_press(v).unwrap(); assert!(!s.tool_busy(), "the tool is at rest"); let st = s.active().unwrap(); assert!(st.interaction.is_none() && st.doc.art_bounds().is_none(), "the polygon is not drawn"); - // A tool whose Escape puts back the options the drag changed stores those; nothing else is stored. - let stored = s.prefs.tool_settings.get("polygon").and_then(|o| o.get("sides")); - assert!(stored.is_none_or(|v| *v == before), "the dropped drag's sides are not stored: {stored:?}"); + assert_eq!(s.tool_options()["sides"], json!(6), "the tool has its sides from before the press"); + assert_eq!(s.prefs.tool_settings.get("polygon").and_then(|o| o.get("sides")), None, "the dropped drag's sides are not stored"); drag_with_one_more_side(&mut s); s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); assert!(s.active().unwrap().doc.art_bounds().is_some(), "a release draws the polygon"); - assert_eq!(s.prefs.tool_settings["polygon"]["sides"], s.tool_options()["sides"], "and stores its sides"); + assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides"); +} + +/// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with +/// the next click. +#[test] +fn a_dropped_pen_press_keeps_the_path_being_drawn() { + let mut s = session(); + select(&mut s, "pen"); + let v = ViewInfo::default(); + let click = |s: &mut Session, x: f64, y: f64| { + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap(); + }; + click(&mut s, 10.0, 10.0); + click(&mut s, 100.0, 10.0); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 120.0), v).unwrap(); + s.drop_tool_press(v).unwrap(); + click(&mut s, 10.0, 100.0); + let d = &s.active().unwrap().doc; + let paths = d.layers[0].children().unwrap(); + assert_eq!(paths.len(), 1, "no new path starts"); + assert_eq!(paths[0].path_data().unwrap().anchor_count(), 3, "the dropped anchor is not placed"); +} + +/// A dropped Pen press on the first anchor does not close the path or end it. +#[test] +fn a_dropped_pen_close_keeps_the_path_open_and_being_drawn() { + let mut s = session(); + select(&mut s, "pen"); + let v = ViewInfo::default(); + let click = |s: &mut Session, x: f64, y: f64| { + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap(); + }; + click(&mut s, 10.0, 10.0); + click(&mut s, 100.0, 10.0); + click(&mut s, 100.0, 100.0); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 30.0), v).unwrap(); + s.drop_tool_press(v).unwrap(); + click(&mut s, 10.0, 100.0); + let d = &s.active().unwrap().doc; + let paths = d.layers[0].children().unwrap(); + assert_eq!(paths.len(), 1, "no new path starts"); + let pd = paths[0].path_data().unwrap(); + assert_eq!(pd.anchor_count(), 4, "the next click goes on the path"); + assert!(!pd.subpaths[0].closed, "the path is not closed"); +} + +/// A dropped marquee selects nothing: the selection stays as it was before the press. +#[test] +fn a_dropped_marquee_leaves_the_selection_alone() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 600, "y": 400, "width": 100, "height": 100})).unwrap(); + let before = s.doc().unwrap().selection.objects.clone(); + assert_eq!(before.len(), 1); + select(&mut s, "selection"); + let v = ViewInfo::default(); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 350.0, 350.0), v).unwrap(); + s.drop_tool_press(v).unwrap(); + assert!(!s.tool_busy(), "the tool is at rest"); + assert_eq!(s.doc().unwrap().selection.objects, before); +} + +/// A dropped Shift-drag marquee of the Artboard tool toggles no artboard: the tool takes Escape, +/// as during a drag, before its release. +#[test] +fn a_dropped_artboard_marquee_toggles_nothing() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + select(&mut s, "artboard"); + let before = s.tool_options()["selected"].clone(); + let v = ViewInfo::default(); + let shift = Mods { shift: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 1200.0, 500.0).with_mods(shift), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 1250.0, 550.0).with_mods(shift), v).unwrap(); + s.drop_tool_press(v).unwrap(); + assert!(!s.tool_busy(), "the tool is at rest"); + assert_eq!(s.tool_options()["selected"], before, "no artboard is toggled"); } #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f8eb5c1f6a..0a959959e6 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -361,20 +361,44 @@ impl Session { self.pointer_event(ev, view, true) } - /// Drop the press in progress (a long touch, a cancelled touch, a second finger): nothing it - /// began is kept. Its interaction is undone, the tool takes Escape as it does during a drag, - /// and then a release that returns it to rest. The options the press changed are not stored, - /// and what the tool asks of the UI along the way (a size dialog for a click) is dropped. + /// Drop the press in progress (a long touch, a canceled touch, a second finger): nothing it + /// began is kept. Its interaction is undone, the tool drops the press ([`Tool::drop_press`]: + /// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what + /// the tool asks for along the way, only a cancel and a notify run, so a marquee selects + /// nothing and a click opens no size dialog. The tool gets back the persistent options it had + /// when the press began, and none of the press's changes to them are stored. pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> { - // Nothing to roll back without a document; the tool still takes Escape and the release. + // Nothing to roll back without a document; the tool still drops the press and gets the release. let _ = self.cancel_interaction(); - let esc = self.tool_key(ToolKey::Escape, Mods::default(), view); + let before = self.press_options.take(); + let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx)); + acts.retain(|a| matches!(a, Action::Cancel | Action::Notify(_))); + let dropped = self.take_tool_panic().and_then(|()| self.apply_actions(acts)); let up = PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote: false, pressure: 1.0, pen: None }; - let up = self.pointer_event(&up, view, false); - esc.and(up).map(drop) + let r = dropped.and(self.pointer_event(&up, view, false)); + if let Some((id, opts)) = before + && id == self.tool.id() + { + let now = self.tool.options(); + for (k, v) in &opts { + if now.get(k) != Some(v) { + self.tool.set_option(k, v); + } + } + } + r.map(drop) } - /// [`Self::pointer`]; a release stores the tool's options only with `keep`. + /// The options of `t` that [`Self::store_tool_settings`] stores. + fn persistent_options(t: &dyn Tool) -> Map { + let opts = t.options(); + let radius = (t.id() == ROUNDED_RECTANGLE).then_some("cornerRadius"); + let keys = settings::stores(t.id()).flat_map(|(_, keys)| keys.iter().copied()).chain(radius); + keys.filter_map(|k| opts.get(k).map(|v| (k.to_string(), v.clone()))).collect() + } + + /// [`Self::pointer`]. Without `keep` (a dropped press's release), the tool's options are not + /// stored and only the tool's `Cancel` and `Notify` actions run. fn pointer_event(&mut self, ev: &PointerEvent, view: ViewInfo, keep: bool) -> Result> { self.last_view = view; match ev.kind { @@ -382,13 +406,21 @@ impl Session { PointerKind::Up | PointerKind::Move => self.pointer_held = false, PointerKind::DoubleClick => {} } + match ev.kind { + PointerKind::Down => self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref()))), + PointerKind::Up => self.press_options = None, + _ => {} + } // The Plane Switching Widget takes its clicks whatever the tool. if let Some(r) = self.plane_widget_pointer(ev, view) { return r; } self.leave_draw_inside(ev, view)?; let ev = &self.lend_selection_tool(ev); - let acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); + let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); + if !keep { + acts.retain(|a| matches!(a, Action::Cancel | Action::Notify(_))); + } let r = self.take_tool_panic().and_then(|()| { // A gesture may change options (Alt-drag sizes a Liquify brush): keep them. if keep && ev.kind == PointerKind::Up { diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index f2b52219e6..90c73620a1 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -534,6 +534,15 @@ impl Tool for SmartPenTool { } } + /// A dropped press does not end the path being drawn, as Escape would: the press and its + /// marquee are forgotten, so the release does nothing. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.press = None; + self.marquee = None; + self.snap.clear(); + vec![] + } + fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Tab && (self.press.is_some() || self.active(cx).is_some()) } diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 8301c108ce..70ad9a7e4a 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -35,6 +35,9 @@ pub struct CurvatureTool { id: Option, /// The point being dragged, the pointer at the press, and whether the drag began. drag: Option<(Grab, Point, bool)>, + /// Where the point of the path being drawn that the press grabbed was at the press, and the + /// current point before the press. + grabbed: Option<(Point, Option)>, /// Last touched point of the path being drawn (Backspace removes it). current: Option, hover: Option, @@ -564,7 +567,7 @@ impl Tool for CurvatureTool { PointerKind::Down => { if let Some(id) = active { if let Some(i) = self.hit_point(cx, p) { - self.current = Some(i); + let was_current = self.current.replace(i); if ev.mods.alt { self.pts[i].1 = !self.pts[i].1; return vec![Action::Exec("path.curvature".into(), self.params())]; @@ -576,6 +579,7 @@ impl Tool for CurvatureTool { // The point dragged and the curve through it move: the rest pull. hold_targets(&mut self.snap, cx, id, 0, &[i]); self.drag = Some((Grab::Drawn(i), p, false)); + self.grabbed = self.pts.get(i).map(|pt| (pt.0, was_current)); return vec![]; } if !self.closed { @@ -650,6 +654,18 @@ impl Tool for CurvatureTool { && self.drag.is_none() && if self.active(cx).is_some() { self.pts.len() > 1 } else { current_point(cx).is_some() } } + /// A dropped press does not end the path being drawn, as Escape would: a point it grabbed + /// goes back to where it was at the press, and the current point to the one before the press. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if let (Some((Grab::Drawn(i), _, _)), Some((at, current))) = (self.drag.take(), self.grabbed.take()) + && let Some(pt) = self.pts.get_mut(i) + { + pt.0 = at; + self.current = current; + } + self.snap.clear(); + vec![] + } fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec { match key { ToolKey::Escape | ToolKey::Enter => { diff --git a/crates/tools/src/draw2/curvature/tests.rs b/crates/tools/src/draw2/curvature/tests.rs index 412292ef91..05593a3dc3 100644 --- a/crates/tools/src/draw2/curvature/tests.rs +++ b/crates/tools/src/draw2/curvature/tests.rs @@ -370,6 +370,34 @@ fn a_press_on_a_point_selects_it_and_a_drag_moves_it() { assert_eq!(press(&mut t, &cx, 100.0, 0.0, false).len(), 1); } +/// A dropped drag of a point of the path being drawn puts the point back where it was at the +/// press, and the path goes on: the next click adds a point to it. +#[test] +fn a_dropped_drag_puts_the_point_back_and_keeps_drawing() { + let (d, id) = doc_with(SubPath::polyline(&[pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], false)); + let (s, p) = (selected(id, None), paint()); + let cx = quiet(&d, &s, &p); + let mut t = CurvatureTool { + pts: vec![(pt(100.0, 100.0), false), (pt(200.0, 100.0), false), (pt(300.0, 100.0), false)], + id: Some(id), + current: Some(2), + ..Default::default() + }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 100.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 220.0, 160.0)); + assert_eq!(a[0], Action::Begin("Curvature".into())); + assert_eq!(t.pts[1].0, pt(220.0, 160.0)); + assert!(t.drop_press(&cx).is_empty(), "the engine has undone the preview"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 0.0, 0.0)), vec![]); + assert_eq!(t.pts[1].0, pt(200.0, 100.0), "the point is back"); + assert_eq!(t.current, Some(2), "the current point is the one before the press"); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 200.0)); + assert!( + matches!(&a[0], Action::Exec(_, v) if v["id"] == id.0 && v["points"][1]["y"] == 100.0 && v["points"].as_array().unwrap().len() == 4), + "{a:?}" + ); +} + /// #2120: the dragged end of a slanted straight path keeps to its extension (Smart Guides). #[test] fn a_dragged_end_of_a_straight_path_keeps_to_its_extension() { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index dd5977f5a1..7aa338ab45 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -124,6 +124,12 @@ pub trait Tool: Send { fn key(&mut self, _cx: &ToolContext, _key: ToolKey, _mods: Mods) -> Vec { vec![] } + /// The press in progress is dropped (a long touch, a canceled touch, a second finger): the + /// engine has undone its interaction and sends a release after this. By default the tool takes + /// Escape, as during a drag. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + self.key(cx, ToolKey::Escape, Mods::default()) + } fn overlays(&self, _cx: &ToolContext) -> Vec { vec![] } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index a2e9d38814..e5906db59f 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -445,6 +445,15 @@ impl Tool for PenTool { _ => vec![], } } + /// A dropped press drops only the anchor it was placing, a handle it was dragging or the + /// close it was making: the path being drawn goes on with the next click. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.drag = None; + self.handle = None; + self.convert = None; + self.snap.clear(); + vec![] + } /// Deactivate the pen tool, committing in-flight operations and restoring compound path selection. fn deactivate(&mut self, cx: &ToolContext) -> Vec { let path = self.path; diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index ef4cc2ad25..3f3c156edd 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -230,8 +230,8 @@ pub fn mods(m: egui::Modifiers, space: bool) -> Mods { pub(super) fn drop_press(app: &mut VectorcraftApp, ui: &Ui, view: vectorcraft_engine::ViewInfo) { match ui.data(|d| d.get_temp::(drag_id())) { Some(Drag::Tool | Drag::Art) => { - // The tool takes Escape, as during a drag, and then a mouse-up that returns it to rest. - // A move waiting over a panel is still live and would otherwise outlive the drag that + // The tool drops the press, and a mouse-up returns it to rest with the options it had + // when the press began. A move waiting over a panel is still live and would otherwise outlive the drag that // owns it (#2826). let r = app.session.drop_tool_press(view); apply_requests(app, r.map(|()| vec![])); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index f0a594f2a1..efb608e74e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6728,10 +6728,10 @@ fn long_touch_drops_a_tool_press_without_committing_art() { assert!(app.session.active().unwrap().doc.art_bounds().is_none(), "releasing cannot commit the cancelled press"); } -/// A cancelled touch drops the tool's drag as Escape does: the options the drag changed (the -/// Polygon tool's sides) are not stored, and nothing is drawn. +/// A canceled touch drops the tool's drag: the options the drag changed (the Polygon tool's +/// sides) are put back and not stored, and nothing is drawn. #[test] -fn a_cancelled_touch_drops_the_drag_without_storing_its_options() { +fn a_canceled_touch_drops_the_drag_without_keeping_its_options() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.prefs.touch_gestures = true; app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); @@ -6745,7 +6745,7 @@ fn a_cancelled_touch_drops_the_drag_without_storing_its_options() { assert!(matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Tool))); assert!(app.session.active().unwrap().interaction.is_some(), "the drag previews the polygon"); let view = app.view_info(); - let before = app.session.tool_options()["sides"].clone(); + assert_eq!(app.session.tool_options()["sides"], json!(6)); app.session.tool_key(vectorcraft_tools::ToolKey::Up, Mods::default(), view).unwrap(); assert_eq!(app.session.tool_options()["sides"], json!(7)); frame(&mut app, &ctx, pen(egui::TouchPhase::Cancel, start + vec2(60.0, 40.0), 0.5)); @@ -6753,9 +6753,9 @@ fn a_cancelled_touch_drops_the_drag_without_storing_its_options() { let st = app.session.active().unwrap(); assert!(st.interaction.is_none() && st.doc.art_bounds().is_none(), "nothing is drawn"); assert!(app.ui.dialog.is_none()); - // A tool whose Escape puts back the options the drag changed stores those; nothing else is stored. + assert_eq!(app.session.tool_options()["sides"], json!(6), "the tool has its sides from before the press"); let stored = app.session.prefs.tool_settings.get("polygon").and_then(|o| o.get("sides")); - assert!(stored.is_none_or(|v| *v == before), "the dropped drag's sides are not stored: {stored:?}"); + assert_eq!(stored, None, "the dropped drag's sides are not stored"); } /// #2826: a second finger drops a move waiting over a panel, so its interaction doesn't diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1ce35dbe36..8fd362eab3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -840,7 +840,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the view rotated, a second Escape less than a second after the first resets the rotation, as Reset Rotate View does. The first Escape may end something else, such as isolation mode or a path being drawn. The second resets the view only when it has nothing else to end, and an Escape that closes a menu does not count. After a click, or a press of another key that is not a modifier (Shift, Control, Alt/Option or Command), the next Escape counts as the first. With the Rotate View tool chosen, one Escape resets the view. A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5° (Preferences › General › Trackpad Gesture to Rotate View, on by default). On a touch screen a second finger cancels the tool press the first finger began, in the frame it lands or later: the Pencil's stroke or a Selection move is rolled back with no undo entry, and a finger that lands while another is down presses nothing, so a pinch or two-finger pan only zooms and pans (#4198; canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`). - A tool press dropped by a second finger, a long touch or a cancelled touch reaches the tool as Escape does during a drag, followed by a release: the options the drag changed (the Polygon tool's sides, set with ↑ and ↓) are not stored, and a press held still opens no size dialog (canvas tests `a_cancelled_touch_drops_the_drag_without_storing_its_options` and `long_touch_drops_a_tool_press_without_committing_art`). + A tool press dropped by a second finger, a long touch or a canceled touch keeps nothing it began: the tool gets back the options it had when the press began (the Polygon tool's sides, set with ↑ and ↓) and they are not stored, a press held still opens no size dialog, a Selection or Artboard tool marquee selects nothing, and the Pen goes on drawing its path without the dropped anchor (canvas tests `a_canceled_touch_drops_the_drag_without_keeping_its_options` and `long_touch_drops_a_tool_press_without_committing_art`; engine tests in `tests::toolsettings`). The status bar navigator's field shows the active artboard's number and name, and its drop-down lists every artboard by number and name, as the Artboards panel does. Choosing an artboard in the list makes it the active artboard and fits it in the window (`view.goToArtboard`). The list opens on the active artboard's row and lays out only the rows in view and at most one more. - **Geometry and effects:** - **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged. From 47bc3dd58c02bbab33ca27d39293135b11abcba2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 16:03:38 +0700 Subject: [PATCH 323/674] Flatten Transparency: iterate the test's groups directly (clippy needless_range_loop) --- crates/engine/src/cmd/flatten/analysis.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/flatten/analysis.rs b/crates/engine/src/cmd/flatten/analysis.rs index e7879ec156..eacd124052 100644 --- a/crates/engine/src/cmd/flatten/analysis.rs +++ b/crates/engine/src/cmd/flatten/analysis.rs @@ -243,8 +243,8 @@ mod tests { } let mut out: Vec> = vec![]; let mut seen = std::collections::HashMap::new(); - for i in 0..n { - let g = *seen.entry(group[i]).or_insert_with(|| { + for (i, &root) in group.iter().enumerate() { + let g = *seen.entry(root).or_insert_with(|| { out.push(vec![]); out.len() - 1 }); From c59cd281dbde39213b71e31c5aea58a0a2f0e8c7 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 15:58:02 +0700 Subject: [PATCH 324/674] Format with rustfmt --- crates/engine/src/cmd/fileio/screens.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index b6fe4d85a2..dcc8833a87 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1340,7 +1340,6 @@ mod tests { assert_eq!(out.claim("same.png", "last").as_deref(), Some("same-20001.png")); } - #[test] fn size_parse_refuses_signs_and_exponents() { for s in ["+2x", "+2", "+100w", "+100h", "+72ppi", "-2x", "1e2", "2e0w"] { From 1bd47ea30d9e7a2909b6094a129632a96e93f6ff Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 15:58:07 +0700 Subject: [PATCH 325/674] Format with rustfmt --- crates/color/src/cms/icc.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 2599956ce7..0b09062b84 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -107,7 +107,10 @@ impl IccProfile { return Err(CmsError::BadProfile(format!("its localized names take more than {} KB", MAX_LOCALIZED_TEXT >> 10))); } if let Some(tag) = repeated_tag(bytes) { - return Err(CmsError::BadProfile(format!("its tag table lists the `{}` tag more than once", String::from_utf8_lossy(&tag.to_be_bytes())))); + return Err(CmsError::BadProfile(format!( + "its tag table lists the `{}` tag more than once", + String::from_utf8_lossy(&tag.to_be_bytes()) + ))); } let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?; Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? }) From a9ce928f063867039176ab29410d02744d694bff Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 15:58:12 +0700 Subject: [PATCH 326/674] Format with rustfmt --- crates/cad/src/import/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 4ecba52f5d..978505ddf3 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -1219,7 +1219,8 @@ fn text_copied_into_array_cells_stops_at_the_text_budget() { // 1,000 characters of text in an anonymous block placed 10 × 10: 100 KB of copies, past the // 64 KB tests import with. let long = "x".repeat(1000); - let blocks = [(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")]; + let blocks = + [(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")]; let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "1"), (45, "1")]; let r = open(&drawing(&[], &[], &blocks, &insert), &points()); let bytes = text_bytes(&r.document); From 6228446e9e6d8638c31021da16e0cfaa44821844 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 15:59:05 +0700 Subject: [PATCH 327/674] Fix #4559: shortcuts can use the ISO key next to left Shift Squashed from #5276 onto main. --- ASSETS.md | 34 +++++++++++++-------------- Cargo.lock | 29 ++++++++++++----------- Cargo.toml | 26 ++++++++++---------- NOTICE | 4 ++-- crates/ui-egui/src/shortcuts/tests.rs | 31 ++++++++++++++++++++++++ docs/pdf-backend.md | 4 ++-- xtask/src/pdf_deps.rs | 10 ++++---- 7 files changed, 83 insertions(+), 55 deletions(-) diff --git a/ASSETS.md b/ASSETS.md index db2a978163..aa3bfeda0f 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -358,20 +358,20 @@ The shared PDF backend keeps the existing standard-font and CMap features. These | Crate / file | Author | Source | Licence | SHA-256 | Use | | --- | --- | --- | --- | --- | --- | -| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) | -| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged | -| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged | +| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) | +| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged | +| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged | diff --git a/Cargo.lock b/Cargo.lock index 0b55428494..dc704e6d15 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -970,17 +970,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1003,7 +1003,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "egui", "serde", @@ -1013,7 +1013,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1024,9 +1024,10 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "craft-winprint-gdi", + "log", "miniz_oxide 0.9.1", "roxmltree 0.21.2", "tempfile", @@ -1037,7 +1038,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1095,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "egui", "objc2 0.6.5", @@ -2205,7 +2206,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "brotli", "hayro-postscript", @@ -2214,7 +2215,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2232,7 +2233,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2250,12 +2251,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "flate2", "hayro-ccitt", @@ -2863,7 +2864,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=fb08be5fa19eee8d37e624397fcdc96df6035e92#fb08be5fa19eee8d37e624397fcdc96df6035e92" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" dependencies = [ "base64 0.22.1", "bumpalo", diff --git a/Cargo.toml b/Cargo.toml index 35be6fd24b..1af59ddfe4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,14 +11,14 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" } # craft-update: app-specific pretend versions apply to startup and manual checks. @@ -147,14 +147,12 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -# The PDF writer takes craft-libs#417 (CMYK, gray and spot colors keep their exact inks); the other -# craft-libs crates stay at 92d392cf. craft-pdf's sources are the same at both revisions. -krilla = { git = "https://github.com/storytold/craft-libs", rev = "fb08be5fa19eee8d37e624397fcdc96df6035e92" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/NOTICE b/NOTICE index 0d0758820e..002fa016ac 100644 --- a/NOTICE +++ b/NOTICE @@ -72,10 +72,10 @@ Shared PDF backend The patched hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0, hayro-cmap 0.1.0 and hayro-postscript 0.1.0 are fetched from https://github.com/storytold/craft-libs at revision -92d392cff132eaf53e13afff77f38b5c11b73aa0. Their upstream project is +f8f8829cc7be65d466d687dae381d1ca60e31242. Their upstream project is https://github.com/LaurenzV/hayro, licensed MIT OR Apache-2.0. The snapshot retains each crate's upstream licence files. The patch ledger is at -https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/README.craft-reader.md. +https://github.com/storytold/craft-libs/blob/f8f8829cc7be65d466d687dae381d1ca60e31242/vendor/README.craft-reader.md. Assets already bundled through Hayro's default features retain their licences: - Foxit standard-14 substitutes: Copyright 2014 PDFium Authors. All rights reserved. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 2693965e5b..50ecd06fa9 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1823,6 +1823,37 @@ fn a_shortcut_on_the_backtick_key_runs_on_every_layout() { assert_eq!(count(&app), 1); } +/// The ISO key next to left Shift (`<` on Turkish Q and many European layouts, egui's +/// `IntlBackslash`) records, saves and runs its shortcut, apart from the `\` key (#4559). +#[test] +fn a_shortcut_on_the_iso_key_next_to_left_shift_records_and_runs() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let recorded = crate::shortcut_editor::chord_from_event(Key::IntlBackslash, Modifiers::NONE).unwrap(); + assert_eq!(recorded, "IntlBackslash"); + crate::shortcut_editor::assign(&mut app.ui.shortcut_overrides, "edit.clear", Some(&recorded), false).unwrap(); + assert_eq!(crate::shortcut_editor::effective_in(&app.ui.shortcut_overrides, "edit.clear").as_deref(), Some("IntlBackslash")); + for text in ["Cmd+IntlBackslash", "Shift+IntlBackslash", "Cmd+Alt+Shift+IntlBackslash"] { + assert_eq!(crate::shortcut_editor::normalize(text).as_deref(), Some(text)); + } + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let backslash = + egui::Event::Key { key: Key::Backslash, physical_key: Some(Key::Backslash), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![backslash, egui::Event::Text("\\".into())]); + assert_eq!(count(&app), 1, "the `\\` key is another key"); + let press = egui::Event::Key { + key: Key::IntlBackslash, + physical_key: Some(Key::IntlBackslash), + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + }; + frame(&mut app, vec![press, egui::Event::Text("<".into())]); + assert_eq!(count(&app), 0, "the key next to left Shift runs Edit › Clear"); +} + /// eframe's web build with no text field focused sends the text before its key: the key after /// the `"` it typed is read when no press comes right before it. #[test] diff --git a/docs/pdf-backend.md b/docs/pdf-backend.md index fb97151ca2..d21ae4145e 100644 --- a/docs/pdf-backend.md +++ b/docs/pdf-backend.md @@ -1,7 +1,7 @@ # PDF backend PDF writing uses `craft-pdf` from `storytold/craft-libs`, pinned to -`92d392cff132eaf53e13afff77f38b5c11b73aa0`. Its `write` feature supplies Krilla configuration, +`f8f8829cc7be65d466d687dae381d1ca60e31242`. Its `write` feature supplies Krilla configuration, metadata construction, fallible font preparation and serialization, and native unwind guards. The dependency disables default features and enables `write` and `interpret`. The production writer retains Krilla’s raster-image support without its optional text shaper. @@ -16,7 +16,7 @@ Desktop printer submission remains in `craft-print`. The shared writer vendors Krilla 0.8.2 with an unwind-safe cleanup and poisoning patch. The root `[patch.crates-io]` selects that copy from craft-libs revision -`fb08be5fa19eee8d37e624397fcdc96df6035e92`, which adds craft-libs#417 (CMYK, gray and spot +`f8f8829cc7be65d466d687dae381d1ca60e31242`, which includes craft-libs#417 (CMYK, gray and spot colors keep their exact inks): Cargo does not inherit a dependency workspace's patches. A failed page or surface cleanup poisons the backend document, so serialization cannot return an incomplete PDF after unwinding. The shared crate's compile-time backend marker and `cargo xtask pdf-deps` (included in CI) diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 6e59920624..49341cc1b4 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,12 +5,10 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "92d392cff132eaf53e13afff77f38b5c11b73aa0"; -/// The writer's revision: craft-libs#417, CMYK, gray and spot colors with their exact inks. -const KRILLA_REV: &str = "fb08be5fa19eee8d37e624397fcdc96df6035e92"; +const REV: &str = "f8f8829cc7be65d466d687dae381d1ca60e31242"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), - ("krilla", "0.8.2", KRILLA_REV), + ("krilla", "0.8.2", REV), ("hayro-syntax", "0.7.2", REV), ("hayro-interpret", "0.7.0", REV), ("hayro-jbig2", "0.3.0", REV), @@ -34,7 +32,7 @@ pub fn run(root: &Path) -> Result<(), String> { } let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|e| format!("cargo metadata: {e}"))?; validate(&metadata)?; - println!("PDF: shared crate and patched backends resolve once to {REV} (krilla to {KRILLA_REV})"); + println!("PDF: shared crate and patched backends resolve once to {REV}"); Ok(()) } @@ -94,7 +92,7 @@ mod tests { ("source", Value::Null), ("source", json!("registry+https://github.com/rust-lang/crates.io-index")), ("source", json!("git+https://github.com/storytold/craft-libs?branch=main#other")), - ("source", json!(source(if PACKAGES[index].2 == REV { KRILLA_REV } else { REV }))), + ("source", json!(source("92d392cff132eaf53e13afff77f38b5c11b73aa0"))), ("version", json!("0.99.0")), ] { let mut m = metadata(); From 58e6ce9f02b04aa7c8dd5e29896b07e86effa60e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 06:11:04 -0800 Subject: [PATCH 328/674] Type: a text.setStyle stroke gives unstroked characters 1 pt A stroke color given without strokeWidth left characters at weight 0, so nothing was drawn. As paint.setStroke does, a painted stroke now gives a run with no weight 1 pt, for the characters and for the label styles a graph keeps; an explicit strokeWidth still sets the weight. --- crates/engine/src/cmd/graph/tests.rs | 12 ++++++++++++ crates/engine/src/cmd/typecmd.rs | 9 ++++++++- crates/engine/src/tests/textedit.rs | 17 +++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 36c9589cd1..66f04f0ef9 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -2588,6 +2588,18 @@ fn formatting_the_whole_graphs_text_survives_it_being_drawn_again() { assert_eq!(spec(&s, id).label_styles, vectorcraft_doc::LabelStyles::default()); } +/// A stroke given to all of a graph's text without a weight is kept at 1 pt, as `paint.setStroke` keeps it. +#[test] +fn a_stroke_given_to_the_whole_graphs_text_is_kept_at_1_pt() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"stroke": "#ff0000"})).unwrap(); + let legend = spec(&s, id).label_styles.legend.unwrap(); + assert_eq!((legend.stroke.color().map(|c| c.to_hex()), legend.stroke_width), (Some("#ff0000".into()), 1.0)); +} + #[test] fn formatting_one_label_keeps_that_kind_of_label() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 9ee14708ac..d4a58c34d3 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -123,7 +123,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -858,6 +858,10 @@ fn set_style(s: &mut Session, p: &Value) -> Result { st.fill = f.clone(); } if let Some(f) = &stroke { + // A painted stroke on a run without a weight gets 1 pt, as with paint.setStroke. + if !f.is_none() { + super::gradient::run_stroke_weight(st); + } st.stroke = f.clone(); } if !stroke_weight.is_empty() { @@ -920,6 +924,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result { st.fill = f.clone(); } if let Some(f) = &stroke { + if !f.is_none() { + super::gradient::run_stroke_weight(st); + } st.stroke = f.clone(); } if !stroke_weight.is_empty() { diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index ea5b38ca47..c6c3587b49 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -175,6 +175,23 @@ fn set_style_sets_the_character_stroke() { assert!(obj(&s, id).runs.iter().all(|r| (r.style.stroke_width - 1.0).abs() < 1e-9), "{:?}", paints(&s)); } +/// `text.setStyle {stroke}` without `strokeWidth` gives type with no stroke weight 1 pt, as +/// `paint.setStroke` does, and keeps a weight the type already has. +#[test] +fn set_style_stroke_without_a_weight_draws_1_pt() { + use vectorcraft_color::Color; + let mut s = session(); + let id = text(&mut s, "Hello"); + assert_eq!(obj(&s, id).runs[0].style.stroke_width, 0.0); + s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "#ff0000"})).unwrap(); + let st = &obj(&s, id).runs[0].style; + assert_eq!((st.stroke.color(), st.stroke_width), (Some(Color::rgb8(255, 0, 0)), 1.0)); + assert!(st.has_stroke()); + s.execute("text.setStyle", &json!({"ids": [id.0], "strokeWidth": 3})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id.0], "stroke": "#0000ff"})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.stroke_width, 3.0, "an existing weight is kept"); +} + #[test] fn optical_command_manual_pair_undo_redo_and_native_reopen() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 24f8a17808..c0aa26a31d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2360,7 +2360,8 @@ characters as its place relative to the Characters row says. To stroke some characters, use `text.setRangeStyle {id, start, end, strokeOptions: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?}}`. `text.setStyle {ids?, stroke?, strokeWidth?, start?, end?}` sets the stroke color and weight of the characters of each object given (without `start` and `end`: all of its text), with its other keys in -one undo step; `strokeWidth` is in document points, as `stroke.set` gives the weight of scaled type. +one undo step; `strokeWidth` is in document points, as `stroke.set` gives the weight of scaled type. A `stroke` color +without `strokeWidth` gives characters that have no stroke weight 1 pt, as `paint.setStroke` does. `align: "inside"|"outside"` keeps the characters' stroke on that side of the glyph outlines, drawn at twice the weight and clipped, while the type stays editable (beyond Illustrator); SVG export writes the text live and that stroke as glyph outlines over it. `inspect_document` reports each object's stroke as `strokeOptions` (type: its first From 76f0a8c6152ffeddef3951ecf3b1cd77241feeaa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:18:08 -0800 Subject: [PATCH 329/674] =?UTF-8?q?Measure:=20a=20Shift-drag=20snaps=20its?= =?UTF-8?q?=20end=20point=20on=20its=2045=C2=B0=20step?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Measure tool and the Measure & Inspect tool snapped the end point of a drag without Shift, but with Shift held they only turned the pointer onto its 45° step and kept its distance: with Snap to Grid on the measurement ended off the grid, with Smart Guides on it did not land in line with an anchor, and with no snapping a drag of (37.3, 12.1) measured 39.2 pt at 0°. Both now project the pointer onto the 45° step nearest its direction and snap it there as the Line Segment tool snaps a Shift-drawn end, so it stays on the step: (37.3, 12.1) measures 36 pt at 0° on a 9 pt grid, and 37.3 pt with no snapping. With Snap to Point alone, the anchor the pointer snaps to is projected onto the step instead, so the end lands on an anchor on the step and in line with one beside it. --- crates/tools/src/addons/measure_inspect.rs | 26 +++-- crates/tools/src/xform.rs | 1 + crates/tools/src/xform/measure.rs | 112 +++++++++++++++++++-- 3 files changed, 127 insertions(+), 12 deletions(-) diff --git a/crates/tools/src/addons/measure_inspect.rs b/crates/tools/src/addons/measure_inspect.rs index d46edb6c64..1ea8a9324d 100644 --- a/crates/tools/src/addons/measure_inspect.rs +++ b/crates/tools/src/addons/measure_inspect.rs @@ -95,12 +95,7 @@ impl Tool for MeasureInspectTool { } PointerKind::Drag | PointerKind::Up if self.dragging => { if let Some((a, _)) = self.line { - let b = if ev.mods.shift { - a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle) - } else { - crate::guides::snap_draw(cx, ev.pos, &[]).0 - }; - self.line = Some((a, b)); + self.line = Some((a, crate::xform::measure_end_point(cx, a, ev.pos, ev.mods.shift))); } self.dragging = ev.kind == PointerKind::Drag; } @@ -213,4 +208,23 @@ mod tests { assert_eq!(t.options(), Value::Null); assert_eq!(area_label(Unit::Points, 2.0), "2.00 pt²"); } + + /// A Shift-drag snaps its end point to the grid, then projects it onto its 45° step. + #[test] + fn shift_drag_snaps_its_end_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.snap_to_grid = true; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = MeasureInspectTool::default(); + // (37.3, 12.1) snaps to (36, 9) on the 9 pt grid, and Shift keeps it at 0°: (36, 0). + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 37.3, 12.1).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 37.3, 12.1).with_mods(shift)); + let o = t.options(); + assert!((o["distance"].as_f64().unwrap() - 36.0).abs() < 1e-9, "on the 9 pt grid: {o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "kept horizontal: {o}"); + } } diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs index de9c9c0cbe..915eb35e8a 100644 --- a/crates/tools/src/xform.rs +++ b/crates/tools/src/xform.rs @@ -22,6 +22,7 @@ pub use artboard::ArtboardTool; pub use eyedropper::EyedropperTool; pub use free::{DistortMode, FreeTransformTool}; pub use gradient::GradientTool; +pub(crate) use measure::end_point as measure_end_point; pub use measure::{MeasureTool, measure}; pub use transform::{TransformKind, TransformTool}; pub use wand::{LassoTool, MagicWandTool}; diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index 3f2b350e01..140697dd6a 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -23,6 +23,28 @@ pub fn measure(a: Point, b: Point) -> (f64, f64, f64, f64) { (d.hypot(), (-d.y).atan2(d.x).to_degrees() + 0.0, d.x, d.y) } +/// The end of a measurement from `a` with the pointer at `p`: `p` snapped as a drawing tool snaps +/// it. With Shift held, the end stays on the 45° step from the Constrain Angle nearest the +/// pointer's direction: `p` is projected onto the step, then snapped along it as the Line Segment +/// tool snaps a Shift-drawn end. With Snap to Point alone, the point `p` snaps to (an anchor, or +/// in line with a ruler guide) is projected instead. +pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Point { + if !shift { + return crate::guides::snap_draw(cx, p, &[]).0; + } + let d = vectorcraft_geom::constrain_angle_from(p - a, 45.0, cx.constrain_angle); + let len = d.hypot(); + if len < 1e-12 { + return a; + } + let u = d / len; + let to_point = cx.snap_to_point && !(cx.smart_guides || cx.snap_to_grid || cx.snap_to_pixel); + let s = if to_point { crate::guides::snap_draw(cx, p, &[]).0 } else { p }; + let q = a + u * (s - a).dot(u); + let leave = crate::guides::Leave::segment(cx, a, true); + crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0 +} + impl Tool for MeasureTool { fn id(&self) -> &'static str { "measure" @@ -42,12 +64,7 @@ impl Tool for MeasureTool { } PointerKind::Drag | PointerKind::Up if self.dragging => { if let Some((a, _)) = self.line { - let b = if ev.mods.shift { - a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle) - } else { - crate::guides::snap_draw(cx, ev.pos, &[]).0 - }; - self.line = Some((a, b)); + self.line = Some((a, end_point(cx, a, ev.pos, ev.mods.shift))); } self.dragging = ev.kind == PointerKind::Drag; } @@ -141,6 +158,89 @@ mod tests { assert!(ov.iter().any(|o| matches!(o, Overlay::Line { .. })), "the measured line stays"); } + /// A Shift-drag snaps its end point as a drag without Shift does, then projects it onto its + /// 45° step: onto the grid with Snap to Grid, in line with an anchor with Smart Guides. With + /// no snapping, the end is the pointer projected onto the step. + #[test] + fn shift_drag_snaps_its_end_point() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.snap_to_grid = true; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = MeasureTool::default(); + // (37.3, 12.1) snaps to (36, 9) on the 9 pt grid, and Shift keeps it at 0°: (36, 0). + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 37.3, 12.1).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 37.3, 12.1).with_mods(shift)); + let o = t.options(); + assert!((o["distance"].as_f64().unwrap() - 36.0).abs() < 1e-9, "on the 9 pt grid: {o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "kept horizontal: {o}"); + // Near 45°: (31.4, 27.7) snaps to (27, 27). + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 31.4, 27.7).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() - 27.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() - 27.0).abs() < 1e-9, "{o}"); + // No snapping: the pointer is projected onto 0°, so the measurement is 37.3 pt. + cx.snap_to_grid = false; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 37.3, 12.1).with_mods(shift)); + let o = t.options(); + assert!((o["distance"].as_f64().unwrap() - 37.3).abs() < 1e-9, "{o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}"); + // Snap to Point alone: the end snaps to the anchor at (200, 200) and is projected onto + // 0°, so it ends in line with it: (200, 203). + assert!(cx.snap_to_point); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 203.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 201.0, 201.0).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}"); + // An anchor on the 45° step: the end lands on it. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 101.0, 100.0).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{o}"); + // Smart Guides: from (300, 300), Shift keeps the end at 0° and it lands in line with x = 200. + cx.snap_to_grid = false; + cx.smart_guides = true; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 203.0, 303.0).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 203.0, 303.0).with_mods(shift)); + let o = t.options(); + assert!((o["distance"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{o}"); + assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}"); + // At 45°, the end slides along the step to where it meets x = 200: (200, 220). + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 320.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 203.0, 222.5).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}"); + } + + /// With Snap to Point alone, a Shift-drag's end slides along its 45° step to a ruler guide. + #[test] + fn shift_drag_meets_a_ruler_guide() { + let (mut d, _) = doc_with_rect(); + d.guides.push(vectorcraft_doc::Guide::new(true, 50.0)); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + assert!(cx.snap_to_point); + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = MeasureTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 51.0, 49.0).with_mods(shift)); + let o = t.options(); + assert!((o["dx"].as_f64().unwrap() - 50.0).abs() < 1e-9, "{o}"); + assert!((o["dy"].as_f64().unwrap() - 50.0).abs() < 1e-9, "{o}"); + } + /// Escape during a drag ends it and brings back the result of the drag before (none at /// first); the release after it measures nothing. #[test] From 49477f8be5e6fd002a8c71422784c5a96a6caea9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 12:04:05 -0800 Subject: [PATCH 330/674] Canvas: keep the last move before the button-up when it is elsewhere When the release frame held moves after the button-up, the last move before it was dropped as the pointer's position, although the release event carries its own position. That move's sample was lost from the stroke. It is now kept unless it is at the button-up's position, and its tilt and rotation still give the release's pose. --- crates/ui-egui/src/canvas/drag.rs | 32 +++++++++++++++++++++--------- crates/ui-egui/src/canvas/tests.rs | 21 ++++++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 871af252f6..88293880a8 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -150,15 +150,20 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no /// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, /// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that -/// button's button-up in this frame, if it came: the moves after it are hover, and the last move -/// before it is the pointer's position. +/// button's button-up in this frame, if it came: the moves after it are hover, and the button-up's +/// position is the pointer's. The last move before it is left out only when it is at that +/// position; its tilt and rotation come second either way. pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option) -> (Vec, Option) { let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { - // How many of the frame's moves came before the button-up, if it came. + // How many of the frame's moves came before the button-up, and where it came, if it came. let before_up = release.and_then(|b| { - let up = i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button, pressed: false, .. } if *button == b))?; - Some(i.events.iter().take(up).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()) + i.events.iter().enumerate().find_map(|(k, e)| match e { + egui::Event::PointerButton { pos, button, pressed: false, .. } if *button == b => { + Some((i.events.iter().take(k).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(), *pos)) + } + _ => None, + }) }); let mut moves = vec![]; if i.events.iter().any(|e| matches!(e, egui::Event::Touch { .. })) { @@ -181,10 +186,19 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option< moves = i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some((*p, None, None)) } else { None }).collect(); } // Cut after pairing: the feed's samples pair with every move of the frame. - if let Some(n) = before_up { - moves.truncate(n); - } - let last_pose = moves.pop().and_then(|(_, _, q)| q); + // The pointer's position is the button-up's: a last move before it that is elsewhere + // stays a move. Its tilt and rotation are still the pose. + let last_pose = match before_up { + Some((n, up_at)) => { + moves.truncate(n); + let pose = moves.last().and_then(|&(_, _, q)| q); + if moves.last().is_some_and(|&(p, _, _)| p == up_at) { + moves.pop(); + } + pose + } + None => moves.pop().and_then(|(_, _, q)| q), + }; // A burst of events (a stalled frame) is thinned to a bounded count. const MAX: usize = 64; if moves.len() > MAX { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 79954a6b0a..3e184bef45 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6636,6 +6636,27 @@ fn frame_moves_stop_at_the_button_up() { assert_eq!(moves, [(a, None, None), (b, None, None), (c, None, None)], "without a release every move counts"); } +/// A button-up away from the last move before it keeps that move: the release takes only its own +/// position, and the pose is still the last move's. +#[test] +fn frame_moves_keep_the_last_move_when_the_button_went_up_elsewhere() { + let ctx = egui::Context::default(); + let (a, b, up_at, c) = (pos2(10.0, 20.0), pos2(20.0, 30.0), pos2(25.0, 35.0), pos2(30.0, 40.0)); + let up = egui::Event::PointerButton { pos: up_at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c)]; + let feed = StylusFeed::default(); + let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; + for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, PenPose::default())] { + feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); + } + let (mut moves, mut last) = (vec![], None); + let release = Some(egui::PointerButton::Primary); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (moves, last) = frame_moves(ui, Some(&feed), release)); + out.textures_delta.clear(); + assert_eq!(moves, [(a, Some(0.4), Some(PenPose::default())), (b, Some(0.6), Some(at_b))], "the move before the button-up is kept"); + assert_eq!(last, Some(at_b), "the pose is the last move's before the button-up"); +} + #[test] fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { let ctx = egui::Context::default(); From 9932096122b9c56fb0aed9eb57859df55098164e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 00:37:29 -0800 Subject: [PATCH 331/674] Canvas: a dropped press keeps Type editing and the Crop Image box A dropped press on the Type tool no longer ends editing and switches tools: the type being edited stays in editing, with the caret and selection it had before the press, and the press does not count toward a double or triple click. A dropped handle or move press with Crop Image puts the box back as it was at the press and keeps earlier adjustments. --- crates/tools/src/cropimage.rs | 31 ++++++++++++++++++++++++++++++ crates/tools/src/text.rs | 3 +++ crates/tools/src/text/tests.rs | 35 ++++++++++++++++++++++++++++++++++ crates/tools/src/text/tool.rs | 17 +++++++++++++++++ 4 files changed, 86 insertions(+) diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 52f347e91c..ff716bf171 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -184,6 +184,16 @@ impl Tool for CropImageTool { } } + /// A dropped press puts the box back as it was at the press; earlier changes to it stay. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + if let Some(Drag::Handle(_, from) | Drag::Move(_, from)) = self.drag.take() + && let Some((id, _, _)) = self.current(cx) + { + self.rect = Some((Some(id), from)); + } + vec![] + } + fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { matches!(key, ToolKey::Enter | ToolKey::Escape) && self.current(cx).is_some() } @@ -368,6 +378,27 @@ mod tests { assert!(t.overlays(&cx).is_empty() && !t.claims_key(&cx, ToolKey::Enter)); } + #[test] + fn a_dropped_press_puts_the_box_back_as_it_was_at_the_press() { + let (d, s) = doc_with_image((50.0, 60.0)); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = CropImageTool::default(); + drag(&mut t, &cx, (50.0, 60.0), (80.0, 70.0)); + assert_eq!(t.options()["rect"], json!([80.0, 70.0, 170.0, 90.0])); + // A handle pressed and dragged, then the press dropped: the box is the adjusted one. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 250.0, 160.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 130.0)); + assert!(t.drop_press(&cx).is_empty()); + assert!(!t.busy()); + assert_eq!(t.options()["rect"], json!([80.0, 70.0, 170.0, 90.0])); + // So is a moved box. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 110.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert!(t.drop_press(&cx).is_empty()); + assert_eq!(t.options()["rect"], json!([80.0, 70.0, 170.0, 90.0])); + } + #[test] fn crop_box_option_requires_exactly_four_finite_numeric_values() { let mut tool = CropImageTool::default(); diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 3e854231d5..b1394c81d6 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -189,6 +189,9 @@ pub struct TypeTool { snap: DrawSnap, /// The press landed in the edited text: dragging selects. selecting: bool, + /// The caret and anchor from before a press in type, kept until its release; a dropped press + /// puts them back. + before_press: Option<(usize, usize)>, /// Click counting for double/triple click (position of the last click, count). clicks: (Option, u8), /// Styled copy of the last copied range (pasting the same plain text keeps its styles). diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index ab3229809a..3c17411720 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -603,6 +603,41 @@ fn a_drag_across_type_not_being_edited_selects_its_text() { assert_eq!((tool.editing, tool.sel()), (Some(id), (7, 7))); } +#[test] +fn a_dropped_press_keeps_the_type_in_editing() { + let (d, id, mut tool) = editing("Hello world"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let t = TypeTool::text(&c, id).unwrap().clone(); + let lay = vectorcraft_text::layout(FontDb::global(), &t); + let pt = |i: usize| { + let (a, b) = vectorcraft_text::caret_position(&lay, i); + t.xf * a.midpoint(b) + }; + let (at, to) = (pt(3), pt(7)); + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x + 0.1, at.y)); + tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x + 0.1, to.y)); + assert!(tool.busy()); + assert_eq!(tool.sel(), (3, 7)); + // The press is dropped: the caret and selection are as they were before it. + let out = tool.drop_press(&c); + assert!(!out.iter().any(|a| matches!(a, Action::SwitchTool(_)))); + assert!(!tool.busy()); + assert_eq!((tool.editing, tool.sel()), (Some(id), (0, 0))); + // The dropped press does not count toward a double or triple click. + assert_eq!(tool.clicks, (None, 0)); + tool.pointer(&c, &PointerEvent::new(PointerKind::Up, at.x + 0.1, at.y)); + assert_eq!((tool.editing, tool.sel()), (Some(id), (0, 0))); + // A Shift-press that extends the selection, dropped, leaves the caret where a click put it. + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x + 0.1, at.y)); + tool.pointer(&c, &PointerEvent::new(PointerKind::Up, at.x + 0.1, at.y)); + assert_eq!(tool.sel(), (3, 3)); + tool.pointer(&c, &PointerEvent { mods: SHIFT, ..PointerEvent::new(PointerKind::Down, to.x + 0.1, to.y) }); + assert_eq!(tool.sel(), (3, 7)); + tool.drop_press(&c); + assert_eq!((tool.editing, tool.sel()), (Some(id), (3, 3))); +} + #[test] fn select_all_and_styled_paste() { let (d, _, mut tool) = editing("abc"); diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index c983205da3..9014f540e6 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -29,6 +29,20 @@ impl Tool for TypeTool { fn claims_key(&self, _: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Escape && self.editing.is_some() } + /// A dropped press drops only the selection drag or the type it was placing: the type being + /// edited stays in editing, with the caret and selection it had before the press. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if let Some((caret, anchor)) = self.before_press.take() { + (self.caret, self.anchor) = (caret, anchor); + } + self.selecting = false; + self.clicks = (None, 0); + self.press = None; + self.held = None; + self.drag = None; + self.snap.clear(); + vec![] + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { match ev.kind { PointerKind::Down => { @@ -36,6 +50,7 @@ impl Tool for TypeTool { let same = self.clicks.0.is_some_and(|q| (q - ev.pos).hypot() <= cx.tol(4.0)); let n = if same { self.clicks.1 + 1 } else { 1 }; self.clicks = (Some(ev.pos), n); + self.before_press = Some((self.caret, self.anchor)); let out = self.move_to(byte, ev.mods.shift); self.goal_x = None; if n >= 3 { @@ -51,6 +66,7 @@ impl Tool for TypeTool { // as it does in the type being edited. if let Some(out) = self.edit_at(cx, ev.pos) { self.selecting = true; + self.before_press = Some((self.caret, self.anchor)); return out; } self.press = Some((ev.pos, self.snap.press(cx, ev.pos, self.editing.as_slice(), None))); @@ -71,6 +87,7 @@ impl Tool for TypeTool { vec![] } PointerKind::Up => { + self.before_press = None; if self.selecting { self.selecting = false; return vec![]; From a230ef854b3f9e3e77391b7848fceab2715ff512 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 00:41:01 -0800 Subject: [PATCH 332/674] Docs: a dropped tool press cancels the drag as Escape does The progress line said a dropped press keeps nothing it began. A Curvature press that adds a point and a press on another text object keep what they did on press, as with Escape during the drag, so the line now says the drag is canceled as Escape cancels it. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8fd362eab3..6337b50d2e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -840,7 +840,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the view rotated, a second Escape less than a second after the first resets the rotation, as Reset Rotate View does. The first Escape may end something else, such as isolation mode or a path being drawn. The second resets the view only when it has nothing else to end, and an Escape that closes a menu does not count. After a click, or a press of another key that is not a modifier (Shift, Control, Alt/Option or Command), the next Escape counts as the first. With the Rotate View tool chosen, one Escape resets the view. A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5° (Preferences › General › Trackpad Gesture to Rotate View, on by default). On a touch screen a second finger cancels the tool press the first finger began, in the frame it lands or later: the Pencil's stroke or a Selection move is rolled back with no undo entry, and a finger that lands while another is down presses nothing, so a pinch or two-finger pan only zooms and pans (#4198; canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`). - A tool press dropped by a second finger, a long touch or a canceled touch keeps nothing it began: the tool gets back the options it had when the press began (the Polygon tool's sides, set with ↑ and ↓) and they are not stored, a press held still opens no size dialog, a Selection or Artboard tool marquee selects nothing, and the Pen goes on drawing its path without the dropped anchor (canvas tests `a_canceled_touch_drops_the_drag_without_keeping_its_options` and `long_touch_drops_a_tool_press_without_committing_art`; engine tests in `tests::toolsettings`). + A tool press dropped by a second finger, a long touch or a canceled touch cancels the tool's drag as Escape does: the tool gets back the options it had when the press began (the Polygon tool's sides, set with ↑ and ↓) and they are not stored, a press held still opens no size dialog, a Selection or Artboard tool marquee selects nothing, and the Pen goes on drawing its path without the dropped anchor (canvas tests `a_canceled_touch_drops_the_drag_without_keeping_its_options` and `long_touch_drops_a_tool_press_without_committing_art`; engine tests in `tests::toolsettings`). The status bar navigator's field shows the active artboard's number and name, and its drop-down lists every artboard by number and name, as the Artboards panel does. Choosing an artboard in the list makes it the active artboard and fits it in the window (`view.goToArtboard`). The list opens on the active artboard's row and lays out only the rows in view and at most one more. - **Geometry and effects:** - **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged. From 5d0cffbba126c6eb5467a0f990eb0f97ececa39f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 01:19:37 -0800 Subject: [PATCH 333/674] Canvas: a dropped press keeps what earlier clicks picked Escape also clears state that earlier clicks set up, so taking Escape for a dropped press lost it in five tools. Each now drops only the press: - Blend: the object picked first and the blend being added to are put back as they were at the press. - Dimension: a dropped click picks nothing, and the points or lines picked before stay; a dropped drag is canceled as before. - Width: the drag ends and the width points selected at the press are selected again. - Gradient: a dropped click on a freeform gradient leaves the line being drawn open. - Selection: with the pointer loaded with text, a dropped press threads nothing and the text stays loaded; a dropped press on a port loads none. --- crates/tools/src/dimension.rs | 43 ++++++++++++ crates/tools/src/distort/width.rs | 42 ++++++++++++ crates/tools/src/meshblend.rs | 105 +++++++++++++++++++++++------ crates/tools/src/select.rs | 31 +++++++++ crates/tools/src/select/tests.rs | 35 ++++++++++ crates/tools/src/xform/freeform.rs | 25 +++++++ crates/tools/src/xform/gradient.rs | 11 +++ 7 files changed, 271 insertions(+), 21 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index d3c7bdf83e..2290f5d2fd 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -390,6 +390,15 @@ impl Tool for DimensionTool { } vec![] } + /// A dropped drag is canceled as by Escape. A dropped click picks nothing, and the points or + /// lines earlier clicks picked stay. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + if self.dragging { + return self.key(cx, ToolKey::Escape, Mods::default()); + } + self.press = None; + vec![] + } fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.key(cx, ToolKey::Escape, Mods::default()) } @@ -465,3 +474,37 @@ impl Tool for DimensionTool { out } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use vectorcraft_doc::Selection; + + /// A dropped click picks nothing and keeps the point an earlier click picked. A dropped drag + /// out from a segment is canceled as by Escape. + #[test] + fn a_dropped_press_keeps_the_earlier_picks() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let mut t = DimensionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 400.0, 400.0)); + t.pointer(&c, &ev(PointerKind::Up, 400.0, 400.0)); + assert_eq!(t.points.len(), 1); + // The engine sends the release after the drop. + t.pointer(&c, &ev(PointerKind::Down, 450.0, 420.0)); + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 450.0, 420.0)).is_empty()); + assert_eq!(t.points.len(), 1, "the earlier pick stays and the dropped click picks nothing"); + assert!(t.pending.is_none() && t.busy()); + let mut t = DimensionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0)); + let acts = t.pointer(&c, &ev(PointerKind::Drag, 150.0, 60.0)); + assert!(matches!(acts.first(), Some(Action::Begin(_))), "{acts:?}"); + assert_eq!(t.drop_press(&c), vec![Action::Cancel]); + assert!(!t.busy()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing"); + } +} diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 27592035b2..e7050d3a79 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -105,6 +105,8 @@ pub struct WidthTool { drag: Option, /// Selected width points: the stroke's owner and their positions t. selected: Option<(NodeId, Vec)>, + /// The selected width points when the button went down: a dropped press puts them back. + before_press: Option<(NodeId, Vec)>, } /// The object whose stroke path `id` draws with: its compound path, if it is a member of one. @@ -308,6 +310,7 @@ impl Tool for WidthTool { vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "index": w.index, "adjustAdjoining": ev.mods.shift}))] } PointerKind::Down => { + self.before_press = self.selected.clone(); let Some(spot) = Self::spot_at(cx, p) else { if !ev.mods.shift { self.selected = None; @@ -401,6 +404,13 @@ impl Tool for WidthTool { && self.drag.is_none() && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty()) } + /// A dropped press ends the drag, and the width points selected when the button went down are + /// selected again. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.drag = None; + self.selected = self.before_press.take(); + vec![] + } fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Escape && self.drag.is_none() { self.selected = None; @@ -691,6 +701,38 @@ mod tests { assert!(t.selected.is_some()); } + /// A dropped press keeps the width points earlier clicks selected: a press away from the + /// path, dropped, deselects nothing, and a dropped drag of another point ends with the points + /// selected before it, and its release commits nothing. + #[test] + fn a_dropped_press_keeps_the_selected_width_points() { + let (d, id) = doc_three_points(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = WidthTool::default(); + let (none, shift) = (Mods::default(), Mods { shift: true, ..Default::default() }); + t.pointer(&c, &ev(PointerKind::Down, 150.0, 200.0, none)); + t.pointer(&c, &ev(PointerKind::Up, 150.0, 200.0, none)); + t.pointer(&c, &ev(PointerKind::Down, 250.0, 200.0, shift)); + t.pointer(&c, &ev(PointerKind::Up, 250.0, 200.0, shift)); + assert_eq!(t.selected_indices(&c, id), vec![1, 3]); + // The engine sends the release after the drop. + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 450.0, shift)).is_empty()); + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 450.0, shift)).is_empty()); + assert_eq!(t.selected_indices(&c, id), vec![1, 3]); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 450.0, none)).is_empty()); + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 450.0, none)).is_empty()); + assert_eq!(t.selected_indices(&c, id), vec![1, 3]); + assert_eq!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0, none)), vec![Action::Begin("Width Point".into())]); + t.pointer(&c, &ev(PointerKind::Drag, 220.0, 200.0, none)); + assert!(t.drop_press(&c).is_empty()); + assert!(!t.busy()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 220.0, 200.0, none)).is_empty(), "the release commits nothing"); + assert_eq!(t.selected_indices(&c, id), vec![1, 3]); + } + #[test] fn width_points_show_on_every_subpath() { let (d, c, _) = doc_compound(); diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 0790407d2a..b32986150c 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -48,6 +48,9 @@ pub struct BlendTool { first: Option, /// A blend was just made: the next click adds to it (the selected blend). chained: bool, + /// `first` and `chained` when the button went down: a dropped press puts them back, unless + /// the press made a blend. + before_press: Option<(Option, bool)>, } /// The anchor of the first subpath of path or compound path `id` (its first member's) nearest @@ -98,25 +101,32 @@ impl Tool for BlendTool { match ev.kind { PointerKind::DoubleClick => options(self), PointerKind::Down if ev.mods.alt => options(self), - PointerKind::Down => match (self.first(cx), pick(cx, ev.pos)) { - (_, None) => { - (self.first, self.chained) = (None, false); - vec![] - } - (None, Some((top, start))) => { - self.first = Some((top, start)); - vec![Action::Exec("select.set".into(), json!({"ids": [top.0]}))] - } - (Some((a, sa)), Some((b, sb))) if a != b && cx.doc.node(a).is_some() => { - (self.first, self.chained) = (None, true); - let mut p = json!({"ids": [a.0, b.0]}); - if sa.is_some() || sb.is_some() { - p["starts"] = json!([sa, sb]); + PointerKind::Down => { + self.before_press = Some((self.first, self.chained)); + match (self.first(cx), pick(cx, ev.pos)) { + (_, None) => { + (self.first, self.chained) = (None, false); + vec![] } - vec![Action::Exec("object.blend.make".into(), p)] + (None, Some((top, start))) => { + self.first = Some((top, start)); + vec![Action::Exec("select.set".into(), json!({"ids": [top.0]}))] + } + (Some((a, sa)), Some((b, sb))) if a != b && cx.doc.node(a).is_some() => { + (self.first, self.chained, self.before_press) = (None, true, None); + let mut p = json!({"ids": [a.0, b.0]}); + if sa.is_some() || sb.is_some() { + p["starts"] = json!([sa, sb]); + } + vec![Action::Exec("object.blend.make".into(), p)] + } + (Some(_), Some(_)) => vec![], } - (Some(_), Some(_)) => vec![], - }, + } + PointerKind::Up => { + self.before_press = None; + vec![] + } _ => vec![], } } @@ -151,6 +161,15 @@ impl Tool for BlendTool { } vec![] } + /// A dropped press puts back the object picked first and the blend being added to as they + /// were when the button went down, so the picks of earlier clicks stay and the press picks + /// nothing. A blend the press made stays made. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if let Some((first, chained)) = self.before_press.take() { + (self.first, self.chained) = (first, chained); + } + vec![] + } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { (self.first, self.chained) = (None, false); vec![] @@ -354,7 +373,7 @@ mod tests { let mut s = Selection::default(); s.set([g]); let c = cx(&d, &s, &p); - let mut t = BlendTool { first: None, chained: true }; + let mut t = BlendTool { first: None, chained: true, ..Default::default() }; assert!(t.first(&c).is_some()); assert!(t.chosen_again(&c).is_empty()); assert!(t.first(&c).is_none(), "choosing the tool again ends adding to the blend just made"); @@ -385,7 +404,7 @@ mod tests { // After a blend is made, a click while the selected blend is gone picks the object it hits. let mut s = Selection::default(); s.set([NodeId(9999)]); - let mut t = BlendTool { first: None, chained: true }; + let mut t = BlendTool { first: None, chained: true, ..Default::default() }; let acts = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 320.0, 120.0)); assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({"ids": [b.0]}))]); } @@ -432,7 +451,7 @@ mod tests { d.insert(Some(l), 1, blend).unwrap(); let mut s = Selection::default(); let p = paint(); - let mut t = BlendTool { first: None, chained: true }; + let mut t = BlendTool { first: None, chained: true, ..Default::default() }; s.set([g]); let c = cx(&d, &s, &p); let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); @@ -477,7 +496,7 @@ mod tests { let mut s = Selection::default(); s.set([g]); let c = cx(&d, &s, &p); - let mut t = BlendTool { first: None, chained: true }; + let mut t = BlendTool { first: None, chained: true, ..Default::default() }; assert!(t.first(&c).is_some()); assert!(t.key(&c, crate::ToolKey::Escape, Mods::default()).is_empty()); assert!(t.first(&c).is_none(), "Escape ends adding to the blend just made"); @@ -485,6 +504,50 @@ mod tests { assert!(esc(&mut BlendTool::default()).is_empty(), "nothing to drop"); } + /// A dropped press (a long touch, a canceled touch) picks nothing, keeps the pick an earlier + /// click made, and keeps adding to the blend just made: the next click blends with them. + #[test] + fn a_dropped_press_keeps_the_blend_tools_first_pick() { + let (mut d, a) = doc_with_rect(); + let l = d.layers[0].id; + let (b, g) = (d.alloc_id(), d.alloc_id()); + let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(300.0, 100.0, 350.0, 150.0)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(b, r, vectorcraft_doc::Appearance::default_art())).unwrap(); + let (k1, k2) = (d.alloc_id(), d.alloc_id()); + let key = |id: NodeId, x: f64| { + let r = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 300.0, x + 20.0, 320.0)); + std::sync::Arc::new(vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())) + }; + let blend = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, 0.0), key(k2, 100.0)], spec: Default::default() }); + d.insert(Some(l), 2, blend).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + // The engine sends the release after the drop. + let dropped = |t: &mut BlendTool, c: &ToolContext, x: f64, y: f64| { + t.pointer(c, &ev(PointerKind::Down, x, y)); + assert!(t.drop_press(c).is_empty()); + assert!(t.pointer(c, &ev(PointerKind::Up, x, y)).is_empty()); + }; + let mut t = BlendTool::default(); + dropped(&mut t, &c, 150.0, 150.0); + assert_eq!(t.first(&c), None, "a dropped first press picks nothing"); + t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0)); + t.pointer(&c, &ev(PointerKind::Up, 150.0, 150.0)); + // A second press on a, and a press on empty canvas, each dropped. + dropped(&mut t, &c, 151.0, 151.0); + dropped(&mut t, &c, 450.0, 450.0); + assert_eq!(t.first(&c), Some((a, None)), "the pick stays"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Down, 320.0, 120.0)), vec![Action::Exec("object.blend.make".into(), json!({"ids": [a.0, b.0]}))]); + // After a blend is made, a dropped press on empty canvas keeps adding to it. + let mut s = Selection::default(); + s.set([g]); + let c = cx(&d, &s, &p); + let mut t = BlendTool { first: None, chained: true, ..Default::default() }; + dropped(&mut t, &c, 450.0, 450.0); + assert_eq!(t.first(&c), Some((g, None)), "the blend just made is still added to"); + } + #[test] fn mesh_tool_click_path_creates_mesh() { let (d, a) = doc_with_rect(); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index b0f8c812b3..be7222f4f5 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -150,6 +150,9 @@ pub struct SelectionTool { /// The last hover had Alt held: what it measures depends on what lies under the pointer /// ([`Tool::wants_rehover`]). alt_hover: bool, + /// The text the pointer was loaded with when the button went down: a dropped press loads it + /// again. + loaded_at_press: Option<(NodeId, bool)>, } /// What Distance Guides measure the selection to. @@ -556,6 +559,21 @@ impl SelectionTool { }) } + /// On a press, notes the text the pointer is loaded with ([`Self::loaded_at_press`]); a + /// release clears it. + fn note_loaded_at_press(&mut self, kind: PointerKind) { + match kind { + PointerKind::Down => { + self.loaded_at_press = match self.state { + State::Loaded { from, before, .. } => Some((from, before)), + _ => None, + } + } + PointerKind::Up => self.loaded_at_press = None, + _ => {} + } + } + /// The pointer loaded with the text of area type or type on a path `from` ([`State::Loaded`]): /// a press starts placing it, and its release threads it (`text.thread.add`), into a frame put /// `before` `from` or after it. None when `from` can no longer thread: the press is an @@ -669,6 +687,18 @@ impl Tool for SelectionTool { if key == ToolKey::Escape { self.guide.cancel() } else { vec![] } } + /// A dropped press is canceled as by Escape, so a dropped press on a port loads no text. With + /// the pointer loaded with text, the press threads nothing and the text stays loaded for the + /// next click, a press on the port that loaded it included. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + let loaded = self.loaded_at_press.take(); + let out = if matches!(self.state, State::Loaded { press: Some(_), .. }) { vec![] } else { self.key(cx, ToolKey::Escape, Mods::default()) }; + if let Some((from, before)) = loaded { + self.state = State::Loaded { from, before, press: None }; + } + out + } + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { match self.state { State::Marquee { .. } => key == ToolKey::Letter('e'), @@ -703,6 +733,7 @@ impl Tool for SelectionTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.note_loaded_at_press(ev.kind); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.alt_hover = hovering && ev.mods.alt; self.distance = hovering.then(|| distance_target(cx, ev.pos, ev.mods)).flatten(); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 8f6299f06d..6638083aca 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1871,6 +1871,41 @@ fn escape_drops_the_loaded_text() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 30.0, 420.0)), vec![Action::Exec("select.none".into(), json!({}))]); } +/// A dropped press with the pointer loaded with text threads nothing, and the text stays loaded: +/// the next click threads it. A dropped press on the port loads no text. +#[test] +fn a_dropped_press_keeps_the_text_loaded() { + let (d, id, _, port) = overflowing_area_type(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.drop_press(&cx); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + assert_ne!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText, "the dropped press loads no text"); + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + // The engine sends the release after the drop. + t.pointer(&cx, &ev(PointerKind::Down, 20.0, 20.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 90.0)); + assert!(t.drop_press(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 80.0, 90.0)).is_empty(), "the release threads nothing"); + assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Marquee(_))), "the new frame's outline is removed"); + assert_eq!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText); + // A press on the port that loaded the text puts it down; dropped, it leaves the text loaded. + t.pointer(&cx, &ev(PointerKind::Down, port.x, port.y)); + assert!(t.drop_press(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, port.x, port.y)); + assert_eq!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText, "a dropped press on the port"); + t.pointer(&cx, &ev(PointerKind::Down, 30.0, 420.0)); + assert_eq!( + t.pointer(&cx, &ev(PointerKind::Up, 30.0, 420.0)), + vec![Action::Exec("text.thread.add".into(), json!({"from": id.0, "at": [30.0, 420.0]}))] + ); +} + /// [`doc_with_area_type`], its text fitting its frame; where its in and out ports are. fn fitting_area_type() -> (vectorcraft_doc::Document, NodeId, Point, Point) { let (d, id) = doc_with_area_type(); diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rs index d2c04aa2a8..fe77ce607c 100644 --- a/crates/tools/src/xform/freeform.rs +++ b/crates/tools/src/xform/freeform.rs @@ -451,6 +451,31 @@ mod tests { assert!(!t.claims_key(&cx, ToolKey::Escape)); } + /// A dropped click adds no point and leaves the line being drawn open: the next click still + /// joins it. A dropped drag of a point is canceled as by Escape. + #[test] + fn a_dropped_click_keeps_the_line_open() { + let (d, s) = doc(FreeformMode::Lines); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let mut t = GradientTool::default(); + let add = |x: f64, y: f64, line: bool| Action::Exec("paint.freeform.addPoint".into(), json!({"at": [x, y], "line": line, "stroke": false})); + assert_eq!(click(&mut t, &cx, 140.0, 150.0), vec![add(140.0, 150.0, false)]); + cx.freeform_point = Some(2); + assert!(t.claims_key(&cx, ToolKey::Escape)); + // The engine sends the release after the drop. + t.pointer(&cx, &ev(PointerKind::Down, 170.0, 160.0)); + assert!(t.drop_press(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 170.0, 160.0)).is_empty(), "the dropped click adds no point"); + assert!(t.claims_key(&cx, ToolKey::Escape), "the line stays open"); + assert_eq!(click(&mut t, &cx, 160.0, 140.0), vec![add(160.0, 140.0, true)]); + t.pointer(&cx, &ev(PointerKind::Down, 120.0, 121.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Drag, 130.0, 140.0))[0], Action::Begin("Gradient".into())); + assert_eq!(t.drop_press(&cx), vec![Action::Cancel]); + assert!(!t.busy()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 130.0, 140.0)).is_empty()); + } + #[test] fn a_point_dragged_out_of_the_object_is_removed() { let (d, s) = doc(FreeformMode::Points); diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rs index 2631514343..7a9b59e2dc 100644 --- a/crates/tools/src/xform/gradient.rs +++ b/crates/tools/src/xform/gradient.rs @@ -511,6 +511,17 @@ impl Tool for GradientTool { && cx.gradient_stop.is_some_and(|i| Annotator::of(cx).is_some_and(|a| i < a.gradient.stops.len())) } + /// A dropped drag is canceled as by Escape. A dropped click does nothing, and the line Lines + /// mode is drawing stays open. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + if self.busy() { + return self.key(cx, ToolKey::Escape, Mods::default()); + } + (self.gesture, self.free) = (None, None); + self.guides.clear(); + vec![] + } + fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { if key == ToolKey::Escape && self.busy() { self.gesture = None; From e01823c2eb94490617ed33464b4f798cdd7ad59d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 01:59:08 -0800 Subject: [PATCH 334/674] Gradient: a dropped or canceled point drag keeps the point selected A drag that takes a selected freeform gradient point out of the object previews its removal, which deselects it. A dropped press now selects again the point that was selected once the tool took the press, and Escape reselects a point dragged out and back inside the object. --- crates/engine/src/lib.rs | 3 +++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/freeform.rs | 26 ++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 13 ++++++++++++- crates/tools/src/xform/freeform.rs | 10 ++++++++-- 5 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f0b7f4b603..2a9fb16289 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -206,6 +206,9 @@ pub struct Session { /// The id and persistent options of the tool when the press under way began, which a dropped /// press puts back ([`Session::drop_tool_press`]). pub(crate) press_options: Option<(String, serde_json::Map)>, + /// The freeform gradient point selected once the tool took the press under way, which a + /// dropped press selects again ([`Session::drop_tool_press`]). + pub(crate) press_point: Option>, /// A guide being dragged out of a ruler ([`Session::ruler_guide`]). pub(crate) ruler_guide: Option, /// Which selected type overflows its frame, for the ports every tool but the Type tools shows. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index da2c659882..ba15d31757 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -93,6 +93,7 @@ impl Session { plane_widget_press: false, pointer_held: false, press_options: None, + press_point: None, ruler_guide: None, port_marks: Default::default(), font_search: None, diff --git a/crates/engine/src/tests/freeform.rs b/crates/engine/src/tests/freeform.rs index df9ed3e4bc..4e65c86894 100644 --- a/crates/engine/src/tests/freeform.rs +++ b/crates/engine/src/tests/freeform.rs @@ -331,3 +331,29 @@ fn type_objects_keep_points_in_text_space() { assert!(close(f.points[i].at, Point::new(90.0, 150.0)), "back in document coordinates: {:?}", f.points[i].at); assert_eq!(f.points[i].color, Color::rgb(1.0, 0.0, 1.0)); } + +/// A dropped press (a long touch, a canceled touch) of the Gradient tool that dragged a selected +/// point out of the object, and out and back in, keeps the point and its selection. +#[test] +fn a_dropped_drag_of_a_point_keeps_it_selected() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let (mut s, id) = freeform_rect(); + let v = ViewInfo::default(); + s.select_tool("gradient", v).unwrap(); + let count = points(&s, id).points.len(); + assert!(count > 1, "a point can be dragged out"); + let at = s.proxy_freeform(false).unwrap().0.points[0].at; + for back in [false, true] { + run(&mut s, "paint.freeform.selectPoint", json!({"index": 0})); + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 400.0, 400.0), v).unwrap(); + assert_eq!(s.selected_freeform_point(), None, "the removal the drag previews deselects the point"); + if back { + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 5.0, at.y + 5.0), v).unwrap(); + } + s.drop_tool_press(v).unwrap(); + assert!(!s.tool_busy(), "the tool is at rest"); + assert_eq!(points(&s, id).points.len(), count, "back inside: {back}"); + assert_eq!(s.selected_freeform_point(), Some(0), "back inside: {back}"); + } +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 0a959959e6..4eb1912294 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -366,16 +366,22 @@ impl Session { /// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what /// the tool asks for along the way, only a cancel and a notify run, so a marquee selects /// nothing and a click opens no size dialog. The tool gets back the persistent options it had - /// when the press began, and none of the press's changes to them are stored. + /// when the press began, and none of the press's changes to them are stored. The freeform + /// gradient point selected once the tool took the press is selected again. pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> { // Nothing to roll back without a document; the tool still drops the press and gets the release. let _ = self.cancel_interaction(); let before = self.press_options.take(); + let point = self.press_point.take(); let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx)); acts.retain(|a| matches!(a, Action::Cancel | Action::Notify(_))); let dropped = self.take_tool_panic().and_then(|()| self.apply_actions(acts)); let up = PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote: false, pressure: 1.0, pen: None }; let r = dropped.and(self.pointer_event(&up, view, false)); + // A drag out of the object previews the point's removal, which deselects it. + if let Some(p) = point { + self.freeform_point = p; + } if let Some((id, opts)) = before && id == self.tool.id() { @@ -428,6 +434,11 @@ impl Session { } self.apply_actions(acts) }); + match ev.kind { + PointerKind::Down => self.press_point = Some(self.freeform_point), + PointerKind::Up => self.press_point = None, + _ => {} + } if ev.kind == PointerKind::Up { self.give_back_tool(view)?; } diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rs index fe77ce607c..89c6faa933 100644 --- a/crates/tools/src/xform/freeform.rs +++ b/crates/tools/src/xform/freeform.rs @@ -274,10 +274,11 @@ pub(super) fn release(cx: &ToolContext, a: Option<&Annotator>, g: Gesture, lines } } -/// Escape during a drag: the point a drag-out deselected is selected again. +/// Escape during a drag: the point a drag-out deselected is selected again, also when the drag +/// came back inside the object. pub(super) fn cancel(g: &Gesture) -> Vec { match g.grab { - Grab::Point(i) if g.out => vec![Action::Cancel, select(Some(i))], + Grab::Point(i) if g.left => vec![Action::Cancel, select(Some(i))], _ => vec![Action::Cancel], } } @@ -499,6 +500,11 @@ mod tests { t.pointer(&cx, &ev(PointerKind::Down, 120.0, 120.0)); t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 60.0)); assert_eq!(t.key(&cx, ToolKey::Escape, Default::default()), vec![Action::Cancel, select(Some(0))]); + // Also after the drag came back inside. + t.pointer(&cx, &ev(PointerKind::Down, 120.0, 120.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 60.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 110.0, 110.0)); + assert_eq!(t.key(&cx, ToolKey::Escape, Default::default()), vec![Action::Cancel, select(Some(0))]); } #[test] From 84e344c475b3fd28302cde1e6cb79d89f2ae49ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 05:45:46 -0800 Subject: [PATCH 335/674] Character Styles: Style Options sets character color and OpenType features Character Style Options and New Character Style get a Character Color section and an OpenType Features section. Character Color sets the fill and stroke (None or a document swatch; a global swatch or a tint of one stays linked, with a Tint from 0% to 100%), the stroke Weight, and Overprint Fill and Overprint Stroke. A gradient or pattern paint the style already has stays until another paint is chosen. OpenType Features sets Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20. A changed control replaces only its own tags in the style's feature list, so other tags stay, and Default Figure and Default Position are stored as their features turned off, distinct from unset. Empty controls stay unset, and each section's Reset Panel clears only its own attributes. charStyle.new, charStyle.edit and charStyle.setAttrs check a changed fill, stroke, stroke weight or feature list: tints from 0 to 1, links to global swatches of the document (the color follows the swatch), weights from 0 to 4000000, and known feature tags, at most 256. Values the style or the text it is made from already has are kept. charStyle.duplicate keeps the copied style's values in the same way, so a style with a language tag that is not in the list can be duplicated. Editing a global swatch now also updates the fill and stroke stored in character styles, so their text no longer shows as overriding the style and text styled later takes the new color. swatch.unused counts a swatch a character style links to as used. --- crates/doc/src/swatches.rs | 27 +- crates/engine/src/cmd/swatch.rs | 13 +- crates/engine/src/cmd/textstyles.rs | 84 ++- crates/engine/src/cmd/textstyles/tests.rs | 138 ++++ .../ui-egui/src/dialogs/char_style_options.rs | 630 +++++++++++++++++- crates/ui-egui/src/dialogs/new_text_style.rs | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/opentype.rs | 10 +- docs/mcp.md | 24 +- docs/target-app-parity.md | 1 + 31 files changed, 1015 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 95978bd8d2..528e33e3e3 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -110,8 +110,9 @@ impl Document { /// Visit every color that can link to a swatch (solid paints and gradient stops of fills, /// strokes and text runs) in the art (opacity masks included), symbol definitions, graph - /// designs, pattern tiles and the tile that pattern editing's Cancel puts back, graphic styles - /// and the swatches themselves (tint swatches, gradient swatches' stops). + /// designs, pattern tiles and the tile that pattern editing's Cancel puts back, graphic styles, + /// character styles' fill and stroke and the swatches themselves (tint swatches, gradient + /// swatches' stops). /// `f(colour, link, tint)` may change them and returns true when it did /// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are /// copied. Returns the number of changed paints. @@ -134,6 +135,11 @@ impl Document { for w in self.swatches_iter_mut() { n += usize::from(w.paint.map_links(f)); } + for def in &mut self.char_styles { + for key in ["fill", "stroke"] { + n += usize::from(map_style_paint(&mut def.attrs, key, f)); + } + } n } @@ -198,6 +204,23 @@ pub fn color_name(c: Color) -> String { /// true when it changed them. pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option, &mut f32) -> bool + 'a; +/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`] +/// does, and store the result in the attribute. True when it changed. +fn map_style_paint(attrs: &mut serde_json::Map, key: &str, f: &mut LinkFn) -> bool { + let Some(value) = attrs.get_mut(key) else { return false }; + let Ok(mut paint) = serde_json::from_value::(value.clone()) else { return false }; + if !paint.map_links(f) { + return false; + } + match serde_json::to_value(&paint) { + Ok(changed) => { + *value = changed; + true + } + Err(_) => false, + } +} + /// Every colour in the subtree of `n` with the swatch it links to: solid fills, strokes, text runs /// and gradient stops (with their link), then mesh points (unlinked), in paint order. pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 80e8e2a122..4aa0c0b472 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -818,7 +818,7 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result { Some(l) if d.swatch(l).is_some() => links.push((l.clone(), tint)), _ => colors.push(*c), }; - d.visit_paints(&mut |p| match p { + let mut paint = |p: &Paint| match p { Paint::Solid { color: c, swatch, tint } => color(c, swatch.as_ref(), *tint), Paint::Gradient(g) => { g.gradient.stops.iter().for_each(|s| color(&s.color, s.swatch.as_ref(), s.tint)); @@ -827,7 +827,16 @@ fn swatch_unused(s: &mut Session, _: &Value) -> Result { } Paint::Pattern { pattern, .. } => patterns.push(pattern.clone()), Paint::None => {} - }); + }; + d.visit_paints(&mut paint); + // A character style's fill and stroke use their swatches even while no text uses the style. + for attrs in d.char_styles.iter().map(|def| &def.attrs) { + for key in ["fill", "stroke"] { + if let Some(p) = attrs.get(key).and_then(|v| serde_json::from_value::(v.clone()).ok()) { + paint(&p); + } + } + } let used = |w: &Swatch| { gradient_links.contains(&w.name) || links.iter().any(|(l, t)| match w.tint_of() { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cb6b1d0b59..4b8baa7c73 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -477,10 +477,12 @@ fn name_param<'a>(p: &'a Value, kind: Kind, verb: &str) -> Result<&'a str> { str_param(p, "name").ok_or_else(|| bad(&kind.cmd(verb), "missing `name`")) } -/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`) or -/// the target text's attributes (`charStyle.new`): a language tag that is not in the list, which a -/// file can give a style or a run, stays when `attrs` keeps it. -fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map>) -> Result>> { +/// The `attrs` of `p`, validated. `kept` holds the style's current attributes (`charStyle.edit`, +/// `charStyle.setAttrs`), the target text's attributes (`charStyle.new`) or the attributes of the +/// style being copied (`charStyle.duplicate`): a language tag that is not in the list, a swatch link the document does +/// not have, or an OpenType feature tag the shaper does not know, which a file can give a style or +/// a run, stays when `attrs` keeps it. +fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Map>) -> Result>> { match p.get("attrs") { None | Some(Value::Null) => Ok(None), Some(Value::Object(m)) => { @@ -490,12 +492,25 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map { let mut st = with_attrs(&CharStyle::default(), m, &c)?; + let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") { st.language = vectorcraft_doc::setup::char_language(l).map_err(|e| bad(&c, e))?.map(str::to_string); } + for (key, paint) in [("fill", &mut st.fill), ("stroke", &mut st.stroke)] { + if changed(key) { + style_paint(d, paint, key, &c)?; + } + } + let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD); + if changed(key) && !(lo..=hi).contains(&st.stroke_width) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + if changed("features") { + style_features(&st.features, kept, &c)?; + } char_attrs(&st) } Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?), @@ -506,6 +521,51 @@ fn attrs_param(p: &Value, kind: Kind, verb: &str, kept: Option<&Map Result<()> { + match paint { + vectorcraft_color::Paint::Solid { color, swatch, tint } => style_color(d, color, swatch.as_deref(), *tint, key, c), + vectorcraft_color::Paint::Gradient(g) => { + g.gradient.stops.iter_mut().try_for_each(|stop| style_color(d, &mut stop.color, stop.swatch.as_deref(), stop.tint, key, c)) + } + _ => Ok(()), + } +} + +/// Check one color of a character style's `key` paint for [`style_paint`]. +fn style_color(d: &Document, color: &mut vectorcraft_color::Color, swatch: Option<&str>, tint: f32, key: &str, c: &str) -> Result<()> { + if !(0.0..=1.0).contains(&tint) { + let (key, lo, hi) = (format!("{key}.tint"), 0, 1); + return Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))); + } + if let Some(name) = swatch { + if d.swatch(name).is_none() { + return Err(bad(c, format!("no swatch `{name}`"))); + } + let base = d.global_color(name).ok_or_else(|| bad(c, format!("`{name}` is a process colour: tints apply to global and spot colours")))?; + *color = base.tinted(tint); + } + Ok(()) +} + +/// Check a character style's OpenType `features`: at most [`vectorcraft_text::MAX_STYLE_FEATURES`] +/// tags, or no more than the `kept` attributes already list, each one the shaper knows or one the +/// `kept` attributes already list. +fn style_features(features: &[String], kept: Option<&Map>, c: &str) -> Result<()> { + let kept: Vec<&str> = kept.and_then(|k| k.get("features")).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + let max = vectorcraft_text::MAX_STYLE_FEATURES; + if features.len() > max.max(kept.len()) { + return Err(bad(c, format!("features lists at most {max} tags"))); + } + // One `-` or `+` at most, as the shaper reads a tag. + let known = |t: &str| vectorcraft_text::OtFeatures::known_tag(t) && !t.strip_prefix(['-', '+']).unwrap_or(t).starts_with(['-', '+']); + match features.iter().find(|t| !known(t) && !kept.contains(&t.as_str())) { + Some(t) => Err(bad(c, format!("unknown OpenType feature `{t}`"))), + None => Ok(()), + } +} + /// The attributes of a new style made from nothing (no `attrs`, no text selected): while the /// interface is in Japanese, new type's em box top-to-top leading (paragraph styles) and em box /// centre alignment (character styles); else none (the defaults). @@ -538,9 +598,15 @@ fn list(s: &mut Session, kind: Kind) -> Result { } fn new(s: &mut Session, p: &Value, kind: Kind) -> Result { + new_from(s, p, kind, None) +} + +/// `charStyle.new`, `paraStyle.new`: `copied` holds the attributes of the style a copy is made of +/// (`charStyle.duplicate`), which `attrs` keeps as [`attrs_param`] keeps the target text's. +fn new_from(s: &mut Session, p: &Value, kind: Kind, copied: Option<&Map>) -> Result { let c = kind.cmd("new"); let target = selection_attrs(s, p, kind)?; - let attrs = match attrs_param(p, kind, "new", target.as_ref())? { + let attrs = match attrs_param(&s.doc()?.doc, p, kind, "new", copied.or(target.as_ref()))? { Some(a) => a, None => match target { Some(a) => a, @@ -668,7 +734,9 @@ fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result { fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result { let name = name_param(p, kind, "setAttrs")?.to_string(); - let attrs = attrs_param(p, kind, "setAttrs", None)?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?; + let d = &s.doc()?.doc; + let old = kind.attrs(d, &name); + let attrs = attrs_param(d, p, kind, "setAttrs", old.as_ref())?.ok_or_else(|| bad(&kind.cmd("setAttrs"), "missing `attrs`"))?; redefine_to(s, kind, &name, attrs, "setAttrs") } @@ -678,7 +746,7 @@ fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result { let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string(); let d = &s.doc()?.doc; let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; - let attrs = attrs_param(p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?; + let attrs = attrs_param(d, p, kind, "edit", Some(&old))?.ok_or_else(|| bad(&c, "missing `attrs`"))?; if name == kind.normal() { return Err(bad(&c, format!("`{name}` can't be edited this way"))); } @@ -726,7 +794,7 @@ fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result { .map(|i| if i == 1 { format!("{stem} copy") } else { format!("{stem} copy {i}") }) .find(|n| kind.attrs(d, n).is_none()) .unwrap_or_else(|| format!("{stem} copy")); - new(s, &json!({ "name": copy, "attrs": attrs }), kind) + new_from(s, &json!({ "name": copy, "attrs": attrs }), kind, Some(&attrs)) } fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index d7021efdab..90bb32bbbb 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -257,6 +257,144 @@ fn new_character_style_keeps_a_language_tag_from_the_text() { assert!(error.contains("unknown language"), "{error}"); } +/// The fill of the first run of `id` and its overprint flags, its stroke and stroke weight. +fn run_paints(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, f64, bool, bool) { + let st = runs(s, id)[0].style.clone(); + (st.fill, st.stroke, st.stroke_width, st.overprint_fill, st.overprint_stroke) +} + +#[test] +fn character_style_color_and_features_reach_text_and_follow_swatch_edits() { + let (mut s, id) = session_with_text("Text 1/2"); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap(); + let brand = s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap(); + let mut tinted = serde_json::to_value(s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()).unwrap(); + // The command takes the color of the link at the tint, whatever color is sent. + tinted["tint"] = json!(0.4); + let attrs = json!({"fill": brand, "stroke": tinted, "stroke_width": 2.0, "overprint_fill": true, "overprint_stroke": false, + "features": ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]}); + s.execute("charStyle.new", &json!({"name": "Ink", "attrs": attrs})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Ink", "id": id})).unwrap(); + let want_stroke = s.doc().unwrap().doc.tint_paint("Brand", 0.4).unwrap(); + assert_eq!(run_paints(&s, id), (brand, want_stroke.clone(), 2.0, true, false)); + assert_eq!(runs(&s, id)[0].style.features, ["dlig", "-liga", "tnum", "lnum", "-onum", "-pnum", "ss02", "-ss01"]); + let def = |s: &Session| s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Ink").unwrap().attrs.clone(); + assert_eq!(def(&s)["stroke"], serde_json::to_value(&want_stroke).unwrap()); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(saved.char_styles.iter().find(|d| d.name == "Ink").unwrap().attrs, def(&s)); + + s.execute("swatch.edit", &json!({"name": "Brand", "color": "#a02050"})).unwrap(); + let (brand, tint40) = (s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap(), s.doc().unwrap().doc.tint_paint("Brand", 0.4).unwrap()); + assert_eq!(run_paints(&s, id).0, brand); + assert_eq!(run_paints(&s, id).1, tint40); + assert_eq!(def(&s)["fill"], serde_json::to_value(&brand).unwrap()); + assert_eq!(def(&s)["stroke"], serde_json::to_value(&tint40).unwrap()); + let later = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Later"})).unwrap()["id"].as_u64().unwrap(); + s.execute("charStyle.apply", &json!({"name": "Ink", "id": later})).unwrap(); + assert_eq!(run_paints(&s, later).0, brand); +} + +#[test] +fn character_style_color_and_features_are_checked() { + let (mut s, _) = session_with_text("Text"); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap(); + let mut over = serde_json::to_value(s.doc().unwrap().doc.tint_paint("Brand", 1.0).unwrap()).unwrap(); + over["tint"] = json!(1.5); + let mut missing = over.clone(); + missing["tint"] = json!(0.5); + missing["swatch"] = json!("Gone"); + s.execute("swatch.new", &json!({"name": "Local", "color": "#102030"})).unwrap(); + let mut local = missing.clone(); + local["swatch"] = json!("Local"); + let many: Vec = (0..=vectorcraft_text::MAX_STYLE_FEATURES).map(|_| "dlig".to_string()).collect(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for (attrs, message) in [ + (json!({"fill": over}), "`fill.tint` must be from 0 to 1"), + (json!({"stroke": missing}), "no swatch `Gone`"), + (json!({"stroke": local}), "`Local` is a process colour"), + (json!({"stroke_width": -1.0}), "`stroke_width` must be from 0 to 4000000"), + (json!({"stroke_width": 5.0e6}), "`stroke_width` must be from 0 to 4000000"), + (json!({"features": ["dlig", "zzzz"]}), "unknown OpenType feature `zzzz`"), + (json!({"features": ["--liga"]}), "unknown OpenType feature `--liga`"), + (json!({"features": many}), "features lists at most 256 tags"), + (json!({"fill": {"type": "solid"}}), "missing field"), + ] { + for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { + let p = match cmd { + "charStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}), + "charStyle.new" => json!({"name": "Other", "attrs": attrs}), + _ => json!({"name": "Body", "attrs": attrs}), + }; + let error = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(error.contains(message), "{cmd} {attrs}: {error}"); + } + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn style_paints_count_as_swatch_uses_and_gradient_stops_are_checked() { + let (mut s, _) = session_with_text("Text"); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Spare", "color": "#a02050", "global": true})).unwrap(); + let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].clone(); + assert!(unused(&mut s).as_array().unwrap().contains(&json!("Brand"))); + let brand = s.doc().unwrap().doc.tint_paint("Brand", 0.5).unwrap(); + s.execute("charStyle.new", &json!({"name": "Ink", "attrs": {"stroke": brand}})).unwrap(); + let names = unused(&mut s); + assert!(!names.as_array().unwrap().contains(&json!("Brand")), "{names}"); + assert!(names.as_array().unwrap().contains(&json!("Spare")), "{names}"); + + let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()); + g.gradient.stops[0].swatch = Some("Brand".into()); + g.gradient.stops[0].tint = 0.25; + let fill = serde_json::to_value(vectorcraft_color::Paint::Gradient(Box::new(g.clone()))).unwrap(); + s.execute("charStyle.new", &json!({"name": "Fade", "attrs": {"fill": fill}})).unwrap(); + let def = s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Fade").unwrap().attrs.clone(); + let want = s.doc().unwrap().doc.global_color("Brand").unwrap().tinted(0.25); + assert_eq!(def["fill"]["gradient"]["stops"][0]["color"], serde_json::to_value(want).unwrap()); + g.gradient.stops[0].swatch = Some("Gone".into()); + let gone = serde_json::to_value(vectorcraft_color::Paint::Gradient(Box::new(g))).unwrap(); + let error = s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"fill": gone}})).unwrap_err().to_string(); + assert!(error.contains("no swatch `Gone`"), "{error}"); +} + +#[test] +fn styles_from_files_keep_their_unknown_feature_tags_and_swatch_links() { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap(); + let linked = json!({"type": "solid", "color": {"model": "rgb", "r": 1.0, "g": 0.0, "b": 0.0}, "swatch": "Gone"}); + if let Some(def) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).char_styles.iter_mut().find(|d| d.name == "Body") { + def.attrs.insert("features".into(), json!(["zzzz", "dlig"])); + def.attrs.insert("fill".into(), linked.clone()); + } + let fill = s.doc().unwrap().doc.char_styles[0].attrs["fill"].clone(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": ["zzzz", "-dlig"], "fill": fill}})).unwrap(); + let def = s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone(); + assert_eq!(def["features"], json!(["zzzz", "-dlig"])); + let mut replaced = def.clone(); + replaced.insert("size".into(), json!(14.0)); + s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": replaced})).unwrap(); + s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": def})).unwrap(); + s.execute("charStyle.duplicate", &json!({"name": "Body"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Body copy").unwrap().attrs, def); + // A list longer than a style made here can have stays editable, but does not grow. + let long: Vec = (0..300).map(|i| if i % 2 == 0 { "dlig".to_string() } else { "-dlig".to_string() }).collect(); + if let Some(def) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).char_styles.iter_mut().find(|d| d.name == "Body") { + def.attrs.insert("features".into(), json!(long)); + } + let mut shorter = long.clone(); + shorter.pop(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": shorter}})).unwrap(); + let mut longer = shorter.clone(); + longer.extend(["swsh".to_string(), "salt".to_string()]); + let error = s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"features": longer}})).unwrap_err().to_string(); + assert!(error.contains("features lists at most 256 tags"), "{error}"); +} + #[test] fn editing_character_style_clears_removed_size_without_losing_local_override() { let (mut s, id) = session_with_text("One two"); diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 7f9ead375d..e2427af629 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -29,6 +29,31 @@ const SWITCHES: &[&str] = &["underline", "strikethrough", "standardVerticalRoman const ADVANCED: &[&str] = &["h_scale", "v_scale", "baseline_shift", "rotation", "language"]; /// The number fields of Advanced Character Formats. const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "rotation"]; +/// The attributes of Character Color. +const COLOR: &[&str] = &["fill", "stroke", "stroke_width", "overprint_fill", "overprint_stroke"]; +/// The fields of Character Color: the fill and stroke paints, their tints in percent, the stroke +/// weight in points and the two overprint checkboxes. +const COLOR_FIELDS: &[&str] = &["fill", "fill_tint", "stroke", "stroke_tint", "stroke_width", "overprint_fill", "overprint_stroke"]; +/// The on, off or unset checkboxes of OpenType Features and the feature tag each one sets. +const OT_SWITCHES: &[(&str, &str)] = &[ + ("ot_liga", "liga"), + ("ot_calt", "calt"), + ("ot_dlig", "dlig"), + ("ot_swsh", "swsh"), + ("ot_salt", "salt"), + ("ot_titl", "titl"), + ("ot_ordn", "ordn"), + ("ot_frac", "frac"), +]; +/// The feature tags the Figure menu sets. +const FIGURE_TAGS: [&str; 4] = ["tnum", "onum", "pnum", "lnum"]; +/// The values of the Figure field, in the order of the OpenType panel's Figure menu. +const FIGURE_VALUES: [&str; 5] = ["default", "tabularLining", "proportionalLining", "proportionalOldstyle", "tabularOldstyle"]; +/// The values of the Position field, in the order of the OpenType panel's Position menu. +const POSITION_VALUES: [&str; 5] = ["default", "superscript", "subscript", "numerator", "denominator"]; +/// The fields of OpenType Features. +const OT_FIELDS: &[&str] = + &["ot_figure", "ot_position", "ot_liga", "ot_calt", "ot_dlig", "ot_swsh", "ot_salt", "ot_titl", "ot_ordn", "ot_frac", "ot_sets"]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Character Style Options").into(), @@ -55,6 +80,24 @@ pub(super) const SPEC: DialogSpec = DialogSpec { "baseline_shift", "rotation", "language", + "fill", + "fill_tint", + "stroke", + "stroke_tint", + "stroke_width", + "overprint_fill", + "overprint_stroke", + "ot_figure", + "ot_position", + "ot_liga", + "ot_calt", + "ot_dlig", + "ot_swsh", + "ot_salt", + "ot_titl", + "ot_ordn", + "ot_frac", + "ot_sets", "section", ] }, @@ -73,6 +116,7 @@ pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { fields.insert("__smallCapsSize".into(), json!(doc.setup.small_caps_size)); fields.insert("__superscript".into(), json!(doc.setup.superscript)); fields.insert("__subscript".into(), json!(doc.setup.subscript)); + fields.insert("__swatches".into(), swatch_choices(doc)); fields.insert("section".into(), json!("general")); fields.insert("preview".into(), json!(true)); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); @@ -100,6 +144,71 @@ pub(crate) fn fields_from_attrs(attrs: &Map) -> Map Value { + if paint.get("swatch").is_some_and(Value::is_string) { + json!(vectorcraft_color::tint_percent(paint.get("tint").and_then(Value::as_f64).unwrap_or(1.0) as f32)) + } else { + json!("") + } +} + +/// The swatches Character Color offers, as `[name, paint]` pairs in the Swatches panel's order, the +/// built-in Registration swatch first: a global color or a tint of one as a paint linked to it, any +/// other solid color as that color. +pub(crate) fn swatch_choices(doc: &vectorcraft_doc::Document) -> Value { + let registration = vectorcraft_color::swatch::registration(); + let builtin = (!doc.swatches_iter().any(|w| w.name == registration.name)).then_some(registration); + let choices = builtin.into_iter().chain(doc.swatches_iter()).filter_map(|w| { + let paint = match (doc.swatch_link(&w.name), &w.paint) { + (Some((base, tint)), _) => doc.tint_paint(&base, tint)?, + (None, vectorcraft_color::Paint::Solid { .. }) => w.paint.clone(), + _ => return None, + }; + Some(json!([w.name, paint])) + }); + Value::Array(choices.collect()) +} + +/// A feature tag without its `-` or `+`. +fn bare(tag: &str) -> &str { + tag.trim_start_matches(['-', '+']) +} + +/// The OpenType Features fields for a style's `features`: each control is unset unless the list +/// names one of its tags, on or off. +fn opentype_fields(features: Option<&Value>) -> Map { + let tags: Vec<&str> = features.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + let names = |set: &[&str]| tags.iter().any(|t| set.contains(&bare(t))); + let f = vectorcraft_text::OtFeatures::from_tags(tags.iter().copied()); + let mut fields = Map::new(); + for (field, tag) in OT_SWITCHES { + let last = tags.iter().rev().find(|t| bare(t) == *tag); + fields.insert((*field).into(), last.map_or(Value::Null, |t| json!(!t.starts_with('-')))); + } + let figure = names(&FIGURE_TAGS).then(|| FIGURE_VALUES.get(crate::panels::opentype::figure(&f))).flatten(); + fields.insert("ot_figure".into(), figure.map_or(Value::Null, |v| json!(v))); + let position = + names(&crate::panels::opentype::POSITION_TAGS).then(|| crate::panels::opentype::position(&f).and_then(|i| POSITION_VALUES.get(i))).flatten(); + fields.insert("ot_position".into(), position.map_or(Value::Null, |v| json!(v))); + let sets: Vec = vectorcraft_text::EXTRA_FEATURES[..20] + .iter() + .filter_map(|set| tags.iter().rev().find(|t| bare(t) == *set).map(|t| if t.starts_with('-') { format!("-{set}") } else { set.to_string() })) + .collect(); + fields.insert("ot_sets".into(), if sets.is_empty() { Value::Null } else { json!(sets) }); fields } @@ -136,6 +245,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { "v_scale" => tl!("Vertical Scale"), "baseline_shift" => tl!("Baseline Shift"), "rotation" => tl!("Character Rotation"), + "fill_tint" | "stroke_tint" => tl!("Tint"), + "stroke_width" => tl!("Weight"), _ => return Err("unknown character style number field".into()), }; match d.fields.get(key) { @@ -160,6 +271,15 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { if key == "baseline_shift" && !(min..=max).contains(&n) { return Err(format!("{label} must be a number from {min} to {max}")); } + // Weight from 0 to the document limit, a tint from 0% to 100%. + let (min, max) = match key { + "stroke_width" => (0.0, max), + "fill_tint" | "stroke_tint" => (0.0, 100.0), + _ => (min, max), + }; + if ["stroke_width", "fill_tint", "stroke_tint"].contains(&key) && !(min..=max).contains(&n) { + return Err(format!("{label} must be a number from {min} to {max}")); + } // An angle from -180 to 180 degrees, as text.setFormat stores it. let n = if key == "rotation" { (n + 180.0).rem_euclid(360.0) - 180.0 } else { n }; Ok(Some(json!(n))) @@ -249,9 +369,121 @@ pub(crate) fn edited_attrs(d: &Dialog) -> Result, String> { } } advanced_attrs(d, &original, &original_fields, &mut attrs)?; + color_attrs(d, &original, &original_fields, &mut attrs)?; + opentype_attrs(d, &original, &original_fields, &mut attrs); Ok(attrs) } +/// Write the Character Color fields of `d` into `attrs`: an unset paint, weight or checkbox +/// leaves its attribute unset, and a field still as it opened keeps the original value, a +/// gradient or pattern paint included. +fn color_attrs( + d: &Dialog, + original: &Map, + original_fields: &Map, + attrs: &mut Map, +) -> Result<(), String> { + let reset = d.bool("__resetColor"); + for key in COLOR { + attrs.remove(*key); + } + let unchanged = |key: &str| !reset && d.fields.get(key) == original_fields.get(key); + for key in ["fill", "stroke"] { + let tint_key = format!("{key}_tint"); + if unchanged(key) && unchanged(&tint_key) { + if let Some(value) = original.get(key) { + attrs.insert(key.into(), value.clone()); + } + continue; + } + let Some(mut paint) = d.fields.get(key).filter(|v| v.is_object()).cloned() else { continue }; + if paint.get("swatch").is_some_and(Value::is_string) + && let Some(Value::Number(tint)) = optional_number(d, &tint_key)? + && let Some(tint) = tint.as_f64() + { + paint["tint"] = json!(tint / 100.0); + } + attrs.insert(key.into(), paint); + } + if unchanged("stroke_width") { + if let Some(value) = original.get("stroke_width") { + attrs.insert("stroke_width".into(), value.clone()); + } + } else if let Some(v) = optional_number(d, "stroke_width")? { + attrs.insert("stroke_width".into(), v); + } + for key in ["overprint_fill", "overprint_stroke"] { + let value = if unchanged(key) { original.get(key).cloned() } else { d.fields.get(key).filter(|v| v.is_boolean()).cloned() }; + if let Some(value) = value { + attrs.insert(key.into(), value); + } + } + Ok(()) +} + +/// The tags a Figure field value sets: its figure features on and the others off. +fn figure_tags(value: &str) -> &'static [&'static str] { + match value { + "tabularLining" => &["tnum", "lnum", "-onum", "-pnum"], + "proportionalLining" => &["pnum", "lnum", "-tnum", "-onum"], + "proportionalOldstyle" => &["onum", "pnum", "-tnum", "-lnum"], + "tabularOldstyle" => &["onum", "tnum", "-pnum", "-lnum"], + "default" => &["-tnum", "-onum", "-pnum", "-lnum"], + _ => &[], + } +} + +/// Write the OpenType Features fields of `d` into `attrs`. When every field is still as it +/// opened, the original `features` list stays as it is. Otherwise each changed control replaces +/// the tags it sets in the original list, which keeps every other tag, and an unset control +/// removes them; a list left empty leaves `features` unset. +fn opentype_attrs(d: &Dialog, original: &Map, original_fields: &Map, attrs: &mut Map) { + let reset = d.bool("__resetOpenType"); + attrs.remove("features"); + let unchanged = |key: &str| !reset && d.fields.get(key) == original_fields.get(key); + if OT_FIELDS.iter().all(|key| unchanged(key)) { + if let Some(value) = original.get("features") { + attrs.insert("features".into(), value.clone()); + } + return; + } + let mut tags: Vec = if reset { + vec![] + } else { + original.get("features").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect() + }; + for (field, tag) in OT_SWITCHES { + if !unchanged(field) { + tags.retain(|t| bare(t) != *tag); + if let Some(on) = d.fields.get(*field).and_then(Value::as_bool) { + tags.push(if on { (*tag).to_string() } else { format!("-{tag}") }); + } + } + } + if !unchanged("ot_figure") { + tags.retain(|t| !FIGURE_TAGS.contains(&bare(t))); + tags.extend(figure_tags(&d.str("ot_figure")).iter().map(|t| t.to_string())); + } + if !unchanged("ot_position") { + let position_tags = crate::panels::opentype::POSITION_TAGS; + tags.retain(|t| !position_tags.contains(&bare(t))); + if let Some(i) = POSITION_VALUES.iter().position(|v| *v == d.str("ot_position")) { + for (k, tag) in position_tags.iter().enumerate() { + tags.push(if k + 1 == i { (*tag).to_string() } else { format!("-{tag}") }); + } + } + } + if !unchanged("ot_sets") { + let sets = &vectorcraft_text::EXTRA_FEATURES[..20]; + tags.retain(|t| !sets.contains(&bare(t))); + let listed = d.fields.get("ot_sets").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str); + tags.extend(listed.filter(|t| sets.contains(&bare(t))).map(str::to_string)); + } + if !tags.is_empty() { + attrs.insert("features".into(), json!(tags)); + } +} + /// Write the Advanced Character Formats fields of `d` into `attrs`: a filled field sets its /// attribute, an empty one leaves it unset, and a field still as it opened keeps the original /// value, an explicit default or a language tag not in the list included. @@ -328,9 +560,27 @@ pub(crate) fn reset_advanced(d: &mut Dialog) { d.fields.insert("language".into(), Value::Null); } -/// Whether the section `d` shows has a Reset Panel: Basic or Advanced Character Formats. +/// Reset Panel in Character Color: its paints, tints, weight and overprint checkboxes become unset. +pub(crate) fn reset_color(d: &mut Dialog) { + d.fields.insert("__resetColor".into(), json!(true)); + for key in COLOR_FIELDS { + let unset = if ["fill_tint", "stroke_tint", "stroke_width"].contains(key) { json!("") } else { Value::Null }; + d.fields.insert((*key).into(), unset); + } +} + +/// Reset Panel in OpenType Features: every control becomes unset, and the style's `features` +/// with it. +pub(crate) fn reset_opentype(d: &mut Dialog) { + d.fields.insert("__resetOpenType".into(), json!(true)); + for key in OT_FIELDS { + d.fields.insert((*key).into(), Value::Null); + } +} + +/// Whether the section `d` shows has a Reset Panel: every section but General. pub(crate) fn can_reset(d: &Dialog) -> bool { - ["basic", "advanced"].contains(&d.str("section").as_str()) + ["basic", "advanced", "color", "opentype"].contains(&d.str("section").as_str()) } /// Reset Panel: clear the settings of the section `d` shows. @@ -338,6 +588,8 @@ pub(crate) fn reset_section(d: &mut Dialog) { match d.str("section").as_str() { "basic" => reset_basic(d), "advanced" => reset_advanced(d), + "color" => reset_color(d), + "opentype" => reset_opentype(d), _ => {} } } @@ -355,7 +607,13 @@ pub fn reset_panel(app: &mut VectorcraftApp) -> Result { /// The section list of Character Style Options and New Character Style. pub(crate) fn section_list(ui: &mut egui::Ui, d: &mut Dialog) { ui.vertical(|ui| { - for (id, label) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats")), ("advanced", tl!("Advanced Character Formats"))] { + for (id, label) in [ + ("general", tl!("General")), + ("basic", tl!("Basic Character Formats")), + ("advanced", tl!("Advanced Character Formats")), + ("color", tl!("Character Color")), + ("opentype", tl!("OpenType Features")), + ] { if ui.selectable_label(d.str("section") == id, label).clicked() { d.fields.insert("section".into(), json!(id)); } @@ -363,7 +621,7 @@ pub(crate) fn section_list(ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// The Reset Panel button, enabled on Basic and Advanced Character Formats. +/// The Reset Panel button, enabled on every section but General. pub(crate) fn reset_button(ui: &mut egui::Ui, d: &mut Dialog) { ui.add_enabled_ui(can_reset(d), |ui| { if ui.button(tl!("Reset Panel")).clicked() { @@ -471,6 +729,151 @@ pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { }); } +/// An on, off or unset checkbox in its own grid row: a click on unset turns it on, on turns it +/// off, and off makes it unset. +fn switch(ui: &mut egui::Ui, d: &mut Dialog, key: &str, caption: &str, enabled: bool) { + ui.label(""); + let value = d.fields.get(key).and_then(Value::as_bool); + if crate::widgets::check3(ui, caption, value, enabled) { + let next = match value { + None => json!(true), + Some(true) => json!(false), + Some(false) => Value::Null, + }; + d.fields.insert(key.into(), next); + } + ui.end_row(); +} + +/// The Fill or Stroke menu (`key`): unset, None, or a swatch of the document. A paint no swatch +/// gives (a gradient, a pattern, a color from a file) shows as its description and stays as it +/// is until another entry is chosen. +fn paint_choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str) { + let swatches: Vec<(String, Value)> = d + .fields + .get("__swatches") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|pair| Some((pair.get(0)?.as_str()?.to_string(), pair.get(1)?.clone()))) + .collect(); + let current = d.fields.get(key).cloned().unwrap_or(Value::Null); + let none = tl!("None"); + let shown = if current.is_null() { + String::new() + } else if current.get("type").and_then(Value::as_str) == Some("none") { + none.to_string() + } else if let Some((name, _)) = swatches.iter().find(|(_, paint)| *paint == current) { + name.clone() + } else if let Some((name, _)) = swatches.iter().find(|(_, paint)| paint.get("swatch").is_some_and(|s| Some(s) == current.get("swatch"))) { + name.clone() + } else { + serde_json::from_value::(current).map(|p| p.label()).unwrap_or_default() + }; + let options: Vec<&str> = [" ", none].into_iter().chain(swatches.iter().map(|(name, _)| name.as_str())).collect(); + if let Some(i) = crate::widgets::dropdown_names(ui, (KIND, key), &shown, &options, 190.0) { + let paint = match i { + 0 => Value::Null, + 1 => json!({"type": "none"}), + _ => swatches.get(i - 2).map_or(Value::Null, |(_, paint)| paint.clone()), + }; + d.fields.insert(format!("{key}_tint"), tint_field(&paint)); + d.fields.insert(key.into(), paint); + } +} + +/// Character Color: the Fill and Stroke paints, the Tint of a paint linked to a global swatch, +/// the stroke Weight and Overprint Fill and Overprint Stroke, each unset or set. +pub(crate) fn color_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("character-style-color").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + for (key, caption) in [("fill", tl!("Fill")), ("stroke", tl!("Stroke"))] { + ui.label(caption); + paint_choice(ui, d, key); + ui.end_row(); + let tint_key = format!("{key}_tint"); + ui.label(tl!("Tint")); + if d.fields.get(&tint_key).is_none_or(Value::is_null) { + d.fields.insert(tint_key.clone(), json!("")); + } + let linked = d.fields.get(key).and_then(|p| p.get("swatch")).is_some_and(Value::is_string); + ui.add_enabled_ui(linked, |ui| { + ui.horizontal(|ui| { + form::text(ui, d, &tint_key, 160.0); + ui.label("%"); + }); + }); + ui.end_row(); + } + ui.label(tl!("Weight")); + if d.fields.get("stroke_width").is_none_or(Value::is_null) { + d.fields.insert("stroke_width".into(), json!("")); + } + let stroked = d.fields.get("stroke").and_then(|p| p.get("type")).and_then(Value::as_str) != Some("none"); + ui.add_enabled_ui(stroked, |ui| { + ui.horizontal(|ui| { + form::text(ui, d, "stroke_width", 160.0); + ui.label("pt"); + }); + }); + ui.end_row(); + switch(ui, d, "overprint_fill", tl!("Overprint Fill"), true); + switch(ui, d, "overprint_stroke", tl!("Overprint Stroke"), true); + }); +} + +/// OpenType Features: the Figure and Position menus, the feature checkboxes and the stylistic +/// sets, each unset or set. +pub(crate) fn opentype_body(ui: &mut egui::Ui, d: &mut Dialog) { + let figures: Vec<(&str, &str)> = FIGURE_VALUES.into_iter().zip(crate::panels::opentype::FIGURES).collect(); + let positions: Vec<(&str, &str)> = POSITION_VALUES.into_iter().zip(crate::panels::opentype::POSITIONS).collect(); + egui::Grid::new("character-style-opentype").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + ui.label(tl!("Figure:")); + choice(ui, d, "ot_figure", &figures); + ui.end_row(); + ui.label(tl!("Position:")); + choice(ui, d, "ot_position", &positions); + ui.end_row(); + for (key, caption) in [ + ("ot_liga", tl!("Standard Ligatures")), + ("ot_calt", tl!("Contextual Alternates")), + ("ot_dlig", tl!("Discretionary Ligatures")), + ("ot_swsh", tl!("Swash")), + ("ot_salt", tl!("Stylistic Alternates")), + ("ot_titl", tl!("Titling Alternates")), + ("ot_ordn", tl!("Ordinals")), + ("ot_frac", tl!("Fractions")), + ] { + switch(ui, d, key, caption, true); + } + }); + ui.add_space(6.0); + ui.label(tl!("Stylistic Sets")); + // Each set is on (`ssNN`), off (`-ssNN`) or unset (not listed), as the other checkboxes are. + let mut listed: Vec = + d.fields.get("ot_sets").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + let mut clicked = None; + egui::Grid::new("character-style-sets").num_columns(5).spacing([12.0, 4.0]).show(ui, |ui| { + for (i, set) in vectorcraft_text::EXTRA_FEATURES[..20].iter().enumerate() { + let value = listed.iter().find(|t| bare(t) == *set).map(|t| !t.starts_with('-')); + if crate::widgets::check3(ui, set, value, true) { + clicked = Some((*set, value)); + } + if i % 5 == 4 { + ui.end_row(); + } + } + }); + if let Some((set, value)) = clicked { + listed.retain(|t| bare(t) != set); + match value { + None => listed.push(set.to_string()), + Some(true) => listed.push(format!("-{set}")), + Some(false) => {} + } + d.fields.insert("ot_sets".into(), if listed.is_empty() { Value::Null } else { json!(listed) }); + } +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.horizontal(|ui| { section_list(ui, d); @@ -480,6 +883,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { basic_body(ui, d); } else if d.str("section") == "advanced" { advanced_body(ui, d); + } else if d.str("section") == "color" { + color_body(ui, d); + } else if d.str("section") == "opentype" { + opentype_body(ui, d); } else { ui.horizontal(|ui| { ui.label(tl!("Style Name:")); @@ -841,6 +1248,221 @@ mod tests { assert!(!def.attrs.contains_key("v_scale")); } + /// The negated tags of the twenty stylistic sets: an explicit empty Stylistic Sets choice. + fn no_sets() -> Vec { + vectorcraft_text::EXTRA_FEATURES[..20].iter().map(|s| format!("-{s}")).collect() + } + + #[test] + fn color_and_opentype_fields_keep_unset_explicit_and_untouched_values() { + let d = dialog_for(json!({})); + for key in ["fill", "stroke", "overprint_fill", "overprint_stroke", "ot_figure", "ot_position", "ot_liga", "ot_frac", "ot_sets"] { + assert!(d.fields[key].is_null(), "{key}"); + } + assert_eq!((d.str("stroke_width"), d.str("fill_tint")), (String::new(), String::new())); + assert_eq!(edited_attrs(&d).unwrap(), Map::new()); + + let mut explicit = + vec!["-tnum", "-onum", "-pnum", "-lnum", "-sups", "-subs", "-numr", "-dnom", "-liga"].into_iter().map(String::from).collect::>(); + explicit.extend(no_sets()); + for original in [ + json!({"fill": {"type": "none"}, "stroke_width": 0.0, "overprint_fill": false, "features": explicit}), + json!({"stroke": {"type": "pattern", "pattern": "Dots"}, "fill": {"type": "solid", "color": {"model": "gray", "k": 0.5}}}), + json!({"features": ["zzzz", "dlig", "ss03"], "size": 9.0}), + ] { + let d = dialog_for(original.clone()); + assert_eq!(edited_attrs(&d).unwrap(), attrs(original.clone()), "{original}"); + } + let d = dialog_for(json!({"fill": {"type": "none"}, "overprint_fill": false, "features": explicit})); + assert_eq!(d.fields["fill"], json!({"type": "none"})); + assert_eq!(d.fields["overprint_fill"], json!(false)); + assert_eq!((d.str("ot_figure"), d.str("ot_position")), ("default".to_string(), "default".to_string())); + assert_eq!( + (d.fields["ot_liga"].clone(), d.fields["ot_dlig"].clone(), d.fields["ot_sets"].clone()), + (json!(false), Value::Null, json!(no_sets())) + ); + + // One changed control keeps every other tag, unknown ones included. + let mut d = dialog_for(json!({"features": ["zzzz", "dlig", "ss03"], "stroke": {"type": "pattern", "pattern": "Dots"}})); + assert_eq!((d.fields["ot_dlig"].clone(), d.fields["ot_sets"].clone()), (json!(true), json!(["ss03"]))); + d.fields.insert("ot_liga".into(), json!(false)); + d.fields.insert("overprint_stroke".into(), json!(true)); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"features": ["zzzz", "dlig", "ss03", "-liga"], "stroke": {"type": "pattern", "pattern": "Dots"}, "overprint_stroke": true})) + ); + d.fields.insert("ot_sets".into(), json!(["ss05", "ss03"])); + d.fields.insert("ot_figure".into(), json!("proportionalOldstyle")); + d.fields.insert("ot_position".into(), json!("numerator")); + d.fields.insert("ot_dlig".into(), Value::Null); + let features = edited_attrs(&d).unwrap()["features"].clone(); + // Sets the list leaves out stay unset, so text that uses the style keeps its own. + assert_eq!(features, json!(["zzzz", "-liga", "onum", "pnum", "-tnum", "-lnum", "-sups", "-subs", "numr", "-dnom", "ss05", "ss03"])); + let reopened = dialog_for(json!({"features": features})); + assert_eq!( + ["ot_figure", "ot_position", "ot_liga", "ot_dlig"].map(|k| reopened.fields[k].clone()), + [json!("proportionalOldstyle"), json!("numerator"), json!(false), Value::Null] + ); + assert_eq!(reopened.fields["ot_sets"], json!(["ss03", "ss05"])); + // Every control unset leaves the attribute unset. + let mut d = dialog_for(json!({"features": ["dlig"]})); + d.fields.insert("ot_dlig".into(), Value::Null); + assert_eq!(edited_attrs(&d).unwrap(), Map::new()); + } + + #[test] + fn color_tint_and_weight_outside_their_limits_are_errors() { + let linked = json!({"type": "solid", "color": {"model": "gray", "k": 0.5}, "swatch": "Ink"}); + for (key, value, message) in [ + ("fill_tint", "150", "Tint must be a number from 0 to 100"), + ("stroke_tint", "-1", "Tint must be a number from 0 to 100"), + ("stroke_width", "-1", "Weight must be a number from 0 to 4000000"), + ("stroke_width", "thick", "Weight must be a number"), + ] { + let mut d = dialog_for(json!({"fill": linked, "stroke": linked})); + d.fields.insert(key.into(), json!(value)); + assert_eq!(edited_attrs(&d).unwrap_err(), message, "{key} {value}"); + } + let mut d = dialog_for(json!({"fill": linked})); + assert_eq!(d.fields["fill_tint"], json!(100.0)); + d.fields.insert("fill_tint".into(), json!("40")); + d.fields.insert("stroke_width".into(), json!("1.5")); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"fill": {"type": "solid", "color": {"model": "gray", "k": 0.5}, "swatch": "Ink", "tint": 0.4}, "stroke_width": 1.5})) + ); + } + + #[test] + fn reset_panel_in_color_and_opentype_clears_only_that_section() { + let original = json!({"size": 12.0, "h_scale": 90.0, "fill": {"type": "none"}, "stroke_width": 2.0, "overprint_stroke": true, "features": ["dlig", "zzzz"]}); + let mut d = dialog_for(original.clone()); + d.fields.insert("section".into(), json!("color")); + assert!(can_reset(&d)); + reset_section(&mut d); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"size": 12.0, "h_scale": 90.0, "features": ["dlig", "zzzz"]}))); + let mut d = dialog_for(original); + d.fields.insert("section".into(), json!("opentype")); + reset_section(&mut d); + assert!(d.fields["ot_dlig"].is_null()); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"size": 12.0, "h_scale": 90.0, "fill": {"type": "none"}, "stroke_width": 2.0, "overprint_stroke": true})) + ); + d.fields.insert("ot_frac".into(), json!(true)); + assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["frac"])); + } + + #[test] + fn color_and_opentype_sections_show_their_controls() { + let mut d = dialog_for(json!({})); + let mut app = app(); + let shown = crate::tests_labels::painted_text(&mut app, |_, ui| section_list(ui, &mut d)); + for label in ["Character Color", "OpenType Features"] { + assert!(shown.contains(label), "{label}: {shown}"); + } + let shown = crate::tests_labels::painted_text(&mut app, |_, ui| color_body(ui, &mut d)); + for label in ["Fill", "Stroke", "Tint", "Weight", "Overprint Fill", "Overprint Stroke"] { + assert!(shown.contains(label), "{label}: {shown}"); + } + let shown = crate::tests_labels::painted_text(&mut app, |_, ui| opentype_body(ui, &mut d)); + for label in [ + "Figure:", + "Position:", + "Standard Ligatures", + "Contextual Alternates", + "Discretionary Ligatures", + "Swash", + "Stylistic Alternates", + "Titling Alternates", + "Ordinals", + "Fractions", + "Stylistic Sets", + "ss01", + "ss20", + ] { + assert!(shown.contains(label), "{label}: {shown}"); + } + assert!(!shown.contains("Small Caps"), "{shown}"); + } + + #[test] + fn color_and_features_preview_cancel_commit_and_new_style() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Brand", "color": "#2050a0", "global": true})).unwrap(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + let brand = json!(before.tint_paint("Brand", 1.0).unwrap()); + open(&mut app, "Body").unwrap(); + let choices = app.ui.dialog.as_ref().unwrap().fields["__swatches"].as_array().unwrap().clone(); + assert!(choices.contains(&json!(["Brand", brand]))); + let registration = vectorcraft_color::swatch::REGISTRATION; + assert_eq!(choices.first(), Some(&json!([registration, before.tint_paint(registration, 1.0).unwrap()]))); + let set = |app: &mut VectorcraftApp| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("color")); + d.fields.insert("fill".into(), brand.clone()); + d.fields.insert("stroke".into(), brand.clone()); + d.fields.insert("stroke_tint".into(), json!("40")); + d.fields.insert("stroke_width".into(), json!("2")); + d.fields.insert("overprint_fill".into(), json!(true)); + d.fields.insert("ot_dlig".into(), json!(true)); + d.fields.insert("ot_figure".into(), json!("tabularLining")); + }; + set(&mut app); + assert!(crate::menus::enabled(&app, "ui.charStyleOptions.resetPanel")); + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs["fill"], brand); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + open(&mut app, "Body").unwrap(); + set(&mut app); + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.history.undo.len(), undo + 1); + let tint40 = state.doc.tint_paint("Brand", 0.4).unwrap(); + let def = state.doc.char_styles[0].attrs.clone(); + assert_eq!(def["stroke"], json!(tint40)); + assert_eq!(def["features"], json!(["dlig", "tnum", "lnum", "-onum", "-pnum"])); + let vectorcraft_doc::NodeKind::Text(t) = &state.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + for run in &t.runs { + assert_eq!( + (run.style.fill.clone(), run.style.stroke.clone(), run.style.stroke_width), + (state.doc.tint_paint("Brand", 1.0).unwrap(), tint40.clone(), 2.0) + ); + assert_eq!(run.style.features, ["dlig", "tnum", "lnum", "-onum", "-pnum"]); + } + open(&mut app, "Body").unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["stroke_tint"].clone(), d.str("ot_figure")), (json!(40.0), "tabularLining".to_string())); + super::super::cancel(&mut app); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("ui.newCharStyle", json!({})).unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + assert!(d.fields["fill"].is_null() && d.fields["ot_sets"].is_null()); + d.fields.insert("name".into(), json!("Ink")); + d.fields.insert("section".into(), json!("opentype")); + d.fields.insert("ot_sets".into(), json!(["-ss02", "ss04"])); + d.fields.insert("ot_frac".into(), json!(false)); + } + assert!(crate::menus::enabled(&app, "ui.charStyleOptions.resetPanel")); + super::super::confirm(&mut app).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let def = doc.char_styles.iter().find(|def| def.name == "Ink").unwrap(); + assert_eq!(def.attrs["features"], json!(["-frac", "-ss02", "ss04"])); + let vectorcraft_doc::NodeKind::Text(t) = &doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(t.runs.iter().all(|r| r.style.style_name.as_deref() == Some("Body"))); + } + #[test] fn invalid_numbers_name_the_visible_field() { let mut d = Dialog::new(KIND, json!({})); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index ad839f345d..3a769670f5 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -42,6 +42,7 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result bool { super::char_style_options::basic_body(ui, d); } else if d.str("section") == "advanced" { super::char_style_options::advanced_body(ui, d); + } else if d.str("section") == "color" { + super::char_style_options::color_body(ui, d); + } else if d.str("section") == "opentype" { + super::char_style_options::opentype_body(ui, d); } else { ui.vertical(|ui| { grid(ui, |ui| { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 53a3ce1ef7..e8ca952958 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5986,6 +5986,11 @@ anchor Points: Punts: Horizontal Scale Escala horitzontal Vertical Scale Escala vertical @msg {label} must be a number from {min} to {max} {label} ha de ser un nombre de {min} a {max} + Character Color Color del caràcter + OpenType Features Funcions OpenType + Stylistic Sets Jocs estilístics +@msg features lists at most {max} tags features admet com a màxim {max} etiquetes +@msg unknown OpenType feature `{t}` funció OpenType desconeguda `{t}` @msg {label} must be a number above 0 and at most {max} {label} ha de ser un nombre superior a 0 i com a màxim {max} @msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e7afe3baf6..7f4beb00c1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6002,6 +6002,11 @@ anchor Points: Body: Horizontal Scale Vodorovná změna velikosti Vertical Scale Svislá změna velikosti @msg {label} must be a number from {min} to {max} {label} musí být číslo od {min} do {max} + Character Color Barva znaků + OpenType Features Funkce OpenType + Stylistic Sets Stylistické sady +@msg features lists at most {max} tags features obsahuje nejvýše {max} značek +@msg unknown OpenType feature `{t}` neznámá funkce OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musí být číslo větší než 0 a nejvýše {max} @msg no character style `{name}` styl znaků `{name}` neexistuje diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fe96b30fbc..6d39cdcdeb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5587,6 +5587,11 @@ anchor Points: Punkte: Horizontal Scale Horizontale Skalierung Vertical Scale Vertikale Skalierung @msg {label} must be a number from {min} to {max} {label} muss eine Zahl von {min} bis {max} sein + Character Color Zeichenfarbe + OpenType Features OpenType-Funktionen + Stylistic Sets Stilsätze +@msg features lists at most {max} tags features enthält höchstens {max} Tags +@msg unknown OpenType feature `{t}` unbekannte OpenType-Funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} muss eine Zahl über 0 und höchstens {max} sein @msg no character style `{name}` Zeichenformat `{name}` nicht gefunden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2a8c832706..644ebd5ee1 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5953,6 +5953,11 @@ anchor Points: Σημεία: Horizontal Scale Οριζόντια κλίμακα Vertical Scale Κατακόρυφη κλίμακα @msg {label} must be a number from {min} to {max} Το {label} πρέπει να είναι αριθμός από {min} έως {max} + Character Color Χρώμα χαρακτήρων + OpenType Features Χαρακτηριστικά OpenType + Stylistic Sets Στιλιστικά σύνολα +@msg features lists at most {max} tags Το features περιέχει έως {max} ετικέτες +@msg unknown OpenType feature `{t}` άγνωστο χαρακτηριστικό OpenType `{t}` @msg {label} must be a number above 0 and at most {max} Το {label} πρέπει να είναι αριθμός μεγαλύτερος από 0 και έως {max} @msg no character style `{name}` Δεν βρέθηκε το στυλ χαρακτήρων `{name}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index dedfa88e05..43bf0eac6d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5944,6 +5944,11 @@ anchor Points: Puntos: Horizontal Scale Escala horizontal Vertical Scale Escala vertical @msg {label} must be a number from {min} to {max} {label} debe ser un número de {min} a {max} + Character Color Color de los caracteres + OpenType Features Funciones OpenType + Stylistic Sets Conjuntos estilísticos +@msg features lists at most {max} tags features admite como máximo {max} etiquetas +@msg unknown OpenType feature `{t}` función OpenType desconocida `{t}` @msg {label} must be a number above 0 and at most {max} {label} debe ser un número mayor que 0 y como máximo {max} @msg no character style `{name}` No existe el estilo de carácter `{name}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d31f24261f..725e924dbd 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6032,6 +6032,11 @@ anchor Points: Pisteet: Horizontal Scale Vaakaskaalaus Vertical Scale Pystyskaalaus @msg {label} must be a number from {min} to {max} {label} on oltava luku {min} ja {max} väliltä + Character Color Merkin väri + OpenType Features OpenType-ominaisuudet + Stylistic Sets Tyylisarjat +@msg features lists at most {max} tags features sisältää enintään {max} tunnistetta +@msg unknown OpenType feature `{t}` tuntematon OpenType-ominaisuus `{t}` @msg {label} must be a number above 0 and at most {max} {label} on oltava luku, joka on yli 0 ja enintään {max} @msg no character style `{name}` Merkkityyliä `{name}` ei löytynyt diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3835db6e9c..b68eef31ca 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5997,6 +5997,11 @@ anchor Points: Points : Horizontal Scale Mise à l’échelle horizontale Vertical Scale Échelle verticale @msg {label} must be a number from {min} to {max} {label} doit être un nombre compris entre {min} et {max} + Character Color Couleur des caractères + OpenType Features Fonctions OpenType + Stylistic Sets Jeux stylistiques +@msg features lists at most {max} tags features contient au plus {max} balises +@msg unknown OpenType feature `{t}` fonction OpenType inconnue `{t}` @msg {label} must be a number above 0 and at most {max} {label} doit être un nombre supérieur à 0 et au plus égal à {max} @msg no character style `{name}` Style de caractère `{name}` introuvable diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 683bd329ea..70c29f4e22 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5986,6 +5986,11 @@ anchor Points: Pontok: Horizontal Scale Vízszintes méretezés Vertical Scale Függőleges méretezés @msg {label} must be a number from {min} to {max} {label} {min} és {max} közötti szám kell legyen + Character Color Karakterszín + OpenType Features OpenType-funkciók + Stylistic Sets Stíluskészletek +@msg features lists at most {max} tags a features legfeljebb {max} címkét tartalmazhat +@msg unknown OpenType feature `{t}` ismeretlen OpenType-funkció: `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0-nál nagyobb és legfeljebb {max} értékű szám kell legyen @msg no character style `{name}` A(z) `{name}` karakterstílus nem található diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d18977cdad..0b1ba1fafc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5621,6 +5621,11 @@ anchor Points: Punti: Horizontal Scale Scala orizzontale Vertical Scale Scala verticale @msg {label} must be a number from {min} to {max} {label} deve essere un numero da {min} a {max} + Character Color Colore carattere + OpenType Features Funzioni OpenType + Stylistic Sets Set stilistici +@msg features lists at most {max} tags features contiene al massimo {max} tag +@msg unknown OpenType feature `{t}` funzione OpenType sconosciuta `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve essere un numero maggiore di 0 e al massimo {max} @msg no character style `{name}` Stile di carattere `{name}` non trovato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f0cc99c69a..b0ce510828 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5686,6 +5686,11 @@ anchor Points: ポイント: Horizontal Scale 水平比率 Vertical Scale 垂直比率 @msg {label} must be a number from {min} to {max} {label} には {min} から {max} までの数値を指定してください + Character Color 文字カラー + OpenType Features OpenType 機能 + Stylistic Sets スタイルセット +@msg features lists at most {max} tags features に指定できるタグは {max} 個までです +@msg unknown OpenType feature `{t}` 不明な OpenType 機能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} には 0 より大きく {max} 以下の数値を指定してください @msg no character style `{name}` 文字スタイル `{name}` が見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8bcf813ccb..649aeb95c7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5990,6 +5990,11 @@ anchor Points: წერტილები: Horizontal Scale ჰორიზონტალური მასშტაბი Vertical Scale ვერტიკალური მასშტაბი @msg {label} must be a number from {min} to {max} {label} უნდა იყოს რიცხვი {min}-დან {max}-მდე + Character Color სიმბოლოს ფერი + OpenType Features OpenType შესაძლებლობები + Stylistic Sets სტილისტური ნაკრებები +@msg features lists at most {max} tags features შეიძლება შეიცავდეს არაუმეტეს {max} ტეგს +@msg unknown OpenType feature `{t}` უცნობი OpenType შესაძლებლობა `{t}` @msg {label} must be a number above 0 and at most {max} {label} უნდა იყოს 0-ზე მეტი და არაუმეტეს {max}-ისა რიცხვი @msg no character style `{name}` სიმბოლოს სტილი `{name}` ვერ მოიძებნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3031e5fc5a..f3efc9cbb3 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5582,6 +5582,11 @@ anchor Points: 포인트: Horizontal Scale 가로 비율 Vertical Scale 세로 비율 @msg {label} must be a number from {min} to {max} {label}은(는) {min}에서 {max} 사이의 숫자여야 합니다 + Character Color 문자 색상 + OpenType Features OpenType 기능 + Stylistic Sets 스타일 세트 +@msg features lists at most {max} tags features에는 태그를 최대 {max}개까지 지정할 수 있습니다 +@msg unknown OpenType feature `{t}` 알 수 없는 OpenType 기능 `{t}` @msg {label} must be a number above 0 and at most {max} {label}은(는) 0 초과 {max} 이하의 숫자여야 합니다 @msg no character style `{name}` 문자 스타일 `{name}`을 찾을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index bd65bde99b..bfa3d2c576 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5856,6 +5856,11 @@ anchor Points: Punkty: Horizontal Scale Skala pozioma Vertical Scale Skala pionowa @msg {label} must be a number from {min} to {max} {label} musi być liczbą od {min} do {max} + Character Color Kolor znaków + OpenType Features Funkcje OpenType + Stylistic Sets Zestawy stylistyczne +@msg features lists at most {max} tags features może zawierać najwyżej {max} znaczników +@msg unknown OpenType feature `{t}` nieznana funkcja OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} musi być liczbą większą od 0 i nie większą niż {max} @msg no character style `{name}` Nie znaleziono stylu znakowego `{name}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 576575cf61..3135901d47 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5918,6 +5918,11 @@ anchor Points: Pontos: Horizontal Scale Escala Horizontal Vertical Scale Escala Vertical @msg {label} must be a number from {min} to {max} {label} deve ser um número de {min} a {max} + Character Color Cor do Caractere + OpenType Features Recursos OpenType + Stylistic Sets Conjuntos Estilísticos +@msg features lists at most {max} tags features aceita no máximo {max} marcas +@msg unknown OpenType feature `{t}` recurso OpenType desconhecido `{t}` @msg {label} must be a number above 0 and at most {max} {label} deve ser um número maior que 0 e no máximo {max} @msg no character style `{name}` Estilo de caractere `{name}` não encontrado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 03dbb91d54..581cecc4fc 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5979,6 +5979,11 @@ anchor Points: Точки: Horizontal Scale Масштаб по горизонтали Vertical Scale Масштаб по вертикали @msg {label} must be a number from {min} to {max} {label} должно быть числом от {min} до {max} + Character Color Цвет символов + OpenType Features Функции OpenType + Stylistic Sets Стилистические наборы +@msg features lists at most {max} tags features содержит не более {max} тегов +@msg unknown OpenType feature `{t}` неизвестная функция OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} должно быть числом больше 0 и не более {max} @msg no character style `{name}` Стиль символов `{name}` не найден diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 94ed6a29ec..a5c492ff00 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6054,6 +6054,11 @@ shape Open Öppen Horizontal Scale Horisontell skala Vertical Scale Vertikal skala @msg {label} must be a number from {min} to {max} {label} måste vara ett tal från {min} till {max} + Character Color Teckenfärg + OpenType Features OpenType-funktioner + Stylistic Sets Stilistiska uppsättningar +@msg features lists at most {max} tags features får innehålla högst {max} taggar +@msg unknown OpenType feature `{t}` okänd OpenType-funktion `{t}` @msg {label} must be a number above 0 and at most {max} {label} måste vara ett tal över 0 och högst {max} @msg no character style `{name}` Teckenformatet `{name}` hittades inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6315c7fc00..f1058a6161 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5959,6 +5959,11 @@ anchor Points: Noktalar: Horizontal Scale Yatay Ölçek Vertical Scale Dikey Ölçek @msg {label} must be a number from {min} to {max} {label} {min} ile {max} arasında bir sayı olmalıdır + Character Color Karakter Rengi + OpenType Features OpenType Özellikleri + Stylistic Sets Stilistik Setler +@msg features lists at most {max} tags features en fazla {max} etiket içerebilir +@msg unknown OpenType feature `{t}` bilinmeyen OpenType özelliği `{t}` @msg {label} must be a number above 0 and at most {max} {label} 0'ın üzerinde ve en fazla {max} olan bir sayı olmalıdır @msg no character style `{name}` `{name}` karakter stili bulunamadı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4a3eabe4d4..ed181d4e5a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5601,6 +5601,11 @@ anchor Points: Точки: Horizontal Scale Масштаб по горизонталі Vertical Scale Масштаб за вертикаллю @msg {label} must be a number from {min} to {max} {label} має бути числом від {min} до {max} + Character Color Колір символів + OpenType Features Функції OpenType + Stylistic Sets Стилістичні набори +@msg features lists at most {max} tags features містить не більше {max} тегів +@msg unknown OpenType feature `{t}` невідома функція OpenType `{t}` @msg {label} must be a number above 0 and at most {max} {label} має бути числом більше 0 і не більше {max} @msg no character style `{name}` Стиль символів `{name}` не знайдено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9c8c731582..882c2d9d0b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5602,6 +5602,11 @@ anchor Points: Điểm: Horizontal Scale Tỷ lệ ngang Vertical Scale Tỷ lệ dọc @msg {label} must be a number from {min} to {max} {label} phải là một số từ {min} đến {max} + Character Color Màu ký tự + OpenType Features Tính năng OpenType + Stylistic Sets Bộ phong cách +@msg features lists at most {max} tags features chứa tối đa {max} thẻ +@msg unknown OpenType feature `{t}` tính năng OpenType không xác định `{t}` @msg {label} must be a number above 0 and at most {max} {label} phải là một số lớn hơn 0 và tối đa {max} @msg no character style `{name}` Không tìm thấy kiểu ký tự `{name}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1e6bdda750..a86bb6fcd7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5843,6 +5843,11 @@ anchor Points: 点: Horizontal Scale 水平缩放 Vertical Scale 垂直缩放 @msg {label} must be a number from {min} to {max} {label} 必须是 {min} 到 {max} 之间的数字 + Character Color 字符颜色 + OpenType Features OpenType 特性 + Stylistic Sets 风格集 +@msg features lists at most {max} tags features 最多包含 {max} 个标签 +@msg unknown OpenType feature `{t}` 未知的 OpenType 特性 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必须是大于 0 且不超过 {max} 的数字 @msg no character style `{name}` 找不到字符样式 `{name}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5cc7916df0..9e547232c7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5639,6 +5639,11 @@ anchor Points: 點: Horizontal Scale 水平縮放 Vertical Scale 垂直縮放 @msg {label} must be a number from {min} to {max} {label} 必須是 {min} 到 {max} 之間的數字 + Character Color 字元顏色 + OpenType Features OpenType 功能 + Stylistic Sets 風格集 +@msg features lists at most {max} tags features 最多包含 {max} 個標籤 +@msg unknown OpenType feature `{t}` 未知的 OpenType 功能 `{t}` @msg {label} must be a number above 0 and at most {max} {label} 必須是大於 0 且不超過 {max} 的數字 @msg no character style `{name}` 找不到字元樣式 `{name}` diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5f7dc201e8..f0446a7663 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -706,7 +706,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.charStyleOptions.resetPanel", "Reset Panel", "", - "{} clear the settings of the section shown, Basic Character Formats or Advanced Character Formats, in the open Character Style Options or New Character Style dialog; available only on those sections", + "{} clear the settings of the section shown, Basic Character Formats, Advanced Character Formats, Character Color or OpenType Features, in the open Character Style Options or New Character Style dialog; available only on those sections", ), ( "ui.newCharStyle", diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 1a7dad123c..d6c62a13d1 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -20,12 +20,12 @@ enum Flag { /// A checkbox row: label and the feature it toggles. type Toggle = (&'static str, Flag); -const FIGURES: [&str; 5] = ["Default Figure", "Tabular Lining", "Proportional Lining", "Proportional Oldstyle", "Tabular Oldstyle"]; +pub(crate) const FIGURES: [&str; 5] = ["Default Figure", "Tabular Lining", "Proportional Lining", "Proportional Oldstyle", "Tabular Oldstyle"]; -const POSITIONS: [&str; 5] = ["Default Position", "Superscript", "Subscript", "Numerator", "Denominator"]; +pub(crate) const POSITIONS: [&str; 5] = ["Default Position", "Superscript", "Subscript", "Numerator", "Denominator"]; /// The features the Position menu's entries after Default Position turn on, in menu order. -const POSITION_TAGS: [&str; 4] = ["sups", "subs", "numr", "dnom"]; +pub(crate) const POSITION_TAGS: [&str; 4] = ["sups", "subs", "numr", "dnom"]; /// The bit of [`OtFeatures::extra`] that turns `tag` on (0 for a tag outside [`EXTRA_FEATURES`]). fn extra_bit(tag: &str) -> u32 { @@ -51,7 +51,7 @@ impl Flag { /// The Figure menu entry `f` shows: Default Figure, Tabular Lining, Proportional Lining /// (`pnum` and `lnum`), Proportional Oldstyle or Tabular Oldstyle. -fn figure(f: &OtFeatures) -> usize { +pub(crate) fn figure(f: &OtFeatures) -> usize { let proportional_lining = extra_bit("pnum") | extra_bit("lnum"); match (f.tabular_figures, f.oldstyle_figures) { (false, false) if f.extra & proportional_lining == proportional_lining => 2, @@ -81,7 +81,7 @@ fn set_figure(f: &mut OtFeatures, i: usize) { /// The Position menu entry `f` shows: Superscript (`sups`), Subscript (`subs`), Numerator /// (`numr`) or Denominator (`dnom`) when `f` turns that one on, Default Position when it turns /// none of them on, and `None` when it turns on more than one. -fn position(f: &OtFeatures) -> Option { +pub(crate) fn position(f: &OtFeatures) -> Option { let mut on = POSITION_TAGS.iter().enumerate().filter(|(_, t)| f.extra & extra_bit(t) != 0).map(|(i, _)| i + 1); match (on.next(), on.next()) { (None, _) => Some(0), diff --git a/docs/mcp.md b/docs/mcp.md index c0aa26a31d..f18766a0a5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5473,19 +5473,39 @@ attribute map in one undo step. `to` is trimmed and must be unique. The command while preserving local overrides; Undo/Redo restores the definition and its users. The `charStyleOptions` dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning`, `tracking`, `case`, `position`, `underline`, `strikethrough`, `charAlign`, `h_scale`, `v_scale`, `baseline_shift`, `rotation`, -`language`, `section` (`general`, `basic` or `advanced`), and `preview`. An empty field leaves its +`language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, +`ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, +`ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. Advanced Character Formats holds `h_scale` and `v_scale` (percent, above 0 and at most 4000000), `baseline_shift` (points, -4000000 to 4000000), `rotation` (degrees, stored from -180 to 180) and `language` (a name or tag from Document Setup's languages; English: USA stores the explicit default `null`, and a tag not in the list that the style already has is kept). Language sets the language the characters are shaped in; it does not change hyphenation or spelling. +Character Color holds `fill` and `stroke` (a paint: `{"type": "none"}` or a solid color; the menu lists None and +the document's solid swatches, a global swatch or a tint of one as a paint linked to it), `fill_tint` and +`stroke_tint` (percent, 0 to 100, for a paint linked to a global swatch), `stroke_width` (points, 0 to 4000000) +and the `overprint_fill` and `overprint_stroke` checkboxes. A gradient or pattern paint the style already has is +kept until another paint is chosen. A paint linked to a global swatch takes the swatch's color at its tint, and +editing the swatch later updates the style and its text. `swatch.unused` counts a swatch a character style's fill or +stroke links to as used, whether or not text uses the style. +OpenType Features holds `ot_figure` (`default`, `tabularLining`, `proportionalLining`, `proportionalOldstyle` or +`tabularOldstyle`), `ot_position` (`default`, `superscript`, `subscript`, `numerator` or `denominator`), the on, +off or unset checkboxes `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn` and `ot_frac`, +and `ot_sets` (a list of stylistic sets `ss01` to `ss20`, each on, or off with a leading `-`, as in +`["ss02", "-ss05"]`; a set not listed is unset). They write the style's `features` list: a changed control +replaces only its own tags, so tags the dialog does not show stay, and Default Figure or Default Position stores +its features turned off, distinct from unset. +`charStyle.new`, `charStyle.setAttrs` and `charStyle.edit` reject a tint outside 0 to 1, a link to a swatch that is +not a global swatch of the document, a stroke weight outside 0 to 4000000, more than 256 feature tags and an +OpenType feature tag the shaper does not know, unless the style or the text it is made from already has that value. The New Character Style dialog accepts the same character fields and starts with the selected text's captured attributes. Without selected text, it starts with the character defaults for the interface language (including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. Without selected text, the New Paragraph Style dialog sends no `attrs`, and the engine gives the new style the paragraph defaults for the interface language. Reset Panel in Basic Character -Formats removes those fields from the definition, and Reset Panel in Advanced Character Formats removes its five. +Formats removes those fields from the definition, Reset Panel in Advanced Character Formats removes its five, Reset +Panel in Character Color removes its five attributes and Reset Panel in OpenType Features removes `features`. `ui.charStyleOptions.resetPanel {}` performs that reset for the section selected in either character-style dialog; it is disabled on General. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6337b50d2e..df438c4090 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -505,6 +505,7 @@ since 2026-10-01. - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (above 0% and at most 4,000,000%), Baseline Shift (-4,000,000 pt to 4,000,000 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) ("Adjust the Horizontal and Vertical Scale, Baseline Shift, Character Rotation, and Language options"). +- **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) ("Change the Character Color, Tint, Weight, and Overprint Fill or Stroke options"; "Set the Figure, Position, Ligatures, Alternates, Ordinals, or Fractions options") and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) ("In the Character Styles or Paragraph Styles panel, select OpenType Features"). - **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy ` copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Auto Leading outside the layout:** a paragraph's Justification… › Auto Leading () also sets the Leading the Character panel shows for Auto type (blank where the selected paragraphs differ), the leading the Alt+↑/↓ nudge (`type.step`) steps from, each paragraph's own, and the lines Fill with Placeholder Text counts in area type. Evidence: `ParaStyle::effective_leading` (`crates/doc/src/text.rs` test `paragraph_effective_leading_follows_auto_leading`), `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading`. From a5870433738c925459a5df9ac1e901221be8198e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 02:03:47 -0800 Subject: [PATCH 336/674] Blend: a dropped press keeps the object it picked and selected The press picks the first object and selects it on the button-down. A dropped press now keeps that pick with the selection, and still puts back the picks of earlier clicks. --- crates/tools/src/meshblend.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index b32986150c..a9f3928ec0 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -49,7 +49,7 @@ pub struct BlendTool { /// A blend was just made: the next click adds to it (the selected blend). chained: bool, /// `first` and `chained` when the button went down: a dropped press puts them back, unless - /// the press made a blend. + /// the press picked an object or made a blend. before_press: Option<(Option, bool)>, } @@ -109,7 +109,7 @@ impl Tool for BlendTool { vec![] } (None, Some((top, start))) => { - self.first = Some((top, start)); + (self.first, self.before_press) = (Some((top, start)), None); vec![Action::Exec("select.set".into(), json!({"ids": [top.0]}))] } (Some((a, sa)), Some((b, sb))) if a != b && cx.doc.node(a).is_some() => { @@ -162,8 +162,8 @@ impl Tool for BlendTool { vec![] } /// A dropped press puts back the object picked first and the blend being added to as they - /// were when the button went down, so the picks of earlier clicks stay and the press picks - /// nothing. A blend the press made stays made. + /// were when the button went down, so the picks of earlier clicks stay. An object the press + /// picked stays picked and selected, and a blend the press made stays made. fn drop_press(&mut self, _cx: &ToolContext) -> Vec { if let Some((first, chained)) = self.before_press.take() { (self.first, self.chained) = (first, chained); @@ -504,8 +504,9 @@ mod tests { assert!(esc(&mut BlendTool::default()).is_empty(), "nothing to drop"); } - /// A dropped press (a long touch, a canceled touch) picks nothing, keeps the pick an earlier - /// click made, and keeps adding to the blend just made: the next click blends with them. + /// A dropped press (a long touch, a canceled touch) keeps the pick an earlier click made and + /// keeps adding to the blend just made: the next click blends with them. A dropped press + /// that picked an object keeps that pick, as the object stays selected. #[test] fn a_dropped_press_keeps_the_blend_tools_first_pick() { let (mut d, a) = doc_with_rect(); @@ -530,10 +531,10 @@ mod tests { assert!(t.pointer(c, &ev(PointerKind::Up, x, y)).is_empty()); }; let mut t = BlendTool::default(); - dropped(&mut t, &c, 150.0, 150.0); - assert_eq!(t.first(&c), None, "a dropped first press picks nothing"); - t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0)); + assert_eq!(t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0)), vec![Action::Exec("select.set".into(), json!({"ids": [a.0]}))]); + assert!(t.drop_press(&c).is_empty()); t.pointer(&c, &ev(PointerKind::Up, 150.0, 150.0)); + assert_eq!(t.first(&c), Some((a, None)), "a dropped first press keeps the object it picked and selected"); // A second press on a, and a press on empty canvas, each dropped. dropped(&mut t, &c, 151.0, 151.0); dropped(&mut t, &c, 450.0, 450.0); From c79fd5c13245c66a2ab338265f09525e0c38ff77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 05:58:45 -0800 Subject: [PATCH 337/674] Character Styles: Style Options leaves Figure unset for figure tags no menu entry matches A style whose features turn on pnum or lnum alone, or pair a figure tag with one the shown entry turns off (onum with lnum, tnum with pnum), showed a Figure entry that does not match its tags. Choosing that entry then left the field unchanged, so the tags could not be cleared. Figure now opens unset for these lists, and choosing Default Figure writes -tnum, -onum, -pnum and -lnum. --- .../ui-egui/src/dialogs/char_style_options.rs | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index e2427af629..38c425a81b 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -189,7 +189,8 @@ fn bare(tag: &str) -> &str { } /// The OpenType Features fields for a style's `features`: each control is unset unless the list -/// names one of its tags, on or off. +/// names one of its tags, on or off. Figure is also unset when the list turns one of its tags on +/// or off against every Figure menu entry, for example `pnum` alone. fn opentype_fields(features: Option<&Value>) -> Map { let tags: Vec<&str> = features.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); let names = |set: &[&str]| tags.iter().any(|t| set.contains(&bare(t))); @@ -199,7 +200,11 @@ fn opentype_fields(features: Option<&Value>) -> Map { let last = tags.iter().rev().find(|t| bare(t) == *tag); fields.insert((*field).into(), last.map_or(Value::Null, |t| json!(!t.starts_with('-')))); } - let figure = names(&FIGURE_TAGS).then(|| FIGURE_VALUES.get(crate::panels::opentype::figure(&f))).flatten(); + let last_on = |tag: &str| tags.iter().rev().find(|t| bare(t) == tag).map(|t| !t.starts_with('-')); + let figure = names(&FIGURE_TAGS) + .then(|| FIGURE_VALUES.get(crate::panels::opentype::figure(&f))) + .flatten() + .filter(|v| figure_tags(v).iter().all(|t| last_on(bare(t)).is_none_or(|on| on != t.starts_with('-')))); fields.insert("ot_figure".into(), figure.map_or(Value::Null, |v| json!(v))); let position = names(&crate::panels::opentype::POSITION_TAGS).then(|| crate::panels::opentype::position(&f).and_then(|i| POSITION_VALUES.get(i))).flatten(); @@ -1310,6 +1315,21 @@ mod tests { assert_eq!(edited_attrs(&d).unwrap(), Map::new()); } + #[test] + fn figure_tags_no_menu_entry_matches_leave_the_figure_unset() { + for features in [json!(["pnum"]), json!(["lnum"]), json!(["onum", "lnum"]), json!(["tnum", "pnum"])] { + let mut d = dialog_for(json!({ "features": features })); + assert!(d.fields["ot_figure"].is_null(), "{features}"); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({ "features": features })), "{features}"); + d.fields.insert("ot_figure".into(), json!("default")); + assert_eq!(edited_attrs(&d).unwrap()["features"], json!(["-tnum", "-onum", "-pnum", "-lnum"]), "{features}"); + } + for (features, shown) in [(json!(["tnum"]), "tabularLining"), (json!(["-pnum"]), "default"), (json!(["pnum", "lnum"]), "proportionalLining")] + { + assert_eq!(dialog_for(json!({ "features": features })).str("ot_figure"), shown, "{features}"); + } + } + #[test] fn color_tint_and_weight_outside_their_limits_are_errors() { let linked = json!({"type": "solid", "color": {"model": "gray", "k": 0.5}, "swatch": "Ink"}); From 2c0ef0f24e912e3869317b51e52f621fe185ca27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 04:05:41 -0800 Subject: [PATCH 338/674] Window: Float in Window, Float All in Windows and Cascade float documents Window > Arrange > Float in Window (window.arrange.floatInWindow) moves the current document out of the tab strip into a floating window of its own, and Float All in Windows (window.arrange.floatAllInWindows), a new item, does so for every tabbed document. Cascade (window.arrange.cascade) floats every document and stacks the windows from the upper left of the document area to its lower right, 30 pt apart, in tab order. On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window, as floating panels are. While the control channel is attached, the windows also open inside the app's window, so ui.click, ui.drag and ui.screenshot reach them. The current document's window holds the canvas. The other windows, and the main window while the current document floats, draw their documents as Tile's panes do, and a press in one makes its document the current one. A document's OS window that takes the keyboard focus makes its document the current one, and keys typed there run the main window's shortcuts. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings floating documents back under the tabs, and Tile brings them back into its grid. Cascade is enabled with two or more documents, Float in Window while the current document is tabbed, Float All in Windows while any document is tabbed, and Consolidate All Windows while documents are tiled or floating. ui.inspect reports the floating documents. --- crates/ui-egui/src/app.rs | 19 +- crates/ui-egui/src/caches.rs | 2 + crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/panes.rs | 75 ++-- crates/ui-egui/src/canvas/panes/tests.rs | 2 +- crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/chrome/tabs.rs | 40 +- crates/ui-egui/src/control.rs | 3 + crates/ui-egui/src/doc_windows.rs | 497 +++++++++++++++++++++++ crates/ui-egui/src/doc_windows/tests.rs | 459 +++++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus/run.rs | 3 + crates/ui-egui/src/menus/state.rs | 15 +- crates/ui-egui/src/menus/tree.rs | 5 +- crates/ui-egui/src/menus/ui_commands.rs | 22 +- crates/ui-egui/src/panel_docking.rs | 5 +- crates/ui-egui/src/state.rs | 11 + docs/gaps.md | 3 +- docs/mcp.md | 16 +- docs/target-app-parity.md | 1 + 46 files changed, 1147 insertions(+), 62 deletions(-) create mode 100644 crates/ui-egui/src/doc_windows.rs create mode 100644 crates/ui-egui/src/doc_windows/tests.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 404eaa81b7..38b3c83d7c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -85,6 +85,7 @@ impl VectorcraftApp { hover_cursor: None, presented: None, panes: Default::default(), + windows: Default::default(), }, perf: Perf::default(), dock_rt: Default::default(), @@ -427,18 +428,31 @@ impl VectorcraftApp { } /// The canvas panel's body: the document tabs, the canvas (a pane for each document while - /// Window › Arrange › Tile is on) and the isolation bar over it. + /// Window › Arrange › Tile is on) and the isolation bar over it. While the current document is + /// in a floating window, the tab strip's document draws as a pane. pub(crate) fn canvas_area(&mut self, ui: &mut egui::Ui) { let t = theme::Tokens::get(ui.ctx()); ui.painter().rect_filled(ui.max_rect(), 0.0, t.pasteboard); if self.ui.screen_mode < 3 { chrome::doc_tabs(self, ui); } + self.canvas.windows.area = Some(ui.available_rect_before_wrap()); + let floats = crate::doc_windows::current_floats(self); if !canvas::tiled_area(self, ui) { - canvas::show(self, ui); + if floats { + let rect = ui.available_rect_before_wrap(); + if let Some(i) = crate::doc_windows::tab_document(self) + && canvas::pane(self, ui, i, rect) + { + chrome::show_document(self, i); + } + } else { + canvas::show(self, ui); + } } // Over the canvas inside the rulers, so the rulers and scroll bars stay uncovered. if self.ui.screen_mode < 3 + && !floats && !menus::home_showing(self) && let Some(area) = self.canvas_rect { @@ -510,6 +524,7 @@ impl VectorcraftApp { panels::library_panel::tidy(self); // The canvas and the panels: one docking layout. Tab hides the panels but not the canvas. egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui)); + crate::doc_windows::show(self, &ctx); dialogs::show(self, &ctx); updates_ui::show(self, &ctx); export_progress::show(self, &ctx); diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 1e50de2284..7361003777 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -60,6 +60,8 @@ pub struct CanvasCache { pub presented: Option, /// Window › Arrange › Tile: the renders the panes of the other documents draw. pub panes: canvas::Panes, + /// Window › Arrange › Float in Window: what the floating document windows keep between frames. + pub windows: crate::doc_windows::Windows, } /// [`CanvasCache::slices`]: the layout of the slices of (document uid, revision). diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index afcd2c37b7..065907b4fb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -61,7 +61,7 @@ use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; use overlays::selected_anchor; use overlays::{HandleLook, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; pub use panes::Panes; -pub(crate) use panes::{consolidate, tile, tiled_area}; +pub(crate) use panes::{consolidate, pane, tile, tiled_area}; use raster::{changed_pixels, pixel_region, upload}; pub(crate) use raster::{color_image, color_image_owned}; use task_bar::task_bar; diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 43e2e4e601..c9e8b1fe87 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -140,9 +140,11 @@ pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. +/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. The +/// documents in floating windows come back under the tabs for it. pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { app.sync_views(); + crate::doc_windows::dock_all(app); let n = app.session.documents().len(); app.ui.tiled = n > 0; if n > 0 { @@ -154,65 +156,80 @@ pub(crate) fn tile(app: &mut VectorcraftApp) -> Result Result { app.ui.tiled = false; + crate::doc_windows::dock_all(app); app.canvas.panes.clear(); - Ok(json!({"tiled": false})) + Ok(json!({"tiled": false, "floating": []})) } -/// Draw the document area as panes while Tile is on and more than one document is open, outside -/// the Home screen and Presentation Mode. False when it did not: the caller draws the canvas. +/// Draw the document area as panes while Tile is on and more than one document is under the tabs, +/// outside the Home screen and Presentation Mode. False when it did not: the caller draws the +/// canvas. The documents in floating windows have no pane. pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { - let n = app.session.documents().len(); - if n == 0 { + if app.session.documents().is_empty() { app.ui.tiled = false; } + let docked = crate::doc_windows::docked(app); + let n = docked.len(); let tiling = app.ui.tiled && n > 1 && app.ui.screen_mode < 3 && !crate::menus::home_showing(app); - let Some(active) = app.session.active_index().filter(|_| tiling) else { - if !app.canvas.panes.shown.is_empty() || !app.canvas.panes.last.is_empty() { + if !tiling { + // The floating windows draw their panes from the same renders. + if app.ui.floating.is_empty() && (!app.canvas.panes.shown.is_empty() || !app.canvas.panes.last.is_empty()) { app.canvas.panes.clear(); } + app.canvas.panes.last.clear(); return false; - }; + } + // The current document's pane is the canvas, unless it is in a floating window. + let active = app.session.active_index().filter(|a| docked.contains(a)); app.sync_views(); let live: Vec = app.session.documents().iter().map(|d| d.uid as usize).collect(); app.canvas.panes.shown.retain(|uid, _| live.contains(uid)); app.canvas.panes.pending.retain(|uid, _| live.contains(uid)); app.canvas.panes.fits.retain(|uid, _| live.contains(uid)); - // A document opened or closed changes the grid, and so does coming back to the panes from one - // document: each document fits its new pane. - if app.canvas.panes.last.len() != n { - for v in &mut app.views { - v.fitted = false; + // A document opened, closed, floated or docked changes the grid, and so does coming back to the + // panes from one document: each document fits its new pane. + if app.canvas.panes.last.iter().map(|(i, _)| *i).ne(docked.iter().copied()) { + for i in &docked { + if let Some(v) = app.views.get_mut(*i) { + v.fitted = false; + } } } let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells = cells(n, ui.available_rect_before_wrap()); - let areas: Vec = cells.iter().map(|c| view_rects(app, *c, ppp).1).collect(); + let cells: Vec<(usize, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let mut areas: Vec> = vec![None; app.session.documents().len()]; + for (i, cell) in &cells { + if let Some(a) = areas.get_mut(*i) { + *a = Some(view_rects(app, *cell, ppp).1); + } + } let unfitted = refit_resized(app, &areas); let mut activate = None; // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) // stays over them. - for (i, cell) in cells.iter().copied().enumerate().filter(|(i, _)| *i != active) { + for (i, cell) in cells.iter().copied().filter(|(i, _)| Some(*i) != active) { if pane(app, ui, i, cell) { activate = Some(i); } ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside); } - if let Some(cell) = cells.get(active).copied() { + if let Some((_, cell)) = cells.iter().copied().find(|(i, _)| Some(*i) == active) { let mut canvas = ui.new_child(egui::UiBuilder::new().max_rect(cell)); super::show(app, &mut canvas); ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); } // Note the fits this frame made, for `refit_resized`. for ((i, area), was_unfitted) in areas.iter().enumerate().zip(unfitted) { - if let (true, Some(v), Some(d)) = (was_unfitted, app.views.get(i).filter(|v| v.fitted), app.session.documents().get(i)) { + if let (Some(area), true, Some(v), Some(d)) = (area, was_unfitted, app.views.get(i).filter(|v| v.fitted), app.session.documents().get(i)) { app.canvas.panes.fits.insert(d.uid as usize, (area.size(), v.zoom, v.center)); } } - app.canvas.panes.last = cells.into_iter().enumerate().collect(); + app.canvas.panes.last = cells; if let Some(i) = activate { crate::chrome::show_document(app, i); } @@ -220,14 +237,15 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { } /// Unfit each document whose view is still where a pane fit left it when its view's area (in -/// `areas`, by document index) has changed size, as when the window or a panel is resized: it -/// fits its pane again. A view zoomed or scrolled since keeps its place. → which views are -/// unfitted now. -fn refit_resized(app: &mut VectorcraftApp, areas: &[egui::Rect]) -> Vec { +/// `areas`, by document index; None for a document without a pane) has changed size, as when the +/// window or a panel is resized: it fits its pane again. A view zoomed or scrolled since keeps its +/// place. → which views are unfitted now. +fn refit_resized(app: &mut VectorcraftApp, areas: &[Option]) -> Vec { let fits = &app.canvas.panes.fits; let docs = app.session.documents(); for ((v, d), area) in app.views.iter_mut().zip(docs).zip(areas) { - if let Some((size, zoom, center)) = fits.get(&(d.uid as usize)) + if let Some(area) = area + && let Some((size, zoom, center)) = fits.get(&(d.uid as usize)) && *size != area.size() && *zoom == v.zoom && *center == v.center @@ -251,8 +269,9 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, rect: egui::Rect) { /// The pane of document `i`, not the current one, in `cell`: its paper, art, grid, artboards, /// guides and selected objects, and its rulers and the room of the canvas's scroll bars, so the /// document stays where it is when the pane becomes the canvas. True when a press in the pane asks -/// for its document to become the current one. -fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect) -> bool { +/// for its document to become the current one. A floating document's window draws its document +/// with this too ([`crate::doc_windows`]). +pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect) -> bool { let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); let (full, rect) = view_rects(app, cell, ppp); diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 49bca99389..943734c0ea 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -151,7 +151,7 @@ fn consolidate_all_windows_shows_one_document_again() { app.run("window.arrange.tile", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); assert_eq!(panes(&app).0.len(), 2); - assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false})); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty() && app.canvas.panes.shown.is_empty()); assert_eq!(app.canvas_rect, Some(tabbed), "the current document fills the document area again"); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index c619748044..c65d0f5153 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -27,10 +27,10 @@ pub use hints::{hint_bar, hint_strings}; pub use status_bar::status_bar; #[cfg(test)] use status_bar::{StatusReadoutWidths, status_readouts}; -pub(crate) use tabs::show_document; #[cfg(test)] use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; +pub(crate) use tabs::{document_window_title, show_document}; /// The application bar's height, in points (compact, as in PhotoCraft). pub const APP_BAR_HEIGHT: f32 = 32.0; diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index cd0fad1f3c..d8b214e9f0 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -19,6 +19,12 @@ pub(super) fn doc_tab_title(app: &VectorcraftApp, i: usize, d: &vectorcraft_engi tab_title(d, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) } +/// The title of document `i`'s floating window ([`crate::doc_windows`]): its tab's title. +pub(crate) fn document_window_title(app: &VectorcraftApp, i: usize) -> Option { + let d = app.session.documents().get(i)?; + Some(doc_tab_title(app, i, d)) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -37,6 +43,8 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs /// taller, with larger titles. Tabs that don't fit are reached from a » button at the strip's /// right end, which lists every open document, and the active tab is always in view (#746). +/// Documents in floating windows have no tab ([`crate::doc_windows`]); while the current document +/// is in one, the tab of the document the strip shows is the highlighted one. pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; @@ -46,15 +54,16 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. - let active = app.session.active_index().filter(|_| app.ui.home.is_none()); - let tabs: Vec<(String, std::sync::Arc)> = app - .session - .documents() + let shown = crate::doc_windows::tab_document(app).filter(|_| app.ui.home.is_none()); + // The documents under the tabs, by index; `active` is the position of the highlighted one. + let docked = crate::doc_windows::docked(app); + let active = docked.iter().position(|i| Some(*i) == shown); + let tabs: Vec<(String, std::sync::Arc)> = docked .iter() - .enumerate() + .filter_map(|i| Some((*i, app.session.documents().get(*i)?))) .map(|(i, d)| { let title = doc_tab_title(app, i, d); - let color = if Some(i) == active { t.text_strong } else { t.text_dim }; + let color = if Some(i) == shown { t.text_strong } else { t.text_dim }; (title.clone(), ui.painter().layout_no_wrap(title, theme::semibold(title_size), color)) }) .collect(); @@ -66,11 +75,12 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let mut activate = None; let mut close = None; let mut hovering_art = false; - for (i, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { - if x + w > strip.left() + room && Some(i) != active { + for (k, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { + if x + w > strip.left() + room && Some(k) != active { break; } - let is_active = Some(i) == active; + let Some(&i) = docked.get(k) else { break }; + let is_active = Some(k) == active; let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); let resp = ui.interact(r, ui.scope_id().with(("tab", i)), Sense::click()); if is_active { @@ -95,10 +105,12 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { x += w; } crate::document_drag::finish_tabs(ui.ctx(), hovering_art); - // The » button: every open document, the active one checked. The list scrolls once it - // reaches the bottom of the window, so every document of a large session stays reachable - // (#4017). + // The » button: every open document, floating ones included, the active one checked. The list + // scrolls once it reaches the bottom of the window, so every document of a large session stays + // reachable (#4017). if overflow { + let current = app.session.active_index().filter(|_| app.ui.home.is_none()); + let titles: Vec = (0..app.session.documents().len()).map(|i| document_window_title(app, i).unwrap_or_default()).collect(); let more = egui::Rect::from_min_max(egui::pos2(strip.right() - MORE, strip.top()), egui::pos2(strip.right(), strip.bottom() - 1.0)); let resp = ui.interact(more, ui.scope_id().with("tabs-more"), Sense::click()); ui.painter().rect_filled(more, 0.0, if resp.hovered() { t.hover.gamma_multiply(0.4) } else { t.tab_strip }); @@ -106,8 +118,8 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let resp = resp.on_hover_text(tl!("Show all open documents")); egui::Popup::menu(&resp).show(|ui| { widgets::menu_scroll(ui, |ui| { - for (i, (title, _)) in tabs.iter().enumerate() { - if widgets::menu_item_name(ui, title, true, Some(i) == active) { + for (i, title) in titles.iter().enumerate() { + if widgets::menu_item_name(ui, title, true, Some(i) == current) { activate = Some(i); ui.close(); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c374b62eec..7f1c6cf039 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -200,6 +200,9 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "rect": [c.left(), c.top(), c.width(), c.height()], "active": app.session.active_index() == Some(*i), })).collect::>(), + // Window › Arrange › Float in Window: the documents in floating windows, by index. While + // the current one floats, `canvasRect` is in its window's coordinates. + "floating": (0..app.session.documents().len()).filter(|i| crate::doc_windows::is_floating(app, *i)).collect::>(), "window": [r.width(), r.height()], "documents": app.session.documents().iter().map(|d| json!({"title": d.title(), "dirty": d.is_dirty()})).collect::>(), "activeDocument": app.session.active_index(), diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs new file mode 100644 index 0000000000..24fa105c3b --- /dev/null +++ b/crates/ui-egui/src/doc_windows.rs @@ -0,0 +1,497 @@ +//! Window › Arrange › Float in Window, Float All in Windows and Cascade: documents in floating +//! windows of their own, out of the tab strip, until Consolidate All Windows. On the desktop each +//! window is an OS window; on the web, on Wayland and wherever egui draws every viewport inside +//! the main window, it is a window inside the app's window, as floating panels are +//! ([`crate::panel_docking`]). The current document's window holds the canvas +//! ([`crate::canvas::show`]); each other window draws its document as a Tile pane does +//! ([`crate::canvas::pane`]), and a press in it makes its document the current one. + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; + +/// How far apart Cascade sets the windows, down and to the right, in points. +pub(crate) const CASCADE_STEP: f32 = 30.0; +/// How far the first cascaded window is from the document area's top-left corner, in points. +const CASCADE_MARGIN: f32 = 24.0; +/// The smallest size of a document window, in points. +const MIN_SIZE: egui::Vec2 = egui::vec2(240.0, 180.0); + +/// A document in a floating window. +#[derive(Clone, Debug)] +pub struct DocWindow { + /// The document ([`vectorcraft_engine::DocState::uid`]). + pub uid: u64, + /// Where the window goes, in the main window's points. + pub place: egui::Rect, + /// Counts the moves Cascade gives the window after it opened. + generation: u32, + /// The OS window's position on the screen when it opened or last moved, and the generation of + /// that move. Repeated each frame, so egui sees an unchanged window. + screen: Option<(egui::Pos2, u32)>, + /// Its OS window had the keyboard focus in the last frame. + focused: bool, + /// Where the last frame drew its document, in its window's coordinates. + pub(crate) body: Option, + /// The size of the body its document was last fitted to, and the zoom and center that fit + /// gave: a window resized while its view is still there fits its document again. + fit: Option, +} + +/// [`DocWindow::fit`]: a body size, and a view's zoom and center. +type Fit = (egui::Vec2, f64, vectorcraft_geom::Point); + +impl DocWindow { + fn new(uid: u64, place: egui::Rect) -> Self { + Self { uid, place, generation: 0, screen: None, focused: false, body: None, fit: None } + } +} + +/// What the document windows keep between frames. +#[derive(Default)] +pub struct Windows { + /// The document area of the main window (the tabs and the canvas) in its last frame. + pub(crate) area: Option, + /// The current document (its uid) when the windows were last drawn: a floating document that + /// becomes the current one comes to the front. + current: Option, + /// While Presentation Mode is on: the floating documents (their uids) it has shown. + presented: Option>, +} + +/// Whether document `i` is in a floating window. +pub(crate) fn is_floating(app: &VectorcraftApp, i: usize) -> bool { + app.session.documents().get(i).is_some_and(|d| app.ui.floating.iter().any(|w| w.uid == d.uid)) +} + +/// The documents under the tab strip, by index, in tab order. +pub(crate) fn docked(app: &VectorcraftApp) -> Vec { + (0..app.session.documents().len()).filter(|i| !is_floating(app, *i)).collect() +} + +/// The document the tab strip shows: the current one when it is under the tabs, else the tabbed +/// document that was current last, else the first tabbed one. +pub(crate) fn tab_document(app: &VectorcraftApp) -> Option { + let docked = docked(app); + let active = app.session.active_index(); + if let Some(a) = active.filter(|a| docked.contains(a)) { + return Some(a); + } + let last = app.ui.tab_document.and_then(|uid| app.session.documents().iter().position(|d| d.uid == uid)); + last.filter(|i| docked.contains(i)).or(docked.first().copied()) +} + +/// Whether the current document is in a floating window, outside the Home screen and Presentation +/// Mode: the main window's canvas then draws the tab strip's document as a pane. +pub(crate) fn current_floats(app: &VectorcraftApp) -> bool { + app.session.active_index().is_some_and(|i| is_floating(app, i)) && !crate::menus::home_showing(app) && !presenting(app) +} + +/// Whether Presentation Mode is on: the main window shows the current document, and the floating +/// windows are hidden until it ends. +fn presenting(app: &VectorcraftApp) -> bool { + app.ui.screen_mode >= 3 +} + +/// The places Cascade gives `n` windows in `area`: each the same size, the first near the area's +/// top-left corner and each next one [`CASCADE_STEP`] further down and to the right, starting +/// again at the corner when the next one would leave the area. Every place lies inside `area`. +pub(crate) fn cascade_places(area: egui::Rect, n: usize) -> Vec { + let size = (area.size() * 0.6).max(MIN_SIZE).min(area.size()); + let room = (area.size() - size).min_elem().max(0.0); + let steps = if room > CASCADE_MARGIN { ((room - CASCADE_MARGIN) / CASCADE_STEP).floor() as usize + 1 } else { 1 }; + (0..n) + .map(|k| { + let offset = (CASCADE_MARGIN + (k % steps) as f32 * CASCADE_STEP).min(room); + egui::Rect::from_min_size(area.min + egui::vec2(offset, offset), size) + }) + .collect() +} + +/// The document area windows open in: the main window's last one, else a 1200 × 800 area. +fn area(app: &VectorcraftApp) -> egui::Rect { + app.canvas.windows.area.filter(|r| r.is_positive()).unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))) +} + +/// Float documents `docs` (indices), each at the next cascade place after the windows already +/// open. Each fits its window. +fn float(app: &mut VectorcraftApp, docs: &[usize]) { + app.sync_views(); + let first = app.ui.floating.len(); + let places = cascade_places(area(app), first + docs.len()); + for (k, i) in docs.iter().enumerate() { + let Some(uid) = app.session.documents().get(*i).map(|d| d.uid) else { continue }; + if app.ui.floating.iter().any(|w| w.uid == uid) { + continue; + } + let place = places.get(first + k).copied().unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, MIN_SIZE)); + app.ui.floating.push(DocWindow::new(uid, place)); + if let Some(v) = app.views.get_mut(*i) { + v.fitted = false; + } + } + if !docs.is_empty() { + app.ui.home = None; + } +} + +/// The floating documents' indices, in the order their windows opened. +fn floating_indices(app: &VectorcraftApp) -> Vec { + app.ui.floating.iter().filter_map(|w| app.session.documents().iter().position(|d| d.uid == w.uid)).collect() +} + +/// `window.arrange.floatInWindow`: the current document leaves the tab strip for a floating window +/// of its own. A document already floating stays where it is. Returns `{floating}`. +pub(crate) fn float_in_window(app: &mut VectorcraftApp) -> Result { + if let Some(i) = app.session.active_index().filter(|i| !is_floating(app, *i)) { + float(app, &[i]); + } + Ok(json!({ "floating": floating_indices(app) })) +} + +/// `window.arrange.floatAllInWindows`: every document under the tab strip goes to a floating window +/// of its own. Returns `{floating}`. +pub(crate) fn float_all(app: &mut VectorcraftApp) -> Result { + let docked = docked(app); + float(app, &docked); + Ok(json!({ "floating": floating_indices(app) })) +} + +/// `window.arrange.cascade`: every document in a floating window, the windows stacked from the +/// document area's upper left to its lower right in tab order, each fitted to its window, the +/// current document's in front. Returns `{floating}`. +pub(crate) fn cascade(app: &mut VectorcraftApp) -> Result { + app.ui.tiled = false; + let docked = docked(app); + float(app, &docked); + let order: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + app.ui.floating.sort_by_key(|w| order.iter().position(|u| *u == w.uid)); + let places = cascade_places(area(app), app.ui.floating.len()); + for (w, place) in app.ui.floating.iter_mut().zip(places) { + w.place = place; + w.generation += 1; + } + for v in &mut app.views { + v.fitted = false; + } + // The current document's window comes to the front. + app.canvas.windows.current = None; + Ok(json!({ "floating": floating_indices(app) })) +} + +/// Every floating document back under the tab strip ([`crate::canvas::consolidate`], Tile), each +/// fitted to where it shows. +pub(crate) fn dock_all(app: &mut VectorcraftApp) { + let floating = floating_indices(app); + for i in floating { + if let Some(v) = app.views.get_mut(i) { + v.fitted = false; + } + } + app.ui.floating.clear(); +} + +/// Whether the floating windows are OS windows: egui runs viewports of their own, the session is +/// not Wayland, where the main window cannot learn where its other windows are (craft-ui's docking +/// floats panels by the same rule), and no control channel is attached. With a control channel the +/// windows stay inside the main window, where `ui.click`, `ui.drag` and `ui.screenshot` reach them +/// and `canvasRect` is in the main window's coordinates. +fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + if ctx.embed_viewports() || app.control_rx.is_some() { + return false; + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] + { + let set = |name: &str| std::env::var_os(name).is_some_and(|v| !v.is_empty()); + if set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET") { + // Under XWayland the main window reports where it is. + return ctx.input_for(egui::ViewportId::ROOT, |i| i.viewport().outer_rect.is_some()); + } + } + true +} + +/// The OS window of document window `uid`. +fn viewport_id(uid: u64) -> egui::ViewportId { + egui::ViewportId::from_hash_of(("vectorcraft-document-window", uid)) +} + +/// The id of document window `w` inside the main window: a new one for each Cascade move, so egui +/// opens it at its new place and size. +fn window_id(w: &DocWindow) -> egui::Id { + egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation)) +} + +/// What happened in a document window this frame. +#[derive(Default)] +struct Shown { + /// Its close button was pressed. + close: bool, + /// Its document asks to become the current one. + activate: bool, + /// Its OS window has the keyboard focus. + focused: bool, + /// Where it drew its document. + body: Option, + /// [`DocWindow::fit`] after this frame. + fit: Option, +} + +/// Draw the floating document windows, after the main window's canvas. Call once per frame from +/// the main window. +pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + let live: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + app.ui.floating.retain(|w| live.contains(&w.uid)); + let current = app.session.active().map(|d| d.uid); + if let Some(uid) = current.filter(|u| !app.ui.floating.iter().any(|w| w.uid == *u)) { + app.ui.tab_document = Some(uid); + } + // Presentation Mode fits each floating document it shows to the main window: back in their + // floating windows, those documents fit their windows again. + let presenting = presenting(app); + if presenting { + let shown = app.canvas.windows.presented.get_or_insert_default(); + if let Some(uid) = current.filter(|u| app.ui.floating.iter().any(|w| w.uid == *u) && !shown.contains(u)) { + shown.push(uid); + if let Some(v) = app.session.active_index().and_then(|i| app.views.get_mut(i)) { + v.fitted = false; + ctx.request_repaint(); + } + } + } else if let Some(shown) = app.canvas.windows.presented.take() { + for (d, v) in app.session.documents().iter().zip(app.views.iter_mut()) { + if shown.contains(&d.uid) { + v.fitted = false; + } + } + } + // While Presentation Mode hides the windows, `current` keeps the document whose window was in + // front, so a document made current meanwhile comes to the front when it ends. + if presenting { + return; + } + if app.ui.floating.is_empty() { + app.canvas.windows.current = current; + return; + } + let raise = current.filter(|u| app.canvas.windows.current != Some(*u)); + let native = native(app, ctx); + // Windows inside the main window that come back (after Presentation Mode) all go to the front + // in their old order, so the raise waits for the next frame. + let returning = !native + && app.ui.floating.iter().any(|w| { + let layer = egui::LayerId::new(egui::Order::Middle, window_id(w)); + ctx.memory(|m| m.area_rect(layer.id).is_some() && !m.areas().visible_last_frame(&layer)) + }); + if raise.is_some() && returning { + ctx.request_repaint(); + } else { + app.canvas.windows.current = current; + } + #[cfg(not(target_arch = "wasm32"))] + if native { + input::register(ctx, app.services.native_input_hook.clone(), app.ui.floating.iter().map(|w| viewport_id(w.uid)).collect()); + } + // While a dialog or other modal is open the windows take no input, as the main window behind + // it takes none: each draws its document as a pane, the current one included. + let blocked = crate::panel_docking::modal_open(app, ctx); + let mut close = None; + let mut activate = None; + for w in app.ui.floating.clone() { + let Some(i) = app.session.documents().iter().position(|d| d.uid == w.uid) else { continue }; + let shown = if native { + os_window(app, ctx, &w, (i, blocked), raise == Some(w.uid)) + } else { + app_window(app, ctx, &w, (i, blocked), raise == Some(w.uid)) + }; + if blocked { + continue; + } + if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) { + // The OS window took the keyboard: its document becomes the current one. + if shown.focused && !win.focused && app.session.active_index() != Some(i) { + activate = Some(i); + } + win.focused = shown.focused; + win.body = shown.body; + win.fit = shown.fit; + } + if shown.close { + close = Some(i); + } else if shown.activate && app.session.active_index() != Some(i) { + activate = Some(i); + } + } + if let Some(i) = close { + // The save prompt opens in the main window. + if let Err(e) = crate::unsaved::close(app, i) { + app.status(e); + } + if native && app.ui.dialog.is_some() { + ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); + } + } else if let Some(i) = activate { + crate::chrome::show_document(app, i); + app.canvas.windows.current = app.session.active().map(|d| d.uid); + } +} + +/// Document `i`'s window body in `ui`: the canvas for the current document, else (and while +/// `blocked` by a modal) a pane. The document fits the body again when the body changed size since +/// `fit` and its view has not moved. → whether a press in the pane asks for its document to become +/// the current one, the body's rect and the fit after this frame. +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (i, blocked): (usize, bool), fit: Option) -> (bool, egui::Rect, Option) { + let t = crate::theme::Tokens::get(ui.ctx()); + let rect = ui.available_rect_before_wrap(); + ui.painter().rect_filled(rect, 0.0, t.pasteboard); + if let (Some(v), Some((size, zoom, center))) = (app.views.get_mut(i), fit) + && size != rect.size() + && zoom == v.zoom + && center == v.center + { + v.fitted = false; + } + let was_fitted = app.views.get(i).is_some_and(|v| v.fitted); + let pressed = if !blocked && app.session.active_index() == Some(i) && !crate::menus::home_showing(app) { + crate::canvas::show(app, ui); + false + } else { + crate::canvas::pane(app, ui, i, rect) + }; + ui.advance_cursor_after_rect(rect); + let fit = match app.views.get(i) { + Some(v) if v.fitted && !was_fitted => Some((rect.size(), v.zoom, v.center)), + _ => fit, + }; + (pressed, rect, fit) +} + +/// Document `i`'s window `w` as an OS window of its own, `blocked` by a modal or not; `raise` +/// brings it to the front. +fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { + let vid = viewport_id(w.uid); + let origin = ctx.input(|inp| inp.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO); + let screen = match w.screen { + Some((pos, generation)) if generation == w.generation => pos, + moved => { + let pos = origin + w.place.min.to_vec2(); + if moved.is_some() { + ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::OuterPosition(pos)); + ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::InnerSize(w.place.size())); + } + if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) { + win.screen = Some((pos, w.generation)); + } + pos + } + }; + if raise { + ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::Focus); + } + let title = crate::chrome::document_window_title(app, i).unwrap_or_default(); + let builder = + egui::ViewportBuilder::default().with_title(title).with_position(screen).with_inner_size(w.place.size()).with_min_inner_size(MIN_SIZE); + let mut forwarded = (Vec::new(), None); + let shown = ctx.show_viewport_immediate(vid, builder, |ui, _| { + let (close, focused) = ui.input(|inp| (inp.viewport().close_requested(), inp.viewport().focused == Some(true))); + if close { + // The OS window stays until its document closes, which stops drawing it: a save prompt + // or a modal can keep the document open. + ui.ctx().send_viewport_cmd(egui::ViewportCommand::CancelClose); + } + let (activate, rect, fit) = body(app, ui, (i, blocked), w.fit); + // Keys the window's widgets left over run the main window's shortcuts and tool keys, as a + // floating panel's do. + if !blocked && !ui.memory(|m| m.focused().is_some()) { + forwarded = ui.input(|inp| { + let events: Vec = inp + .events + .iter() + .filter(|e| { + matches!(e, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_)) + }) + .cloned() + .collect(); + (events, Some(inp.modifiers)) + }); + } + Shown { close, activate, focused, body: Some(rect), fit } + }); + if !forwarded.0.is_empty() { + crate::panel_docking::forward_keys(app, ctx, forwarded.0, forwarded.1); + } + shown +} + +/// Document `i`'s window `w` as a window inside the main window, `blocked` by a modal or not; +/// `raise` brings it to the front. +fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { + let id = window_id(w); + if raise { + ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); + } + let title = crate::chrome::document_window_title(app, i).unwrap_or_default(); + let mut open = true; + let (mut activate, mut rect, mut fit) = (false, None, w.fit); + let frame = egui::Frame::window(&ctx.global_style()).inner_margin(0.0); + let shown = egui::Window::new(title) + .id(id) + .default_rect(w.place) + .min_size(MIN_SIZE) + .collapsible(false) + .resizable(true) + .constrain_to(ctx.content_rect()) + .frame(frame) + .open(&mut open) + .show(ctx, |ui| { + let (pressed, r, f) = body(app, ui, (i, blocked), fit); + (activate, rect, fit) = (pressed, Some(r), f); + }); + // A press on its title bar or edges, which brings the window to the front, also makes its + // document the current one. + activate |= shown.is_some_and(|s| s.response.contains_pointer()) && ctx.input(|inp| inp.pointer.any_pressed()); + Shown { close: !open, activate, focused: false, body: rect, fit } +} + +/// The host's rewrites of raw input ([`crate::services::Services::native_input_hook`]) for the +/// document windows' OS windows: eframe runs the host's hook for the main window only. +#[cfg(not(target_arch = "wasm32"))] +mod input { + use std::collections::HashSet; + + use crate::services::NativeInputHook; + + /// Runs the hook on the input of the document windows' OS windows. + #[derive(Default)] + struct DocumentWindowInput { + hook: Option, + windows: HashSet, + } + + impl egui::Plugin for DocumentWindowInput { + fn debug_name(&self) -> &'static str { + "vectorcraft document windows input" + } + + fn input_hook(&mut self, _: &egui::Context, input: &mut egui::RawInput) { + if let Some(hook) = self.hook.as_ref().filter(|_| self.windows.contains(&input.viewport_id)) { + hook(input); + } + } + } + + /// Run `hook` on the input of `windows` from their next frame on. + pub(super) fn register(ctx: &egui::Context, hook: Option, windows: HashSet) { + if hook.is_none() && ctx.with_plugin(|_: &mut DocumentWindowInput| ()).is_none() { + return; + } + ctx.add_plugin(DocumentWindowInput::default()); + ctx.with_plugin(|p: &mut DocumentWindowInput| { + p.hook = hook; + p.windows = windows; + }); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs new file mode 100644 index 0000000000..f49728e954 --- /dev/null +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -0,0 +1,459 @@ +use egui::{Pos2, Shape, pos2, vec2}; +use vectorcraft_engine::Session; + +use super::*; +use crate::menus::enabled; + +/// An app with `n` new 400 × 300 pt documents, the last one current. +fn app_with(n: usize) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for _ in 0..n { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + } + app +} + +/// One headless frame of the canvas panel's body (the tabs and the canvas or panes) on a +/// 1200 × 800 window, then the floating document windows, which egui draws inside the window → +/// the shapes it drew, `Shape::Vec`s flattened. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), + max_texture_side: Some(8192), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + app.canvas_area(ui); + show(app, ui.ctx()); + }); + out.textures_delta.clear(); + let mut shapes = vec![]; + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes)); + shapes +} + +fn button(pos: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A press and release at `pos`, then a frame to settle. +fn click(app: &mut VectorcraftApp, ctx: &egui::Context, pos: Pos2) { + frame(app, ctx, vec![egui::Event::PointerMoved(pos), button(pos, true)]); + frame(app, ctx, vec![button(pos, false)]); + frame(app, ctx, vec![]); +} + +/// Where the last frame drew document `i`'s window body. +fn body_of(app: &VectorcraftApp, i: usize) -> egui::Rect { + let uid = app.session.documents()[i].uid; + app.ui.floating.iter().find(|w| w.uid == uid).and_then(|w| w.body).unwrap() +} + +/// The whole of document `i`'s window inside the main window, title bar included. +fn window_of(app: &VectorcraftApp, ctx: &egui::Context, i: usize) -> egui::Rect { + let uid = app.session.documents()[i].uid; + let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); + ctx.memory(|m| m.area_rect(egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation)))).unwrap() +} + +/// A drag with the primary button from `from` to `to`, then a frame to settle. +fn drag(app: &mut VectorcraftApp, ctx: &egui::Context, from: Pos2, to: Pos2) { + frame(app, ctx, vec![egui::Event::PointerMoved(from)]); + frame(app, ctx, vec![button(from, true)]); + for k in 1..=4 { + frame(app, ctx, vec![egui::Event::PointerMoved(from + (to - from) * (k as f32 / 4.0))]); + } + frame(app, ctx, vec![button(to, false)]); + frame(app, ctx, vec![]); +} + +/// Whether the last frame drew text holding `title` in the tab strip (the top 35 points). +fn tab_drawn(shapes: &[Shape], title: &str) -> bool { + shapes.iter().any(|s| matches!(s, Shape::Text(t) if t.pos.y < 35.0 && t.galley.text().contains(title))) +} + +#[test] +fn cascade_places_step_down_and_right_inside_the_area() { + let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1190.0, 765.0)); + let places = cascade_places(area, 5); + assert_eq!(places.len(), 5); + for (k, p) in places.iter().enumerate() { + assert!(area.contains_rect(*p), "place {k} is inside the area: {p:?}"); + assert_eq!(p.size(), places[0].size(), "every window is the same size"); + let offset = CASCADE_MARGIN + k as f32 * CASCADE_STEP; + assert_eq!(p.min, area.min + vec2(offset, offset), "place {k} is {offset} pt down and right"); + } + // A small area holds fewer steps: the stack starts again at the corner and stays inside. + let small = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(500.0, 400.0)); + let places = cascade_places(small, 12); + assert!(places.iter().all(|p| small.contains_rect(*p)), "{places:?}"); + assert!(places.iter().skip(1).any(|p| p.min == places[0].min), "the stack starts again: {places:?}"); + // An area smaller than a window: the window fills it. + let tiny = egui::Rect::from_min_size(pos2(5.0, 5.0), vec2(100.0, 80.0)); + assert_eq!(cascade_places(tiny, 2), [tiny, tiny]); +} + +#[test] +fn a_control_channel_keeps_the_windows_inside_the_main_window() { + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let plain = app_with(0); + let wayland = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET"].iter().any(|n| std::env::var_os(n).is_some_and(|v| !v.is_empty())); + if !wayland { + assert!(native(&plain, &ctx), "without a control channel the windows are OS windows"); + } + let (_tx, rx) = std::sync::mpsc::channel(); + let controlled = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + assert!(!native(&controlled, &ctx), "with a control channel the windows stay inside the main window"); + ctx.set_embed_viewports(true); + assert!(!native(&plain, &ctx), "where egui draws every viewport inside the main window"); +} + +#[test] +fn float_in_window_moves_the_current_document_out_of_the_tabs() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + let shapes = frame(&mut app, &ctx, vec![]); + let title = app.session.documents()[2].title(); + assert!(tab_drawn(&shapes, &title), "the current document has a tab"); + let tabbed = app.canvas_rect.unwrap(); + assert_eq!(app.run("window.arrange.floatInWindow", json!({})).unwrap(), json!({"floating": [2]})); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(!tab_drawn(&shapes, &title), "a floating document has no tab"); + assert!(tab_drawn(&shapes, &app.session.documents()[0].title())); + assert_eq!(docked(&app), [0, 1]); + assert_eq!(app.session.active_index(), Some(2), "the floating document stays the current one"); + // Its window holds the canvas, fitted to the window; the main window shows a tabbed document. + let body = body_of(&app, 2); + let canvas = app.canvas_rect.unwrap(); + assert!(body.contains_rect(canvas) && canvas.width() < tabbed.width(), "the canvas is in the window: {canvas:?} in {body:?}"); + assert!(app.views[2].fitted); + assert_eq!(tab_document(&app), Some(0)); + assert_eq!(crate::control::inspect(&app, &ctx)["floating"], json!([2])); + // Floating it again leaves it where it is. + assert_eq!(app.run("window.arrange.floatInWindow", json!({})).unwrap(), json!({"floating": [2]})); + assert_eq!(app.ui.floating.len(), 1); +} + +#[test] +fn a_press_in_another_documents_window_or_the_main_window_makes_its_document_current() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(1)); + // The lower left of document 0's window, clear of document 1's window, which cascades below + // and to the right of it, and of the window's resize edges. + let body = body_of(&app, 0); + click(&mut app, &ctx, pos2(body.left() + 12.0, body.bottom() - 12.0)); + assert_eq!(app.session.active_index(), Some(0), "a press in its window makes document 0 current"); + assert!(body_of(&app, 0).contains_rect(app.canvas_rect.unwrap()), "its window holds the canvas now"); + // The main window shows the only tabbed document as a pane: a press there makes it current. + assert_eq!(tab_document(&app), Some(2)); + click(&mut app, &ctx, pos2(1100.0, 700.0)); + assert_eq!(app.session.active_index(), Some(2)); + // A press on the title bar of document 0's window, in front, makes document 0 current again. + let (window, body) = (window_of(&app, &ctx, 0), body_of(&app, 0)); + click(&mut app, &ctx, pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0)); + assert_eq!(app.session.active_index(), Some(0), "a press on its title bar makes document 0 current"); +} + +#[test] +fn a_resized_window_fits_its_document_again_unless_it_was_zoomed() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let (before, other) = (app.views[1].zoom, app.views[0].zoom); + // Document 1's window, in front and holding the canvas, grows from its lower-right corner. + let window = window_of(&app, &ctx, 1); + drag(&mut app, &ctx, window.right_bottom() - vec2(2.0, 2.0), window.right_bottom() + vec2(150.0, 100.0)); + assert!(window_of(&app, &ctx, 1).width() > window.width() + 100.0, "the window grew"); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(1)); + assert!(app.views[1].zoom > before, "the document fits its larger window: {before} → {}", app.views[1].zoom); + assert_eq!(app.views[0].zoom, other, "the other window keeps its size and its document's zoom"); + // A zoomed view keeps its zoom when its window changes size again. + app.run("view.zoomIn", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let zoomed = app.views[1].zoom; + let window = window_of(&app, &ctx, 1); + drag(&mut app, &ctx, window.right_bottom() - vec2(2.0, 2.0), window.right_bottom() - vec2(100.0, 60.0)); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.views[1].zoom, zoomed, "a zoomed document keeps its zoom"); +} + +#[test] +fn cascade_floats_every_document_and_stacks_the_windows() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + assert_eq!(app.run("window.arrange.cascade", json!({})).unwrap(), json!({"floating": [0, 1, 2]})); + assert!(!app.ui.tiled, "Cascade ends Tile"); + assert!(docked(&app).is_empty()); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let area = app.canvas.windows.area.unwrap(); + let places: Vec = app.ui.floating.iter().map(|w| w.place).collect(); + assert_eq!(places, cascade_places(area, 3), "the windows stack in tab order, document 1's moved from where it floated"); + for (i, place) in places.iter().copied().enumerate() { + let body = body_of(&app, i); + assert!((body.left() - place.left()).abs() < 4.0 && body.top() > place.top(), "document {i}'s window is at its place: {body:?} {place:?}"); + assert!(app.views[i].fitted, "document {i} fits its window"); + } + assert!(body_of(&app, 1).contains_rect(app.canvas_rect.unwrap()), "the current document's window holds the canvas"); +} + +#[test] +fn float_all_in_windows_floats_the_tabbed_documents_and_consolidate_brings_them_back() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let tabbed = app.canvas_rect.unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let first = app.ui.floating[0].place; + assert_eq!(app.run("window.arrange.floatAllInWindows", json!({})).unwrap(), json!({"floating": [2, 0, 1]})); + assert_eq!(app.ui.floating[0].place, first, "a window already floating stays where it is"); + assert!(docked(&app).is_empty()); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert_eq!(docked(&app), [0, 1, 2]); + for d in app.session.documents() { + assert!(tab_drawn(&shapes, &d.title()), "{} has its tab again", d.title()); + } + assert_eq!(app.canvas_rect, Some(tabbed), "the canvas is under the tabs again"); + assert!(app.views[2].fitted); +} + +#[test] +fn tile_brings_floating_documents_back_into_the_grid() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let docs: Vec = app.canvas.panes.last.iter().map(|(i, _)| *i).collect(); + assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it"); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + frame(&mut app, &ctx, vec![]); + let docs: Vec = app.canvas.panes.last.iter().map(|(i, _)| *i).collect(); + assert_eq!(docs, [0, 1, 2]); + assert!(app.ui.floating.is_empty()); +} + +#[test] +fn closing_a_floating_window_closes_its_document_and_asks_to_save_an_unsaved_one() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + // Document 0's window is behind document 1's: its close button is at the top right of its + // title bar, clear of document 1's window to the right and below. + let close_button = |app: &VectorcraftApp, i: usize| { + let uid = app.session.documents()[i].uid; + let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); + let area = ctx.memory(|m| m.area_rect(egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation)))).unwrap(); + let body = w.body.unwrap(); + (area, body) + }; + let (area0, body0) = close_button(&app, 0); + assert!(body0.top() > area0.top(), "the window has a title bar"); + // Close document 1 (in front): it is unsaved after an edit, so the app asks first. + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + assert!(app.session.documents()[1].is_dirty()); + frame(&mut app, &ctx, vec![]); + // The close button sits near the right end of the title bar. + let press_close = |app: &mut VectorcraftApp, i: usize| { + let (area, body) = close_button(app, i); + let bar = (area.top() + body.top()) / 2.0; + let n = app.session.documents().len(); + for dx in (4..40).step_by(3) { + click(app, &ctx, pos2(area.right() - dx as f32, bar)); + if app.ui.dialog.is_some() || app.session.documents().len() < n { + return true; + } + } + false + }; + assert!(press_close(&mut app, 1), "the close button of document 1's window acts"); + assert!(app.ui.dialog.is_some(), "an unsaved document asks to be saved"); + assert_eq!(app.session.documents().len(), 2); + // While the prompt is open the windows take no press. + let body = body_of(&app, 0); + click(&mut app, &ctx, pos2(body.left() + 12.0, body.bottom() - 12.0)); + assert_eq!(app.session.active_index(), Some(1), "a press in another window waits for the prompt"); + app.ui.dialog = None; + // Document 0 has no changes: its window closes with it. + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(press_close(&mut app, 0), "the close button of document 0's window acts"); + assert_eq!(app.session.documents().len(), 1); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.ui.floating.len(), 1, "its window has gone"); +} + +#[test] +fn presentation_mode_shows_the_floating_current_document_in_the_main_window() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let body = body_of(&app, 1); + assert!(body.contains_rect(app.canvas_rect.unwrap()), "the current document's window holds the canvas"); + let windowed = (app.views[0].zoom, app.views[1].zoom); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let shown = app.canvas_rect.unwrap(); + assert!(shown.width() > body.width() + 100.0, "the main window shows the current document: {shown:?}, its window was {body:?}"); + // The presentation goes on to the other floating document, fitted to the main window, then + // ends on the first one. + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.views[0].zoom > windowed.0, "the presentation fitted document 0 to the main window"); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(body_of(&app, 1).contains_rect(app.canvas_rect.unwrap()), "the window holds the canvas again"); + assert_eq!(app.ui.floating.len(), 2, "the windows come back"); + for (i, before) in [windowed.0, windowed.1].into_iter().enumerate() { + assert!((app.views[i].zoom - before).abs() < 1e-6, "document {i} fits its window again: {before} → {}", app.views[i].zoom); + } +} + +#[test] +fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let layer = |app: &VectorcraftApp, i: usize| { + let uid = app.session.documents()[i].uid; + let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); + egui::LayerId::new(egui::Order::Middle, egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation))) + }; + let top = |ctx: &egui::Context| ctx.memory(|m| m.areas().top_layer_id(egui::Order::Middle)); + assert_eq!(top(&ctx), Some(layer(&app, 1)), "the current document's window is in front"); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(top(&ctx), Some(layer(&app, 0)), "document 0's window comes to the front"); +} + +/// A stand-in for the window system of the documents' OS windows: it runs each one's frame, asks +/// each to close while `close` is set, and records the commands the windows were sent. +#[derive(Default)] +struct Host { + close: bool, + commands: Vec<(egui::ViewportId, egui::ViewportCommand)>, +} + +fn native_host() -> std::rc::Rc> { + let host = std::rc::Rc::new(std::cell::RefCell::new(Host::default())); + let shared = host.clone(); + egui::Context::set_immediate_viewport_renderer(move |ctx, mut viewport| { + let id = viewport.ids.this; + let events = if shared.borrow().close { vec![egui::ViewportEvent::Close] } else { vec![] }; + let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0)); + let info = egui::ViewportInfo { events, inner_rect: Some(rect), outer_rect: Some(rect), focused: Some(false), ..Default::default() }; + let input = + egui::RawInput { viewport_id: id, viewports: std::iter::once((id, info)).collect(), screen_rect: Some(rect), ..Default::default() }; + let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); + full.textures_delta.clear(); + let mut host = shared.borrow_mut(); + for (vid, output) in full.viewport_output { + host.commands.extend(output.commands.into_iter().map(|c| (vid, c))); + } + }); + host +} + +#[test] +fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() { + let host = native_host(); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let mut app = app_with(2); + if !native(&app, &ctx) { + // Wayland: the windows are inside the main window. + return; + } + frame(&mut app, &ctx, vec![]); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let vid = viewport_id(app.session.documents()[1].uid); + host.borrow_mut().close = true; + frame(&mut app, &ctx, vec![]); + host.borrow_mut().close = false; + assert!(app.ui.dialog.is_some(), "the unsaved document asks to be saved"); + assert_eq!(app.session.documents().len(), 2); + assert!(is_floating(&app, 1), "the document still floats"); + assert!( + host.borrow().commands.iter().any(|(id, c)| *id == vid && *c == egui::ViewportCommand::CancelClose), + "its OS window is kept open: {:?}", + host.borrow().commands + ); +} + +#[test] +fn the_arrange_items_are_enabled_as_the_documents_allow() { + let ids = [ + "window.arrange.cascade", + "window.arrange.tile", + "window.arrange.floatInWindow", + "window.arrange.floatAllInWindows", + "window.arrange.consolidateAllWindows", + ]; + let states = |app: &VectorcraftApp| ids.map(|id| enabled(app, id)); + let mut app = app_with(0); + assert_eq!(states(&app), [false; 5], "no document"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(states(&app), [false, false, true, true, false], "one tabbed document"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(states(&app), [true, true, true, true, false], "two tabbed documents"); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + assert_eq!(states(&app), [true, true, false, true, true], "the current document floats, one is tabbed"); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + assert_eq!(states(&app), [true, true, false, false, true], "every document floats"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert_eq!(states(&app), [true, true, true, true, false], "consolidated"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 9b878ba85f..fe8c162df1 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1177,6 +1177,7 @@ font-technology Variable Променливи Flip Row Order Обръщане реда на редовете Flip Vertical Вертикално обръщане Float in Window Плаващ прозорец + Float All in Windows Всички в плаващи прозорци Focal Fill Фокусно запълване Focal Stroke Фокусен щрих Folder Папка diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9534ca7a9f..003a6189a5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -628,6 +628,7 @@ Cascade Kaskadno Tile Popločaj Float in Window Odvoji u prozor + Float All in Windows Odvoji sve u prozore Consolidate All Windows Objedini sve prozore Workspace Radni prostor Reset Essentials Vrati Osnove na početno diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e8ca952958..a28db5502e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1610,6 +1610,7 @@ digits Malayalam Malaiàlam Flip Vertical Inverteix verticalment Flip: Inverteix: Float in Window Flota a la finestra + Float All in Windows Flota-ho tot en finestres Float Panel Flota el panell Float Tool Group Flota el grup d’eines Focal Fill Farciment focal diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7f4beb00c1..f69545e1b6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -636,6 +636,7 @@ Cascade Do kaskády Tile Vedle sebe Float in Window Uvolnit do samostatného okna + Float All in Windows Uvolnit vše do samostatných oken Consolidate All Windows Sloučit všechna okna Workspace Pracovní prostor Reset Essentials Obnovit Essentials diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f19aa9edf2..d78046e91d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -586,6 +586,7 @@ Cascade Kaskade Tile Fliselæg Float in Window Flyd i vindue + Float All in Windows Flyd alle i vinduer Consolidate All Windows Saml alle vinduer Workspace Arbejdsområde Reset Essentials Nulstil Essentials diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6d39cdcdeb..cde85a2c0b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1208,6 +1208,7 @@ file-filter Templates Vorlagen Flip Row Order Zeilenreihenfolge umkehren Flip Vertical Vertikal spiegeln Float in Window In eigenem Fenster anzeigen + Float All in Windows Alle in eigenen Fenstern anzeigen Focal Fill Fläche im Fokus Focal Stroke Kontur im Fokus Folder Ordner diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 644ebd5ee1..1dbe39f0f2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1150,6 +1150,7 @@ font-technology Variable Μεταβλητές Flip Row Order Αντιστροφή σειράς γραμμών Flip Vertical Κατακόρυφη αναστροφή Float in Window Μετατροπή σε ανεξάρτητο παράθυρο + Float All in Windows Μετατροπή όλων σε ανεξάρτητα παράθυρα Focal Fill Εστιακό γέμισμα Focal Stroke Εστιακό περίγραμμα Folder Φάκελος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 43bf0eac6d..ad27598386 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1226,6 +1226,7 @@ font-technology Variable Variables Flip Row Order Invertir orden de filas Flip Vertical Voltear verticalmente Float in Window Flotar en ventana + Float All in Windows Flotar todo en ventanas Focal Fill Relleno focal Focal Stroke Trazo focal Folder Carpeta diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 725e924dbd..294c513871 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -627,6 +627,7 @@ Cascade Porrasta Tile Vierekkäin Float in Window Kelluta ikkunassa + Float All in Windows Kelluta kaikki ikkunoissa Consolidate All Windows Yhdistä kaikki ikkunat Workspace Työtila Reset Essentials Palauta Essentials diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b68eef31ca..f5e604a258 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1220,6 +1220,7 @@ font-technology Variable Variables Flip Row Order Inverser l’ordre des lignes Flip Vertical Retourner verticalement Float in Window Flottant dans une fenêtre + Float All in Windows Tout flottant dans des fenêtres Focal Fill Fond actif Focal Stroke Contour actif Folder Dossier diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 70c29f4e22..1ce300e5db 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1528,6 +1528,7 @@ file-filter Templates Sablonok Flip Vertical Függőleges tükrözés Flip: Tükrözés: Float in Window Lebegtetés ablakban + Float All in Windows Összes lebegtetése ablakokban Float Panel Panel lebegtetése Float Tool Group Eszközcsoport lebegtetése Focal Fill Aktív kitöltés diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 5973cf3b65..336e64182f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -586,6 +586,7 @@ Cascade Bertingkat Tile Ubin Float in Window Mengambang di jendela + Float All in Windows Mengambangkan semua di jendela Consolidate All Windows Konsolidasikan semua jendela Workspace Ruang kerja Reset Essentials Atur ulang Essentials diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0b1ba1fafc..72d8ab51fe 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1238,6 +1238,7 @@ file-filter Templates Modelli Flip Row Order Inverti ordine delle righe Flip Vertical Capovolgi verticalmente Float in Window Rendi mobile nella finestra + Float All in Windows Rendi tutto mobile nelle finestre Focal Fill Riempimento attivo Focal Stroke Traccia attiva Folder Cartella diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b0ce510828..2fd494bd37 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -648,6 +648,7 @@ digits Malayalam マラヤーラム数字 Cascade 重ねて表示 Tile 並べて表示 Float in Window ウィンドウを分離 + Float All in Windows すべてをウィンドウに分離 Consolidate All Windows すべてのウィンドウを統合 Workspace ワークスペース Reset Essentials 初期設定をリセット diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 649aeb95c7..3ab0c61b4f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -538,6 +538,7 @@ Cascade კასკადად Tile ფილებად Float in Window ცალკე ფანჯარაში გამოტანა + Float All in Windows ყველას ცალკე ფანჯრებში გამოტანა Consolidate All Windows ყველა ფანჯრის გაერთიანება Workspace სამუშაო სივრცე Reset Essentials Essentials-ის ჩამოყრა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f3efc9cbb3..7f95429201 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -641,6 +641,7 @@ digits Malayalam 말라얄람어 Cascade 계단식 배열 Tile 바둑판식 배열 Float in Window 창에 플로팅 + Float All in Windows 모두 창에 플로팅 Consolidate All Windows 모든 창 통합 Workspace 작업 영역 Reset Essentials Essentials 재설정 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9c34aff5ac..65a015fd29 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -600,6 +600,7 @@ Cascade Trapsgewijs schikken Tile Naast elkaar schikken Float in Window In venster zweven + Float All in Windows Alles in vensters zweven Consolidate All Windows Alle vensters samenvoegen Workspace Werkruimte Reset Essentials Essentials herstellen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index bfa3d2c576..3eb6257e7a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -594,6 +594,7 @@ Cascade Kaskadowo Tile Sąsiadująco Float in Window Pływające w oknie + Float All in Windows Wszystkie pływające w oknach Consolidate All Windows Scal wszystkie okna Workspace Obszar roboczy Reset Essentials Resetuj Essentials diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 3135901d47..15bccd1f7a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1091,6 +1091,7 @@ Flip Row Order Inverter Ordem das Linhas Flip Vertical Espelhar Verticalmente Float in Window Flutuar na Janela + Float All in Windows Flutuar Tudo em Janelas Folder Pasta Folder Name: Nome da Pasta: Font Fonte diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 581cecc4fc..ccf399ddfe 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1235,6 +1235,7 @@ file-filter Templates Шаблоны Flip Row Order Изменить порядок строк Flip Vertical Отразить по вертикали Float in Window Плавать в окне + Float All in Windows Все плавающие в окнах Focal Fill Фокусная заливка Focal Stroke Фокусная обводка Folder Папка diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a5c492ff00..4ee641f804 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1185,6 +1185,7 @@ font-technology Variable Variabla Flip Row Order Vänd radordning Flip Vertical Vänd lodrätt Float in Window Gör flytande i fönster + Float All in Windows Gör alla flytande i fönster Focal Fill Fokal fyllning Focal Stroke Fokal kontur Folder Mapp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f1058a6161..cbf5bf629f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1179,6 +1179,7 @@ font-technology Variable Değişken Flip Row Order Satır Sırasını Çevir Flip Vertical Dikey Çevir Float in Window Pencerede Yüzer Yap + Float All in Windows Tümünü Pencerelerde Yüzer Yap Focal Fill Odak Dolgusu Focal Stroke Odak Konturu Folder Klasör diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ed181d4e5a..037d980501 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1232,6 +1232,7 @@ file-filter Templates Шаблони Flip Row Order Змінити порядок рядків Flip Vertical Відобразити по вертикалі Float in Window Відкріпити у вікні + Float All in Windows Відкріпити все у вікна Focal Fill Фокусна заливка Focal Stroke Фокусне обведення Folder Папка diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 882c2d9d0b..c4666f6ca0 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1431,6 +1431,7 @@ file-filter Templates Mẫu Flip Vertical Lật dọc Flip: Lật: Float in Window Nổi trong cửa sổ + Float All in Windows Nổi tất cả trong cửa sổ Float Panel Thả nổi bảng Float Tool Group Thả nổi nhóm công cụ Focal Fill Tô tiêu điểm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a86bb6fcd7..0a0bee4c15 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1176,6 +1176,7 @@ file-filter Templates 模板 Flip Row Order 反转行顺序 Flip Vertical 垂直翻转 Float in Window 在窗口中浮动 + Float All in Windows 全部在窗口中浮动 Focal Fill 焦点填色 Focal Stroke 焦点描边 Folder 文件夹 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9e547232c7..b96f2a2a11 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1202,6 +1202,7 @@ file-filter Templates 範本 Flip Row Order 反轉列順序 Flip Vertical 垂直翻轉 Float in Window 在視窗中浮動 + Float All in Windows 全部在視窗中浮動 Focal Fill 焦點填色 Focal Stroke 焦點筆畫 Folder 資料夾 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index de33cfcce6..bdfcaffffa 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -34,6 +34,7 @@ pub mod credits; pub mod cursors; mod custom_toolbars; pub mod dialogs; +pub mod doc_windows; pub mod dock; mod edit_toolbar; pub mod export_progress; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5ba39f237d..d54173c3de 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -545,7 +545,10 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("brightness must be dark|mediumDark|mediumLight|light".into()), }, "window.newWindow" => Err("New Window isn't available yet: a document opens in one window".into()), + "window.arrange.cascade" => crate::doc_windows::cascade(app), "window.arrange.tile" => crate::canvas::tile(app), + "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app), + "window.arrange.floatAllInWindows" => crate::doc_windows::float_all(app), "window.arrange.consolidateAllWindows" => crate::canvas::consolidate(app), "window.nextDocument" => crate::chrome::step_document(app, true), "window.previousDocument" => crate::chrome::step_document(app, false), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 26904fcae6..523d930e0d 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -283,11 +283,18 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { app.session.active().is_some() && crate::dialogs::perspective_presets::slot_preset(app, id).is_some() } "ui.perspectivePlane" => app.session.active().is_some(), - // Only one window per document so far: greyed out, as Cascade and Float in Window are (#3724). + // Only one window per document so far: grayed out (#3724). "window.newWindow" => false, - // Tile with two documents or more; Consolidate All Windows while they are tiled. - "window.arrange.tile" => app.session.documents().len() > 1, - "window.arrange.consolidateAllWindows" => app.ui.tiled && !app.session.documents().is_empty(), + // Tile and Cascade with two documents or more; Float in Window for a current document under + // the tabs; Float All in Windows while a document is under the tabs; Consolidate All + // Windows while documents are tiled or floating. + "window.arrange.tile" | "window.arrange.cascade" => app.session.documents().len() > 1, + "window.arrange.floatInWindow" => app.session.active_index().is_some_and(|i| !crate::doc_windows::is_floating(app, i)), + "window.arrange.floatAllInWindows" => !crate::doc_windows::docked(app).is_empty(), + "window.arrange.consolidateAllWindows" => { + let n = app.session.documents().len(); + n > 0 && (app.ui.tiled || crate::doc_windows::docked(app).len() < n) + } "window.nextDocument" | "window.previousDocument" => !app.session.documents().is_empty(), _ => true, } diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index d197ee9061..3a55ab37c0 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -612,9 +612,10 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { sub( "Arrange", vec![ - todo("Cascade"), + c("Cascade", "window.arrange.cascade"), c("Tile", "window.arrange.tile"), - todo("Float in Window"), + c("Float in Window", "window.arrange.floatInWindow"), + c("Float All in Windows", "window.arrange.floatAllInWindows"), c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), ], ), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f0446a7663..c974500935 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -581,17 +581,35 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("window.workspace.rename", "Rename Workspace", "", "{name, to}"), ("window.workspace.list", "List Workspaces", "", "{}"), ("window.newWindow", "New Window", "", "{}"), + ( + "window.arrange.cascade", + "Cascade", + "", + "{} put every open document in a floating window of its own and stack the windows from the upper left of the document area to its lower right, 30 pt apart, in tab order, each fitted to its window, the current document's in front; on the desktop each is an OS window, on the web and Wayland a window inside the app's window; returns {floating} (document indices)", + ), ( "window.arrange.tile", "Tile", "", - "{} show every open document at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of documents, rounded up), each fitted to its pane; the current document's pane takes the tools, a click in another pane makes its document the current one; the tabs stay; returns {tiled: true, panes}", + "{} show every open document at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of documents, rounded up), each fitted to its pane; the current document's pane takes the tools, a click in another pane makes its document the current one; the tabs stay; documents in floating windows come back under the tabs first; returns {tiled: true, panes}", + ), + ( + "window.arrange.floatInWindow", + "Float in Window", + "", + "{} move the current document out of the tab strip into a floating window of its own, fitted to it; the window holding the current document takes the tools, a click in another document's window makes its document the current one; a document already floating stays where it is; returns {floating} (document indices)", + ), + ( + "window.arrange.floatAllInWindows", + "Float All in Windows", + "", + "{} move every document under the tab strip into a floating window of its own, at the next places of a cascade; returns {floating} (document indices)", ), ( "window.arrange.consolidateAllWindows", "Consolidate All Windows", "", - "{} show one document at a time again, under its tab, after Tile; returns {tiled: false}", + "{} show one document at a time again, under its tab, after Tile, Float in Window, Float All in Windows or Cascade; returns {tiled: false, floating: []}", ), ( "window.nextDocument", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0375ed76f6..9d8c71538c 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1177,8 +1177,9 @@ pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { /// Keys, text and clipboard events that a floating panel's own OS window left over run the main /// window's shortcuts, tool keys and clipboard on its next frame ([`VectorcraftApp::raw_input_hook`]). /// craft-ui forwards nothing while a field in that window has the keyboard. A field of the main -/// window loses it, as a click elsewhere in one window would take it. -fn forward_keys(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: Option) { +/// window loses it, as a click elsewhere in one window would take it. A floating document's OS +/// window forwards its keys here too ([`crate::doc_windows`]). +pub(crate) fn forward_keys(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: Option) { if events.is_empty() { return; } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ccced48139..4dd6d9012d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -463,6 +463,15 @@ pub struct UiState { /// Consolidate All Windows. Not saved: the reference app does not save windows with a document. #[serde(skip)] pub tiled: bool, + /// Window › Arrange › Float in Window, Float All in Windows and Cascade: the documents in + /// floating windows of their own, out of the tab strip, until Consolidate All Windows. Not + /// saved, as `tiled` is not. + #[serde(skip)] + pub floating: Vec, + /// The document (its uid) the tab strip shows while the current document is in a floating + /// window: the tabbed document that was current last. + #[serde(skip)] + pub tab_document: Option, /// Draw Normal / Behind / Inside. pub draw_mode: u8, pub about: bool, @@ -944,6 +953,8 @@ impl Default for UiState { palette_query: String::new(), screen_mode: 0, tiled: false, + floating: Vec::new(), + tab_document: None, draw_mode: 0, about: false, action_sets: crate::panels::actions::default_sets(), diff --git a/docs/gaps.md b/docs/gaps.md index d7276abeab..292905bb71 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -592,7 +592,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done (#4135):** floating panels open in OS windows of their own on the desktop, so they can sit on another monitor; on the web and on Wayland they float inside the window. - **Done:** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)): a document keeps up to 25 named views (zoom, centre and rotation), saved with the file; every one is listed by name at the bottom of the View menu (`view.goto1`–`view.goto25`), and choosing one changes the current window to it. Edit Views… lists them to rename or delete, applied together on OK as one undo step (`view.saved.edit {edits}`); a file's views are checked when it opens. Estimate unchanged. - **Done:** Window › Arrange › Tile (`window.arrange.tile`) shows every open document in its own pane, edge to edge in the document area, and Consolidate All Windows (`window.arrange.consolidateAllWindows`) goes back to one document under its tab, on the desktop and the web. Estimate unchanged. -- **Missing:** multiple windows and the rest of Window › Arrange (Cascade, Float in Window, Float All in Windows). +- **Done:** Window › Arrange › Float in Window (`window.arrange.floatInWindow`), Float All in Windows (`window.arrange.floatAllInWindows`) and Cascade (`window.arrange.cascade`) move documents out of the tab strip into floating windows of their own, OS windows on the desktop and windows inside the app's window on the web and on Wayland; Cascade stacks them from the upper left to the lower right. Consolidate All Windows brings them back under the tabs. Estimate unchanged. +- **Missing:** several windows of one document (Window › New Window), dragging a tab out to float its document and back in to dock it. - **Estimate:** 15–25 h. ## G6 Automation and scripting diff --git a/docs/mcp.md b/docs/mcp.md index f18766a0a5..4db07abae8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3639,10 +3639,18 @@ the current one. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to its pane; it returns `{tiled, panes}`. The current document's pane is the canvas, and a press in another pane makes its -document the current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one -document under its tab again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` -and `panes` (each pane's `document` index, `rect` and whether it is `active`); canvas coordinates map to the current -document's pane (`canvasRect`). +document the current one. `window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document +out of the tab strip into a floating window of its own, `window.arrange.floatAllInWindows` (Float All in Windows) does +so for every tabbed document, and `window.arrange.cascade` (Cascade) floats every document and stacks the windows 30 pt +apart from the upper left of the document area; each returns `{floating}`, the floating documents' indices. On the +desktop each window is an OS window; on the web, on Wayland and while the control channel is attached (`--control`), +it is a window inside the app's window, so `ui.click`, `ui.drag` and `ui.screenshot` reach it. The current +document's window holds the canvas, and a press in another document's window makes its document the current one. +`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab +again, floating ones included, and returns `{tiled: false, floating: []}`; Tile brings floating documents back into its +grid. The arrangement is not saved. `ui.inspect` reports `tiled`, `panes` (each pane's `document` index, `rect` and +whether it is `active`) and `floating`; canvas coordinates map to the current document's pane or window +(`canvasRect`), in that window's coordinates while it floats. ```json {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index df438c4090..3d5685c43a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -527,6 +527,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Tile displays windows edge to edge"), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. +- **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "drag the window's tab out of the group"). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Cascade displays windows stacked and descending from the upper-left to the lower-right of the screen"). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From ca8aba6d6a0da67775c5cd0ab75c004967e86c18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 13:50:02 -0800 Subject: [PATCH 339/674] Window: drag a document tab out to float it, and a window back to dock it A document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer and makes it the current document (window.arrange.floatInWindow takes index and at for this). A shorter drag, or one along the strip, leaves the tabs as they are. A document window dragged by its title bar onto the tab strip goes back under the tabs; the strip shows an outline while a window is over it. A desktop document window is an OS window, so it has the document's tab at its top: dragging that tab moves the window, and dropping it on the main window's tab strip docks it (window.arrange.consolidateAllWindows takes index for one document). A document floated again opens where it is asked to, not where its last window was. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/chrome/tabs.rs | 61 ++++++- crates/ui-egui/src/doc_windows.rs | 175 +++++++++++++++++-- crates/ui-egui/src/doc_windows/tests.rs | 218 +++++++++++++++++++++++- crates/ui-egui/src/menus/run.rs | 3 +- crates/ui-egui/src/menus/ui_commands.rs | 4 +- docs/gaps.md | 3 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 10 files changed, 443 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 38b3c83d7c..8b3a3932f2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -433,6 +433,7 @@ impl VectorcraftApp { pub(crate) fn canvas_area(&mut self, ui: &mut egui::Ui) { let t = theme::Tokens::get(ui.ctx()); ui.painter().rect_filled(ui.max_rect(), 0.0, t.pasteboard); + self.canvas.windows.strip = None; if self.ui.screen_mode < 3 { chrome::doc_tabs(self, ui); } diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index c65d0f5153..eecaa22fd3 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -30,7 +30,7 @@ use status_bar::{StatusReadoutWidths, status_readouts}; #[cfg(test)] use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; -pub(crate) use tabs::{document_window_title, show_document}; +pub(crate) use tabs::{document_window_title, show_document, window_tab}; /// The application bar's height, in points (compact, as in PhotoCraft). pub const APP_BAR_HEIGHT: f32 = 32.0; diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index d8b214e9f0..cac5949161 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -25,6 +25,51 @@ pub(crate) fn document_window_title(app: &VectorcraftApp, i: usize) -> Option (f32, f32) { + if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) } +} + +/// The tab at the top of document `i`'s floating OS window ([`crate::doc_windows`]): a strip with +/// the document's tab, as the main window's strip draws it but without its ×. → the tab's +/// response, which senses clicks and drags. +pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, i: usize) -> egui::Response { + let t = Tokens::get(ui.ctx()); + let (height, title_size) = tab_size(app); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + ui.painter().rect_filled(strip, 0.0, t.tab_strip); + ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); + let title = document_window_title(app, i).unwrap_or_default(); + let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong); + let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); + ui.painter().rect_filled(r, 0.0, t.panel); + ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); + ui.painter().galley(egui::pos2(r.left() + 14.0, r.center().y - galley.size().y / 2.0), galley, t.text); + ui.interact(r, ui.scope_id().with("window-tab"), Sense::click_and_drag()) +} + +/// While document tab `r` is dragged off the tab `strip` far enough to float its document, an +/// outline under the pointer where its window will open; → the window's top-left corner when the +/// drag ends there. +fn tear_off(ui: &Ui, resp: &egui::Response, strip: egui::Rect) -> Option { + use crate::doc_windows::{GRAB, torn_off}; + if resp.dragged() + && let Some(p) = resp.interact_pointer_pos().filter(|p| torn_off(strip, *p)) + { + let t = Tokens::get(ui.ctx()); + let ghost = egui::Rect::from_min_size(p - GRAB, vec2(240.0, 160.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("tab-tear-off"))); + painter.rect_filled(ghost, 0.0, t.accent.gamma_multiply(0.12)); + painter.rect_stroke(ghost, 0.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } + if !resp.drag_stopped() { + return None; + } + let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()))?; + torn_off(strip, p).then_some(p - GRAB) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -44,13 +89,16 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// taller, with larger titles. Tabs that don't fit are reached from a » button at the strip's /// right end, which lists every open document, and the active tab is always in view (#746). /// Documents in floating windows have no tab ([`crate::doc_windows`]); while the current document -/// is in one, the tab of the document the strip shows is the highlighted one. +/// is in one, the tab of the document the strip shows is the highlighted one. A tab dragged more +/// than [`crate::doc_windows::TEAR_OFF`] above or below the strip floats its document in a window +/// under the pointer. pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; let t = Tokens::get(ui.ctx()); - let (height, title_size) = if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) }; + let (height, title_size) = tab_size(app); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + app.canvas.windows.strip = Some(strip); ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. @@ -74,6 +122,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let mut x = strip.left(); let mut activate = None; let mut close = None; + let mut float = None; let mut hovering_art = false; for (k, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { if x + w > strip.left() + room && Some(k) != active { @@ -82,7 +131,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(&i) = docked.get(k) else { break }; let is_active = Some(k) == active; let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); - let resp = ui.interact(r, ui.scope_id().with(("tab", i)), Sense::click()); + let resp = ui.interact(r, ui.scope_id().with(("tab", i)), Sense::click_and_drag()); if is_active { ui.painter().rect_filled(r, 0.0, t.panel); } else if resp.hovered() { @@ -101,6 +150,8 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { close = Some(i); } else if resp.clicked() { activate = Some(i); + } else if let Some(at) = tear_off(ui, &resp, strip) { + float = Some((i, at)); } x += w; } @@ -131,6 +182,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { if let Err(e) = crate::unsaved::close(app, i) { app.status(e); } + } else if let Some((i, at)) = float { + if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "at": [at.x, at.y]})) { + app.status(e); + } } else if let Some(i) = activate { show_document(app, i); } diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 24fa105c3b..2fb682e778 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -5,11 +5,21 @@ //! ([`crate::panel_docking`]). The current document's window holds the canvas //! ([`crate::canvas::show`]); each other window draws its document as a Tile pane does //! ([`crate::canvas::pane`]), and a press in it makes its document the current one. +//! +//! A document tab dragged off the tab strip floats its document in a window under the pointer, +//! and a document window dragged onto the tab strip by its title bar (an OS window by the tab at +//! its top) goes back under the tabs. use serde_json::{Value, json}; use crate::VectorcraftApp; +/// How far above or below the tab strip, in points, a dragged document tab must be released to +/// float its document. +pub(crate) const TEAR_OFF: f32 = 24.0; +/// Where a torn-off document's window opens: this far up and left of the pointer, so the pointer +/// is over its title bar. +pub(crate) const GRAB: egui::Vec2 = egui::vec2(40.0, 12.0); /// How far apart Cascade sets the windows, down and to the right, in points. pub(crate) const CASCADE_STEP: f32 = 30.0; /// How far the first cascaded window is from the document area's top-left corner, in points. @@ -24,6 +34,9 @@ pub struct DocWindow { pub uid: u64, /// Where the window goes, in the main window's points. pub place: egui::Rect, + /// The window's own number ([`Windows::opened`]): a document floated again gets a new window, + /// which opens where it is asked to, not where its last window was. + number: u32, /// Counts the moves Cascade gives the window after it opened. generation: u32, /// The OS window's position on the screen when it opened or last moved, and the generation of @@ -36,6 +49,9 @@ pub struct DocWindow { /// The size of the body its document was last fitted to, and the zoom and center that fit /// gave: a window resized while its view is still there fits its document again. fit: Option, + /// While its OS window's tab is dragged: where the pointer is from the window's top-left + /// corner, on the screen. + grab: Option, } /// [`DocWindow::fit`]: a body size, and a view's zoom and center. @@ -43,7 +59,7 @@ type Fit = (egui::Vec2, f64, vectorcraft_geom::Point); impl DocWindow { fn new(uid: u64, place: egui::Rect) -> Self { - Self { uid, place, generation: 0, screen: None, focused: false, body: None, fit: None } + Self { uid, place, number: 0, generation: 0, screen: None, focused: false, body: None, fit: None, grab: None } } } @@ -57,6 +73,15 @@ pub struct Windows { current: Option, /// While Presentation Mode is on: the floating documents (their uids) it has shown. presented: Option>, + /// The main window's tab strip in its last frame, while it was drawn. + pub(crate) strip: Option, + /// Counts the windows opened ([`DocWindow::number`]). + opened: u32, +} + +/// Whether a document tab dragged from `strip` to `p` has left it far enough to float. +pub(crate) fn torn_off(strip: egui::Rect, p: egui::Pos2) -> bool { + p.y > strip.bottom() + TEAR_OFF || p.y < strip.top() - TEAR_OFF } /// Whether document `i` is in a floating window. @@ -125,7 +150,10 @@ fn float(app: &mut VectorcraftApp, docs: &[usize]) { continue; } let place = places.get(first + k).copied().unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, MIN_SIZE)); - app.ui.floating.push(DocWindow::new(uid, place)); + app.canvas.windows.opened = app.canvas.windows.opened.wrapping_add(1); + let mut w = DocWindow::new(uid, place); + w.number = app.canvas.windows.opened; + app.ui.floating.push(w); if let Some(v) = app.views.get_mut(*i) { v.fitted = false; } @@ -140,15 +168,60 @@ fn floating_indices(app: &VectorcraftApp) -> Vec { app.ui.floating.iter().filter_map(|w| app.session.documents().iter().position(|d| d.uid == w.uid)).collect() } -/// `window.arrange.floatInWindow`: the current document leaves the tab strip for a floating window -/// of its own. A document already floating stays where it is. Returns `{floating}`. -pub(crate) fn float_in_window(app: &mut VectorcraftApp) -> Result { - if let Some(i) = app.session.active_index().filter(|i| !is_floating(app, *i)) { +/// The open document `p`'s `index` names: `Ok(None)` without one. +fn document_param(app: &VectorcraftApp, p: &Value) -> Result, String> { + match p.get("index") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < app.session.documents().len()) + .map(Some) + .ok_or_else(|| "no such document".to_string()), + } +} + +/// `window.arrange.floatInWindow`: the current document, or document `index`, leaves the tab strip +/// for a floating window of its own, with its top-left corner at `at` (`[x, y]` in the main +/// window's points) when given, else at the next cascade place. A document already floating stays +/// where it is. Document `index` becomes the current one. Returns `{floating}`. +pub(crate) fn float_in_window(app: &mut VectorcraftApp, p: &Value) -> Result { + let index = document_param(app, p)?; + let at = p + .get("at") + .and_then(Value::as_array) + .and_then(|a| Some(egui::pos2(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32))) + .filter(|at| at.is_finite()); + if let Some(i) = index.or(app.session.active_index()).filter(|i| !is_floating(app, *i)) { float(app, &[i]); + if let (Some(at), Some(w)) = (at, app.ui.floating.last_mut()) { + w.place = egui::Rect::from_min_size(at, w.place.size()); + } + } + if let Some(i) = index { + crate::chrome::show_document(app, i); } Ok(json!({ "floating": floating_indices(app) })) } +/// `window.arrange.consolidateAllWindows` with an `index`: document `index`, floating or not, +/// goes back under its tab, fitted there, and becomes the current one; the other windows and Tile +/// stay as they are. Returns `{tiled, floating}`. +pub(crate) fn dock(app: &mut VectorcraftApp, p: &Value) -> Result { + let Some(i) = document_param(app, p)? else { + return Err("no such document".into()); + }; + if is_floating(app, i) { + let uid = app.session.documents().get(i).map(|d| d.uid); + app.ui.floating.retain(|w| Some(w.uid) != uid); + if let Some(v) = app.views.get_mut(i) { + v.fitted = false; + } + } + crate::chrome::show_document(app, i); + Ok(json!({ "tiled": app.ui.tiled, "floating": floating_indices(app) })) +} + /// `window.arrange.floatAllInWindows`: every document under the tab strip goes to a floating window /// of its own. Returns `{floating}`. pub(crate) fn float_all(app: &mut VectorcraftApp) -> Result { @@ -216,10 +289,10 @@ fn viewport_id(uid: u64) -> egui::ViewportId { egui::ViewportId::from_hash_of(("vectorcraft-document-window", uid)) } -/// The id of document window `w` inside the main window: a new one for each Cascade move, so egui -/// opens it at its new place and size. +/// The id of document window `w` inside the main window: a new one for each window and each +/// Cascade move, so egui opens it at its new place and size. fn window_id(w: &DocWindow) -> egui::Id { - egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation)) + egui::Id::unique(("vectorcraft-document-window", w.uid, w.number, w.generation)) } /// What happened in a document window this frame. @@ -229,6 +302,10 @@ struct Shown { close: bool, /// Its document asks to become the current one. activate: bool, + /// It is being dragged over the main window's tab strip. + over_strip: bool, + /// It was dropped on the main window's tab strip: its document goes back under the tabs. + dock: bool, /// Its OS window has the keyboard focus. focused: bool, /// Where it drew its document. @@ -297,6 +374,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let blocked = crate::panel_docking::modal_open(app, ctx); let mut close = None; let mut activate = None; + let mut dock = None; + let mut over_strip = false; for w in app.ui.floating.clone() { let Some(i) = app.session.documents().iter().position(|d| d.uid == w.uid) else { continue }; let shown = if native { @@ -316,12 +395,22 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { win.body = shown.body; win.fit = shown.fit; } + over_strip |= shown.over_strip; if shown.close { close = Some(i); + } else if shown.dock { + dock = Some(i); } else if shown.activate && app.session.active_index() != Some(i) { activate = Some(i); } } + // The tab strip a dragged window would go back under shows where it lands. + if let Some(strip) = app.canvas.windows.strip.filter(|_| over_strip) { + let t = crate::theme::Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("vectorcraft-document-dock"))); + painter.rect_filled(strip, 0.0, t.accent.gamma_multiply(0.12)); + painter.rect_stroke(strip, 0.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); + } if let Some(i) = close { // The save prompt opens in the main window. if let Err(e) = crate::unsaved::close(app, i) { @@ -330,6 +419,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if native && app.ui.dialog.is_some() { ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); } + } else if let Some(i) = dock { + if let Err(e) = app.run("window.arrange.consolidateAllWindows", json!({ "index": i })) { + app.status(e); + } + if native { + ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus); + } } else if let Some(i) = activate { crate::chrome::show_document(app, i); app.canvas.windows.current = app.session.active().map(|d| d.uid); @@ -367,7 +463,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (i, blocked): (usize, bool) } /// Document `i`'s window `w` as an OS window of its own, `blocked` by a modal or not; `raise` -/// brings it to the front. +/// brings it to the front. The document's tab is at the top of the window, above its body. fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { let vid = viewport_id(w.uid); let origin = ctx.input(|inp| inp.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO); @@ -392,6 +488,8 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b let builder = egui::ViewportBuilder::default().with_title(title).with_position(screen).with_inner_size(w.place.size()).with_min_inner_size(MIN_SIZE); let mut forwarded = (Vec::new(), None); + // The main window's tab strip on the screen. + let strip = app.canvas.windows.strip.map(|s| s.translate(origin.to_vec2())); let shown = ctx.show_viewport_immediate(vid, builder, |ui, _| { let (close, focused) = ui.input(|inp| (inp.viewport().close_requested(), inp.viewport().focused == Some(true))); if close { @@ -399,7 +497,10 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b // or a modal can keep the document open. ui.ctx().send_viewport_cmd(egui::ViewportCommand::CancelClose); } - let (activate, rect, fit) = body(app, ui, (i, blocked), w.fit); + let tab = crate::chrome::window_tab(app, ui, i); + let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, (w.uid, origin), &tab, strip) }; + let (pressed, rect, fit) = body(app, ui, (i, blocked), w.fit); + let activate = pressed || (!blocked && (tab.clicked() || tab.drag_started())); // Keys the window's widgets left over run the main window's shortcuts and tool keys, as a // floating panel's do. if !blocked && !ui.memory(|m| m.focused().is_some()) { @@ -415,7 +516,7 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b (events, Some(inp.modifiers)) }); } - Shown { close, activate, focused, body: Some(rect), fit } + Shown { close, activate, over_strip, dock, focused, body: Some(rect), fit } }); if !forwarded.0.is_empty() { crate::panel_docking::forward_keys(app, ctx, forwarded.0, forwarded.1); @@ -423,6 +524,45 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b shown } +/// A drag of document window `uid`'s OS window by the `tab` at its top: the window follows the +/// pointer, and its document goes back under the tabs when the tab is released over the main +/// window's tab `strip` (on the screen). `origin` is the main window's top-left corner on the +/// screen. → whether the pointer is over the strip, and whether the tab was released there. +fn drag_tab( + app: &mut VectorcraftApp, + ui: &egui::Ui, + (uid, origin): (u64, egui::Pos2), + tab: &egui::Response, + strip: Option, +) -> (bool, bool) { + let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == uid) else { + return (false, false); + }; + if !tab.dragged() && !tab.drag_stopped() { + win.grab = None; + return (false, false); + } + let (inner, outer, pointer) = ui.input(|inp| (inp.viewport().inner_rect, inp.viewport().outer_rect, inp.pointer.latest_pos())); + let (Some(inner), Some(outer), Some(pointer)) = (inner, outer, pointer) else { + return (false, false); + }; + let at = inner.min + pointer.to_vec2(); + // The pointer stays where it pressed the tab, relative to the window. + let pressed = ui.input(|inp| inp.pointer.press_origin()).map_or(at, |p| inner.min + p.to_vec2()); + let grab = *win.grab.get_or_insert(pressed - outer.min); + let over = strip.is_some_and(|s| s.contains(at)); + if tab.drag_stopped() { + win.grab = None; + return (over, over); + } + let pos = at - grab; + if pos != outer.min { + win.screen = Some((pos, win.generation)); + win.place = egui::Rect::from_min_size(pos - origin.to_vec2(), win.place.size()); + } + (over, false) +} + /// Document `i`'s window `w` as a window inside the main window, `blocked` by a modal or not; /// `raise` brings it to the front. fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown { @@ -449,8 +589,15 @@ fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, }); // A press on its title bar or edges, which brings the window to the front, also makes its // document the current one. - activate |= shown.is_some_and(|s| s.response.contains_pointer()) && ctx.input(|inp| inp.pointer.any_pressed()); - Shown { close: !open, activate, focused: false, body: rect, fit } + activate |= shown.as_ref().is_some_and(|s| s.response.contains_pointer()) && ctx.input(|inp| inp.pointer.any_pressed()); + // Moved by its title bar onto the main window's tab strip, it goes back under the tabs. + // egui moves a window by the drag of its title bar's own widget, or, where it moves windows by + // a drag anywhere (after touch input), by the drag of the window itself. + let mover = ctx.read_response(id.with("__title_click")).or_else(|| shown.as_ref().map(|s| s.response.clone())); + let moved = mover.map_or((false, false), |r| (r.dragged(), r.drag_stopped())); + let pointer = ctx.input(|inp| inp.pointer.latest_pos()); + let over_strip = !blocked && (moved.0 || moved.1) && app.canvas.windows.strip.zip(pointer).is_some_and(|(strip, p)| strip.contains(p)); + Shown { close: !open, activate, over_strip, dock: over_strip && moved.1, focused: false, body: rect, fit } } /// The host's rewrites of raw input ([`crate::services::Services::native_input_hook`]) for the diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index f49728e954..08306804b2 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -60,7 +60,7 @@ fn body_of(app: &VectorcraftApp, i: usize) -> egui::Rect { fn window_of(app: &VectorcraftApp, ctx: &egui::Context, i: usize) -> egui::Rect { let uid = app.session.documents()[i].uid; let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); - ctx.memory(|m| m.area_rect(egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation)))).unwrap() + ctx.memory(|m| m.area_rect(window_id(w))).unwrap() } /// A drag with the primary button from `from` to `to`, then a frame to settle. @@ -279,7 +279,7 @@ fn closing_a_floating_window_closes_its_document_and_asks_to_save_an_unsaved_one let close_button = |app: &VectorcraftApp, i: usize| { let uid = app.session.documents()[i].uid; let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); - let area = ctx.memory(|m| m.area_rect(egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation)))).unwrap(); + let area = ctx.memory(|m| m.area_rect(window_id(w))).unwrap(); let body = w.body.unwrap(); (area, body) }; @@ -363,7 +363,7 @@ fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { let layer = |app: &VectorcraftApp, i: usize| { let uid = app.session.documents()[i].uid; let w = app.ui.floating.iter().find(|w| w.uid == uid).unwrap(); - egui::LayerId::new(egui::Order::Middle, egui::Id::unique(("vectorcraft-document-window", w.uid, w.generation))) + egui::LayerId::new(egui::Order::Middle, window_id(w)) }; let top = |ctx: &egui::Context| ctx.memory(|m| m.areas().top_layer_id(egui::Order::Middle)); assert_eq!(top(&ctx), Some(layer(&app, 1)), "the current document's window is in front"); @@ -378,11 +378,15 @@ fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { } /// A stand-in for the window system of the documents' OS windows: it runs each one's frame, asks -/// each to close while `close` is set, and records the commands the windows were sent. +/// each to close while `close` is set, and records the commands the windows were sent. Each +/// window is 500 × 400 points with its top-left corner at `origin` on the screen, and its next +/// frame takes `events`. #[derive(Default)] struct Host { close: bool, commands: Vec<(egui::ViewportId, egui::ViewportCommand)>, + origin: Pos2, + events: Vec, } fn native_host() -> std::rc::Rc> { @@ -390,11 +394,25 @@ fn native_host() -> std::rc::Rc> { let shared = host.clone(); egui::Context::set_immediate_viewport_renderer(move |ctx, mut viewport| { let id = viewport.ids.this; - let events = if shared.borrow().close { vec![egui::ViewportEvent::Close] } else { vec![] }; - let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0)); - let info = egui::ViewportInfo { events, inner_rect: Some(rect), outer_rect: Some(rect), focused: Some(false), ..Default::default() }; - let input = - egui::RawInput { viewport_id: id, viewports: std::iter::once((id, info)).collect(), screen_rect: Some(rect), ..Default::default() }; + let close = if shared.borrow().close { vec![egui::ViewportEvent::Close] } else { vec![] }; + let size = vec2(500.0, 400.0); + let rect = egui::Rect::from_min_size(Pos2::ZERO, size); + let on_screen = egui::Rect::from_min_size(shared.borrow().origin, size); + let info = egui::ViewportInfo { + events: close, + inner_rect: Some(on_screen), + outer_rect: Some(on_screen), + focused: Some(false), + ..Default::default() + }; + let events = std::mem::take(&mut shared.borrow_mut().events); + let input = egui::RawInput { + viewport_id: id, + viewports: std::iter::once((id, info)).collect(), + screen_rect: Some(rect), + events, + ..Default::default() + }; let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); full.textures_delta.clear(); let mut host = shared.borrow_mut(); @@ -433,6 +451,188 @@ fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() { ); } +/// Where the last frame drew the title of `title`'s tab in the tab strip. +fn tab_at(shapes: &[Shape], title: &str) -> Pos2 { + shapes + .iter() + .find_map(|s| match s { + Shape::Text(t) if t.pos.y < 35.0 && t.galley.text().contains(title) => Some(t.pos + vec2(4.0, 4.0)), + _ => None, + }) + .unwrap() +} + +#[test] +fn a_tab_is_torn_off_only_well_above_or_below_the_strip() { + let strip = egui::Rect::from_min_max(pos2(0.0, 40.0), pos2(1200.0, 75.0)); + assert!(!torn_off(strip, pos2(300.0, 60.0)), "along the strip"); + assert!(!torn_off(strip, pos2(300.0, 75.0 + TEAR_OFF - 1.0)), "a wobble below the strip"); + assert!(torn_off(strip, pos2(300.0, 75.0 + TEAR_OFF + 1.0))); + assert!(torn_off(strip, pos2(300.0, 40.0 - TEAR_OFF - 1.0)), "dragged up"); +} + +#[test] +fn dragging_a_tab_off_the_strip_floats_its_document_at_the_pointer() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + let title = app.session.documents()[0].title(); + let tab = tab_at(&shapes, &title); + // A short drag, and a drag along the strip, leave the tabs as they are. + drag(&mut app, &ctx, tab, tab + vec2(0.0, 35.0 + TEAR_OFF - 10.0 - tab.y)); + drag(&mut app, &ctx, tab, tab + vec2(300.0, 0.0)); + assert!(app.ui.floating.is_empty(), "the document stays under its tab"); + assert_eq!(app.session.active_index(), Some(2), "a drag is not a click"); + // Dragged well below the strip, it floats in a window under the pointer and becomes current. + let to = pos2(300.0, 200.0); + drag(&mut app, &ctx, tab, to); + assert_eq!(docked(&app), [1, 2]); + assert_eq!(app.session.active_index(), Some(0), "the torn-off document is the current one"); + assert_eq!(app.ui.floating[0].place.min, to - GRAB, "its window opens under the pointer"); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(!tab_drawn(&shapes, &title), "it has left the strip"); + let window = window_of(&app, &ctx, 0); + assert!(window.contains(to) && (window.min - (to - GRAB)).length() < 1.0, "the pointer is over its window: {window:?}"); + assert!(body_of(&app, 0).contains_rect(app.canvas_rect.unwrap()), "its window holds the canvas"); +} + +#[test] +fn a_window_dragged_by_its_title_bar_onto_the_strip_goes_back_under_the_tabs() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let title_bar = |app: &VectorcraftApp, i: usize| { + let (window, body) = (window_of(app, &ctx, i), body_of(app, i)); + pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0) + }; + // Moved elsewhere, document 2's window (in front) stays a window. + let from = title_bar(&app, 2); + drag(&mut app, &ctx, from, from + vec2(40.0, 30.0)); + assert_eq!(app.ui.floating.len(), 3, "a window moved off the strip still floats"); + // Dropped on the strip, it goes back under its tab, current; the other windows stay. + let from = title_bar(&app, 2); + drag(&mut app, &ctx, from, pos2(600.0, 15.0)); + assert_eq!(docked(&app), [2]); + assert_eq!(app.session.active_index(), Some(2)); + assert_eq!(app.ui.floating.len(), 2); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(tab_drawn(&shapes, &app.session.documents()[2].title()), "it has its tab again"); + assert!(app.views[2].fitted, "it fits the canvas under the tabs"); + let canvas = app.canvas_rect.unwrap(); + assert!(canvas.top() >= 35.0 && canvas.width() > 1000.0, "the canvas under the tabs shows it: {canvas:?}"); + // Torn off again, it opens where its tab is dropped, not where its last window was. + let to = pos2(200.0, 300.0); + let tab = tab_at(&shapes, &app.session.documents()[2].title()); + drag(&mut app, &ctx, tab, to); + frame(&mut app, &ctx, vec![]); + let window = window_of(&app, &ctx, 2); + assert!((window.min - (to - GRAB)).length() < 1.0, "its new window is under the pointer: {window:?}"); +} + +#[test] +fn after_touch_input_a_window_dragged_onto_the_strip_still_docks() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + // A touch makes egui move windows by a drag anywhere on them. + let touch = egui::Event::Touch { + device_id: egui::TouchDeviceId(1), + id: egui::TouchId(1), + phase: egui::TouchPhase::Start, + pos: pos2(1100.0, 700.0), + force: None, + }; + frame(&mut app, &ctx, vec![touch]); + frame(&mut app, &ctx, vec![]); + let (window, body) = (window_of(&app, &ctx, 1), body_of(&app, 1)); + let from = pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0); + drag(&mut app, &ctx, from, pos2(600.0, 15.0)); + assert_eq!(docked(&app), [1], "document 1 is back under the tabs"); +} + +#[test] +fn a_document_floated_again_after_cascade_opens_where_it_is_asked_to() { + let mut app = app_with(2); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.cascade", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.consolidateAllWindows", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + let at = pos2(200.0, 300.0); + app.run("window.arrange.floatInWindow", json!({"index": 1, "at": [at.x, at.y]})).unwrap(); + frame(&mut app, &ctx, vec![]); + let window = window_of(&app, &ctx, 1); + assert!((window.min - at).length() < 1.0, "its new window opens at {at:?}: {window:?}"); +} + +#[test] +fn float_in_window_and_consolidate_take_a_document() { + let mut app = app_with(3); + assert_eq!(app.run("window.arrange.floatInWindow", json!({"index": 0, "at": [100, 120]})).unwrap(), json!({"floating": [0]})); + assert_eq!(app.session.active_index(), Some(0), "document 0 becomes the current one"); + assert_eq!(app.ui.floating[0].place.min, pos2(100.0, 120.0)); + app.run("window.arrange.floatInWindow", json!({"index": 1})).unwrap(); + assert_eq!(app.run("window.arrange.floatInWindow", json!({"index": 3})), Err("no such document".to_string())); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({"index": 1})).unwrap(), json!({"tiled": true, "floating": [0, 2]})); + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(docked(&app), [1], "only document 1 goes back under the tabs"); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({"index": 7})), Err("no such document".to_string())); + assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); +} + +#[test] +fn an_os_window_moves_by_its_tab_and_docks_on_the_strip() { + let host = native_host(); + let ctx = egui::Context::default(); + ctx.set_embed_viewports(false); + let mut app = app_with(2); + if !native(&app, &ctx) { + // Wayland: the windows are inside the main window. + return; + } + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + // The OS window's top-left corner is at (300, 300) on the screen; the main window's at (0, 0). + host.borrow_mut().origin = pos2(300.0, 300.0); + frame(&mut app, &ctx, vec![]); + let os_drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| { + let steps = [vec![egui::Event::PointerMoved(from)], vec![button(from, true)]] + .into_iter() + .chain((1..=4).map(|k| vec![egui::Event::PointerMoved(from + (to - from) * (k as f32 / 4.0))])) + .chain([vec![button(to, false)], vec![]]); + for events in steps { + host.borrow_mut().events = events; + frame(app, &ctx, vec![]); + } + }; + // The tab at the top of the window: dragged down and right, the window follows the pointer. + let tab = pos2(20.0, 15.0); + os_drag(&mut app, tab, tab + vec2(100.0, 50.0)); + assert!(is_floating(&app, 1), "a window moved off the strip still floats"); + let w = &app.ui.floating[0]; + assert_eq!(w.screen.map(|s| s.0), Some(pos2(400.0, 350.0)), "the window moved with the pointer"); + assert_eq!(w.place.min, pos2(400.0, 350.0), "in the main window's points"); + // Released over the main window's tab strip (y 0 to 35 on the screen), it docks. + os_drag(&mut app, tab, pos2(20.0, -280.0)); + assert!(app.ui.floating.is_empty(), "the document is back under the tabs"); + assert_eq!(docked(&app), [0, 1]); + assert_eq!(app.session.active_index(), Some(1)); +} + #[test] fn the_arrange_items_are_enabled_as_the_documents_allow() { let ids = [ diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index d54173c3de..b788cd58bb 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -547,8 +547,9 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("New Window isn't available yet: a document opens in one window".into()), "window.arrange.cascade" => crate::doc_windows::cascade(app), "window.arrange.tile" => crate::canvas::tile(app), - "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app), + "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app, p), "window.arrange.floatAllInWindows" => crate::doc_windows::float_all(app), + "window.arrange.consolidateAllWindows" if p.get("index").is_some_and(|i| !i.is_null()) => crate::doc_windows::dock(app, p), "window.arrange.consolidateAllWindows" => crate::canvas::consolidate(app), "window.nextDocument" => crate::chrome::step_document(app, true), "window.previousDocument" => crate::chrome::step_document(app, false), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c974500935..8d1b6b36bd 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -597,7 +597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.floatInWindow", "Float in Window", "", - "{} move the current document out of the tab strip into a floating window of its own, fitted to it; the window holding the current document takes the tools, a click in another document's window makes its document the current one; a document already floating stays where it is; returns {floating} (document indices)", + "{index?, at?: [x, y]} move the current document, or document `index` (which becomes the current one), out of the tab strip into a floating window of its own, fitted to it, with the window's top-left corner at `at` (main window points) or else at the next place of a cascade; dragging a document tab more than 24 pt above or below the tab strip does this at the pointer; the window holding the current document takes the tools, a click in another document's window makes its document the current one; a document already floating stays where it is; returns {floating} (document indices)", ), ( "window.arrange.floatAllInWindows", @@ -609,7 +609,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.consolidateAllWindows", "Consolidate All Windows", "", - "{} show one document at a time again, under its tab, after Tile, Float in Window, Float All in Windows or Cascade; returns {tiled: false, floating: []}", + "{index?} show one document at a time again, under its tab, after Tile, Float in Window, Float All in Windows or Cascade; returns {tiled: false, floating: []}; with `index`, only document `index` goes back under its tab and becomes the current one, the other windows and Tile staying as they are, as when a document window is dragged by its title bar (an OS window by the tab at its top) onto the tab strip; returns {tiled, floating} (document indices)", ), ( "window.nextDocument", diff --git a/docs/gaps.md b/docs/gaps.md index 292905bb71..3ccde6d984 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -593,7 +593,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)): a document keeps up to 25 named views (zoom, centre and rotation), saved with the file; every one is listed by name at the bottom of the View menu (`view.goto1`–`view.goto25`), and choosing one changes the current window to it. Edit Views… lists them to rename or delete, applied together on OK as one undo step (`view.saved.edit {edits}`); a file's views are checked when it opens. Estimate unchanged. - **Done:** Window › Arrange › Tile (`window.arrange.tile`) shows every open document in its own pane, edge to edge in the document area, and Consolidate All Windows (`window.arrange.consolidateAllWindows`) goes back to one document under its tab, on the desktop and the web. Estimate unchanged. - **Done:** Window › Arrange › Float in Window (`window.arrange.floatInWindow`), Float All in Windows (`window.arrange.floatAllInWindows`) and Cascade (`window.arrange.cascade`) move documents out of the tab strip into floating windows of their own, OS windows on the desktop and windows inside the app's window on the web and on Wayland; Cascade stacks them from the upper left to the lower right. Consolidate All Windows brings them back under the tabs. Estimate unchanged. -- **Missing:** several windows of one document (Window › New Window), dragging a tab out to float its document and back in to dock it. +- **Done:** a document tab dragged off the tab strip floats its document in a window under the pointer, and a document window dragged by its title bar (an OS window by the tab at its top) onto the tab strip goes back under the tabs. Estimate unchanged. +- **Missing:** several windows of one document (Window › New Window). - **Estimate:** 15–25 h. ## G6 Automation and scripting diff --git a/docs/mcp.md b/docs/mcp.md index 4db07abae8..4081cc27a9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3648,7 +3648,12 @@ it is a window inside the app's window, so `ui.click`, `ui.drag` and `ui.screens document's window holds the canvas, and a press in another document's window makes its document the current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab again, floating ones included, and returns `{tiled: false, floating: []}`; Tile brings floating documents back into its -grid. The arrangement is not saved. `ui.inspect` reports `tiled`, `panes` (each pane's `document` index, `rect` and +grid. `window.arrange.floatInWindow {index, at: [x, y]}` floats document `index`, makes it the current one and puts its +window's top-left corner at `at` in the main window's points, as dragging its tab more than 24 pt above or below the tab +strip does. `window.arrange.consolidateAllWindows {index}` brings only document `index` back under its tab and makes it +the current one, as dragging its window by the title bar (an OS window by the tab at its top) onto the tab strip does; +it returns `{tiled, floating}`. An `index` that names no open document fails with "no such document". The arrangement +is not saved. `ui.inspect` reports `tiled`, `panes` (each pane's `document` index, `rect` and whether it is `active`) and `floating`; canvas coordinates map to the current document's pane or window (`canvasRect`), in that window's coordinates while it floats. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3d5685c43a..208a8bf0ee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -528,6 +528,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Tile displays windows edge to edge"), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "drag the window's tab out of the group"). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Cascade displays windows stacked and descending from the upper-left to the lower-right of the screen"). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "To undock (float or untab) a Document window from a group of windows, drag the window’s tab out of the group. To dock a Document window to a separate group of Document windows, drag the window into the group."). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). From 4b683c3a9845b1f1effabf3a92e072ff8b10e397 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 17:42:06 -0800 Subject: [PATCH 340/674] Window: with Open Documents As Tabs cleared, new documents open in windows Preferences > User Interface > Open Documents As Tabs was stored but did nothing. With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Window > Arrange > Float in Window floats it. Documents already open, and documents open when the app starts, keep their tabs; checking the box again leaves floating documents in their windows. The engine records the preference on each document as it opens (DocState::opened_as_tab), and the UI finds new documents by uid, so a command batch that closes and opens documents, or changes the preference between opening them, places each one as the preference was when it opened. --- crates/engine/src/doc_state.rs | 4 ++ crates/engine/src/session/documents.rs | 2 + crates/ui-egui/src/app.rs | 3 +- crates/ui-egui/src/app/view.rs | 4 +- crates/ui-egui/src/doc_windows.rs | 35 +++++++++++++ crates/ui-egui/src/doc_windows/tests.rs | 68 +++++++++++++++++++++++++ docs/gaps.md | 13 +++-- docs/target-app-parity.md | 5 +- docs/ui-parity.md | 2 +- 9 files changed, 126 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index dc1df88bed..5ed2abe1ce 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -52,6 +52,9 @@ pub struct DocState { pub recalled_selection: RecalledSelection, /// Process-unique id of this open document (tab indices shift when tabs close). pub uid: u64, + /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, + /// the UI opens it in a floating window of its own. + pub opened_as_tab: bool, /// View Opacity Mask (Alt-click the mask thumbnail): the masked object whose mask the canvas /// shows alone, in greyscale, while that mask is edited (see [`DocState::shown_mask`]). pub mask_view: Option, @@ -255,6 +258,7 @@ impl DocState { last_selection_cmd: None, recalled_selection: RecalledSelection::default(), uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + opened_as_tab: true, mask_view: None, transparency_grid, format: "vectorcraft", diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index ba15d31757..ba6ee2f1fe 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -209,6 +209,7 @@ impl Session { self.reset_tool_for_doc_switch(); let mut st = DocState::new(doc, path); st.history.limit = self.prefs.history_states as usize; + st.opened_as_tab = self.prefs.open_documents_as_tabs; self.docs.push(st); let i = self.docs.len() - 1; self.active = Some(i); @@ -239,6 +240,7 @@ impl Session { st.history.limit = old.history.limit; // Same open document (caches keyed by uid stay valid); a new revision redraws it. st.uid = old.uid; + st.opened_as_tab = old.opened_as_tab; st.revision = old.revision + 1; st.format = old.format; st.save_options = old.save_options.clone(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8b3a3932f2..63bb4de7b0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -54,6 +54,7 @@ impl VectorcraftApp { // ([`place::place_from_cursor`]). session.place_cursor_requests = true; let views = session.documents().iter().map(View::of).collect(); + let known = session.documents().iter().map(|d| d.uid).collect(); Self { session, ui: UiState::default(), @@ -85,7 +86,7 @@ impl VectorcraftApp { hover_cursor: None, presented: None, panes: Default::default(), - windows: Default::default(), + windows: crate::doc_windows::Windows::new(known), }, perf: Perf::default(), dock_rt: Default::default(), diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index fd38968d2d..0100ed100b 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -1,7 +1,8 @@ use super::{Value, VectorcraftApp, View, ViewInfo, panels}; impl VectorcraftApp { - /// Keep `views` aligned with the session's documents (a new one starts at its saved view). + /// Keep `views` aligned with the session's documents (a new one starts at its saved view, and + /// opens in a floating window while Open Documents As Tabs is cleared). pub fn sync_views(&mut self) { let docs = self.session.documents(); self.views.truncate(docs.len()); @@ -9,6 +10,7 @@ impl VectorcraftApp { for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); } + crate::doc_windows::opened(self); // Undo can remove the Artboard tool's active or additionally selected boards. Repair only // invalid indices: valid multiselection, drag state and tool options must survive history. if self.session.tool_id() != "artboard" || self.session.tool_busy() { diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 2fb682e778..6c70eb4491 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -9,6 +9,9 @@ //! A document tab dragged off the tab strip floats its document in a window under the pointer, //! and a document window dragged onto the tab strip by its title bar (an OS window by the tab at //! its top) goes back under the tabs. +//! +//! With Preferences › User Interface › Open Documents As Tabs cleared, each document opened or +//! created afterwards opens in a floating window ([`opened`]). use serde_json::{Value, json}; @@ -77,6 +80,16 @@ pub struct Windows { pub(crate) strip: Option, /// Counts the windows opened ([`DocWindow::number`]). opened: u32, + /// The open documents (their uids) when [`opened`] last ran, or when the app started. + known: Vec, +} + +impl Windows { + /// No windows yet, with `known` (uids) the documents open when the app starts: they keep their + /// tabs, whatever Open Documents As Tabs says. + pub(crate) fn new(known: Vec) -> Self { + Self { known, ..Default::default() } + } } /// Whether a document tab dragged from `strip` to `p` has left it far enough to float. @@ -142,6 +155,28 @@ fn area(app: &VectorcraftApp) -> egui::Rect { /// open. Each fits its window. fn float(app: &mut VectorcraftApp, docs: &[usize]) { app.sync_views(); + place(app, docs); +} + +/// The documents opened or created since the last call: each one opened while Preferences › User +/// Interface › Open Documents As Tabs was cleared ([`vectorcraft_engine::DocState::opened_as_tab`]) +/// opens in a floating window of its own, at the next cascade place. Documents already open stay +/// where they are. Called by [`VectorcraftApp::sync_views`]. +pub(crate) fn opened(app: &mut VectorcraftApp) { + let docs = app.session.documents(); + let known = &app.canvas.windows.known; + if known.len() == docs.len() && known.iter().zip(docs).all(|(u, d)| *u == d.uid) { + return; + } + let new: Vec = docs.iter().enumerate().filter(|(_, d)| !d.opened_as_tab && !known.contains(&d.uid)).map(|(i, _)| i).collect(); + app.canvas.windows.known = docs.iter().map(|d| d.uid).collect(); + if !new.is_empty() { + place(app, &new); + } +} + +/// [`float`] for documents whose views exist. +fn place(app: &mut VectorcraftApp, docs: &[usize]) { let first = app.ui.floating.len(); let places = cascade_places(area(app), first + docs.len()); for (k, i) in docs.iter().enumerate() { diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 08306804b2..f32e0b2ab6 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -594,6 +594,74 @@ fn float_in_window_and_consolidate_take_a_document() { assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); } +#[test] +fn with_open_documents_as_tabs_cleared_new_documents_open_in_floating_windows() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": false})).unwrap(); + assert_eq!(docked(&app), [0], "a document already open stays under its tab"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(docked(&app), [0]); + assert_eq!(floating_indices(&app), [1, 2], "each new document opens in a window of its own"); + assert_eq!(app.session.active_index(), Some(2), "the newest document is the current one"); + assert_ne!(app.ui.floating[0].place.min, app.ui.floating[1].place.min, "the windows open at cascade places"); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + assert!(!tab_drawn(&shapes, &app.session.documents()[2].title()), "a document in a window has no tab"); + assert!(tab_drawn(&shapes, &app.session.documents()[0].title())); + assert!(body_of(&app, 2).contains_rect(app.canvas_rect.unwrap()), "the new document's window holds the canvas"); +} + +#[test] +fn documents_open_when_the_app_starts_keep_their_tabs() { + let mut session = Session::new(); + session.prefs.open_documents_as_tabs = false; + session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut app = VectorcraftApp::new(session, Default::default()); + app.sync_views(); + assert_eq!(docked(&app), [0]); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(floating_indices(&app), [1]); +} + +#[test] +fn a_document_created_in_a_batch_that_closes_another_still_floats() { + let mut app = app_with(2); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": false})).unwrap(); + let steps = json!([ + {"command": "file.close", "params": {}}, + {"command": "file.new", "params": {"width": 400, "height": 300}}, + ]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(app.session.documents().len(), 2, "one document closed and one opened"); + assert_eq!(docked(&app), [0]); + assert_eq!(floating_indices(&app), [1], "the new document opens in a window of its own"); +} + +#[test] +fn each_document_in_a_batch_follows_the_preference_when_it_opened() { + let mut app = app_with(1); + let new = json!({"command": "file.new", "params": {"width": 400, "height": 300}}); + let tabs = |on: bool| json!({"command": "prefs.set", "params": {"key": "openDocumentsAsTabs", "value": on}}); + let steps = json!([tabs(false), new, tabs(true), new, tabs(false)]); + app.run("command.batch", json!({"commands": steps})).unwrap(); + assert_eq!(floating_indices(&app), [1], "opened with the box cleared"); + assert_eq!(docked(&app), [0, 2], "opened with the box checked"); +} + +#[test] +fn checking_open_documents_as_tabs_again_leaves_floating_documents_where_they_are() { + let mut app = app_with(0); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": false})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("prefs.set", json!({"key": "openDocumentsAsTabs", "value": true})).unwrap(); + assert_eq!(floating_indices(&app), [0], "the floating document stays in its window"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + assert_eq!(docked(&app), [1], "a new document opens under a tab"); + assert_eq!(floating_indices(&app), [0]); +} + #[test] fn an_os_window_moves_by_its_tab_and_docks_on_the_strip() { let host = native_host(); diff --git a/docs/gaps.md b/docs/gaps.md index 3ccde6d984..6e401036b9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -416,13 +416,16 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall the other Units preferences. The model stays in points; any length field reads `13q` or `13h` (`Ha`, `H`) with or without a space. Not done: no field shows in it (it waits for a source). Tests `east_asian_*` and `q_and_ha_*` in `crates/doc` and `crates/engine`. Estimate unchanged. -- **Audited (2026-10-30, #394):** every Preferences dialog option but the four below is read by shipped code, +- **Audited (2026-10-30, #394):** every Preferences dialog option but four is read by shipped code, by its field or its key; Highlight Alternate Glyphs (the canvas's render options), Real-time Drawing and Editing (tool previews wait for the commit), Show Tool Tips, Anti-aliased Artwork, Use Precise Cursors and Devices › - Enable Touch Workspace and Touch Gestures included. -- **Missing:** 4 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: - User Interface › Open Documents As Tabs (off would open documents in floating windows; one window per - document is G7), Hyphenation › Default Language (hyphenation is English-only, with no per-language + Enable Touch Workspace and Touch Gestures included. One of the four, Open Documents As Tabs, acts now (below); + the other three are listed under Missing. +- **Done:** User Interface › Open Documents As Tabs: with the box cleared, each document opened or created + afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they + are. Estimate unchanged. +- **Missing:** 3 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: + Hyphenation › Default Language (hyphenation is English-only, with no per-language dictionaries), Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to disk), and Clipboard Handling › Legacy vector clipboard with its Preserve Paths / Preserve Appearance and Overprints choice (Illustrator's own clipboard flavour, which has no public specification). Also Properties diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 208a8bf0ee..0cd246dd7d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -529,6 +529,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Tile displays windows edge to edge"), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "drag the window's tab out of the group"). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Cascade displays windows stacked and descending from the upper-left to the lower-right of the screen"). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "To undock (float or untab) a Document window from a group of windows, drag the window’s tab out of the group. To dock a Document window to a separate group of Document windows, drag the window into the group."). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html): "When you create or open documents, they are arranged in tabs in a single document window"). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). @@ -638,9 +639,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default: on, pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (on by default: pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Four stored options still do nothing yet (the audit below). + - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Three stored options still do nothing yet (the audit below). - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except User Interface › Open Documents As Tabs, Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type, stored only on the day of the audit, acts since 2026-10-31); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. + - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - Units › East Asian Type (#394, `unitsAsianType`): Points by default; it offers every unit and Q and Ha, a quarter of a millimetre each (0.709 pt: the [Illustrator Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/); `q` and `h` are the field suffixes [InDesign's notation table](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html) lists), and only it lists them: rulers, Document Setup and the other Units preferences keep their ten. The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. The model stays in points; any length field reads `13q`/`13h`. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` (`crates/engine/src/tests/units.rs`). - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except User Interface › Open Documents As Tabs, Units › East Asian Type, Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only; [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - With Performance › Real-time Drawing and Editing off, the bounding box moves with a Selection-tool move drag and the object moves when the button is released ([help](https://web.archive.org/web/20220324053041id_/https://helpx.adobe.com/illustrator/using/real-time-editing.html); `real_time_drawing_off_moves_the_bounding_box_with_a_move_drag`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b001155030..17175d53f5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -334,7 +334,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library::`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; native CIRCLE/ARC export and CNC preset remain pending | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | -| Preferences: every option acts | partial | 4 stored but unused (#394, audited 2026-10-30): Open Documents As Tabs, Hyphenation › Default Language, Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | +| Preferences: every option acts | partial | 3 stored but unused (#394, audited 2026-10-30): Hyphenation › Default Language, Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | | Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); arcs, spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | From 2a95625b99cc8f4aaf81ebfb57beaaf6a80867af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 21:04:24 -0800 Subject: [PATCH 341/674] Type: step font families with the mouse wheel Apply wheel steps over the closed family fields in Character, Properties and Control, preserving event order and one undo step per effective notch. Document the supported controls and the application choices. Fixes #5253. --- ROADMAP.md | 4 +- crates/ui-egui/src/font_menu.rs | 160 ++++++++++++++++++--- crates/ui-egui/src/font_menu/tests.rs | 37 +++++ crates/ui-egui/src/panels/character.rs | 6 +- crates/ui-egui/src/tests/font_menu.rs | 181 ++++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/dropdowns.rs | 15 +- docs/gaps.md | 10 +- docs/roadmap.md | 3 +- docs/target-app-parity.md | 4 +- docs/type-parity.md | 4 +- docs/ui-parity.md | 4 +- 12 files changed, 398 insertions(+), 32 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8ebfd65222..bce1cab0c4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). @@ -214,6 +215,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 93ae778e5f..540951d586 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -8,7 +8,9 @@ //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable //! in-menu font previews and Font Preview Size turn the samples off or size the rows. Recently //! used families appear first, in the order they were last applied, within the same search and -//! filters as the remaining families. +//! filters as the remaining families. In the Character and Properties panels and the Control bar, +//! the mouse wheel turned over the closed field applies the next family down the menu (or up it) to +//! the selected text, one undo step per notch, stopping at the menu's first and last family. use std::collections::HashMap; use std::sync::Arc; @@ -33,9 +35,13 @@ pub enum FontPick { EndPreview, /// The star of a family was clicked: add it to the favourites, or take it out. Favorite(String), + /// The mouse wheel turned over the closed field: apply each of these families in turn, one + /// undo step each. + Wheel(Vec), } -/// How the menu looks: from the preferences and the favourites. +/// How the menu looks (from the preferences and the favourites) and whether its closed field +/// takes the mouse wheel. #[derive(Clone, Copy, Debug)] pub struct MenuLook<'a> { /// Show each family's sample (Preferences › Type › Enable in-menu font previews). @@ -48,12 +54,15 @@ pub struct MenuLook<'a> { pub favorites: &'a [String], /// Recently applied families, newest first, limited by Number of Recent Fonts. pub recent: &'a [String], + /// The mouse wheel turned over the closed field steps through the families in the menu's + /// order ([`FontPick::Wheel`]): the Character and Properties panels and the Control bar. + pub wheel: bool, } impl Default for MenuLook<'static> { - /// Samples on, English names, medium rows, no favourites. + /// Samples on, English names, medium rows, no favourites, no wheel. fn default() -> Self { - Self { samples: true, english_names: true, row: ROW, favorites: &[], recent: &[] } + Self { samples: true, english_names: true, row: ROW, favorites: &[], recent: &[], wheel: false } } } @@ -70,6 +79,7 @@ impl<'a> MenuLook<'a> { row, favorites: &app.ui.favorite_fonts, recent: app.recent_fonts(), + wheel: false, } } } @@ -235,6 +245,10 @@ struct MenuState { rows_key: Option, /// The height of the search field and filters last frame. header: f32, + /// The families the wheel steps through, listed at its first notch over the closed field and + /// kept while the pointer stays on it: each step makes its family a recent one, which would + /// otherwise move it in the order. + wheel_order: Option>, } /// The font family menu showing `current`, `width` points wide, rows sampling `sample` (the @@ -254,7 +268,7 @@ pub fn font_menu( // The search field and filters stay in place over the rows, which scroll. The rows are all // one height (a family's styles too), so only those in view are laid out: there are thousands // of families. - let shown = widgets::combo_menu(ui, &id, current, width, |menu| { + let (field, shown) = widgets::combo_menu_field(ui, &id, current, width, |menu| { menu.height(height).show_rows_with_header( |ui| header(ui, state_id, state, current, look), look.row, @@ -268,6 +282,31 @@ pub fn font_menu( // Closed (Escape, a click outside) with a preview showing. out = Some(FontPick::EndPreview); } + if !look.wheel || drawn || !field.contains_pointer() { + st.wheel_order = None; + ui.data_mut(|d| d.remove::(field.id.with("wheel"))); + } else if out.is_none() { + let notches = wheel_notches(ui, &field); + if !notches.is_empty() { + let mut own = vectorcraft_text::FontDb::global().canonical(current, "").0; + if st.wheel_order.is_none() { + st.wheel_order = Some(wheel_order(&st, look).into()); + } + let mut steps = Vec::new(); + if let Some(order) = st.wheel_order.as_deref() { + for notch in notches { + let next = wheel_steps(order, &own, notch); + if let Some(last) = next.last() { + own.clone_from(last); + } + steps.extend(next); + } + } + if !steps.is_empty() { + out = Some(FontPick::Wheel(steps)); + } + } + } if matches!(out, Some(FontPick::Chosen(..))) { st.previewed = None; } @@ -275,6 +314,83 @@ pub fn font_menu( out } +/// Does the menu list family `f` for search `query` (lowercase) under the filters of `st`? +fn listed(db: &vectorcraft_text::FontDb, f: &str, query: &str, st: &MenuState, look: MenuLook) -> bool { + let label = db.family_display_name(f, look.english_names); + if !(query.is_empty() || f.to_lowercase().contains(query) || label.to_lowercase().contains(query)) { + return false; + } + if st.favorites_only && !look.favorites.iter().any(|x| x.eq_ignore_ascii_case(f)) { + return false; + } + if st.script == 0 && st.class.is_none() && !st.variable_only { + return true; + } + let traits = db.family_traits(f); + script_matches(st.script, traits) && st.class.is_none_or(|c| c == traits.class) && (!st.variable_only || traits.variable) +} + +/// The families the closed field's wheel steps through, in the open menu's order with no search: +/// the recent families first, then the others, under the menu's filters. +fn wheel_order(st: &MenuState, look: MenuLook) -> Vec { + let db = vectorcraft_text::FontDb::global(); + let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, "", st, look)).cloned().collect(); + grouped_rows(&families, look.recent, &[], |_| vec![]) + .into_iter() + .filter_map(|r| match r { + Row::Family(f) => Some(f), + Row::Heading(_) | Row::Style(..) => None, + }) + .collect() +} + +/// The families `notches` turns of the wheel step to from family `current` in `order`, one per +/// notch: forward (down the menu) when positive, back when negative. The steps stop at either end +/// of the order, and there are none when `current` is not in it. +fn wheel_steps(order: &[String], current: &str, notches: i32) -> Vec { + let Some(at) = order.iter().position(|f| f.eq_ignore_ascii_case(current)) else { return vec![] }; + let last = order.len().saturating_sub(1); + let n = notches.unsigned_abs() as usize; + let to = if notches >= 0 { at.saturating_add(n).min(last) } else { at.saturating_sub(n) }; + if to >= at { order.iter().skip(at + 1).take(to - at).cloned().collect() } else { order.iter().take(at).skip(to).rev().cloned().collect() } +} + +/// Whole notches of the mouse wheel turned over closed field `resp` this frame, positive when it +/// turns down (towards the user). A wheel notch is a line, or `line_scroll_speed` points of a +/// trackpad or fine wheel; what is left of a notch carries over to the next turn. The wheel over +/// the field is the field's: the panel under it does not scroll. A turn with a modifier key is +/// left to the panel and the canvas. +fn wheel_notches(ui: &Ui, resp: &egui::Response) -> Vec { + let (line, id) = (ui.ctx().options(|o| o.input_options.line_scroll_speed), resp.id.with("wheel")); + let mut notches: f32 = ui.data(|d| d.get_temp(id)).unwrap_or(0.0); + let mut completed = Vec::new(); + let mut turned = false; + ui.input_mut(|i| { + i.events.retain(|e| match e { + egui::Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.is_none() => { + notches -= match unit { + egui::MouseWheelUnit::Point => delta.y / line.max(1.0), + egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, + }; + let whole = notches.trunc(); + if whole != 0.0 { + completed.push(whole as i32); + notches -= whole; + } + turned = true; + false + } + _ => true, + }); + if turned || i.modifiers.is_none() { + // The rest of a turn egui spreads over the next frames scrolls nothing either. + i.smooth_scroll_delta = egui::Vec2::ZERO; + } + }); + ui.data_mut(|d| d.insert_temp(id, notches)); + completed +} + /// What the menu's header hands its rows. struct Listed<'s> { st: &'s mut MenuState, @@ -372,7 +488,6 @@ fn header<'s>(ui: &mut Ui, state_id: egui::Id, st: &'s mut MenuState, current: & // as it was before any preview. let current = db.canonical(&st.current, "").0; let current = current.as_str(); - let favorite = |f: &str| look.favorites.iter().any(|x| x.eq_ignore_ascii_case(f)); // The generation is read first: fonts that load meanwhile make the next frame list them. let key: RowsKey = ( query.clone(), @@ -387,21 +502,7 @@ fn header<'s>(ui: &mut Ui, state_id: egui::Id, st: &'s mut MenuState, current: & db.generation(), ); if st.rows_key.as_ref() != Some(&key) { - let wanted = |f: &str| { - let label = db.family_display_name(f, look.english_names); - if !(query.is_empty() || f.to_lowercase().contains(&query) || label.to_lowercase().contains(&query)) { - return false; - } - if st.favorites_only && !favorite(f) { - return false; - } - if st.script == 0 && st.class.is_none() && !st.variable_only { - return true; - } - let traits = db.family_traits(f); - script_matches(st.script, traits) && st.class.is_none_or(|c| c == traits.class) && (!st.variable_only || traits.variable) - }; - let families: Vec<_> = db.menu_family_list().iter().filter(|f| wanted(f)).cloned().collect(); + let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect(); let rows = grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)); // Filter changes (including un-starring a favourite) may remove rows; expanding // another family or a background font scan can insert rows before the highlight. @@ -823,6 +924,21 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, pick: FontPic } } FontPick::Favorite(f) => toggle_favorite(app, f), + FontPick::Wheel(families) => { + if previewing { + app.session.cancel_interaction().ok(); + crate::panels::set_pstate(ctx, PREVIEWING, false); + } + crate::panels::character::end_typing(app); + // Each family is its own step, keeping the style when the family has it, else the + // closest it has. + for f in families { + let (cmd, params) = font_command(app, &f, None); + if app.run(cmd, params).is_err() { + break; + } + } + } FontPick::Chosen(f, style) => { if previewing { app.session.cancel_interaction().ok(); @@ -856,7 +972,7 @@ pub(crate) fn picked(app: &mut VectorcraftApp, pick: Option) -> Option toggle_favorite(app, f); None } - FontPick::Preview(..) | FontPick::EndPreview => None, + FontPick::Preview(..) | FontPick::EndPreview | FontPick::Wheel(_) => None, } } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 4fdfc5733c..3643c54d27 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -225,6 +225,43 @@ fn expanded_style_rows_do_not_retarget_the_highlight() { assert_eq!(remap_highlight(&after, Some(1), &before), None); } +/// #5253: each wheel notch over the closed field steps one family, down the menu or up it, and the +/// steps stop at its first and last family without going round. +#[test] +fn the_wheel_steps_one_family_per_notch_and_stops_at_the_ends() { + let order: Vec = ["Alpha", "Bravo", "Charlie", "Delta"].map(str::to_string).into(); + let steps = |current, notches| super::wheel_steps(&order, current, notches); + assert_eq!(steps("Bravo", 1), ["Charlie"]); + assert_eq!(steps("bravo", -1), ["Alpha"], "any case"); + assert_eq!(steps("Alpha", 2), ["Bravo", "Charlie"], "a step for each notch"); + assert_eq!(steps("Bravo", 5), ["Charlie", "Delta"], "stops at the last family"); + assert_eq!(steps("Charlie", -5), ["Bravo", "Alpha"], "stops at the first family"); + assert!(steps("Delta", 1).is_empty() && steps("Alpha", -1).is_empty(), "no wrapping"); + assert!(steps("Missing", 1).is_empty() && steps("Bravo", 0).is_empty()); +} + +/// #5253: the wheel follows the open menu's order and filters: the recent families first, then the +/// others in the database's order, under the favourites (and other) filters. +#[test] +fn the_wheel_follows_the_menus_order_and_filters() { + let names = vectorcraft_text::FontDb::global().menu_family_list(); + if names.len() < 3 { + return; + } + let recent = vec![names[2].clone()]; + let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() }; + let order = super::wheel_order(&super::MenuState::default(), look); + assert_eq!(order.first(), Some(&names[2]), "the recent family first"); + // Other tests add fonts to the process-wide database meanwhile: compare places, not neighbours. + let at = |f: &String| order.iter().position(|x| x == f); + assert!(matches!((at(&names[0]), at(&names[1])), (Some(a), Some(b)) if 0 < a && a < b), "then the others in the menu's order"); + assert_eq!(order.iter().filter(|f| **f == names[2]).count(), 1, "once each"); + let favorites = vec![names[0].clone(), names[1].clone()]; + let st = super::MenuState { favorites_only: true, ..Default::default() }; + let order = super::wheel_order(&st, super::MenuLook { favorites: &favorites, ..look }); + assert_eq!(order, favorites, "the favourites filter"); +} + /// The Font Technology filter's Variable is the font adjective, not the Variables panel's noun. #[test] fn the_variable_filter_is_named_as_fonts_are() { diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index f1f0707f69..b81ed8cd25 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -801,10 +801,12 @@ fn font_height_reference(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) { } /// The font family menu and the font style dropdown of style `s` (Character and Properties panels, -/// Control bar), with their `ids` and `widths`. +/// Control bar), with their `ids` and `widths`. The mouse wheel over the closed family field steps +/// the text through the families. pub(crate) fn font_pickers(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, ids: (&str, &str), widths: (f32, f32)) { let sample = crate::font_menu::sample_text(app); - if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), crate::font_menu::MenuLook::of(app)) { + let look = crate::font_menu::MenuLook { wheel: true, ..crate::font_menu::MenuLook::of(app) }; + if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), look) { crate::font_menu::apply(app, ui.ctx(), pick); } let styles = vectorcraft_text::FontDb::global().styles(&s.font_family); diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 680afa6d1a..42548244d2 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -203,6 +203,187 @@ fn a_press_outside_the_menu_ends_the_preview_at_once() { assert!(!frame(vec![button(outside, false)]).1); } +/// A document with point type in Inter, selected; its id. +fn selected_inter(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Gagaku", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + id +} + +fn first_style(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::CharStyle { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.first_style(), + _ => panic!("not type"), + } +} + +fn wheel(unit: egui::MouseWheelUnit, dy: f32, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, dy), modifiers, phase: egui::TouchPhase::Move, source: egui::MouseWheelSource::Unknown } +} + +/// One frame of `draw` over `app`, as the shell runs it; the middle of the text naming `family` +/// lowest on the screen (the closed family field), if drawn, and whether the menu's search field +/// is drawn (the menu is open). +fn panel_frame( + ctx: &egui::Context, + app: &mut VectorcraftApp, + events: Vec, + family: &str, + draw: &dyn Fn(&mut VectorcraftApp, &mut egui::Ui), +) -> (Option, bool) { + let input = + egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + crate::font_menu::end_stale_preview(app, ui.ctx()); + draw(app, ui); + }); + out.textures_delta.clear(); + let text = |label: &str| { + out.shapes.iter().find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos + egui::vec2(4.0, t.galley.size().y * 0.5)), + _ => None, + }) + }; + (text(family), text("Search").is_some()) +} + +/// #5253: in the Character panel, each notch of the mouse wheel over the closed font family field +/// applies the next family down the menu (up it when turned up) to the selected type, each its own +/// undo step, with the menu closed. Leaving the field or Escape keeps it; Undo puts it back. +#[test] +fn the_wheel_over_the_family_field_steps_the_selected_type_through_the_families() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let font = |app: &VectorcraftApp| first_style(app, id).font_family; + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + // Other tests add fonts to the process-wide database meanwhile: compare places, not neighbours. + let place = |f: &str| FontDb::global().menu_family_list().iter().position(|x| x == f); + let before = steps(&app); + let line = egui::MouseWheelUnit::Line; + let (_, open) = panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(field), wheel(line, -1.0, Default::default())], "Inter", &draw); + let next = font(&app); + assert!(place(&next) > place("Inter") && steps(&app) == before + 1, "a notch down applies a family below, one step: {next}"); + assert!(!open && !app.session.in_interaction(), "the menu stays closed and nothing is left previewed"); + // The family is now a recent one: the order stays as it was while the pointer stays on the field. + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default())], &next, &draw); + let after = font(&app); + assert!(place(&after) > place(&next) && steps(&app) == before + 2, "{after}"); + panel_frame(&ctx, &mut app, vec![wheel(line, 1.0, Default::default())], &after, &draw); + assert_eq!((font(&app), steps(&app)), (next.clone(), before + 3), "a notch up, back"); + // A turn of a fine wheel in points: a notch is `line_scroll_speed` points, the rest carries over. + let speed = ctx.options(|o| o.input_options.line_scroll_speed); + panel_frame(&ctx, &mut app, vec![wheel(egui::MouseWheelUnit::Point, speed * 0.5, Default::default())], &next, &draw); + assert_eq!(font(&app), next, "less than a notch"); + panel_frame(&ctx, &mut app, vec![wheel(egui::MouseWheelUnit::Point, speed * 0.5, Default::default())], &next, &draw); + assert_eq!((font(&app), steps(&app)), ("Inter".to_string(), before + 4), "the rest of the notch"); + // A turn with a modifier key is not the field's. + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, egui::Modifiers::COMMAND)], "Inter", &draw); + assert_eq!((font(&app), steps(&app)), ("Inter".to_string(), before + 4), "Ctrl/Cmd-wheel"); + // Two notches at once: two families, two steps. + panel_frame(&ctx, &mut app, vec![wheel(line, -2.0, Default::default())], "Inter", &draw); + assert_eq!((font(&app), steps(&app)), (after.clone(), before + 6)); + // Escape and leaving the field keep the family. + panel_frame(&ctx, &mut app, key(egui::Key::Escape), &after, &draw); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(egui::pos2(580.0, 780.0))], &after, &draw); + panel_frame(&ctx, &mut app, vec![], &after, &draw); + assert_eq!((font(&app), steps(&app)), (after, before + 6), "the family stays applied"); + // The wheel away from the field does not change the font. + let shown = font(&app); + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default())], &shown, &draw); + assert_eq!(steps(&app), before + 6, "the wheel off the field"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(font(&app), next, "Undo takes back one notch"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(font(&app), "Inter"); +} + +/// Opposite wheel notches in one frame apply in order, each with its own undo step. +#[test] +fn opposite_wheel_notches_in_one_frame_keep_their_undo_steps() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + let before = app.session.active().unwrap().history.undo.len(); + let line = egui::MouseWheelUnit::Line; + panel_frame( + &ctx, + &mut app, + vec![egui::Event::PointerMoved(field), wheel(line, -1.0, Default::default()), wheel(line, 1.0, Default::default())], + "Inter", + &draw, + ); + assert_eq!(first_style(&app, id).font_family, "Inter"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 2); + app.run("edit.undo", json!({})).unwrap(); + assert_ne!(first_style(&app, id).font_family, "Inter"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(first_style(&app, id).font_family, "Inter"); +} + +/// #5253: the Properties panel and the Control bar have the same family field, and the wheel steps +/// the families over it too. +#[test] +fn the_wheel_steps_the_families_in_properties_and_the_control_bar() { + type Draw = fn(&mut VectorcraftApp, &mut egui::Ui); + let places: [(&str, Draw); 2] = [ + ("Properties", |app, ui| crate::panels::properties::type_sections(app, ui)), + ("Control bar", |app, ui| crate::panels::character::control_bar(app, ui)), + ]; + let at = |f: &str| FontDb::global().menu_family_list().iter().position(|x| x == f); + for (place, draw) in places { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.unwrap_or_else(|| panic!("{place} shows the family field")); + let steps = app.session.active().unwrap().history.undo.len(); + let notch = wheel(egui::MouseWheelUnit::Line, -1.0, Default::default()); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(field), notch], "Inter", &draw); + let next = first_style(&app, id).font_family; + assert!(at(&next) > at("Inter"), "{place}: {next}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "{place}"); + } +} + +/// #5253: a family the wheel steps to keeps the type's style when it has that style, else takes the +/// closest it has, as a family picked from the menu does. The menus that only pick a font ignore +/// the wheel. +#[test] +fn a_family_stepped_to_keeps_the_style_it_has() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let db = FontDb::global(); + let bold: Vec = db.menu_family_list().iter().filter(|f| db.styles(f).iter().any(|s| s == "Bold")).take(2).cloned().collect(); + let [from, to] = bold.as_slice() else { panic!("two families with a Bold style: {bold:?}") }; + app.run("text.setStyle", json!({"font": from, "style": "Bold"})).unwrap(); + crate::font_menu::apply(&mut app, &ctx, FontPick::Wheel(vec![to.clone()])); + let s = first_style(&app, id); + assert_eq!((&s.font_family, s.font_style.as_str()), (to, "Bold")); + assert_eq!(crate::font_menu::picked(&mut app, Some(FontPick::Wheel(vec![from.clone()]))), None); + assert_eq!(&first_style(&app, id).font_family, to, "picking menus leave the document alone"); +} + #[test] fn bundled_families_are_classified() { use vectorcraft_text::FontClass; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index e8da10df34..0e6bb21a74 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -43,7 +43,7 @@ pub use drag::{ }; #[cfg(test)] use dropdowns::combo_button_id; -pub(crate) use dropdowns::{combo, combo_menu, combo_named}; +pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 22ae68345f..781fd7b787 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -135,6 +135,18 @@ pub(crate) fn combo_menu( width: f32, menu: impl FnOnce(craft_ui::combo::Menu<'_>) -> Option, ) -> Option { + combo_menu_field(ui, id, current, width, menu).1 +} + +/// [`combo_menu`], also returning the closed field's response (the font family field reads the +/// mouse wheel turned over it). +pub(crate) fn combo_menu_field( + ui: &mut Ui, + id: impl std::hash::Hash, + current: &str, + width: f32, + menu: impl FnOnce(craft_ui::combo::Menu<'_>) -> Option, +) -> (Response, Option) { let t = Tokens::get(ui.ctx()); let label = take_previous_label(ui); egui::Frame::NONE @@ -148,7 +160,8 @@ pub(crate) fn combo_menu( egui::Popup::open_id(ui.ctx(), egui::Popup::default_response_id(&resp)); ui.memory_mut(|m| m.stop_text_input()); } - menu(craft_ui::combo::Menu::new(ui, &resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)) + let shown = menu(craft_ui::combo::Menu::new(ui, &resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)); + (resp, shown) }) .inner } diff --git a/docs/gaps.md b/docs/gaps.md index cfa4881c13..7c00ad0b94 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,9 +1,16 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Symbol editing shows draggable 9-slice guides; G5: dynamic symbols, #4938; estimate 15–26 → 14–24 h) · **Target:** Adobe Illustrator 2026 (30.x; G12: Units › East Asian Type acts, with Q and Ha units; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; G12: Units › East Asian Type acts, with Q and Ha units; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence +The closed font-family fields in Character, Properties and Control now accept the +mouse wheel for selected text (#5253). Each effective notch applies one family and +adds one undo step; the list follows saved font filters, ignores search text, and +stops at its ends. These interaction details +are VectorCraft's choices. Scores and estimates are unchanged. + +**Feature evidence last updated:** 2026-11-02. **Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -19,6 +26,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | diff --git a/docs/roadmap.md b/docs/roadmap.md index a879347a6a..bf5f67279b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Symbol editing shows draggable 9-slice guides; M5: supersampled exports avoid redundant opaque knockout layers; File formats: `.ai`/EPS import fidelity from a user's file audit; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -145,6 +145,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Font-family fields in Character, Properties and Control step selected text with the wheel (#5253), with one undo step per notch; scores and estimates unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-10-30 | patch | M5: opaque solid-fill knockout paths avoid redundant erase/add layers in hard-edge frames and supersampled raster export; exact-pixel regression coverage retains analytical-AA rounding and translucent knockout behavior; scores and estimates unchanged | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ed3f6b6cca..3864183396 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (SVG ellipse import, inline-graphic kerning, Recolor Artwork displays, and canvas 9-slice guides; Color Effects add-on: Find Nearest Swatch, #4923; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -885,6 +885,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) ("Kerning is the process of adding or subtracting space between specific pairs of characters."). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). +- **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family down the font menu to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps follow the menu's saved font filters but ignore its search text, put recent families first, and stop at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. @@ -1543,6 +1544,7 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Wheel input over closed font-family fields changes selected text (#5253); public documentation and application choices distinguished; scores and estimates unchanged. | | 2026-11-03 | minor | SVG imports preserve exported ellipses as four-anchor paths (#5243). Inline graphics use manual kerning (#5245). Symbol editing shows draggable 9-slice guides (#5280). Recolor Artwork offers smooth and segmented wheels and color bars (#5249). Scores and hours remain unchanged. | | 2026-11-01 | minor | Repeat: a double-click isolates it to edit its source art, text included (#5054); evidence added; scores unchanged. | | 2026-11-01 | minor | Live Corners: Up/Down while dragging a corner widget step the corner kind (#2898); evidence added; scores unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 9c0b7d4006..9ecf0f1663 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (the Type tools make area type or type on a path from a clicked path; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -18,6 +18,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Feature | Status | Notes | |---|---|---| +| Mouse wheel over the closed font-family field | done | #5253: Character, Properties and Control step selected text through the family list using saved font filters (excluding search text), one undo step per notch; the style is matched and the list stops at either end. Escape and leaving the field keep the change. Order, bounds and Undo grouping are VectorCraft's choices; scores unchanged. | | Soft return (forced line break, Shift+Enter) | done | Shift+Enter inserts a soft return (U+2028), breaking the line without starting a new paragraph; paragraph spacing (space before/after) and first-line indents apply only at paragraph ends; continuation lines in lists do not repeat the marker; soft return lines in justified text do not spread (#2754) | | Native font-family labels | partial | With Show Font Names in English off, localized legacy names are used when typographic names contain no native label (#2208); loaded-font and catalog-only regressions. Choosing among multiple native languages is unchanged. | | Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802); `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands; the Type and Vertical Type tools make area type when a closed path's outline is clicked and type on a path when an open one is, with pointers that say which, as the public help describes ([Create text](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html), [Create type on a path](https://web.archive.org/web/20220127090635/https://helpx.adobe.com/illustrator/using/creating-type-path.html)) | @@ -75,6 +76,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | The wheel over Character, Properties and Control font-family fields changes selected text, one undo step per notch (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | The Type and Vertical Type tools make area type in a clicked closed path and type on a path along a clicked open one, with their own pointers; each type tool has its own icon; scores unchanged (estimated) | | 2026-10-31 | minor | Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; scores unchanged | | 2026-11-01 | minor | Glyphs panel (#4908): the character selected with the Type tool (a range's first, else the one before the caret) is highlighted in the grid and scrolled into view when the selection moves to another character; Show › Alternates for Current Selection not yet; scores unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bb52e61812..ae4eb5626b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Symbol editing shows draggable 9-slice guides; Color Effects add-on: Find Nearest Swatch, #4923) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -194,6 +194,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| +| Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. Other font-picking menus and modifier-wheel input keep their existing behavior. | | Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Alt copies | done | | | Fields commit what was typed on a click away or a move to another field, as Enter does; Escape discards it | done | #1787 | | Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a focused field; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370 | @@ -400,6 +401,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | | 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-01 | minor | A double-click on a Repeat with the Selection tool enters isolation mode on it, where its source art (type included: a double-click there edits the text) is edited and every copy follows (#5054); scores and estimates unchanged | | 2026-11-01 | minor | Live Corners: while a corner widget is pressed or dragged with the Selection or Direct Selection tool, the Up and Down arrows step the corners' kind (round, inverted round, chamfer) with the radius, as one undo step (#2898); scores and estimates unchanged | From 13ede29a5e00a2743b99fa50657e890b696c42be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:08:48 -0800 Subject: [PATCH 342/674] Type: route font wheel input before scroll smoothing --- crates/ui-egui/src/app/frame.rs | 2 +- crates/ui-egui/src/app/input.rs | 6 + crates/ui-egui/src/font_menu.rs | 233 ++++++++++++++++++++----- crates/ui-egui/src/font_menu/tests.rs | 93 ++++++++++ crates/ui-egui/src/panels/character.rs | 1 + crates/ui-egui/src/tests/font_menu.rs | 116 +++++++++++- 6 files changed, 404 insertions(+), 47 deletions(-) diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 5fd9dd8d07..0b87eb16b8 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -63,7 +63,7 @@ impl VectorcraftApp { /// Identify the document, modal dialog and focused widget that the current accepted input batch /// belongs to. - pub(super) fn input_generation(&self) -> InputGeneration { + pub(crate) fn input_generation(&self) -> InputGeneration { InputGeneration { document: self.session.active().map_or(0, |document| document.uid), dialog: self.ui.dialog.as_ref().map(|dialog| egui::Id::unique(&dialog.kind)), diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 6bcfdfd3f2..2854e11d6a 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -175,6 +175,12 @@ impl VectorcraftApp { /// injected until the batch was actually applied, so a burst of hidden ticks cannot queue /// several steps of a drag or replay them together later. pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + self.fill_raw_input(ctx, raw); + crate::font_menu::sync_wheel_target(self, ctx, raw.viewport_id); + crate::font_menu::take_raw_wheel(ctx, raw); + } + + fn fill_raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { // Both hosts call this hook once per host iteration, before deciding whether a UI pass // follows; it is the iteration boundary, not a UI-phase marker. self.begin_host_iteration(); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 540951d586..f686b84c9a 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -249,6 +249,7 @@ struct MenuState { /// kept while the pointer stays on it: each step makes its family a recent one, which would /// otherwise move it in the order. wheel_order: Option>, + wheel_target: Option, } /// The font family menu showing `current`, `width` points wide, rows sampling `sample` (the @@ -263,6 +264,12 @@ pub fn font_menu( ) -> Option { let state_id = ui.scope_id().with(&id).with("font-menu"); let mut st: MenuState = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); + let target = ui.data(|d| d.get_temp(wheel_fields_id(ui.ctx().viewport_id()).with("target"))); + let target_changed = st.wheel_target != target; + if target_changed { + st.wheel_order = None; + st.wheel_target = target; + } let height = st.header + LIST_HEIGHT; let state = &mut st; // The search field and filters stay in place over the rows, which scroll. The rows are all @@ -277,35 +284,53 @@ pub fn font_menu( ) }); let drawn = shown.is_some(); + if target_changed { + ui.data_mut(|d| d.remove::(field.id.with("wheel"))); + } let mut out = shown.flatten(); if !drawn && out.is_none() && st.previewed.take().is_some() { // Closed (Escape, a click outside) with a preview showing. out = Some(FontPick::EndPreview); } - if !look.wheel || drawn || !field.contains_pointer() { + let turns = remember_wheel_field(ui, &field, look.wheel && !drawn && field.enabled()); + if !look.wheel || !field.enabled() { st.wheel_order = None; ui.data_mut(|d| d.remove::(field.id.with("wheel"))); - } else if out.is_none() { - let notches = wheel_notches(ui, &field); - if !notches.is_empty() { + } else if out.is_none() || drawn { + if !turns.is_empty() { let mut own = vectorcraft_text::FontDb::global().canonical(current, "").0; - if st.wheel_order.is_none() { - st.wheel_order = Some(wheel_order(&st, look).into()); - } let mut steps = Vec::new(); - if let Some(order) = st.wheel_order.as_deref() { - for notch in notches { - let next = wheel_steps(order, &own, notch); - if let Some(last) = next.last() { - own.clone_from(last); + for turn in turns { + match turn { + WheelInput::Leave => st.wheel_order = None, + WheelInput::Notches(notches) => { + if st.wheel_order.is_none() { + st.wheel_order = Some(wheel_order(&st, look).into()); + } + if let Some(order) = st.wheel_order.as_deref() { + let next = wheel_steps(order, &own, notches); + if let Some(last) = next.last() { + own.clone_from(last); + } + steps.extend(next); + } } - steps.extend(next); } } if !steps.is_empty() { + if drawn { + // These turns preceded the opener. The popup cancels back to the newly + // applied family, and any preview drawn this pass has not been applied. + st.current.clone_from(&own); + st.previewed = None; + } out = Some(FontPick::Wheel(steps)); } } + if drawn || !field.contains_pointer() { + st.wheel_order = None; + ui.data_mut(|d| d.remove::(field.id.with("wheel"))); + } } if matches!(out, Some(FontPick::Chosen(..))) { st.previewed = None; @@ -355,40 +380,158 @@ fn wheel_steps(order: &[String], current: &str, notches: i32) -> Vec { if to >= at { order.iter().skip(at + 1).take(to - at).cloned().collect() } else { order.iter().take(at).skip(to).rev().cloned().collect() } } -/// Whole notches of the mouse wheel turned over closed field `resp` this frame, positive when it -/// turns down (towards the user). A wheel notch is a line, or `line_scroll_speed` points of a -/// trackpad or fine wheel; what is left of a notch carries over to the next turn. The wheel over -/// the field is the field's: the panel under it does not scroll. A turn with a modifier key is -/// left to the panel and the canvas. -fn wheel_notches(ui: &Ui, resp: &egui::Response) -> Vec { - let (line, id) = (ui.ctx().options(|o| o.input_options.line_scroll_speed), resp.id.with("wheel")); - let mut notches: f32 = ui.data(|d| d.get_temp(id)).unwrap_or(0.0); - let mut completed = Vec::new(); - let mut turned = false; - ui.input_mut(|i| { - i.events.retain(|e| match e { - egui::Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.is_none() => { - notches -= match unit { - egui::MouseWheelUnit::Point => delta.y / line.max(1.0), - egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, - }; - let whole = notches.trunc(); - if whole != 0.0 { - completed.push(whole as i32); - notches -= whole; - } - turned = true; - false - } - _ => true, - }); - if turned || i.modifiers.is_none() { - // The rest of a turn egui spreads over the next frames scrolls nothing either. - i.smooth_scroll_delta = egui::Vec2::ZERO; +#[derive(Clone)] +enum WheelInput { + Leave, + Notches(i32), +} + +#[derive(Clone, Copy)] +struct WheelField { + id: egui::Id, + rect: egui::Rect, + layer: egui::LayerId, +} + +#[derive(Clone, Default)] +struct WheelFields { + pass: u64, + pending_frame: u64, + activation_pass: u64, + activating: Vec, + pointer: Option, + fields: Vec, + pending: HashMap>, +} + +fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique("font-wheel-fields").with(viewport) +} + +/// Pending turns belong to the document, dialog and focus that received their input batch. +pub(crate) fn sync_wheel_target(app: &VectorcraftApp, ctx: &egui::Context, viewport: egui::ViewportId) { + let target = app.input_generation(); + let key = wheel_fields_id(viewport); + ctx.data_mut(|d| { + if d.get_temp::(key.with("target")).is_some_and(|old| old != target) { + d.remove::(key); } + d.insert_temp(key.with("target"), target); }); - ui.data_mut(|d| d.insert_temp(id, notches)); - completed +} + +/// Remember the visible closed fields for the next input batch and take this field's turns. +fn remember_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool) -> Vec { + let key = wheel_fields_id(ui.ctx().viewport_id()); + let pass = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| { + let mut fields: WheelFields = d.get_temp(key).unwrap_or_default(); + if fields.pass != pass { + fields.pass = pass; + fields.fields.clear(); + } + fields.fields.retain(|f| f.id != resp.id); + if enabled { + fields.fields.push(WheelField { id: resp.id, rect: resp.interact_rect, layer: resp.layer_id }); + } + let turns = fields.pending.remove(&resp.id).unwrap_or_default(); + d.insert_temp(key, fields); + turns + }) +} + +/// Take the closed font fields' wheel events before egui smooths and combines them. Other +/// events stay in the input, so scrolling elsewhere keeps its own delta and event order. +pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { + let key = wheel_fields_id(raw.viewport_id); + let Some(mut fields) = ctx.data(|d| d.get_temp::(key)) else { return }; + if !ctx.input(|i| i.raw.viewports.contains_key(&raw.viewport_id)) { + ctx.data_mut(|d| d.remove::(key)); + return; + } + let frame = ctx.cumulative_frame_nr_for(raw.viewport_id); + let pass = ctx.cumulative_pass_nr_for(raw.viewport_id); + if pass < fields.pass || pass.saturating_sub(fields.pass) > 1 { + fields.fields.clear(); + fields.pointer = None; + } + if fields.pending_frame != frame { + fields.pending_frame = frame; + fields.pending.clear(); + } + let line = ctx.options(|o| o.input_options.line_scroll_speed).max(1.0); + let mut pointer = fields.pointer.or_else(|| ctx.input(|i| i.pointer.latest_pos())); + let over = + |field: &WheelField, point: Option| point.is_some_and(|p| field.rect.contains(p) && ctx.layer_id_at(p) == Some(field.layer)); + // An activation batch belongs to the popup, including a release after a prior press. + if fields.activation_pass != pass { + fields.activation_pass = pass; + fields.activating.clear(); + let pressed = ctx.input(|i| if i.pointer.button_down(egui::PointerButton::Primary) { i.pointer.press_origin() } else { None }); + if let Some(field) = fields.fields.iter().find(|f| over(f, pressed)) { + fields.activating.push(field.id); + } + } + let focused = ctx.memory(|m| m.focused()); + let mut captured = false; + raw.events.retain(|event| { + let opening = match event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => { + fields.fields.iter().rev().find(|f| over(f, Some(*pos))).map(|f| f.id) + } + egui::Event::Key { key: egui::Key::Enter | egui::Key::Space, pressed: true, .. } if raw.focused => { + focused.filter(|id| fields.fields.iter().any(|f| f.id == *id)) + } + _ => None, + }; + if let Some(id) = opening + && !fields.activating.contains(&id) + { + fields.activating.push(id); + } + match event { + egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } => { + for field in &fields.fields { + if over(field, pointer) && !over(field, Some(*p)) { + ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); + fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + } + } + pointer = Some(*p); + } + egui::Event::PointerGone => { + pointer = None; + for field in &fields.fields { + ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); + fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + } + } + egui::Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.is_none() && delta.y != 0.0 => { + if let Some(field) = fields.fields.iter().rev().find(|f| !fields.activating.contains(&f.id) && over(f, pointer)).copied() { + let id = field.id.with("wheel"); + let mut notches: f32 = ctx.data(|d| d.get_temp(id)).unwrap_or(0.0); + notches -= match unit { + egui::MouseWheelUnit::Point => delta.y / line, + egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, + }; + let whole = notches.trunc(); + ctx.data_mut(|d| d.insert_temp(id, notches - whole)); + if whole != 0.0 { + fields.pending.entry(field.id).or_default().push(WheelInput::Notches(whole as i32)); + } + captured = true; + return false; + } + } + _ => {} + } + true + }); + fields.pointer = pointer; + ctx.data_mut(|d| d.insert_temp(key, fields)); + if captured { + ctx.request_repaint(); + } } /// What the menu's header hands its rows. diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 3643c54d27..73db46de30 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -262,6 +262,99 @@ fn the_wheel_follows_the_menus_order_and_filters() { assert_eq!(order, favorites, "the favourites filter"); } +/// A field removed by a later layout pass must not intercept the next wheel event. +#[test] +fn a_family_field_omitted_from_the_last_pass_leaves_the_wheel_to_its_owner() { + let ctx = egui::Context::default(); + let mut point = egui::Pos2::ZERO; + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let resp = ui.button("Family"); + point = resp.rect.center(); + super::remember_wheel_field(ui, &resp, true); + }); + out.textures_delta.clear(); + } + let mut pass = 0; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + if pass == 0 { + let resp = ui.button("Family"); + point = resp.rect.center(); + super::remember_wheel_field(ui, &resp, true); + ui.ctx().request_discard("the next pass removes the field"); + } + pass += 1; + }); + out.textures_delta.clear(); + assert!(pass > 1); + let mut raw = egui::RawInput { + events: vec![ + egui::Event::PointerMoved(point), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ], + ..Default::default() + }; + super::take_raw_wheel(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))); +} + +/// Activation leaves later wheel input to the popup; an earlier turn still belongs to the field. +#[test] +fn activating_the_family_popup_leaves_its_wheel_input_available() { + let activations = [None, Some((egui::Key::Enter, egui::Modifiers::NONE)), Some((egui::Key::Space, egui::Modifiers::SHIFT))]; + for activation in activations { + let ctx = egui::Context::default(); + let frame = |events| { + let mut raw = egui::RawInput { events, ..Default::default() }; + super::take_raw_wheel(&ctx, &mut raw); + let mut point = egui::Pos2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + let resp = ui.button("Family"); + point = resp.rect.center(); + if activation.is_some() { + resp.request_focus(); + } + super::remember_wheel_field(ui, &resp, true); + }); + out.textures_delta.clear(); + point + }; + let mut point = egui::Pos2::ZERO; + for _ in 0..3 { + point = frame(vec![]); + } + let button = + |pressed| egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let opener = if let Some((key, modifiers)) = activation { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } + } else { + frame(vec![egui::Event::PointerMoved(point), button(true)]); + button(false) + }; + let turn = || egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + let mut events = vec![egui::Event::PointerMoved(point)]; + if activation.is_some() { + events.push(turn()); + } + events.extend([opener, turn()]); + let mut raw = egui::RawInput { events, ..Default::default() }; + super::take_raw_wheel(&ctx, &mut raw); + assert_eq!(raw.events.iter().filter(|e| matches!(e, egui::Event::MouseWheel { .. })).count(), 1); + } +} + /// The Font Technology filter's Variable is the font adjective, not the Variables panel's noun. #[test] fn the_variable_filter_is_named_as_fonts_are() { diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index b81ed8cd25..be3daf2d42 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -804,6 +804,7 @@ fn font_height_reference(app: &mut VectorcraftApp, ui: &mut Ui, width: f32) { /// Control bar), with their `ids` and `widths`. The mouse wheel over the closed family field steps /// the text through the families. pub(crate) fn font_pickers(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, ids: (&str, &str), widths: (f32, f32)) { + crate::font_menu::sync_wheel_target(app, ui.ctx(), ui.ctx().viewport_id()); let sample = crate::font_menu::sample_text(app); let look = crate::font_menu::MenuLook { wheel: true, ..crate::font_menu::MenuLook::of(app) }; if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), look) { diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 42548244d2..078286133f 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -232,8 +232,9 @@ fn panel_frame( family: &str, draw: &dyn Fn(&mut VectorcraftApp, &mut egui::Ui), ) -> (Option, bool) { - let input = + let mut input = egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), ..Default::default() }; + app.raw_input_hook(ctx, &mut input); let mut out = ctx.run_ui(input, |ui| { crate::font_menu::end_stale_preview(app, ui.ctx()); draw(app, ui); @@ -336,6 +337,119 @@ fn opposite_wheel_notches_in_one_frame_keep_their_undo_steps() { assert_eq!(first_style(&app, id).font_family, "Inter"); } +/// A turn before opening applies once; the popup keeps the later wheel and cancels to that font. +#[test] +fn a_wheel_before_opening_the_family_popup_keeps_its_committed_change() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + let button = |pressed| egui::Event::PointerButton { pos: field, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let turn = || wheel(egui::MouseWheelUnit::Line, -1.0, Default::default()); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(field), turn(), button(true), button(false), turn()], "Inter", &draw); + let applied = first_style(&app, id).font_family; + assert_ne!(applied, "Inter"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + for _ in 0..3 { + panel_frame(&ctx, &mut app, vec![], &applied, &draw); + } + panel_frame(&ctx, &mut app, key(egui::Key::Escape), &applied, &draw); + assert_eq!(first_style(&app, id).font_family, applied); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(first_style(&app, id).font_family, "Inter"); +} + +/// A later pointer move must not change which field owns an earlier wheel event. +#[test] +fn wheel_events_use_the_pointer_position_when_they_occurred() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + let outside = egui::pos2(580.0, 780.0); + panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(outside)], "Inter", &draw); + let before = app.session.active().unwrap().history.undo.len(); + let line = egui::MouseWheelUnit::Line; + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default()), egui::Event::PointerMoved(field)], "Inter", &draw); + assert_eq!(first_style(&app, id).font_family, "Inter", "the wheel was outside the field"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + assert!(ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))), "outside wheel input is left for its owner"); + panel_frame(&ctx, &mut app, vec![wheel(line, -1.0, Default::default()), egui::Event::PointerMoved(outside)], "Inter", &draw); + assert_ne!(first_style(&app, id).font_family, "Inter", "the wheel was over the field before the pointer left"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(first_style(&app, id).font_family, "Inter"); + let button = |pos| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + panel_frame(&ctx, &mut app, vec![button(field), wheel(line, -1.0, Default::default()), button(outside)], "Inter", &draw); + assert_ne!(first_style(&app, id).font_family, "Inter", "button events also carry the pointer's position"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + app.run("edit.undo", json!({})).unwrap(); + let end = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::Vec2::ZERO, + modifiers: Default::default(), + phase: egui::TouchPhase::End, + source: egui::MouseWheelSource::Unknown, + }; + panel_frame(&ctx, &mut app, vec![end], "Inter", &draw); + panel_frame( + &ctx, + &mut app, + vec![ + wheel(egui::MouseWheelUnit::Point, -2.0, Default::default()), + egui::Event::PointerMoved(field), + wheel(line, -1.0, Default::default()), + egui::Event::PointerMoved(outside), + ], + "Inter", + &draw, + ); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + assert_eq!(ctx.input(|i| i.smooth_scroll_delta.y), -2.0, "only the outside wheel contributes to panel scrolling"); +} + +/// A turn queued for one document cannot restyle another document opened before its UI pass. +#[test] +fn a_wheel_queued_for_another_document_is_discarded() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + selected_inter(&mut app); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + let field = field.expect("the Character panel shows the family field"); + let mut raw = egui::RawInput { + events: vec![egui::Event::PointerMoved(field), wheel(egui::MouseWheelUnit::Line, -1.0, Default::default())], + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), + ..Default::default() + }; + app.raw_input_hook(&ctx, &mut raw); + assert!(!raw.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))); + let id = selected_inter(&mut app); + let before = app.session.active().unwrap().history.undo.len(); + let mut out = ctx.run_ui(raw, |ui| draw(&mut app, ui)); + out.textures_delta.clear(); + assert_eq!(first_style(&app, id).font_family, "Inter"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); +} + /// #5253: the Properties panel and the Control bar have the same family field, and the wheel steps /// the families over it too. #[test] From 89f3d79eecbc6f52f5a97eb25a203159d88f26b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:14:10 -0800 Subject: [PATCH 343/674] Type: clarify stable font wheel ordering --- crates/ui-egui/src/font_menu.rs | 5 +++-- docs/target-app-parity.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index f686b84c9a..bf30ba9bcf 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -9,8 +9,9 @@ //! in-menu font previews and Font Preview Size turn the samples off or size the rows. Recently //! used families appear first, in the order they were last applied, within the same search and //! filters as the remaining families. In the Character and Properties panels and the Control bar, -//! the mouse wheel turned over the closed field applies the next family down the menu (or up it) to -//! the selected text, one undo step per notch, stopping at the menu's first and last family. +//! the mouse wheel turned over the closed field applies the next family (or previous one) to the +//! selected text, one undo step per notch. The menu's order at the first turn stays fixed until the +//! pointer leaves the field; steps stop at its first and last family. use std::collections::HashMap; use std::sync::Arc; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3864183396..b61a86b065 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -885,7 +885,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) ("Kerning is the process of adding or subtracting space between specific pairs of characters."). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). -- **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family down the font menu to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps follow the menu's saved font filters but ignore its search text, put recent families first, and stop at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`. +- **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field, so recent-font updates do not reshuffle later turns. That order follows the menu's saved font filters but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. From 80f51a62da9b9128dc7071af9c1c60d69bda9e2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:37:08 -0800 Subject: [PATCH 344/674] Type: stop hidden font fields from capturing wheel input --- crates/ui-egui/src/font_menu.rs | 93 ++++++++++++++++++-- crates/ui-egui/src/panels/character.rs | 31 +++++-- crates/ui-egui/src/tests/font_menu.rs | 32 +++++++ crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/dropdowns.rs | 8 +- crates/ui-egui/tests/font_wheel.rs | 107 ++++++++++++++++++++++++ 6 files changed, 259 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/tests/font_wheel.rs diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index bf30ba9bcf..567e260a60 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -41,6 +41,42 @@ pub enum FontPick { Wheel(Vec), } +/// The UI that contains a font family field. +#[derive(Clone, Copy, Debug)] +pub enum WheelOwner { + Character, + Properties, + Control, + /// The Character popover attached to this Control bar link. + ControlPopover(egui::Id), +} + +impl WheelOwner { + fn visible(self, app: &VectorcraftApp, ctx: &egui::Context) -> bool { + if crate::panels::character::text_style(app).is_none() { + return false; + } + let panel = match self { + Self::Control => return app.ui.control_bar && app.ui.screen_mode < 2, + Self::ControlPopover(anchor) => { + return app.ui.control_bar && app.ui.screen_mode < 2 && widgets::popover_is_open(ctx, anchor); + } + Self::Character => "character", + Self::Properties => { + let selected = app.session.active().and_then(|document| document.selection.objects.first().and_then(|id| document.doc.node(*id))); + if !selected.is_some_and(|n| matches!(&n.kind, vectorcraft_doc::NodeKind::Text(_))) { + return false; + } + "properties" + } + }; + app.ui.dock + && app.ui.screen_mode < 3 + && (crate::panel_docking::showing(&app.ui, panel) + || (app.ui.transient_panel.as_deref() == Some(panel) && crate::panel_docking::showing(&app.ui, "appearance"))) + } +} + /// How the menu looks (from the preferences and the favourites) and whether its closed field /// takes the mouse wheel. #[derive(Clone, Copy, Debug)] @@ -58,12 +94,14 @@ pub struct MenuLook<'a> { /// The mouse wheel turned over the closed field steps through the families in the menu's /// order ([`FontPick::Wheel`]): the Character and Properties panels and the Control bar. pub wheel: bool, + /// Its owner, so a field hidden before the next layout cannot capture wheel input. + pub wheel_owner: Option, } impl Default for MenuLook<'static> { /// Samples on, English names, medium rows, no favourites, no wheel. fn default() -> Self { - Self { samples: true, english_names: true, row: ROW, favorites: &[], recent: &[], wheel: false } + Self { samples: true, english_names: true, row: ROW, favorites: &[], recent: &[], wheel: false, wheel_owner: None } } } @@ -81,6 +119,7 @@ impl<'a> MenuLook<'a> { favorites: &app.ui.favorite_fonts, recent: app.recent_fonts(), wheel: false, + wheel_owner: None, } } } @@ -250,7 +289,7 @@ struct MenuState { /// kept while the pointer stays on it: each step makes its family a recent one, which would /// otherwise move it in the order. wheel_order: Option>, - wheel_target: Option, + wheel_target: Option, } /// The font family menu showing `current`, `width` points wide, rows sampling `sample` (the @@ -293,7 +332,7 @@ pub fn font_menu( // Closed (Escape, a click outside) with a preview showing. out = Some(FontPick::EndPreview); } - let turns = remember_wheel_field(ui, &field, look.wheel && !drawn && field.enabled()); + let turns = remember_owned_wheel_field(ui, &field, look.wheel && !drawn && field.enabled(), state_id, look.wheel_owner); if !look.wheel || !field.enabled() { st.wheel_order = None; ui.data_mut(|d| d.remove::(field.id.with("wheel"))); @@ -390,6 +429,8 @@ enum WheelInput { #[derive(Clone, Copy)] struct WheelField { id: egui::Id, + menu: egui::Id, + owner: Option, rect: egui::Rect, layer: egui::LayerId, } @@ -409,20 +450,58 @@ fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { egui::Id::unique("font-wheel-fields").with(viewport) } -/// Pending turns belong to the document, dialog and focus that received their input batch. +#[derive(Clone, Copy, PartialEq)] +struct WheelTarget { + input: crate::state::InputGeneration, + workspace: u64, +} + +/// Pending turns and field rectangles belong to their input target and visible workspace. pub(crate) fn sync_wheel_target(app: &VectorcraftApp, ctx: &egui::Context, viewport: egui::ViewportId) { - let target = app.input_generation(); + let target = WheelTarget { input: app.input_generation(), workspace: app.ui.docking_generation }; let key = wheel_fields_id(viewport); + let (previous, mut fields) = ctx.data(|d| (d.get_temp::(key.with("target")), d.get_temp::(key))); + if previous.is_some_and(|old| old != target) { + fields = None; + } + let mut hidden = Vec::new(); + if let Some(fields) = &mut fields { + fields.fields.retain(|field| { + if field.owner.is_none_or(|owner| owner.visible(app, ctx)) { + true + } else { + hidden.push(*field); + false + } + }); + for field in &hidden { + fields.pending.remove(&field.id); + } + } ctx.data_mut(|d| { - if d.get_temp::(key.with("target")).is_some_and(|old| old != target) { + if let Some(fields) = fields { + d.insert_temp(key, fields); + } else { d.remove::(key); } + for field in hidden { + d.remove::(field.id.with("wheel")); + if let Some(mut state) = d.get_temp::(field.menu) { + state.wheel_order = None; + d.insert_temp(field.menu, state); + } + } d.insert_temp(key.with("target"), target); }); } /// Remember the visible closed fields for the next input batch and take this field's turns. +#[cfg(test)] fn remember_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool) -> Vec { + remember_owned_wheel_field(ui, resp, enabled, resp.id, None) +} + +fn remember_owned_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool, menu: egui::Id, owner: Option) -> Vec { let key = wheel_fields_id(ui.ctx().viewport_id()); let pass = ui.ctx().cumulative_pass_nr(); ui.data_mut(|d| { @@ -433,7 +512,7 @@ fn remember_wheel_field(ui: &Ui, resp: &egui::Response, enabled: bool) -> Vec Some(crate::font_menu::WheelOwner::Character), + "font" => Some(crate::font_menu::WheelOwner::Properties), + "cb-font" => Some(crate::font_menu::WheelOwner::Control), + _ => None, + }; + font_pickers_owned(app, ui, s, ids, widths, wheel_owner); +} + +fn font_pickers_owned( + app: &mut VectorcraftApp, + ui: &mut Ui, + s: &CharStyle, + ids: (&str, &str), + widths: (f32, f32), + wheel_owner: Option, +) { crate::font_menu::sync_wheel_target(app, ui.ctx(), ui.ctx().viewport_id()); let sample = crate::font_menu::sample_text(app); - let look = crate::font_menu::MenuLook { wheel: true, ..crate::font_menu::MenuLook::of(app) }; + let look = crate::font_menu::MenuLook { wheel: true, wheel_owner, ..crate::font_menu::MenuLook::of(app) }; if let Some(pick) = crate::font_menu::font_menu(ui, ids.0, &s.font_family, widths.0, sample.as_deref(), look) { crate::font_menu::apply(app, ui.ctx(), pick); } @@ -895,7 +912,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .on_hover_text(tl!("Character options")); widgets::popover(&link, link.clicked(), |ui| { ui.set_width(260.0); - show(app, ui); + show_owned(app, ui, crate::font_menu::WheelOwner::ControlPopover(link.id)); }); font_pickers(app, ui, &s, ("cb-font", "cb-font-style"), (150.0, 96.0)); size_field(app, ui, "cb-font-size", 96.0); @@ -907,7 +924,11 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { const SNAP_TO_GLYPH_OPTIONS: &str = "ch-snap-to-glyph-options"; pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - attributes(app, ui); + show_owned(app, ui, crate::font_menu::WheelOwner::Character); +} + +fn show_owned(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::WheelOwner) { + attributes(app, ui, owner); // Drawing over type needs no type selected, so the options show without one too. if pstate::(ui.ctx(), SNAP_TO_GLYPH_OPTIONS) { snap_to_glyph_options(app, ui); @@ -945,7 +966,7 @@ fn snap_to_glyph_options(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The character attributes of the type selected (an empty state without any). -fn attributes(app: &mut VectorcraftApp, ui: &mut Ui) { +fn attributes(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::WheelOwner) { let Some((s, _)) = text_style(app) else { app.character_focus = None; super::empty_state(ui, "type", tl!("No text selected"), tl!("Select a text object to edit its character attributes.")); @@ -957,7 +978,7 @@ fn attributes(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(f) = app.character_focus { widgets::arm_field_focus(ui.ctx(), f.salt()); } - font_pickers(app, ui, &s, ("ch-font", "ch-style"), (w - 4.0, w - 4.0)); + font_pickers_owned(app, ui, &s, ("ch-font", "ch-style"), (w - 4.0, w - 4.0), Some(owner)); variable_font(app, ui, &s, w - 4.0); ui.add_space(2.0); let hidden = pstate::(ui.ctx(), "ch-hide-options"); diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 078286133f..624c32c7ea 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -208,6 +208,9 @@ fn selected_inter(app: &mut VectorcraftApp) -> u64 { app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Gagaku", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + if !crate::panel_docking::showing(&app.ui, "character") { + app.run("window.panel", json!({"panel": "character"})).unwrap(); + } id } @@ -450,6 +453,34 @@ fn a_wheel_queued_for_another_document_is_discarded() { assert_eq!(app.session.active().unwrap().history.undo.len(), before); } +/// Presentation mode hides an Appearance row's Character popup even if its state is still open. +#[test] +fn presentation_mode_leaves_a_transient_font_fields_wheel_available() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + selected_inter(&mut app); + app.run("window.panel.close", json!({"panel": "character"})).unwrap(); + app.run("window.panel.close", json!({"panel": "properties"})).unwrap(); + app.run("window.panel", json!({"panel": "appearance"})).unwrap(); + assert!(!crate::panel_docking::showing(&app.ui, "character")); + assert!(!crate::panel_docking::showing(&app.ui, "properties")); + assert!(crate::panel_docking::showing(&app.ui, "appearance")); + app.ui.transient_panel = Some("character".into()); + let draw = |app: &mut VectorcraftApp, ui: &mut egui::Ui| crate::panels::character::show(app, ui); + let mut field = None; + for _ in 0..3 { + field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; + } + app.ui.screen_mode = 3; + let mut raw = egui::RawInput { + events: vec![egui::Event::PointerMoved(field.unwrap()), wheel(egui::MouseWheelUnit::Line, -1.0, Default::default())], + ..Default::default() + }; + app.raw_input_hook(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, egui::Event::MouseWheel { .. }))); +} + /// #5253: the Properties panel and the Control bar have the same family field, and the wheel steps /// the families over it too. #[test] @@ -465,6 +496,7 @@ fn the_wheel_steps_the_families_in_properties_and_the_control_bar() { crate::theme::install_fonts(&ctx); let mut app = VectorcraftApp::new(Session::new(), Default::default()); let id = selected_inter(&mut app); + app.ui.control_bar = true; let mut field = None; for _ in 0..3 { field = panel_frame(&ctx, &mut app, vec![], "Inter", &draw).0; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 0e6bb21a74..b6b4130b88 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -43,7 +43,7 @@ pub use drag::{ }; #[cfg(test)] use dropdowns::combo_button_id; -pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named}; +pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field, combo_named, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 781fd7b787..a9b56e0914 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -217,7 +217,7 @@ pub fn popover(resp: &Response, toggle: bool, content: impl FnOnce(&mut Ui) - let ctx = &resp.ctx; let id = resp.id.with("popover"); let frame = ctx.cumulative_frame_nr(); - let was_open = ctx.data(|d| d.get_temp::(id)).is_some_and(|f| f + 1 >= frame); + let was_open = popover_is_open(ctx, resp.id); let mut open = if toggle { !was_open } else { @@ -246,6 +246,12 @@ pub fn popover(resp: &Response, toggle: bool, content: impl FnOnce(&mut Ui) - inner } +/// Whether the popover for this anchor was open in the latest completed frame. +pub(crate) fn popover_is_open(ctx: &egui::Context, anchor: egui::Id) -> bool { + let frame = ctx.cumulative_frame_nr(); + ctx.data(|d| d.get_temp::(anchor.with("popover"))).is_some_and(|f| f + 1 >= frame) +} + /// Records where the bottom bars (status and hint bars) start this frame, so menus can stop above /// them (#2086). Without bars it is the bottom of the window. pub fn set_menu_floor(ctx: &egui::Context, y: f32) { diff --git a/crates/ui-egui/tests/font_wheel.rs b/crates/ui-egui/tests/font_wheel.rs new file mode 100644 index 0000000000..7f8e0353c0 --- /dev/null +++ b/crates/ui-egui/tests/font_wheel.rs @@ -0,0 +1,107 @@ +//! Wheel routing when a font field disappears before the next layout pass. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use egui::{Event, MouseWheelSource, MouseWheelUnit, Pos2, RawInput, Rect, Shape, TouchPhase, vec2}; +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_ui_egui::VectorcraftApp; + +#[test] +fn hiding_control_between_passes_leaves_its_old_fields_wheel_available() { + assert!(control_wheel_available_after("window.control", json!({}))); +} + +#[test] +fn hiding_properties_preserves_the_visible_control_fields_wheel() { + assert!(!control_wheel_available_after("window.panel.close", json!({"panel": "properties"}))); +} + +#[test] +fn deselecting_type_leaves_the_missing_control_fields_wheel_available() { + assert!(control_wheel_available_after("select.set", json!({"ids": []}))); +} + +#[test] +fn the_control_character_popover_keeps_its_visible_font_wheel() { + let (ctx, mut app) = selected_type_with_control(); + app.run("window.panel.close", json!({"panel": "character"})).unwrap(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let link = texts.iter().find(|(t, p)| t == "Character:" && p.y < 100.0).unwrap().1; + let button = |pressed| Event::PointerButton { pos: link, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(link), button(true)]); + frame(&mut app, &ctx, vec![button(false)]); + for _ in 0..3 { + texts = frame(&mut app, &ctx, vec![]); + } + let point = texts + .iter() + .find(|(t, p)| t == "Inter" && p.y > link.y + 10.0 && p.y < link.y + 100.0 && (p.x - link.x).abs() < 100.0) + .expect("the Character popover shows its family field") + .1; + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(!raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the visible popover keeps font wheel input"); + app.run("window.control", json!({})).unwrap(); + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "hiding Control also hides its popover"); +} + +fn selected_type_with_control() -> (egui::Context, VectorcraftApp) { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 250})).unwrap(); + let text = app.run("text.create", json!({"x": 30, "y": 70, "text": "Control wheel", "font": "Inter"})).unwrap(); + app.run("select.set", json!({"ids": [text["id"]]})).unwrap(); + app.run("window.control", json!({})).unwrap(); + (ctx, app) +} + +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Pos2)> { + let mut raw = RawInput { events, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; + app.raw_input_hook(ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + let texts = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + Shape::Text(t) => Some((t.galley.text().to_string(), t.pos + vec2(4.0, 6.0))), + _ => None, + }) + .collect(); + out.textures_delta.clear(); + texts +} + +fn control_wheel_available_after(command: &str, params: Value) -> bool { + let (ctx, mut app) = selected_type_with_control(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let point = texts.iter().find(|(t, p)| t == "Inter" && p.y < 150.0).expect("the Control bar's family field is rendered").1; + app.run(command, params).unwrap(); + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })) +} + +fn wheel_input(point: Pos2) -> RawInput { + RawInput { + events: vec![ + Event::PointerMoved(point), + Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: TouchPhase::Move, + modifiers: Default::default(), + source: MouseWheelSource::Unknown, + }, + ], + ..Default::default() + } +} From a9048ddfabb9c8ffc3dcd109f21a7b9d4dbe134a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:44:40 -0800 Subject: [PATCH 345/674] Type: leave wheel input to replacement Artboard controls --- crates/ui-egui/src/font_menu.rs | 1 + crates/ui-egui/tests/font_wheel.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 567e260a60..953be1a56b 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -57,6 +57,7 @@ impl WheelOwner { return false; } let panel = match self { + Self::Control | Self::ControlPopover(_) | Self::Properties if app.session.tool_id() == "artboard" => return false, Self::Control => return app.ui.control_bar && app.ui.screen_mode < 2, Self::ControlPopover(anchor) => { return app.ui.control_bar && app.ui.screen_mode < 2 && widgets::popover_is_open(ctx, anchor); diff --git a/crates/ui-egui/tests/font_wheel.rs b/crates/ui-egui/tests/font_wheel.rs index 7f8e0353c0..5c27c1db62 100644 --- a/crates/ui-egui/tests/font_wheel.rs +++ b/crates/ui-egui/tests/font_wheel.rs @@ -22,6 +22,23 @@ fn deselecting_type_leaves_the_missing_control_fields_wheel_available() { assert!(control_wheel_available_after("select.set", json!({"ids": []}))); } +#[test] +fn artboard_controls_leave_replaced_font_fields_wheel_available() { + let (ctx, mut app) = selected_type_with_control(); + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let fields: Vec<_> = texts.iter().filter(|(t, _)| t == "Inter").map(|(_, point)| *point).collect(); + assert_eq!(fields.len(), 2, "Control and Properties each show a font field"); + app.select_tool("artboard"); + for point in fields { + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the Artboard tool replaces this font field"); + } +} + #[test] fn the_control_character_popover_keeps_its_visible_font_wheel() { let (ctx, mut app) = selected_type_with_control(); From 012ac29d15f397e31a8cfe404d5523f5b81fd9fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:00:31 +0700 Subject: [PATCH 346/674] Window: Tile with one document open leaves the documents under their tabs Squashed from #5256 onto main. --- crates/ui-egui/src/canvas/panes.rs | 16 +++++++++------- crates/ui-egui/src/canvas/panes/tests.rs | 12 ++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 6 ++++++ docs/roadmap.md | 4 ++-- docs/target-app-parity.md | 7 ++++--- 6 files changed, 34 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index c9e8b1fe87..5876537c3b 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -140,16 +140,18 @@ pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. The -/// documents in floating windows come back under the tabs for it. +/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. With +/// fewer than two documents open (when the menu item is grayed out) it leaves the view and `tiled` as +/// they are. The documents in floating windows come back under the tabs for it. pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { + let n = app.session.documents().len(); + if n < 2 { + return Ok(json!({"tiled": app.ui.tiled, "panes": n})); + } app.sync_views(); crate::doc_windows::dock_all(app); - let n = app.session.documents().len(); - app.ui.tiled = n > 0; - if n > 0 { - app.ui.home = None; - } + app.ui.tiled = true; + app.ui.home = None; for v in &mut app.views { v.fitted = false; } diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 943734c0ea..cdd6add6dc 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -179,6 +179,18 @@ fn arrange_items_follow_the_open_documents() { assert!(!app.ui.tiled); } +#[test] +fn tile_with_one_document_leaves_the_next_one_under_its_tab() { + let mut app = app_with(1); + let ctx = egui::Context::default(); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1})); + assert!(!app.ui.tiled); + assert!(!enabled(&app, "window.arrange.consolidateAllWindows")); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(panes(&app).0.is_empty(), "the second document opens under its tab"); +} + #[test] fn closing_a_document_while_tiled_tiles_the_others() { let mut app = app_with(3); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 8d1b6b36bd..97b7926e83 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -591,7 +591,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of documents, rounded up), each fitted to its pane; the current document's pane takes the tools, a click in another pane makes its document the current one; the tabs stay; documents in floating windows come back under the tabs first; returns {tiled: true, panes}", + "{} show every open document at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of documents, rounded up), each fitted to its pane; the current document's pane takes the tools, a click in another pane makes its document the current one; the tabs stay; documents in floating windows come back under the tabs first; with fewer than two documents open the view stays as it is; returns {tiled, panes}", ), ( "window.arrange.floatInWindow", diff --git a/docs/mcp.md b/docs/mcp.md index 4081cc27a9..ab1a022a29 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3638,6 +3638,12 @@ document. With no document open they fail with "no document open". `document.act the current one. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to +its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. +The current document's pane is the canvas, and a press in another pane makes its document the current one. +`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab +again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` and `panes` (each pane's +`document` index, `rect` and whether it is `active`); canvas coordinates map to the current document's pane +(`canvasRect`). its pane; it returns `{tiled, panes}`. The current document's pane is the canvas, and a press in another pane makes its document the current one. `window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document out of the tab strip into a floating window of its own, `window.arrange.floatAllInWindows` (Float All in Windows) does diff --git a/docs/roadmap.md b/docs/roadmap.md index abfaea70ba..aaf046994a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -98,9 +98,9 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; broader scripting and batch work remains | 18–27 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0cd246dd7d..b6de6486ec 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -144,10 +144,10 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | -| View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | +| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | -| View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | -| View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated | +| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | +| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; status-bar X/Y uses the active ruler origin and General units | @@ -526,6 +526,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Global and artboard rulers:** View › Rulers › Change to Global / Artboard Rulers (Cmd+Alt+R, `view.globalRulers`). A new document has artboard rulers: the rulers and the Transform, Properties, Control and Info X/Y count from the active artboard's top-left corner, or the zero point dragged out for that artboard, which moves with it; with global rulers one document zero point serves every artboard. Guide readouts and Shift ruler-tick snapping follow the same zero point. The mode is saved with the document; files from before it open with global rulers, as they measured. Regression tests: `engine/tests/it/ruler_origin.rs`, `ui-egui/src/tests/ruler_origin.rs`, `tools/src/rulerguide.rs`. Public reference: [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html). - **Video display options (#2849):** Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio, and View › Rulers › Show Video Rulers ([Set video display options for artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)). Each artboard has its own (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1), set in one undo step and written to the native format only when on or not 1, so other documents save byte for byte as before. The help page names the safe areas without numbers; our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s (note 5): the canvas outlines the action-safe area 3.5% and the title-safe (graphics-safe) area 5% in from each edge, 1 point wide and turned with the view; exports and print leave them out. Show Video Rulers (`view.videoRulers`) shows the rulers counting the active artboard in pixels from its top-left corner, whatever the ruler origin: a pixel is as many points wide as the ratio and one point tall, so a 720 × 480 pt artboard at 0.9 reads 800 × 480. Hide Video Rulers returns them to the General unit; Shift ruler-tick snapping of new guides keeps the General unit. Regression tests: `tests/panelcmds.rs` (`artboard_video_display_options_*`, `artboard_display_marks_stay_out_of_exports`), `tests/docsetup.rs` (`an_artboard_shows_its_video_safe_areas`), `canvas.rs` (`video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`), `tests/ruler_origin.rs` (`show_video_rulers_counts_the_active_artboard_in_pixels`), `dialogs/tests.rs` (`artboard_options_show_video_display_options`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). +- **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Tile displays windows edge to edge"), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "drag the window's tab out of the group"). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): "Cascade displays windows stacked and descending from the upper-left to the lower-right of the screen"). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html): "To undock (float or untab) a Document window from a group of windows, drag the window’s tab out of the group. To dock a Document window to a separate group of Document windows, drag the window into the group."). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. From 449dd5f5edeb4d0bf8973ebbea5715bab35c9e2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:23:13 -0800 Subject: [PATCH 347/674] Preserve SVG styles with encoded attribute selectors --- crates/svg/src/import/prepass.rs | 7 ++++--- crates/svg/tests/it/import_live.rs | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index 245392fda3..5a393e79aa 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -149,7 +149,7 @@ fn named_made_up_ids(xml: &roxmltree::Document) -> HashSet { /// * so do objects with attributes in other applications' namespaces ([`foreign`]); /// * so do `` and `` elements, recorded: usvg makes their arcs into a varying /// number of curves, and they come back as the ellipse VectorCraft draws (not in a file whose -/// style sheet has an `[id` selector); +/// style sheet has an attribute selector); /// * linked files are read ([`files`]); /// * percentage lengths in a `` with a `viewBox` become numbers ([`symbol_units`]); /// * what style sheet rules with a `:not()` set goes in `style` attributes ([`not_rules`]). @@ -164,8 +164,9 @@ pub(super) fn prepass<'s>(svg: &'s str, markers: &str, xml: &roxmltree::Document let not = markers.contains(":not("); let events = SVG_EVENTS.iter().any(|e| markers.contains(e)); let foreign_attrs = markers.contains("xmlns:") && has_foreign_attributes(xml); - // An id would change what a style sheet's `[id]` selector matches: such files keep usvg's curves. - let ellipses = !markers.contains("[id") && [" (Document, Vec) { import_with_report(&svg(body)).unwrap() } +#[test] +fn decoded_id_selectors_do_not_recolor_bare_ellipses() { + for selector in ["circle[id]", "ellipse[id]", "circle[id]", "ellipse[id]", "circle[ id ]", r"ellipse[\69 d]"] { + let source = svg(&format!( + "" + )); + let doc = import(&source).unwrap(); + let actual = render_artboard(&doc); + let expected = resvg_render(&source, 200, 120); + assert_eq!((actual.width, actual.height), (expected.width, expected.height)); + for (x, y) in [(40, 50), (100, 50), (40, 100), (100, 100)] { + let at = 4 * (y * actual.width + x) as usize; + assert_eq!(&actual.rgba[at..at + 4], &expected.rgba[at..at + 4], "{selector}: ({x}, {y})"); + } + } +} + /// All non-layer nodes in paint order. fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); From c633e09d3ad98723cf1dcfa1b8b6ddd8e5fb3bad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:35:36 -0800 Subject: [PATCH 348/674] Exclude empty runs from matching text selections --- crates/engine/src/cmd/docmenu.rs | 2 +- crates/engine/src/tests/menucmds.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 3d77bde156..58d5daf17a 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -325,7 +325,7 @@ fn first_text_style(s: &Session) -> Option { fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) -> Result { let r = first_text_style(s).ok_or_else(|| bad(cmd, "select a text object"))?; let ids = candidates(s, |n| match &n.kind { - NodeKind::Text(t) => t.runs.iter().any(|run| eq(&run.style, &r)), + NodeKind::Text(t) => t.runs.iter().any(|run| !run.text.is_empty() && eq(&run.style, &r)), _ => false, })?; finish_same(s, cmd, ids) diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index f378554562..0c351dba7d 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1991,6 +1991,19 @@ fn select_same_text_fill_and_stroke_color_needs_both_to_match() { assert!(s.execute("select.same.textFillAndStrokeColor", &json!({})).is_err()); } +#[test] +fn select_same_character_colors_ignore_empty_text() { + let mut s = session(); + let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 20, "text": "a"})).unwrap()); + let b = id_of(&s.execute("text.create", &json!({"x": 0, "y": 40, "text": "b"})).unwrap()); + let empty = id_of(&s.execute("text.create", &json!({"x": 0, "y": 60, "text": ""})).unwrap()); + for cmd in ["select.same.textFillColor", "select.same.textStrokeColor", "select.same.textFillAndStrokeColor"] { + sel(&mut s, &[a]); + s.execute(cmd, &json!({})).unwrap(); + assert_eq!(selected(&s), vec![a, b], "{cmd}: empty object {empty:?}"); + } +} + #[test] fn select_same_link_block_series_selects_the_frames_of_a_thread() { let mut s = session(); From 2b6cbfda5de5669cf9be83d6f68e976a9f60c437 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:23:03 -0800 Subject: [PATCH 349/674] Update SVG, type, recoloring, and symbol feature records --- docs/gaps.md | 5 +++-- docs/roadmap.md | 9 +++++++-- docs/target-app-parity.md | 13 +++++++------ docs/ui-parity.md | 5 +++-- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 6e401036b9..cfa4881c13 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,10 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (G5: dynamic symbols, #4938; estimate 15–26 → 14–24 h) · **Target:** Adobe Illustrator 2026 (30.x; G12: Units › East Asian Type acts, with Q and Ha units; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Symbol editing shows draggable 9-slice guides; G5: dynamic symbols, #4938; estimate 15–26 → 14–24 h) · **Target:** Adobe Illustrator 2026 (30.x; G12: Units › East Asian Type acts, with Q and Ha units; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-22. +**Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -709,6 +709,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | | 2026-10-31 | minor | G12: Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; 4 Preferences options remain stored but not acted on. Estimate unchanged. | | 2026-11-01 | minor | G5: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance fill, stroke, opacity and blend for objects of a dynamic symbol's art that stay linked (redefining keeps them, Break Link bakes them, Reset and Static drop them; `symbol.instance.setAppearance`, `symbol.instance.reset`; `crates/engine/src/tests/dynamic_symbols.rs`); on-canvas Direct Selection of the parts and `.ai` round trip remain. Estimate 15–26 → 14–24 h. | | 2026-11-01 | minor | G13: Artboard background colors in output (#4937): raster exports (a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print (and its preview) draw each artboard's color behind its art, inside the artboard and in the color's own model; Export for Screens has Include Artboard Fill beside Include Bleed (on by default, remembered; `includeArtboardFill`, also on `document.export` and `file.print`); editing data keeps the color as the artboard's, and Export for Screens' document rows keep it too; estimate unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index aaf046994a..a879347a6a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,10 +1,10 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (M5: supersampled exports avoid redundant opaque knockout layers; File formats: `.ai`/EPS import fidelity from a user's file audit; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Symbol editing shows draggable 9-slice guides; M5: supersampled exports avoid redundant opaque knockout layers; File formats: `.ai`/EPS import fidelity from a user's file audit; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-30. +**Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -97,6 +97,10 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | @@ -141,6 +145,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-10-30 | patch | M5: opaque solid-fill knockout paths avoid redundant erase/add layers in hard-edge frames and supersampled raster export; exact-pixel regression coverage retains analytical-AA rounding and translucent knockout behavior; scores and estimates unchanged | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b6de6486ec..09e3842955 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,10 +1,10 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Color Effects add-on: Find Nearest Swatch, #4923; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (SVG ellipse import, inline-graphic kerning, Recolor Artwork displays, and canvas 9-slice guides; Color Effects add-on: Find Nearest Swatch, #4923; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-22. +**Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -130,9 +130,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, more built-in symbol libraries, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guide settings (stored, not drawn) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, on-canvas Direct Selection of parts inside dynamic symbol instances and their `.ai` round trip, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic symbols keep per-instance appearance linked, #4938) are done | 4–8 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; scores and hours unchanged | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility); materials, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | @@ -405,7 +405,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, 3D Classic and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Fractional Widths and System Layout are done | 14–19 | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | more built-in symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type done (9-slice guides remain) | 4–7 | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | more built-in symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | @@ -996,7 +996,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html): "Select a smooth color wheel, a segmented color wheel, or color bars to display and edit colors"). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. + - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. @@ -1542,6 +1542,7 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | SVG imports preserve exported ellipses as four-anchor paths (#5243). Inline graphics use manual kerning (#5245). Symbol editing shows draggable 9-slice guides (#5280). Recolor Artwork offers smooth and segmented wheels and color bars (#5249). Scores and hours remain unchanged. | | 2026-11-01 | minor | Repeat: a double-click isolates it to edit its source art, text included (#5054); evidence added; scores unchanged. | | 2026-11-01 | minor | Live Corners: Up/Down while dragging a corner widget step the corner kind (#2898); evidence added; scores unchanged. | | 2026-11-01 | minor | Shortcuts for Effect menu items (#3296); evidence added; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 17175d53f5..bb52e61812 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,10 +1,10 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (Color Effects add-on: Find Nearest Swatch, #4923) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Symbol editing shows draggable 9-slice guides; Color Effects add-on: Find Nearest Swatch, #4923) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**Feature evidence last updated:** 2026-10-22. +**Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -400,6 +400,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-01 | minor | A double-click on a Repeat with the Selection tool enters isolation mode on it, where its source art (type included: a double-click there edits the text) is edited and every copy follows (#5054); scores and estimates unchanged | | 2026-11-01 | minor | Live Corners: while a corner widget is pressed or dragged with the Selection or Direct Selection tool, the Up and Down arrows step the corners' kind (round, inverted round, chamfer) with the radius, as one undo step (#2898); scores and estimates unchanged | | 2026-11-01 | minor | Keyboard Shortcuts: every Effect menu item (Distort & Transform › Transform…, Stylize › Drop Shadow…, …) is listed under its menu path and takes a shortcut of its own, which the menu shows and which opens that effect's dialog (or applies an effect without options) (#3296); scores and estimates unchanged | From 2bc284aa259d0e21ee2806678744ce47425bf5ce Mon Sep 17 00:00:00 2001 From: ham9zah Date: Tue, 3 Nov 2026 16:01:10 +0700 Subject: [PATCH 350/674] Path type brackets: 8 px reach, hover highlight, and the nearest of a bracket and a port takes the press Squashed from #5332 onto main. --- crates/tools/src/direct.rs | 18 +++- crates/tools/src/pathtype.rs | 185 ++++++++++++++++++++++++++++----- crates/tools/src/select.rs | 10 +- crates/tools/src/text.rs | 2 +- crates/tools/src/text/ports.rs | 18 +++- 5 files changed, 197 insertions(+), 36 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 4a38efc82a..c321975182 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -57,7 +57,7 @@ use crate::bbox::move_delta; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{HandleSnap, Leave, PointSnap, Targets}; use crate::meshedit::{MeshEdit, grid_of}; -use crate::pathtype::{self, BracketDrag, over_bracket}; +use crate::pathtype::{self, BracketDrag, near_bracket}; use crate::rulerguide::GuideEdit; use crate::select::{MoveSnap, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -227,6 +227,8 @@ pub struct DirectSelectionTool { /// The already selected frame anchor the press landed on without Shift: a click (no drag) /// selects it alone, as a drag moves every selected frame anchor with it. frame_click: Option<(NodeId, AnchorRef)>, + /// Where the pointer last hovered: the type on a path bracket under it draws thicker. + bracket_hover: Option, } impl DirectSelectionTool { @@ -253,6 +255,7 @@ impl DirectSelectionTool { frame: BTreeMap::new(), frame_revision: (0, 0), frame_click: None, + bracket_hover: None, } } @@ -643,6 +646,11 @@ fn segment_at(cx: &ToolContext, id: NodeId, p: Point) -> Option { } impl Tool for DirectSelectionTool { + /// The pointer hovers nothing for the tool: no bracket is highlighted. + fn hover_ended(&mut self, _cx: &ToolContext) { + self.bracket_hover = None; + } + fn id(&self) -> &'static str { if self.group { "groupSelection" } else { "directSelection" } } @@ -703,6 +711,7 @@ impl Tool for DirectSelectionTool { } } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.bracket_hover = (ev.kind == PointerKind::Move).then_some(ev.pos); if let Some(out) = self.guide.pointer(cx, ev) { return out; } @@ -727,7 +736,7 @@ impl Tool for DirectSelectionTool { return vec![]; } if !over_path_type_anchor(cx, p) - && let Some(b) = BracketDrag::hit(cx, ev) + && let Some(b) = BracketDrag::hit_any(cx, ev) { self.state = State::Bracket(b); return vec![]; @@ -915,7 +924,8 @@ impl Tool for DirectSelectionTool { out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id))); if !self.group { out.extend(frame_overlays(cx, &self.frame_anchors(cx))); - out.extend(pathtype::overlays(cx)); + let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None }; + out.extend(pathtype::overlays(cx, self.bracket_hover, drag)); } if matches!(self.state, State::Handle { .. } | State::MoveAnchors { .. } | State::MoveObject { .. }) { out.extend(self.guides.iter().cloned()); @@ -932,7 +942,7 @@ impl Tool for DirectSelectionTool { if !self.group && (matches!(self.state, State::Corner(_)) || over_widget(cx, p, true)) { return Cursor::CornerRadius; } - if !self.group && (matches!(self.state, State::Bracket(_)) || over_bracket(cx, p) && !over_path_type_anchor(cx, p)) { + if !self.group && (matches!(self.state, State::Bracket(_)) || near_bracket(cx, p) && !over_path_type_anchor(cx, p)) { return Cursor::PathBracket; } let rest = if self.group { Cursor::GroupSelection } else { Cursor::ArrowHollow }; diff --git a/crates/tools/src/pathtype.rs b/crates/tools/src/pathtype.rs index 21fdaefc93..9f888de6cb 100644 --- a/crates/tools/src/pathtype.rs +++ b/crates/tools/src/pathtype.rs @@ -3,8 +3,12 @@ //! type begins or ends along its path; dragging the centre bracket slides the type along the path //! (its brackets with it) and, dragged across the path, flips the type to the other side //! (Cmd/Ctrl held: it only slides). Each drag is one undo step of `type.pathOptions`. The tools -//! draw the brackets from the same geometry they hit-test. With more than 10,000 type on a path -//! objects selected, they neither draw nor hit-test any bracket. +//! draw the brackets from the same geometry they hit-test. A press within [`HIT_PX`] of a bracket +//! takes the nearest one, and the bracket a press would take draws thicker under the pointer. In +//! the Selection tool, which loads text from ports, the nearer of a bracket and a text port takes a +//! press (and the highlight); Direct Selection has no ports, so a bracket within reach always takes +//! it there. With more than 10,000 type on a path objects selected, they neither draw nor hit-test +//! any bracket. use serde_json::{Map, Value, json}; use vectorcraft_doc::{NodeId, NodeKind, TextKind}; @@ -20,6 +24,10 @@ const DOWN_PX: f64 = 4.0; const FOOT_PX: f64 = 4.0; /// How far past the path (screen px) the centre bracket goes before the type flips. const FLIP_PX: f64 = 6.0; +/// How near (screen px) a press must be to a bracket to take it. +const HIT_PX: f64 = 8.0; +/// The stroke width (screen px) of the bracket under the pointer; the others are hairlines. +const HOT_WIDTH: f32 = 2.5; /// The most points the tools draw for the brackets of a selection, the same number as the canvas's /// limit on the anchor points it outlines (`OVERLAY_MAX_ANCHORS` in `crates/ui-egui/src/canvas.rs`). /// Past it the tools neither draw nor hit-test any bracket. @@ -107,9 +115,14 @@ impl Brackets { } } - /// The bracket within `tol` (document units) of `p`. - fn hit(&self, p: Point, zoom: f64, tol: f64) -> Option { - Bracket::ALL.into_iter().find(|b| self.lines(*b, zoom).iter().any(|(a, c)| Line::new(*a, *c).nearest(p, 1e-9).distance_sq <= tol * tol)) + /// How far (document units) bracket `b` is from `p`. + fn distance(&self, b: Bracket, p: Point, zoom: f64) -> f64 { + self.lines(b, zoom).into_iter().map(|(a, c)| Line::new(a, c).nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min) + } + + /// The bracket nearest `p` within `tol` (document units), and how far it is. + fn hit(&self, p: Point, zoom: f64, tol: f64) -> Option<(Bracket, f64)> { + Bracket::ALL.into_iter().map(|b| (b, self.distance(b, p, zoom))).filter(|(_, d)| *d <= tol).min_by(|a, b| a.1.total_cmp(&b.1)) } /// The fraction of the path's length nearest document point `p`. @@ -125,29 +138,64 @@ fn too_many(cx: &ToolContext) -> bool { cx.selection.objects.iter().filter(on_path).nth(MAX_POINTS / POINTS_EACH).is_some() } -/// The selected type on a path's bracket under `p`, if any. -fn bracket_at(cx: &ToolContext, p: Point) -> Option<(Brackets, Bracket)> { - Brackets::of(cx).into_iter().find_map(|b| { - let which = b.hit(p, cx.zoom, cx.tol(5.0))?; - Some((b, which)) - }) +/// The selected type on a path's bracket nearest `p` within [`HIT_PX`], and how far it is. +fn bracket_at(cx: &ToolContext, p: Point) -> Option<(Brackets, Bracket, f64)> { + Brackets::of(cx) + .into_iter() + .filter_map(|b| { + let (which, d) = b.hit(p, cx.zoom, cx.tol(HIT_PX))?; + Some((b, which, d)) + }) + .min_by(|a, b| a.2.total_cmp(&b.2)) } -/// Is `p` over a bracket of the selected type on a path? +/// How far (document units) the bracket of the selected type on a path under `p` is from it; None +/// when no bracket is within reach. +pub fn bracket_distance(cx: &ToolContext, p: Point) -> Option { + if too_many(cx) { + return None; + } + bracket_at(cx, p).map(|(_, _, d)| d) +} + +/// Is `p` within reach of a bracket of the selected type on a path, ports or not (Direct +/// Selection, which takes no clicks on ports)? +pub fn near_bracket(cx: &ToolContext, p: Point) -> bool { + bracket_distance(cx, p).is_some() +} + +/// Is `p` over a bracket of the selected type on a path, nearer than any text port (a start +/// bracket and an in port sit side by side: the nearer takes the press)? For the Selection tool, +/// which loads text from ports. pub fn over_bracket(cx: &ToolContext, p: Point) -> bool { - !too_many(cx) && bracket_at(cx, p).is_some() + bracket_distance(cx, p).is_some_and(|d| crate::text::port_near(cx, p).is_none_or(|(_, _, port)| d <= port)) } -/// The brackets of the selected type on a path, in their layer's colour. -pub fn overlays(cx: &ToolContext) -> Vec { +/// The brackets of the selected type on a path, in their layer's colour: the one under `hover` +/// thicker (the caller passes only a hover that would take the bracket), or the one `drag` moves. +pub fn overlays(cx: &ToolContext, hover: Option, drag: Option<&BracketDrag>) -> Vec { if too_many(cx) { return vec![]; } + let hot = match drag { + Some(d) => Some((d.brackets.id, d.which)), + None => hover.and_then(|p| bracket_at(cx, p)).map(|(b, which, _)| (b.id, which)), + }; let mut out = vec![]; for b in Brackets::of(cx) { let color = cx.doc.layer_color(b.id); for which in Bracket::ALL { - out.extend(b.lines(which, cx.zoom).into_iter().map(|(a, b)| Overlay::Line { a, b, color, dashed: false })); + let lines = b.lines(which, cx.zoom); + if hot == Some((b.id, which)) { + let mut path = vectorcraft_geom::kurbo::BezPath::new(); + for (a, c) in lines { + path.move_to(a); + path.line_to(c); + } + out.push(Overlay::Path { path, color, width: HOT_WIDTH, dashed: false }); + } else { + out.extend(lines.into_iter().map(|(a, b)| Overlay::Line { a, b, color, dashed: false })); + } } } out @@ -165,12 +213,22 @@ pub struct BracketDrag { } impl BracketDrag { - /// Start a drag when the press `ev` is on a bracket of the selected type on a path. + /// Start a drag when the press `ev` is on a bracket of the selected type on a path, nearer than + /// any text port (the Selection tool, [`over_bracket`]). pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + if !over_bracket(cx, ev.pos) { + return None; + } + Self::hit_any(cx, ev) + } + + /// Start a drag when the press `ev` is within reach of a bracket, ports or not (Direct + /// Selection, [`near_bracket`]). + pub fn hit_any(cx: &ToolContext, ev: &PointerEvent) -> Option { if too_many(cx) { return None; } - let (brackets, which) = bracket_at(cx, ev.pos)?; + let (brackets, which, _) = bracket_at(cx, ev.pos)?; let grab = brackets.fraction_at(ev.pos)?; Some(Self { brackets, which, start: ev.pos, grab, began: false }) } @@ -271,12 +329,13 @@ mod tests { let p = paint(); let cx = cx(&d, &s, &p); let b = Brackets::of(&cx).pop().unwrap(); - assert_eq!(b.hit(Point::new(160.0, 290.0), 1.0, 2.0), Some(Bracket::Start)); - assert_eq!(b.hit(Point::new(280.0, 290.0), 1.0, 2.0), Some(Bracket::Centre)); - assert_eq!(b.hit(Point::new(400.0, 290.0), 1.0, 2.0), Some(Bracket::End)); - assert_eq!(b.hit(Point::new(220.0, 290.0), 1.0, 2.0), None); + let which = |p: Point| b.hit(p, 1.0, 2.0).map(|(w, _)| w); + assert_eq!(which(Point::new(160.0, 290.0)), Some(Bracket::Start)); + assert_eq!(which(Point::new(280.0, 290.0)), Some(Bracket::Centre)); + assert_eq!(which(Point::new(400.0, 290.0)), Some(Bracket::End)); + assert_eq!(which(Point::new(220.0, 290.0)), None); // Drawn over the type's side of the path, with feet pointing into the span. - let o = overlays(&cx); + let o = overlays(&cx, None, None); assert_eq!(o.len(), 5); assert!(o.contains(&Overlay::Line { a: Point::new(160.0, 286.0), b: Point::new(164.0, 286.0), color: d.layer_color(id), dashed: false })); // Nothing for unselected or other type. @@ -316,13 +375,13 @@ mod tests { }; { let cx = cx(&d, &s, &p); - assert_eq!(overlays(&cx).len(), 50_000); + assert_eq!(overlays(&cx, None, None).len(), 50_000); assert!(over_bracket(&cx, at) && BracketDrag::hit(&cx, &press).is_some()); assert_eq!(tools(&cx), vec![(50_000, Cursor::PathBracket); 2]); } add(&mut d, &mut s, 1); let cx = cx(&d, &s, &p); - assert!(overlays(&cx).is_empty()); + assert!(overlays(&cx, None, None).is_empty()); assert!(!over_bracket(&cx, at) && BracketDrag::hit(&cx, &press).is_none()); for (n, cursor) in tools(&cx) { assert_eq!(n, 0); @@ -364,4 +423,80 @@ mod tests { let v = preview(&drag(&cx, Point::new(400.0, 295.0), Point::new(110.0, 300.0), Mods::default())).clone(); assert!((v["end"].as_f64().unwrap() - 0.2).abs() < 1e-6, "{v}"); } + + /// A press takes a bracket within 8 screen px at any zoom, and not further. + #[test] + fn brackets_are_hit_within_eight_screen_pixels_at_any_zoom() { + let (d, id) = doc_with_path_type(); + let s = selected(id); + let p = paint(); + for zoom in [0.25, 1.0, 8.0] { + let mut cx = cx(&d, &s, &p); + cx.zoom = zoom; + let px = 1.0 / zoom; + // The start bracket's stem stands at x 160, from 4 px below the path to 14 px above it. + let near = |dx: f64| near_bracket(&cx, Point::new(160.0 - dx * px, 300.0 - 7.0 * px)); + assert!(near(7.5), "7.5 px beside the stem at zoom {zoom}"); + assert!(!near(9.0), "9 px beside the stem at zoom {zoom}"); + } + } + + /// The bracket a press would take draws thicker under the pointer; elsewhere they are all + /// hairlines. + #[test] + fn the_hovered_bracket_draws_thicker() { + let (d, id) = doc_with_path_type(); + let s = selected(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let hot = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Path { width, .. } if *width == HOT_WIDTH)).count(); + assert_eq!(hot(&overlays(&cx, Some(Point::new(400.0, 293.0)), None)), 1); + assert_eq!(hot(&overlays(&cx, Some(Point::new(220.0, 250.0)), None)), 0); + let mut t = crate::select::SelectionTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 400.0, 293.0)); + assert_eq!(hot(&t.overlays(&cx)), 1); + t.hover_ended(&cx); + assert_eq!(hot(&t.overlays(&cx)), 0, "the highlight goes with the hover"); + } + + /// A press on a bracket takes it rather than moving the type; where the in port sits beside the + /// start bracket, the Selection tool gives a press nearer the port to the port (no bracket drag, + /// cursor or highlight), while Direct Selection, which has no ports, takes the bracket. + #[test] + fn the_nearer_of_a_bracket_and_a_port_takes_a_selection_press() { + let (d, id) = doc_with_path_type(); + let s = selected(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = crate::select::SelectionTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 280.0, 296.0)); + let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 310.0, 296.0)); + assert!(out.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "type.pathOptions")), "{out:?}"); + // A point nearer the in port with the start bracket in reach. + let mut between = None; + for i in 0..400 { + for j in 0..120 { + let q = Point::new(130.0 + i as f64 * 0.1, 282.0 + j as f64 * 0.2); + let Some((_, crate::text::Port::In, port)) = crate::text::port_near(&cx, q) else { continue }; + if bracket_distance(&cx, q).is_some_and(|b| port < b) { + between = Some(q); + } + } + } + let q = between.expect("a point nearer the in port with the start bracket in reach"); + let down = PointerEvent::new(PointerKind::Down, q.x, q.y); + let hot = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Path { width, .. } if *width == HOT_WIDTH)); + assert!(!over_bracket(&cx, q) && BracketDrag::hit(&cx, &down).is_none()); + let mut select = crate::select::SelectionTool::default(); + select.pointer(&cx, &PointerEvent::new(PointerKind::Move, q.x, q.y)); + assert!(!hot(&select.overlays(&cx))); + assert_ne!(select.cursor(&cx, q, Mods::default()), Cursor::PathBracket); + let mut direct = crate::direct::DirectSelectionTool::new(false); + assert_eq!(direct.cursor(&cx, q, Mods::default()), Cursor::PathBracket); + direct.pointer(&cx, &PointerEvent::new(PointerKind::Move, q.x, q.y)); + assert!(hot(&direct.overlays(&cx))); + direct.pointer(&cx, &down); + let out = direct.pointer(&cx, &PointerEvent::new(PointerKind::Drag, q.x + 30.0, q.y)); + assert!(out.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "type.pathOptions")), "{out:?}"); + } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index be7222f4f5..8cbade741e 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -153,6 +153,8 @@ pub struct SelectionTool { /// The text the pointer was loaded with when the button went down: a dropped press loads it /// again. loaded_at_press: Option<(NodeId, bool)>, + /// Where the pointer last hovered: the type on a path bracket under it draws thicker. + bracket_hover: Option, } /// What Distance Guides measure the selection to. @@ -713,6 +715,7 @@ impl Tool for SelectionTool { self.hover = None; self.distance = None; self.alt_hover = false; + self.bracket_hover = None; } fn wants_rehover(&self) -> bool { @@ -735,6 +738,7 @@ impl Tool for SelectionTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); + self.bracket_hover = hovering.then_some(ev.pos); self.alt_hover = hovering && ev.mods.alt; self.distance = hovering.then(|| distance_target(cx, ev.pos, ev.mods)).flatten(); if let State::Loaded { from, before, press } = self.state @@ -930,7 +934,9 @@ impl Tool for SelectionTool { } fn overlays(&self, cx: &ToolContext) -> Vec { - let mut o = pathtype::overlays(cx); + // Highlighted only where a press would take the bracket, not a nearer port. + let drag = if let State::Bracket(b) = &self.state { Some(b) } else { None }; + let mut o = pathtype::overlays(cx, self.bracket_hover.filter(|p| over_bracket(cx, *p)), drag); if let Some(source) = cx.isolation.and_then(|id| cx.doc.node(id)).filter(|n| n.name.as_deref() == Some(vectorcraft_doc::shaper::SOURCES)) { for n in source.children().into_iter().flatten() { if let Some(path) = n.path_data() { @@ -1345,7 +1351,7 @@ impl SelectionTool { fn press_widgets(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Option> { // 0. A port of selected area type or type on a path: the pointer takes its text, // to thread on from the out port or back from the in port. - if let Some((from, port)) = crate::text::port_at(cx, p) { + if let Some((from, port)) = crate::text::port_at(cx, p).filter(|_| !over_bracket(cx, p)) { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index b1394c81d6..646dbd6384 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -51,8 +51,8 @@ mod tool; use plain::char_range_to_bytes; use plain::common_affixes; pub use plain::step_key; -pub(crate) use ports::port_at; pub use ports::{PORT_RISE_PX, PORTS_MAX, Port, PortMarks, PortState, port_centre, port_states, ported, ports_shown, push_port, thread_ports}; +pub(crate) use ports::{port_at, port_near}; /// Which of the Type tools this is. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/crates/tools/src/text/ports.rs b/crates/tools/src/text/ports.rs index d9c027fbc1..554a1cd611 100644 --- a/crates/tools/src/text/ports.rs +++ b/crates/tools/src/text/ports.rs @@ -145,15 +145,25 @@ pub fn ports_shown(d: &vectorcraft_doc::Document, selected: &[NodeId]) -> bool { /// on the in port to thread into one before it. Every such frame has both ports, threaded, /// overflowing or not, while their ports show ([`PORTS_MAX`]). pub(crate) fn port_at(cx: &ToolContext, p: Point) -> Option<(NodeId, Port)> { + port_near(cx, p).map(|(id, port, _)| (id, port)) +} + +/// [`port_at`], with how far (document units) the port's centre is from `p`: the nearest port +/// within reach, of every selected frame (ports of overlapping frames can both be in reach). +pub(crate) fn port_near(cx: &ToolContext, p: Point) -> Option<(NodeId, Port, f64)> { if !ports_shown(cx.doc, &cx.selection.objects) { return None; } let h = cx.tol(PORT_HALF_PX + 1.0); let near = |c: Point| (c.x - p.x).abs() <= h && (c.y - p.y).abs() <= h; - cx.selection.objects.iter().find_map(|id| { - let t = ported(cx.doc, *id)?; - [Port::Out, Port::In].into_iter().find(|port| port_centre(t, *port, cx.tol(1.0)).is_some_and(near)).map(|port| (*id, port)) - }) + cx.selection + .objects + .iter() + .filter_map(|id| ported(cx.doc, *id).map(|t| (*id, t))) + .flat_map(|(id, t)| [Port::Out, Port::In].into_iter().filter_map(move |port| port_centre(t, port, cx.tol(1.0)).map(|c| (id, port, c)))) + .filter(|(_, _, c)| near(*c)) + .map(|(id, port, c)| (id, port, c.distance(p))) + .min_by(|a, b| a.2.total_cmp(&b.2)) } /// Which selected text overflows, for [`thread_ports`]: each text object's layout verdict kept From 2b29a680f30b7060d4a6308a3ba00d1739e73f0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:32:00 -0800 Subject: [PATCH 351/674] Objects on Path: the Space widget spaces the attached objects along the path With one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square Space widget beyond the last object, ahead along the path. Dragging it moves the last object along the path, around its bends, as far as the pointer moves along it, and the objects between follow evenly while the first one stays. With Alt (Option on macOS) the objects spread from both ends toward or away from the center of an open path, or of the first anchor of a closed one. The distance between the objects shows next to the pointer in the document's units; the drag is one undo step, and Escape cancels it. - object.objectsOnPath.options takes spacing (points, or "auto", the default even spread) and start (points from the first anchor). A spacing the path has no room for is drawn smaller and kept, so a longer path brings it back. Older files read as Auto. - Moving the group, Pivot, Rotate, path edits, copies and saving keep the Space. Scaling, rotating or shearing the group keeps the first and last objects where the transform takes them on the new path, live shapes included; a value that cannot be kept that way scales with the path's length. - The Rotate All widget follows the first object when Space moves it. Behavior: https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html and https://helpx.adobe.com/illustrator/using/objects-on-path.html. --- crates/doc/src/blend.rs | 46 ++ crates/doc/src/node/ops.rs | 22 +- crates/doc/src/node/tests.rs | 28 ++ crates/doc/src/objects_on_path.rs | 340 +++++++++++++- crates/engine/src/cmd/objects_on_path.rs | 28 +- crates/engine/src/tests/objects_on_path.rs | 88 ++++ crates/eps/src/import/ai/read/on_path.rs | 2 +- crates/tools/src/objects_on_path.rs | 519 ++++++++++++++++++++- crates/tools/src/select.rs | 27 +- crates/ui-egui/src/canvas/overlays.rs | 27 +- crates/ui-egui/src/canvas/tests.rs | 35 ++ docs/mcp.md | 22 +- docs/target-app-parity.md | 3 +- 13 files changed, 1121 insertions(+), 66 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index ce20d29cd8..8bca517ee1 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -862,6 +862,52 @@ impl Spine { pub fn anchor_length(&self, i: usize) -> Option { self.anchors.get(i).copied() } + /// Arc length of the point of the spine nearest `p`. An open spine's end segments run on past + /// its ends as lines, so the result is below 0 before the start and above [`Spine::length`] + /// beyond the end. With `from`, the arc length of an earlier point a drag followed, each point + /// counts as farther by half its distance along the spine from there, so a pointer passing + /// near another part of the spine stays on the part it follows. Where two points count as + /// near as each other, the one earlier along the spine counts. + pub fn length_near(&self, p: Point, from: Option) -> f64 { + self.nearest(p, from).map_or(0.0, |(_, s)| s) + } + /// [`Spine::length_near`] with how near the point counts: its distance from `p`, plus half its + /// distance along the spine from `from`. `None` for a point that is not finite. + pub fn nearest(&self, p: Point, from: Option) -> Option<(f64, f64)> { + if !p.x.is_finite() || !p.y.is_finite() { + return None; + } + let last = self.pts.len().saturating_sub(2); + let mut best: Option<(f64, f64)> = None; + for (i, (w, c)) in self.pts.windows(2).zip(&self.cum).enumerate() { + let [a, b] = [w[0], w[1]]; + let d = b - a; + let l2 = d.dot(d); + if !l2.is_finite() || l2 <= 0.0 { + continue; + } + let t = (p - a).dot(d) / l2; + let t = match (self.closed, i == 0, i == last) { + (false, true, true) => t, + (false, true, false) => t.min(1.0), + (false, false, true) => t.max(0.0), + _ => t.clamp(0.0, 1.0), + }; + let s = c + t * l2.sqrt(); + let dist = p.distance(a + d * t) + from.filter(|f| f.is_finite()).map_or(0.0, |f| self.apart(s, f) / 2.0); + if dist.is_finite() && best.is_none_or(|(b, _)| dist < b) { + best = Some((dist, s)); + } + } + best + } + /// How far apart arc lengths `s` and `f` are along the spine: the shorter way round a closed + /// spine, across its first anchor. + pub fn apart(&self, s: f64, f: f64) -> f64 { + let len = self.length(); + let d = (s - f).abs(); + if self.closed && len > 0.0 { d.rem_euclid(len).min(len - d.rem_euclid(len)) } else { d } + } /// Point and tangent angle (radians) at arc-length fraction `f` (0..1). pub fn at(&self, f: f64) -> (Point, f64) { self.at_length(f.clamp(0.0, 1.0) * self.length()) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index b5ae03e8b1..755cb51c4a 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -393,6 +393,12 @@ impl Node { self.transform_scaled(a, &scaling.into()); } + /// The path of the child an Objects on Path group's objects are attached to. + fn on_path_data(&self) -> Option<&PathData> { + let r = self.extras().objects_on_path.as_deref()?; + self.children()?.iter().find(|c| c.id == r.path)?.path_data() + } + fn transform_scaled(&mut self, a: Affine, sc: &Scaling) { // A dimension's measurement moves with it. if let Some(e) = self.extras_if_any() @@ -400,12 +406,8 @@ impl Node { { dimension.transform(a); } - // The frames of the objects attached to a path move with them. - if let Some(e) = self.extras_if_any() - && let Some(on_path) = &mut e.objects_on_path - { - on_path.transform(a); - } + // The path the objects are attached to, before it is transformed. + let on_path_before = self.on_path_data().cloned(); if !self.is_layer() { self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a); } @@ -496,6 +498,14 @@ impl Node { NodeKind::Mesh(m) => m.transform(a), NodeKind::Repeat(r) => r.transform(a, *sc), } + // The frames of the objects attached to a path move with them, and the distances along the + // path follow the path as it is now (a live shape's path is regenerated). + let on_path_after = on_path_before.as_ref().and_then(|_| self.on_path_data().cloned()); + if let Some(e) = self.extras_if_any() + && let Some(on_path) = &mut e.objects_on_path + { + on_path.transform(a, on_path_before.as_ref().zip(on_path_after.as_ref())); + } if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut()) && m.linked { diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index df675580e2..882018e1d1 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -241,6 +241,34 @@ fn uneven_scales_keep_live_corners_circular() { assert_round_corners(&n, Affine::IDENTITY, 40.0); } +/// Objects attached to a rounded rectangle that keeps its corners when scaled stay where the scale +/// takes them on the regenerated path, which is not twice as long when twice the size. +#[test] +fn objects_on_a_live_rectangle_follow_its_regenerated_path() { + use crate::objects_on_path::{CENTER, ObjectsOnPath, stops}; + let path = live_rect(100.0, 100.0, 20.0, Affine::IDENTITY); + let objects: Vec = + (2..5).map(|i| Node::path(NodeId(i), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default())).collect(); + let members: Vec<&Node> = objects.iter().collect(); + let rec = ObjectsOnPath { spacing: Some(20.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &members, CENTER, 0.0) }; + let mut children = vec![Arc::new(path)]; + children.extend(objects.iter().cloned().map(Arc::new)); + let mut g = Node::new(NodeId(9), NodeKind::Group { children, clip: false }); + g.extras_mut().objects_on_path = Some(Box::new(rec)); + let path_of = |g: &Node| g.children().and_then(|c| c.first()).and_then(|p| p.path_data().cloned()).unwrap(); + let rec_of = |g: &Node| g.extras().objects_on_path.as_deref().cloned().unwrap(); + let r = rec_of(&g); + let before = stops(&path_of(&g), 3, r.spacing, r.start).unwrap(); + let a = Affine::scale(2.0); + g.transform(a, KEEP_CORNERS); + assert_round_corners(&g.children().unwrap()[0], Affine::IDENTITY, 20.0); + let r = rec_of(&g); + let after = stops(&path_of(&g), 3, r.spacing, r.start).unwrap(); + for ((p, _), (q, _)) in before.iter().zip(&after) { + assert!((a * *p).distance(*q) < 1e-6, "{p:?} went to {q:?}: {r:?}"); + } +} + #[test] fn rotated_and_reflected_live_rectangles_scale_along_their_own_sides() { let place = Affine::translate((200.0, 100.0)) * Affine::rotate(30f64.to_radians()); diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index 779e2eced3..67c9c0ee87 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -5,8 +5,9 @@ //! the other children are the attached objects, kept where they are drawn: the group draws, hits, //! saves and exports as a group. The record lists the objects in their order along the path, each //! with the frame it is drawn in and the angle that frame is turned by. [`place`] spreads them -//! evenly along the path from its first anchor (the first object sits on that anchor, and the last -//! one sits on the end of an open path), puts the attachment point of each one +//! along the path ([`stops`]): evenly from its first anchor by default (the first object sits on +//! that anchor, and the last one sits on the end of an open path), or [`ObjectsOnPath::spacing`] +//! apart from [`ObjectsOnPath::start`]. It puts the attachment point of each one //! ([`ObjectsOnPath::pivot`]) on the path, and turns its frame to the path's direction there, //! tilted by [`ObjectsOnPath::rotate`]. //! @@ -45,6 +46,14 @@ pub struct ObjectsOnPath { /// upright object has its frame's x axis along the path's direction at its attachment point. #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub rotate: f64, + /// Space: the distance along the path (points) from each object's attachment point to the + /// next one's. `None` (Auto) spreads the objects evenly ([`layout`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spacing: Option, + /// The distance along the path (points) from its first anchor to the first object's + /// attachment point. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub start: f64, } /// An object attached to the path of an Objects on Path group. @@ -95,19 +104,38 @@ impl ObjectsOnPath { /// in its frame as drawn ([`upright_frame`]). pub fn new(path: NodeId, members: &[&Node], pivot: u8, rotate: f64) -> Self { let members = members.iter().map(|n| Member::new(n)).collect(); - Self { path, members, pivot: pivot.min(8), rotate: if rotate.is_finite() { rotate } else { 0.0 } } + Self { path, members, pivot: pivot.min(8), rotate: if rotate.is_finite() { rotate } else { 0.0 }, spacing: None, start: 0.0 } } /// The frames go with the group, and each frame's angle becomes the transformed path's /// direction at the object plus the tilt, so that [`place`] keeps each object's scale, shear /// and reflection when it spreads the objects along the transformed path again. A reflection - /// also reverses Rotate: the objects keep the mirrored tilt to the mirrored path. - pub fn transform(&mut self, a: Affine) { + /// also reverses Rotate: the objects keep the mirrored tilt to the mirrored path. With `paths`, + /// the group's path before the transform and as it is after it, the start and a Space value + /// keep the first and last objects where the transform takes them on the path; a value that + /// cannot be followed that way scales by how much the path's length changed. Without `paths`, + /// they scale by the transform's average scale (the square root of its area scale). A + /// value that would not be finite once scaled stays as it is. + pub fn transform(&mut self, a: Affine, paths: Option<(&PathData, &PathData)>) { let before = tilt(self.rotate); + let [a0, a1, a2, a3, _, _] = a.as_coeffs(); if a.determinant() < 0.0 && self.rotate != 0.0 { self.rotate = -self.rotate; } + let along = paths.and_then(|(old, new)| { + let s = path_length(new)?.0 / path_length(old)?.0; + (s.is_finite() && s > 0.0).then_some(s) + }); + let scale = along.unwrap_or_else(|| a.determinant().abs().sqrt()); + // A move leaves the distances along the path as they are. + let moves = a0 == 1.0 && a1 == 0.0 && a2 == 0.0 && a3 == 1.0; + if !moves && scale.is_finite() && scale > 0.0 { + let scaled = |v: f64| Some(v * scale).filter(|s| s.is_finite()).unwrap_or(v); + let moved = paths.and_then(|(old, new)| self.moved_along(a, old, new, scale)); + let (spacing, start) = moved.unwrap_or((None, None)); + self.spacing = self.spacing.map(|g| spacing.unwrap_or_else(|| scaled(g))); + self.start = start.unwrap_or_else(|| scaled(self.start)); + } let after = tilt(self.rotate); - let [a0, a1, a2, a3, _, _] = a.as_coeffs(); for m in &mut self.members { m.frame = a * m.frame; let (sin, cos) = (m.angle - before).sin_cos(); @@ -117,6 +145,41 @@ impl ObjectsOnPath { } } } + /// The start and Space value on `new`, the path `old` after the transform `a` (regenerated, for + /// a live shape), that keep the first object and the last one where `a` takes them: each one's + /// point on `old`, mapped by `a`, measured along `new` near `scale` times its distance along + /// `old`. Either one is `None` when it cannot be followed that way: a start before or beyond the + /// ends of an open path, or a Space value of 0, one the path has no room for, or one with fewer + /// than two objects. `None` for a path without length or a start that is not finite. + fn moved_along(&self, a: Affine, old: &PathData, new: &PathData, scale: f64) -> Option<(Option, Option)> { + let (was, is) = (Spine::new(old)?, Spine::new(new)?); + let (len, closed) = path_length(old)?; + let (new_len, _) = path_length(new)?; + if !self.start.is_finite() { + return None; + } + let n = self.members.len(); + let (s0, gap) = layout(len, closed, n, self.spacing, self.start); + let follow = |s: f64| -> Option { + let (p, _) = was.at_length(s); + let t = is.nearest(a * p, Some(s * scale))?.1; + t.is_finite().then_some(if closed { wrap(t, new_len) } else { t.clamp(0.0, new_len) }) + }; + let t0 = follow(s0)?; + // On a closed path the start keeps the number of times it goes round, when that stays finite. + let start = + if closed { Some(t0 + ((self.start - s0) / len).round() * new_len).filter(|s| s.is_finite()) } else { (s0 == self.start).then_some(t0) }; + let spacing = self.spacing.filter(|g| n > 1 && g.is_finite() && *g > 0.0 && *g <= gap).and_then(|g| { + let t1 = follow(nth_length(len, closed, s0, gap, n - 1))?; + let steps = (n - 1) as f64; + // Round a closed path, the span nearest the scaled one. + let expected = steps * g * scale; + let span = if closed { wrap(t1 - t0 - expected + new_len / 2.0, new_len) - new_len / 2.0 + expected } else { t1 - t0 }; + let g = span / steps; + (g.is_finite() && g >= 0.0).then_some(g) + }); + Some((spacing, start)) + } /// The children given new ids (a copy of the group): the path and the objects by their new ids. pub fn rename(&mut self, ids: &HashMap) { let to = |id: NodeId| ids.get(&id).copied().unwrap_or(id); @@ -210,19 +273,75 @@ pub fn upright_frame(n: &Node) -> Affine { } } -/// Where `n` objects attach along `path` (its first subpath): the point and the direction there -/// (radians, as `atan2` gives in the document's axes). They are spread evenly by length from the -/// first anchor: on an open path the last one is at its end, on a closed path the gaps go all the way -/// around. `None` for a path without length. -pub fn stops(path: &PathData, n: usize) -> Option> { - let spine = Spine::new(path)?; - let len = spine.length(); - if !len.is_finite() || len <= 1e-9 { - return None; - } +/// The length of `path`'s first subpath and whether it is closed. `None` for a path without +/// length. +pub fn path_length(path: &PathData) -> Option<(f64, bool)> { + let len = Spine::new(path)?.length(); let closed = path.subpaths.first().is_some_and(|s| s.closed); - let gaps = if closed { n } else { n.saturating_sub(1) }.max(1); - Some((0..n).map(|i| spine.at_length(len * i as f64 / gaps as f64)).collect()) + (len.is_finite() && len > 1e-9).then_some((len, closed)) +} + +/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the +/// distance from each object's attachment point to the next one's, both along the path (points), +/// for Space `spacing` (`None`: Auto) from `start`: +/// - The first object is `start` from the first anchor: on an open path no further than its end, +/// and on a closed path less than once around. +/// - Auto spreads the objects evenly from there: on an open path the last one is at its end, and on +/// a closed path the gaps go all the way around. +/// - A Space value is kept to what the path has room for, so a shorter path draws the objects +/// closer while the value stays: on an open path the last object reaches its end at most, and on +/// a closed path the last one stops at least a gap short of the first. +/// +/// A Space value that is negative or not finite counts as Auto, and a `start` that is not finite as 0. +pub fn layout(len: f64, closed: bool, n: usize, spacing: Option, start: f64) -> (f64, f64) { + let start = match (start.is_finite(), closed) { + (false, _) => 0.0, + (true, true) => wrap(start, len), + (true, false) => start.clamp(0.0, len.max(0.0)), + }; + let room = if closed { + len / n.max(1) as f64 + } else if n > 1 { + (len - start) / (n - 1) as f64 + } else { + 0.0 + }; + let room = if room.is_finite() { room.max(0.0) } else { 0.0 }; + match spacing.filter(|g| g.is_finite() && *g >= 0.0) { + Some(g) => (start, g.min(room)), + None => (start, room), + } +} + +/// `s` taken round a closed path of length `len`: 0 or more, and less than `len`. +fn wrap(s: f64, len: f64) -> f64 { + let w = s.rem_euclid(len); + if w.is_finite() && w < len { w } else { 0.0 } +} + +/// Where `n` objects attach along `path` (its first subpath): the point and the direction there +/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them +/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length. +pub fn stops(path: &PathData, n: usize, spacing: Option, start: f64) -> Option> { + let spine = Spine::new(path)?; + let (len, closed) = path_length(path)?; + let (start, gap) = layout(len, closed, n, spacing, start); + Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect()) +} + +/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others. +pub fn stop(path: &PathData, n: usize, spacing: Option, start: f64, i: usize) -> Option<(Point, f64)> { + let spine = Spine::new(path)?; + let (len, closed) = path_length(path)?; + let (start, gap) = layout(len, closed, n, spacing, start); + (i < n).then(|| spine.at_length(nth_length(len, closed, start, gap, i))) +} + +/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and +/// `gap` apart as [`layout`] gives them. +pub fn nth_length(len: f64, closed: bool, start: f64, gap: f64, i: usize) -> f64 { + let s = start + gap * i as f64; + if closed { wrap(s, len) } else { s.min(len) } } /// The tilt Rotate gives (radians, the document's axes, where y points down): `rotate` degrees @@ -277,7 +396,7 @@ pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool { } } let mut moved = false; - if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len())) { + if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len(), rec.spacing, rec.start)) { let turn = tilt(rec.rotate); for (m, (p, dir)) in rec.members.iter_mut().zip(stops) { let Some(c) = at.get(&m.id).and_then(|i| children.get_mut(*i)) else { continue }; @@ -309,15 +428,192 @@ mod tests { #[test] fn stops_spread_from_the_first_anchor() { let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0)); - let s = stops(&open, 4).unwrap(); + let s = stops(&open, 4, None, 0.0).unwrap(); let xs: Vec = s.iter().map(|(p, _)| p.x.round()).collect(); assert_eq!(xs, [0.0, 100.0, 200.0, 300.0], "first at the start, last at the end of an open path"); let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); - let s = stops(&closed, 4).unwrap(); + let s = stops(&closed, 4, None, 0.0).unwrap(); let mut pts: Vec<(i64, i64)> = s.iter().map(|(p, _)| (p.x.round() as i64, p.y.round() as i64)).collect(); pts.sort(); assert_eq!(pts, [(0, 0), (0, 100), (100, 0), (100, 100)], "a closed path spreads them all the way round"); - assert!(stops(&shapes::line(Point::ZERO, Point::ZERO), 2).is_none()); + assert!(stops(&shapes::line(Point::ZERO, Point::ZERO), 2, None, 0.0).is_none()); + } + + /// The x of each stop on the `len` pt line from (0, 0) to the right, to 1/1000 pt. + fn xs_on_line(len: f64, n: usize, spacing: Option, start: f64) -> Vec { + let open = shapes::line(Point::new(0.0, 0.0), Point::new(len, 0.0)); + stops(&open, n, spacing, start).unwrap().iter().map(|(p, _)| (p.x * 1000.0).round() / 1000.0).collect() + } + + #[test] + fn space_sets_the_distance_between_the_stops() { + assert_eq!(xs_on_line(300.0, 4, Some(60.0), 0.0), [0.0, 60.0, 120.0, 180.0], "the first stays on the first anchor"); + assert_eq!(xs_on_line(300.0, 4, Some(60.0), 60.0), [60.0, 120.0, 180.0, 240.0], "centered on the path"); + assert_eq!(xs_on_line(300.0, 4, Some(0.0), 0.0), [0.0; 4], "no space stacks them"); + // More than the path has room for: the last one reaches the end. + assert_eq!(xs_on_line(300.0, 4, Some(500.0), 0.0), [0.0, 100.0, 200.0, 300.0]); + assert_eq!(xs_on_line(300.0, 4, Some(500.0), 150.0), [150.0, 200.0, 250.0, 300.0]); + // A shorter path draws them closer, while the Space value stays to come back with the length. + assert_eq!(xs_on_line(90.0, 4, Some(60.0), 0.0), [0.0, 30.0, 60.0, 90.0]); + assert_eq!(layout(90.0, false, 4, Some(60.0), 0.0), (0.0, 30.0)); + assert_eq!(layout(300.0, false, 4, Some(60.0), 0.0), (0.0, 60.0)); + // Values that are not usable count as Auto, and a start beyond the end stops at it. + assert_eq!(xs_on_line(300.0, 4, Some(f64::NAN), f64::INFINITY), [0.0, 100.0, 200.0, 300.0]); + assert_eq!(xs_on_line(300.0, 4, Some(-5.0), 0.0), [0.0, 100.0, 200.0, 300.0]); + assert_eq!(xs_on_line(300.0, 2, Some(10.0), 400.0), [300.0, 300.0]); + assert_eq!(xs_on_line(300.0, 1, Some(10.0), 20.0), [20.0], "one object has no space to set"); + assert_eq!(xs_on_line(300.0, 0, Some(10.0), 0.0), Vec::::new()); + // One stop on its own is where the stops put it. + let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0)); + let all = stops(&open, 4, Some(60.0), 60.0).unwrap(); + for (i, s) in all.iter().enumerate() { + assert_eq!(stop(&open, 4, Some(60.0), 60.0, i), Some(*s)); + } + assert_eq!(stop(&open, 4, Some(60.0), 60.0, 4), None); + } + + #[test] + fn space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object() { + // The square's outline is 400 pt round, from (0, 0) to the right and on clockwise. + let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let pts = |spacing, start| -> Vec<(i64, i64)> { + stops(&closed, 4, spacing, start).unwrap().iter().map(|(p, _)| (p.x.round() as i64, p.y.round() as i64)).collect() + }; + assert_eq!(pts(Some(50.0), 0.0), [(0, 0), (50, 0), (100, 0), (100, 50)]); + // Centered on the first anchor: the span goes back past it. + assert_eq!(pts(Some(50.0), -75.0), [(0, 75), (0, 25), (25, 0), (75, 0)]); + // At most a quarter of the way round each: no two objects meet at the first anchor. + assert_eq!(pts(Some(300.0), 0.0), [(0, 0), (100, 0), (100, 100), (0, 100)]); + assert_eq!(layout(400.0, true, 4, Some(300.0), 400.0), (0.0, 100.0)); + } + + #[test] + fn a_group_saved_without_space_reads_as_auto() { + let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)); + let rec = ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0); + let v = serde_json::to_value(&rec).unwrap(); + assert!(v.get("spacing").is_none() && v.get("start").is_none(), "Auto is not written: {v}"); + let back: ObjectsOnPath = serde_json::from_value(v).unwrap(); + assert_eq!((back.spacing, back.start), (None, 0.0)); + let set = ObjectsOnPath { spacing: Some(60.0), start: 12.5, ..rec }; + let back: ObjectsOnPath = serde_json::from_value(serde_json::to_value(&set).unwrap()).unwrap(); + assert_eq!(back, set); + } + + #[test] + fn transforming_the_group_scales_its_space() { + let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut rec = ObjectsOnPath { spacing: Some(60.0), start: 12.5, ..ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 30.0) }; + rec.transform(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 5.0]), None); + assert_eq!((rec.spacing, rec.start, rec.rotate), (Some(120.0), 25.0, -30.0)); + rec.transform(Affine::translate((40.0, 0.0)) * Affine::rotate(0.7), None); + assert!((rec.spacing.unwrap() - 120.0).abs() < 1e-9 && (rec.start - 25.0).abs() < 1e-9, "{rec:?}"); + // Twice as wide and no higher: a level path is stretched twice along its length. + let level = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0)); + let stretch = Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + rec.transform(stretch, Some((&level, &level.transformed(stretch)))); + assert!((rec.spacing.unwrap() - 240.0).abs() < 1e-9 && (rec.start - 50.0).abs() < 1e-9, "{rec:?}"); + let mut auto = ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0); + auto.transform(Affine::scale(3.0), None); + assert_eq!((auto.spacing, auto.start), (None, 0.0), "Auto stays Auto"); + let mut huge = ObjectsOnPath { spacing: Some(1e308), start: -1e308, ..auto }; + huge.transform(Affine::scale(2.0), None); + assert_eq!((huge.spacing, huge.start), (Some(1e308), -1e308), "kept finite"); + } + + /// Stretching a path that turns a corner keeps the first and last objects where the stretch + /// takes them, not where the whole path's change in length would. + #[test] + fn a_stretch_keeps_the_first_and_last_objects_where_it_takes_them() { + // 100 pt to the right, then 100 pt down; twice as wide, the first part is 200 pt long. + let points = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0)]; + let corner = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)); + let stretch = Affine::scale_non_uniform(2.0, 1.0); + let wide = corner.transformed(stretch); + let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0))); + let mut rec = ObjectsOnPath { spacing: Some(40.0), start: 50.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) }; + rec.transform(stretch, Some((&corner, &wide))); + assert!((rec.start - 100.0).abs() < 1e-9 && (rec.spacing.unwrap() - 80.0).abs() < 1e-9, "{rec:?}"); + // Round a closed path, from before its first anchor: the start goes round as many times. + let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let wide = square.transformed(stretch); + let mut rec = ObjectsOnPath { spacing: Some(50.0), start: -75.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) }; + let before = stops(&square, 2, rec.spacing, rec.start).unwrap(); + rec.transform(stretch, Some((&square, &wide))); + let after = stops(&wide, 2, rec.spacing, rec.start).unwrap(); + for ((p, _), (q, _)) in before.iter().zip(&after) { + assert!((stretch * *p).distance(*q) < 1e-9, "{p:?} went to {q:?}: {rec:?}"); + } + assert!(rec.start < 0.0, "{rec:?}"); + } + + /// A start round a closed path so many times that scaling it would not be finite stays as it is. + #[test] + fn a_closed_path_start_too_large_to_scale_stays_finite() { + let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let grow = Affine::scale(2.0); + let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut rec = ObjectsOnPath { start: 1e308, ..ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0) }; + rec.transform(grow, Some((&square, &square.transformed(grow)))); + assert_eq!(rec.start, 1e308, "{rec:?}"); + } + + /// Stretching the group across its level path only keeps the objects where the stretch takes + /// them: twice as far apart. + #[test] + fn a_group_stretched_along_its_path_keeps_the_objects_in_proportion() { + let line = Node::path(NodeId(1), shapes::line(Point::new(0.0, 100.0), Point::new(300.0, 100.0)), Default::default()); + let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0))); + let mut g = Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(line), Arc::new(a.clone()), Arc::new(b.clone())], clip: false }); + let rec = ObjectsOnPath { spacing: Some(20.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) }; + g.extras_mut().objects_on_path = Some(Box::new(rec)); + let empty = crate::Document::new(1.0, 1.0); + let symbols = empty.symbol_boxes(); + place(&mut g, &symbols); + g.transform(Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]), false); + let rec = g.extras().objects_on_path.as_deref().cloned().unwrap(); + assert_eq!((rec.spacing, rec.start), (Some(40.0), 20.0)); + place(&mut g, &symbols); + let x = |id| g.children().and_then(|c| c.iter().find(|c| c.id == id).cloned()).unwrap().geometric_bounds().unwrap().center().x; + assert!((x(NodeId(2)) - 20.0).abs() < 1e-9 && (x(NodeId(3)) - 60.0).abs() < 1e-9, "{} {}", x(NodeId(2)), x(NodeId(3))); + } + + #[test] + fn length_near_measures_along_the_path_and_past_its_ends() { + // An L: 400 pt to the right, then 300 pt up. + let points = [Point::new(0.0, 300.0), Point::new(400.0, 300.0), Point::new(400.0, 0.0)]; + let l = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)); + let spine = Spine::new(&l).unwrap(); + assert!((spine.length_near(Point::new(300.0, 320.0), None) - 300.0).abs() < 1e-9); + assert!((spine.length_near(Point::new(420.0, 100.0), None) - 600.0).abs() < 1e-9); + assert!((spine.length_near(Point::new(400.0, -26.0), None) - 726.0).abs() < 1e-9, "beyond the end"); + assert!((spine.length_near(Point::new(-50.0, 300.0), None) + 50.0).abs() < 1e-9, "before the start"); + // A path that turns back near its start: beyond its end, the pointer is nearer the first + // segment than the last one, but on the line of the last one. + let hook = [Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 10.0), Point::new(100.0, 10.0)]; + let hook = Spine::new(&PathData::single(vectorcraft_geom::SubPath::polyline(&hook, false))).unwrap(); + assert!((hook.length_near(Point::new(80.0, 10.0), None) - 330.0).abs() < 1e-9); + assert!((hook.length_near(Point::new(50.0, 10.0), None) - 360.0).abs() < 1e-9); + let closed = Spine::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))).unwrap(); + assert!((closed.length_near(Point::new(-30.0, -30.0), None)).abs() < 1e-9, "a closed path has no ends"); + } + + #[test] + fn length_near_a_point_followed_stays_on_that_part_of_the_path() { + // A narrow U, open on the left: its ends are 20 pt apart, 620 pt from each other along it. + let u = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(300.0, 20.0), Point::new(0.0, 20.0)]; + let u = Spine::new(&PathData::single(vectorcraft_geom::SubPath::polyline(&u, false))).unwrap(); + assert!((u.length_near(Point::new(-26.0, 20.0), None) - 646.0).abs() < 1e-9, "beyond the end"); + // Nearer the first segment's line, the pointer stays beyond the end it was following. + assert!((u.length_near(Point::new(-26.0, 8.0), None) + 26.0).abs() < 1e-9); + assert!((u.length_near(Point::new(-26.0, 8.0), Some(646.0)) - 646.0).abs() < 1e-9); + // Following the path round, it goes on from where it was. + assert!((u.length_near(Point::new(305.0, 10.0), Some(312.0)) - 310.0).abs() < 1e-9); + // Round a closed path's first anchor: from 10 pt short of it to 20 pt past it. + let square = Spine::new(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0))).unwrap(); + let (at, _) = square.at_length(390.0); + assert!((square.length_near(at, None) - 390.0).abs() < 1e-9); + assert!((square.length_near(Point::new(20.0, -5.0), Some(390.0)) - 20.0).abs() < 1e-9); } #[test] diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index eebdd3e046..e2bd0957d9 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -7,7 +7,8 @@ //! path column by column from left to right, top to bottom in each column, spread evenly from its //! first anchor and turned to follow it. Pivot and Rotate come from the command's params, otherwise //! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the -//! group's Pivot and Rotate, and `object.objectsOnPath.expand` makes it a plain group. +//! group's Pivot, Rotate and Space (the distance between the objects along the path, and where the +//! first one attaches), and `object.objectsOnPath.expand` makes it a plain group. //! //! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back //! on its path: editing the path moves them, an object moved on its own goes back to its place, @@ -48,7 +49,7 @@ pub fn specs() -> Vec { "Objects on Path Options", [], None, - "{ids?: Objects on Path groups or objects in them (default: the selection), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; 4: the center), rotate?: degrees counter-clockwise from upright on the path} set how the objects of the groups attach → {ids}", + "{ids?: Objects on Path groups or objects in them (default: the selection), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; 4: the center), rotate?: degrees counter-clockwise from upright on the path, spacing?: points along the path from each object's attachment point to the next one's (0 or more, kept to what the path has room for; or \"auto\", the default: spread evenly with the last object at the end of an open path), start?: points along the path from its first anchor to the first object's attachment point (default 0)} set how the objects of the groups attach and are spaced → {ids}", has_objects_on_path, options ), @@ -256,16 +257,37 @@ fn attach(s: &mut Session, p: &Value) -> Result { // ---------- Options ---------- +/// `spacing` and `start` from `p`, each checked: `spacing` takes points (0 or more) or `"auto"` +/// (`None`), and `start` points along the path. +fn spacing_start(p: &Value, cmd: &str, spacing: Option, start: f64) -> Result<(Option, f64)> { + let spacing = match p.get("spacing").filter(|v| !v.is_null()) { + None => spacing, + Some(Value::String(a)) if a == "auto" => None, + Some(v) => Some( + v.as_f64() + .filter(|g| g.is_finite() && *g >= 0.0) + .ok_or_else(|| bad(cmd, "`spacing` must be a number of points, 0 or more, or \"auto\""))?, + ), + }; + let start = match p.get("start").filter(|v| !v.is_null()) { + None => start, + Some(v) => v.as_f64().filter(|s| s.is_finite()).ok_or_else(|| bad(cmd, "`start` must be a finite number"))?, + }; + Ok((spacing, start)) +} + fn options(s: &mut Session, p: &Value) -> Result { const C: &str = "object.objectsOnPath.options"; let groups = target_groups(s, p, C)?; pivot_rotate(p, C, CENTER, 0.0)?; + spacing_start(p, C, None, 0.0)?; s.edit("Objects on Path Options", |d, _| { for g in &groups { let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; let Some(rec) = n.extras().objects_on_path.as_deref().cloned() else { continue }; let (pivot, rotate) = pivot_rotate(p, C, rec.pivot, rec.rotate)?; - n.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath { pivot, rotate, ..rec })); + let (spacing, start) = spacing_start(p, C, rec.spacing, rec.start)?; + n.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath { pivot, rotate, spacing, start, ..rec })); } Ok(()) })?; diff --git a/crates/engine/src/tests/objects_on_path.rs b/crates/engine/src/tests/objects_on_path.rs index a309eb69ba..8c0f359df4 100644 --- a/crates/engine/src/tests/objects_on_path.rs +++ b/crates/engine/src/tests/objects_on_path.rs @@ -460,3 +460,91 @@ fn options_and_expand_take_ids_without_a_selection() { assert_eq!(s.doc().unwrap().doc.node(g).unwrap().kind_label(), "Group"); assert!(s.execute("object.objectsOnPath.expand", &json!({"ids": [g.0]})).is_err(), "no longer an Objects on Path group"); } + +/// The Space and start of group `g`. +fn space(s: &Session, g: NodeId) -> (Option, f64) { + let rec = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap(); + (rec.spacing, rec.start) +} + +#[test] +fn space_sets_the_distance_between_the_objects_in_one_undo_step() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({"rotate": 30, "pivot": 7})); + assert_eq!(space(&s, g), (None, 0.0), "Auto"); + let before = (bounds(&s, left), bounds(&s, middle).width()); + s.execute("object.objectsOnPath.options", &json!({"spacing": 60})).unwrap(); + assert_eq!(space(&s, g), (Some(60.0), 0.0)); + // The first object stays; the others come 60 pt apart, keeping Pivot and Rotate. + assert_eq!(bounds(&s, left), before.0); + let x = |s: &Session, id| bounds(s, id).center().x - bounds(s, left).center().x; + assert!((x(&s, middle) - 60.0).abs() < 1e-6 && (x(&s, right) - 120.0).abs() < 1e-6); + assert!((bounds(&s, middle).width() - before.1).abs() < 1e-6, "still turned by Rotate"); + // Centered: from 90 pt along the 300 pt line. + s.execute("object.objectsOnPath.options", &json!({"spacing": 60, "start": 90})).unwrap(); + assert!((x(&s, right) - 120.0).abs() < 1e-6); + assert!((bounds(&s, left).center().x - before.0.center().x - 90.0).abs() < 1e-6); + // Pivot and Rotate keep the Space. + s.execute("object.objectsOnPath.options", &json!({"rotate": 0, "pivot": 4})).unwrap(); + assert_eq!(space(&s, g), (Some(60.0), 90.0)); + assert_eq!( + (center(&s, left), center(&s, middle), center(&s, right)), + (Point::new(140.0, 300.0), Point::new(200.0, 300.0), Point::new(260.0, 300.0)) + ); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(space(&s, g), (Some(60.0), 0.0), "each change is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(space(&s, g), (None, 0.0)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(space(&s, g), (Some(60.0), 0.0)); + s.execute("object.objectsOnPath.options", &json!({"spacing": "auto", "start": 0})).unwrap(); + assert_eq!(space(&s, g), (None, 0.0)); + assert_eq!(center(&s, right).x - center(&s, left).x, 300.0, "Auto spreads them to the end again"); +} + +#[test] +fn a_space_that_is_not_usable_is_refused_and_one_too_large_is_kept_to_the_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + for bad in + [json!({"spacing": -1}), json!({"spacing": "wide"}), json!({"spacing": true}), json!({"start": "x"}), json!({"spacing": 10, "start": [1]})] + { + assert!(s.execute("object.objectsOnPath.options", &bad).is_err(), "{bad}"); + assert_eq!(space(&s, g), (None, 0.0), "{bad} changes nothing"); + } + s.execute("object.objectsOnPath.options", &json!({"spacing": 1e9})).unwrap(); + assert_eq!(space(&s, g), (Some(1e9), 0.0)); + assert_eq!((center(&s, middle), center(&s, right)), (Point::new(200.0, 300.0), Point::new(350.0, 300.0)), "the last one reaches the end"); + // A shorter path draws them closer; the full length brings the Space back. + s.execute("object.objectsOnPath.options", &json!({"spacing": 100})).unwrap(); + set_line(&mut s, path, (50.0, 300.0), (150.0, 300.0)); + assert_eq!((center(&s, middle), center(&s, right)), (Point::new(100.0, 300.0), Point::new(150.0, 300.0))); + assert_eq!(space(&s, g), (Some(100.0), 0.0)); + set_line(&mut s, path, (50.0, 300.0), (350.0, 300.0)); + assert_eq!((center(&s, middle), center(&s, right)), (Point::new(150.0, 300.0), Point::new(250.0, 300.0))); + // An object moved on its own goes back, and the Space stays. + s.execute("object.move", &json!({"ids": [middle.0], "dx": 30, "dy": -40})).unwrap(); + assert_eq!(center(&s, middle), Point::new(150.0, 300.0)); + assert_eq!(space(&s, g), (Some(100.0), 0.0)); +} + +#[test] +fn the_space_saves_and_reopens_and_goes_with_a_copy() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + s.execute("object.objectsOnPath.options", &json!({"spacing": 40, "start": 25})).unwrap(); + let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "objects.vectorcraft", "dataBase64": data})).unwrap(); + assert_eq!(space(&o, g), (Some(40.0), 25.0)); + assert_eq!(center(&o, right), Point::new(155.0, 300.0)); + select(&mut s, &[g]); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let copy = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(space(&s, copy[0]), (Some(40.0), 25.0)); +} diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs index 4fe14e8545..1e33e09a1b 100644 --- a/crates/eps/src/import/ai/read/on_path.rs +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -182,7 +182,7 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap let center = doc.node_at(place)?.geometric_bounds()?.center(); members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); } - let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate }; + let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate, spacing: None, start: 0.0 }; doc.node_mut_at(group_at)?.extras_mut().objects_on_path = Some(Box::new(on_path)); Some(()) } diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index 47aff8910f..fe5a8b9215 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -11,10 +11,21 @@ //! previewed while dragging and kept as one undo step on release. Shift turns in steps of 15°, and //! Escape cancels the drag. //! -//! Behavior: . +//! The Space widget: with one Objects on Path group of two or more objects selected, the same +//! tools show a square handle beyond the group's last object, ahead along the path. Dragging it +//! along the path sets the distance between the objects' attachment points +//! (`object.objectsOnPath.options` with `spacing` and `start`): the first object stays where it is +//! and the others move toward or away from it. With Alt (Option on macOS) the objects spread from +//! both ends toward or away from the center of an open path, or of the first anchor of a closed +//! one. The distance shows next to the pointer in the document's units, the drag is previewed and +//! kept as one undo step on release, and Escape cancels it. +//! +//! Behavior: , +//! . use serde_json::{Value, json}; -use vectorcraft_doc::objects_on_path::{CENTER, attachable_path, is_objects_on_path, stops}; +use vectorcraft_doc::blend::Spine; +use vectorcraft_doc::objects_on_path::{CENTER, ObjectsOnPath, attachable_path, is_objects_on_path, layout, nth_length, path_length, stop}; use vectorcraft_doc::{Document, NodeId, Selection}; use vectorcraft_geom::{BezPath, Point, Vec2}; @@ -33,6 +44,35 @@ const ROTATE_ALL_HIT_PX: f64 = 6.0; /// The step (degrees) a Shift-drag of the Rotate All widget turns by. const ROTATE_ALL_STEP: f64 = 15.0; +/// The Space widget's center sits this far (screen px) beyond the last object, ahead along the path. +const SPACE_OFFSET_PX: f64 = 16.0; +/// Half the side of the Space widget's square (screen px), as the canvas draws it. +pub const SPACE_HALF_PX: f32 = 3.5; +/// How near (screen px) the pointer must be to hit the Space widget. +const SPACE_HIT_PX: f64 = 6.0; + +/// The Objects on Path group the widgets show for at `zoom` (screen px per document point), with +/// its record, its children and its path: only when the selection is that one editable group, on +/// a path with length, and no anchors are Direct-Selected. +fn one_group<'a>( + doc: &'a Document, + selection: &Selection, + zoom: f64, +) -> Option<(NodeId, &'a ObjectsOnPath, &'a [std::sync::Arc], &'a vectorcraft_geom::PathData)> { + if !selection.anchors.is_empty() || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let [group] = selection.objects.as_slice() else { return None }; + if !doc.editable()(*group) { + return None; + } + let n = doc.node(*group)?; + let rec = n.extras().objects_on_path.as_deref()?; + let children = n.children()?; + let path = attachable_path(children.iter().find(|c| c.id == rec.path)?)?; + Some((*group, rec, children.as_slice(), path)) +} + /// The Rotate All widget of a selected Objects on Path group. #[derive(Clone, Copy, Debug, PartialEq)] pub struct RotateAllWidget { @@ -50,20 +90,9 @@ impl RotateAllWidget { /// selection is one editable Objects on Path group with at least one object on a path with /// length, and no anchors are Direct-Selected. pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { - if !selection.anchors.is_empty() || !zoom.is_finite() || zoom <= 0.0 { - return None; - } - let [group] = selection.objects.as_slice() else { return None }; - if !doc.editable()(*group) { - return None; - } - let n = doc.node(*group)?; - let rec = n.extras().objects_on_path.as_deref()?; - let children = n.children()?; - let path = attachable_path(children.iter().find(|c| c.id == rec.path)?)?; + let (group, rec, children, path) = one_group(doc, selection, zoom)?; let first = rec.members.first()?; - // The first object attaches at the path's start, whatever the number of objects. - let (pivot, _) = *stops(path, 1)?.first()?; + let (pivot, _) = stop(path, rec.members.len(), rec.spacing, rec.start, 0)?; let art = children.iter().find(|c| c.id == first.id)?; let b = art.geometric_bounds_with(&doc.symbol_boxes())?; // The object's top is the -y direction of the frame it is drawn in (the document's y axis @@ -80,7 +109,7 @@ impl RotateAllWidget { let reach = corners.iter().map(|c| (*c - pivot).dot(up)).fold(0.0, f64::max); let at = pivot + up * (reach + ROTATE_ALL_OFFSET_PX / zoom); let finite = at.x.is_finite() && at.y.is_finite() && pivot.x.is_finite() && pivot.y.is_finite(); - finite.then_some(Self { group: *group, pivot, at, rotate: rec.rotate }) + finite.then_some(Self { group, pivot, at, rotate: rec.rotate }) } /// The widget of `cx` when `p` is within reach of it. @@ -166,6 +195,205 @@ impl RotateAllDrag { } } +/// The Space widget of a selected Objects on Path group. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SpaceWidget { + pub group: NodeId, + /// The last object's attachment point, in the document. + pub last: Point, + /// The distance along the path to the last object's attachment point (points). + pub last_length: f64, + /// The widget's center in the document. + pub at: Point, + /// The path's direction at the last object's attachment point: a unit vector in the + /// document's axes, in which the widget sits beyond the object. + pub dir: Vec2, + /// The length of the path (points). + pub len: f64, + /// Is the path closed? + pub closed: bool, + /// The number of objects on the path: 2 or more. + pub count: usize, + /// Where the first object attaches along the path (points from its first anchor), as drawn. + pub start: f64, + /// The distance along the path between neighboring objects' attachment points (points), as drawn. + pub gap: f64, + /// The group's Space value (`None`: Auto) and start, as saved: more than is drawn when the path + /// is too short for them. + pub saved: (Option, f64), +} + +impl SpaceWidget { + /// The widget of the selection at `zoom` (screen px per document point): only when the + /// selection is one editable Objects on Path group with two or more objects on a path with + /// length, and no anchors are Direct-Selected. It sits beyond the last object's bounds, ahead + /// along the path's direction there. + pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { + let (group, rec, children, path) = one_group(doc, selection, zoom)?; + let count = rec.members.len(); + if count < 2 { + return None; + } + let (len, closed) = path_length(path)?; + let (start, gap) = layout(len, closed, count, rec.spacing, rec.start); + let (last, angle) = stop(path, count, rec.spacing, rec.start, count - 1)?; + let dir = Vec2::new(angle.cos(), angle.sin()); + let m = rec.members.last()?; + let b = children.iter().find(|c| c.id == m.id)?.geometric_bounds_with(&doc.symbol_boxes())?; + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; + let reach = corners.iter().map(|c| (*c - last).dot(dir)).fold(0.0, f64::max); + let at = last + dir * (reach + SPACE_OFFSET_PX / zoom); + let finite = at.x.is_finite() && at.y.is_finite() && last.x.is_finite() && last.y.is_finite(); + let last_length = nth_length(len, closed, start, gap, count - 1); + finite.then_some(Self { group, last, last_length, at, dir, len, closed, count, start, gap, saved: (rec.spacing, rec.start) }) + } + + /// The widget of `cx` when `p` is within reach of it. + fn at_point(cx: &ToolContext, p: Point) -> Option { + Self::of(cx.doc, cx.selection, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(SPACE_HIT_PX)) + } +} + +/// Is `p` over the Space widget? +pub fn over_space(cx: &ToolContext, p: Point) -> bool { + SpaceWidget::at_point(cx, p).is_some() +} + +/// The distance along the path of the Objects on Path group of `w` in `doc` to the point nearest +/// `p` ([`Spine::nearest`]: past the ends of an open path, along the lines of its end segments), +/// staying near `from` when the pointer is following the path from there. The line from the last +/// object's attachment point through the widget counts as the path too, as far as the pointer is +/// ahead of that object along it, so a widget beyond a corner measures from where it is. The flag +/// says whether the point is on that line, where the distance runs on past the end of a closed path +/// instead of round it. +fn length_near(doc: &Document, w: &SpaceWidget, p: Point, from: Option) -> Option<(f64, bool)> { + let n = doc.node(w.group)?; + let rec = n.extras().objects_on_path.as_deref()?; + let path = attachable_path(n.children()?.iter().find(|c| c.id == rec.path)?)?; + let spine = Spine::new(path)?; + let bias = |s: f64| from.filter(|f| f.is_finite()).map_or(0.0, |f| spine.apart(s, f) / 2.0); + let ahead = (p - w.last).dot(w.dir); + let line = (ahead >= 0.0).then(|| { + let s = w.last_length + ahead; + ((p - w.last).cross(w.dir).abs() + bias(s), s) + }); + let (s, on_line) = match (spine.nearest(p, from), line) { + (Some(on), Some(line)) if line.0 < on.0 => (line.1, true), + (Some(on), _) => (on.1, false), + (None, line) => (line?.1, true), + }; + s.is_finite().then_some((s, on_line)) +} + +/// Dragging the Space widget: the distance the pointer moves along the path moves the last object +/// along it as far, and the objects between follow evenly. With Alt the first object moves the +/// other way as far, so the objects spread from both ends. +#[derive(Clone, Debug)] +pub struct SpaceDrag { + widget: SpaceWidget, + start: Point, + began: bool, + /// The distance along the path to the point nearest the pointer at the last drag (points). + last: f64, + /// The distance the pointer has moved along the path since the press (points). + along: f64, + /// The distance between neighboring objects the drag sets (points). + gap: f64, + at: Point, +} + +impl SpaceDrag { + /// The drag has left the click: the distance is changing. + pub fn adjusting(&self) -> bool { + self.began + } + + /// Start a drag when the press `ev` is on the Space widget. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let widget = SpaceWidget::at_point(cx, ev.pos)?; + let (last, _) = length_near(cx.doc, &widget, ev.pos, None)?; + Some(Self { widget, start: ev.pos, began: false, last, along: 0.0, gap: widget.gap, at: ev.pos }) + } + + /// The pointer moved to `p` from `self.at`: add the distance it moved along the path. On the + /// line through the widget, from a point ahead of the last object, that is how far it moved + /// along the line; otherwise it takes the shorter way round a closed path. + fn follow(&mut self, doc: &Document, p: Point) { + let w = &self.widget; + let Some((t, on_line)) = length_near(doc, w, p, Some(self.last)) else { return }; + let before = (self.at - w.last).dot(w.dir); + let step = if on_line && before >= 0.0 { + (p - w.last).dot(w.dir) - before + } else if w.closed { + (t - self.last + w.len / 2.0).rem_euclid(w.len) - w.len / 2.0 + } else { + t - self.last + }; + if step.is_finite() { + self.along += step; + self.last = t; + } + } + + /// The Space and start the drag sets: without `alt` the first object stays and the last one goes + /// no further than the end of an open path; with `alt` the objects are centered on an open path, + /// or on the first anchor of a closed one, and spread over the whole path at most. On a closed + /// path the objects go no more than once around. + fn spacing_at(&self, alt: bool) -> (f64, f64) { + let w = &self.widget; + let k = (w.count - 1) as f64; + let along = self.along; + let round = w.len / w.count as f64; + if alt { + let most = if w.closed { round } else { w.len / k }; + let gap = (w.gap + 2.0 * along / k).clamp(0.0, most); + let span = gap * k; + (gap, if w.closed { (-span / 2.0).rem_euclid(w.len) } else { (w.len - span) / 2.0 }) + } else { + let most = if w.closed { round } else { (w.len - w.start) / k }; + ((w.gap + along / k).clamp(0.0, most.max(0.0)), w.start) + } + } + + /// The pointer moved to `p`; `alt` spreads the objects from both ends. + pub fn drag(&mut self, cx: &ToolContext, p: Point, alt: bool) -> Vec { + let mut out = vec![]; + if !self.began { + if p.distance(self.start) < cx.tol(3.0) { + return out; + } + self.began = true; + out.push(Action::Begin("Objects on Path Options".into())); + } + self.follow(cx.doc, p); + let (gap, start) = self.spacing_at(alt); + self.gap = gap; + self.at = p; + // Where the objects stay as they are drawn, the group keeps its saved values: Auto, or a + // Space value the path is too short for. + let w = &self.widget; + let (spacing, start) = if (gap - w.gap).abs() < 1e-9 && (start - w.start).abs() < 1e-9 { + (w.saved.0.map_or_else(|| json!("auto"), |g| json!(g)), json!(w.saved.1)) + } else { + (json!(gap), json!(start)) + }; + out.push(Action::Preview("object.objectsOnPath.options".into(), json!({ "ids": [w.group.0], "spacing": spacing, "start": start }))); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + /// The distance between the objects next to the pointer, in the document's units. + pub fn overlays(&self, cx: &ToolContext) -> Vec { + if !self.began || !cx.measurement_labels { + return vec![]; + } + vec![Overlay::Measure { p: self.at, text: cx.len(self.gap) }] + } +} + /// The path a click at `p` attaches the selected objects to: the path object hit there, when it can /// take objects, is in no Objects on Path group, is not a clipping path or part of a compound path, /// blend, envelope, repeat or Intertwine group ([`vectorcraft_doc::objects_on_path::held`]), and @@ -190,6 +418,8 @@ pub struct ObjectsOnPathTool { press: Option, /// The Rotate All widget drag, while the button is down after a press on the widget. rotating: Option, + /// The Space widget drag, while the button is down after a press on the widget. + spacing: Option, /// The reference point of each object attached next (0-8, row by row from the top left). pivot: u8, /// The angle of each object attached next, in degrees counter-clockwise from upright on the path. @@ -198,7 +428,7 @@ pub struct ObjectsOnPathTool { impl Default for ObjectsOnPathTool { fn default() -> Self { - Self { hover: None, press: None, rotating: None, pivot: CENTER, rotate: 0.0 } + Self { hover: None, press: None, rotating: None, spacing: None, pivot: CENTER, rotate: 0.0 } } } @@ -216,9 +446,16 @@ impl Tool for ObjectsOnPathTool { _ => vec![], }; } + if let Some(d) = &mut self.spacing { + return match ev.kind { + PointerKind::Drag => d.drag(cx, p, ev.mods.alt), + PointerKind::Up => self.spacing.take().map(SpaceDrag::finish).unwrap_or_default(), + _ => vec![], + }; + } match ev.kind { PointerKind::Move => { - self.hover = if over_rotate_all(cx, p) { None } else { target(cx, p) }; + self.hover = if over_rotate_all(cx, p) || over_space(cx, p) { None } else { target(cx, p) }; vec![] } PointerKind::Down => { @@ -227,6 +464,11 @@ impl Tool for ObjectsOnPathTool { self.hover = None; return vec![]; } + if let Some(d) = SpaceDrag::hit(cx, ev) { + self.spacing = Some(d); + self.hover = None; + return vec![]; + } self.press = Some(p); vec![] } @@ -247,12 +489,17 @@ impl Tool for ObjectsOnPathTool { if let Some(d) = &self.rotating { o.extend(d.overlays(cx)); } + if let Some(d) = &self.spacing { + o.extend(d.overlays(cx)); + } o } fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor { - if self.rotating.is_some() || over_rotate_all(cx, p) { + if self.rotating.is_some() || (self.spacing.is_none() && over_rotate_all(cx, p)) { Cursor::Rotate + } else if self.spacing.is_some() || over_space(cx, p) { + Cursor::ArrowHollow } else if target(cx, p).is_some() { Cursor::ObjectsOnPath } else { @@ -261,12 +508,14 @@ impl Tool for ObjectsOnPathTool { } /// Escape while the button is down cancels the click, so the release attaches nothing, or the - /// Rotate All drag, so the objects go back to the Rotate they had. + /// Rotate All or Space drag, so the objects go back to the Rotate or Space they had. fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Escape { self.press = None; self.hover = None; - if self.rotating.take().is_some_and(|d| d.adjusting()) { + let rotated = self.rotating.take().is_some_and(|d| d.adjusting()); + let spaced = self.spacing.take().is_some_and(|d| d.adjusting()); + if rotated || spaced { return vec![Action::Cancel]; } } @@ -296,11 +545,11 @@ impl Tool for ObjectsOnPathTool { } fn busy(&self) -> bool { - self.press.is_some() || self.rotating.is_some() + self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() } fn transforming(&self) -> bool { - self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting) + self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting) || self.spacing.as_ref().is_some_and(SpaceDrag::adjusting) } } @@ -602,4 +851,228 @@ mod tests { assert!(t.pointer(&cx, &ev(PointerKind::Up, p.0, p.1)).is_empty(), "a click on {what} attaches nothing"); } } + + /// [`group_doc`] with the group's Space `spacing` from `start`, its objects placed again. + fn spaced_doc(spacing: Option, start: f64) -> (Document, NodeId, Selection) { + let (mut d, g, sel) = group_doc(0.0); + let empty = Document::new(1.0, 1.0); + let symbols = empty.symbol_boxes(); + let n = d.node_mut(g).unwrap(); + let rec = n.extras().objects_on_path.as_deref().cloned().unwrap(); + n.extras_mut().objects_on_path = Some(Box::new(vectorcraft_doc::objects_on_path::ObjectsOnPath { spacing, start, ..rec })); + vectorcraft_doc::objects_on_path::place(n, &symbols); + (d, g, sel) + } + + /// The Space and start a drag's last action previews, to 1/1,000,000 pt. + fn spaced(acts: &[Action]) -> Option<(f64, f64)> { + let round = |v: f64| (v * 1e6).round() / 1e6 + 0.0; + match acts.last() { + Some(Action::Preview(cmd, p)) if cmd == "object.objectsOnPath.options" => { + Some((round(p["spacing"].as_f64()?), round(p["start"].as_f64()?))) + } + _ => None, + } + } + + fn alt(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent { mods: Mods { alt: true, ..Mods::default() }, ..ev(kind, x, y) } + } + + #[test] + fn the_space_widget_sits_beyond_the_last_object_ahead_along_the_path() { + // Auto: the second square sits on the end (400, 300) and spans 390 to 410. + let (d, g, sel) = group_doc(0.0); + let w = SpaceWidget::of(&d, &sel, 1.0).unwrap(); + assert_eq!((w.group, w.count, w.closed), (g, 2, false)); + assert!(near(w.last, Point::new(400.0, 300.0)) && near(w.at, Point::new(426.0, 300.0)), "{w:?}"); + assert!((w.len - 400.0).abs() < 1e-9 && w.start == 0.0 && (w.gap - 400.0).abs() < 1e-9, "{w:?}"); + assert!(near(SpaceWidget::of(&d, &sel, 2.0).unwrap().at, Point::new(418.0, 300.0))); + // With a Space set it follows the last object, and Rotate All follows the first one. + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let w = SpaceWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.last, Point::new(150.0, 300.0)) && near(w.at, Point::new(176.0, 300.0)), "{w:?}"); + assert!(near(RotateAllWidget::of(&d, &sel, 1.0).unwrap().pivot, Point::new(50.0, 300.0))); + // No widget for an object in the group, or for a locked group. + let children: Vec = d.node(sel.objects[0]).and_then(|n| n.children()).unwrap().iter().map(|c| c.id).collect(); + let mut one = Selection::default(); + one.set([children[1]]); + assert!(SpaceWidget::of(&d, &one, 1.0).is_none()); + let (mut d, g, sel) = group_doc(0.0); + if let Some(n) = d.node_mut(g) { + n.locked = true; + } + assert!(SpaceWidget::of(&d, &sel, 1.0).is_none()); + } + + /// Dragging the widget 100 pt back along the path brings the last object 100 pt nearer the + /// first one, which stays; with Alt the first one comes as far the other way. Switching Alt + /// during the drag works from where the drag began. + #[test] + fn dragging_the_space_widget_spaces_the_objects_from_the_first_one() { + let (d, g, sel) = group_doc(0.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let at = SpaceWidget::of(&d, &sel, 1.0).unwrap().at; + let tools: [Box; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())]; + for mut t in tools { + let id = t.id(); + assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::ArrowHollow, "{id}"); + assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty(), "{id}"); + let a = t.pointer(&c, &ev(PointerKind::Drag, at.x - 100.0, at.y + 30.0)); + assert_eq!(a.first(), Some(&Action::Begin("Objects on Path Options".into())), "{id}"); + assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["ids"] == json!([g.0])), "{a:?}"); + assert_eq!(spaced(&a), Some((300.0, 0.0)), "{id}: the first object stays"); + assert!(t.transforming() && t.cursor(&c, at, Mods::default()) == Cursor::ArrowHollow, "{id}"); + let label = c.len(300.0); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == label)), "{id}"); + assert_eq!(spaced(&t.pointer(&c, &alt(PointerKind::Drag, at.x - 100.0, at.y))), Some((200.0, 100.0)), "{id}: from both ends"); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 100.0, at.y))), Some((300.0, 0.0)), "{id}: Alt let go"); + // No further than the end, where the objects are as drawn and the group stays Auto; and no + // less than 0. + let a = t.pointer(&c, &ev(PointerKind::Drag, at.x + 50.0, at.y)); + assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["spacing"] == "auto" && p["start"] == 0.0), "{id}: {a:?}"); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 0.0)), "{id}"); + assert_eq!(spaced(&t.pointer(&c, &alt(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 200.0)), "{id}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}"); + assert!(!t.busy(), "{id}"); + // A click on the widget that does not move changes nothing. + assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)).is_empty(), "{id}"); + } + } + + /// A Space value the path is too short for stays when a drag leaves the objects where they are + /// drawn, and a drag that moves them sets the drawn value. + #[test] + fn a_drag_that_leaves_the_objects_as_drawn_keeps_the_saved_space() { + let (d, _, sel) = spaced_doc(Some(1000.0), 0.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = SpaceWidget::of(&d, &sel, 1.0).unwrap(); + assert_eq!((w.gap, w.saved), (400.0, (Some(1000.0), 0.0)), "drawn to the end of the 400 pt path"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x + 50.0, w.at.y))), Some((1000.0, 0.0))); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x - 50.0, w.at.y))), Some((350.0, 0.0))); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x, w.at.y))), Some((1000.0, 0.0)), "back where it began"); + } + + /// On a closed path the objects go no more than once around, and Alt centers them on the + /// first anchor. + #[test] + fn dragging_the_space_widget_on_a_closed_path_wraps_at_the_first_anchor() { + let w = SpaceWidget { + group: NodeId(1), + last: Point::ZERO, + last_length: 300.0, + at: Point::ZERO, + dir: Vec2::new(1.0, 0.0), + len: 400.0, + closed: true, + count: 4, + start: 0.0, + gap: 100.0, + saved: (None, 0.0), + }; + let moved = |along| SpaceDrag { widget: w, start: Point::ZERO, began: true, last: 0.0, along, gap: w.gap, at: Point::ZERO }; + assert_eq!(moved(30.0).spacing_at(false), (100.0, 0.0), "a quarter of the way round at most"); + assert_eq!(moved(-60.0).spacing_at(false), (80.0, 0.0)); + assert_eq!(moved(-60.0).spacing_at(true), (60.0, 310.0), "the span of 180 centered on the first anchor"); + } + + /// An Objects on Path group of two 20 × 20 squares on an L: 400 pt to the right from (0, 300), + /// then 300 pt up, with Space `spacing`; and a selection of the group. + fn corner_doc(spacing: Option) -> (Document, Selection) { + let points = [Point::new(0.0, 300.0), Point::new(400.0, 300.0), Point::new(400.0, 0.0)]; + path_doc(vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)), spacing) + } + + /// An Objects on Path group of two 20 × 20 squares on `path`, with Space `spacing`; and a + /// selection of the group. + fn path_doc(path: vectorcraft_geom::PathData, spacing: Option) -> (Document, Selection) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (line, a, b, g) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let line = Node::path(line, path, Appearance::default_art()); + let a = Node::path(a, shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), Appearance::default_art()); + let b = Node::path(b, shapes::rectangle(Rect::new(100.0, 50.0, 120.0, 70.0)), Appearance::default_art()); + let rec = vectorcraft_doc::objects_on_path::ObjectsOnPath::new(line.id, &[&a, &b], CENTER, 0.0); + let rec = vectorcraft_doc::objects_on_path::ObjectsOnPath { spacing, ..rec }; + let mut group = Node::new(g, NodeKind::Group { children: vec![Arc::new(line), Arc::new(a), Arc::new(b)], clip: false }); + group.extras_mut().objects_on_path = Some(Box::new(rec)); + vectorcraft_doc::objects_on_path::place(&mut group, &Document::new(1.0, 1.0).symbol_boxes()); + d.insert(Some(l), 0, group).unwrap(); + let mut sel = Selection::default(); + sel.set([g]); + (d, sel) + } + + /// On an L-shaped path the drag counts the distance along the path, round the corner. + #[test] + fn a_space_drag_follows_the_path_round_a_corner() { + let (d, sel) = corner_doc(None); + let paint = paint(); + let c = cx(&d, &sel, &paint); + // The path is 700 pt long; the second object sits on its end (400, 0), and the widget above it. + let w = SpaceWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.last, Point::new(400.0, 0.0)) && (w.gap - 700.0).abs() < 1e-9, "{w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + // The press, 26 pt beyond the end, is 726 pt along. Down the upright leg to 500 pt along, + // then round the corner onto the level one at 300 pt along. + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 400.0, 200.0))), Some((474.0, 0.0))); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 300.0, 310.0))), Some((274.0, 0.0))); + } + + /// With the last object just short of the corner, the widget sits past the corner; the drag + /// measures from the widget, so the objects follow the pointer from the start. + #[test] + fn a_space_widget_past_a_corner_measures_from_where_it_is() { + let (d, sel) = corner_doc(Some(390.0)); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = SpaceWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.last, Point::new(390.0, 300.0)) && near(w.at, Point::new(416.0, 300.0)) && w.last_length == 390.0, "{w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 396.0, 300.0))), Some((370.0, 0.0)), "20 pt back"); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 386.0, 300.0))), Some((360.0, 0.0))); + } + + /// On a closed path, a drag far ahead along the line through the widget spreads the objects + /// apart, however far the pointer goes at once. + #[test] + fn a_long_drag_ahead_on_a_closed_path_spreads_the_objects() { + // The square's outline is 800 pt round, from (100, 100) to the right. + let (d, sel) = path_doc(shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), Some(100.0)); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = SpaceWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.last, Point::new(200.0, 100.0)) && near(w.at, Point::new(226.0, 100.0)), "{w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 236.0, 100.0))), Some((110.0, 0.0))); + assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 1000.0, 100.0))), Some((400.0, 0.0)), "half way round at most"); + } + + /// Escape during a Space drag cancels it: the readout is removed, and the release keeps + /// nothing. + #[test] + fn escape_cancels_a_space_drag() { + let (d, _, sel) = group_doc(0.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let at = SpaceWidget::of(&d, &sel, 1.0).unwrap().at; + let tools: [Box; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())]; + for mut t in tools { + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + assert!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 40.0, at.y))).is_some()); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{}", t.id()); + assert!(!t.busy() && !t.transforming(), "{}", t.id()); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. })), "{}", t.id()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, at.x, at.y)).is_empty(), "{}", t.id()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)).is_empty(), "{}: the release keeps nothing", t.id()); + } + } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 8cbade741e..572c667e4b 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -47,7 +47,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path}; -use crate::objects_on_path::{RotateAllDrag, over_rotate_all}; +use crate::objects_on_path::{RotateAllDrag, SpaceDrag, over_rotate_all, over_space}; use crate::pathtype::{self, BracketDrag, over_bracket}; use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; @@ -107,6 +107,8 @@ enum State { Pie(PieDrag), /// Dragging an Objects on Path group's Rotate All widget. RotateAll(RotateAllDrag), + /// Dragging an Objects on Path group's Space widget. + Space(SpaceDrag), /// Move or rotate a live mirror axis. Mirror(crate::mirror::MirrorDrag), /// Drag a grid repeat's row, column or corner handle or a spacing slider. @@ -642,7 +644,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or - /// rotation, a marquee, a corner widget, a pie widget, the Rotate All widget, the brackets of type on a path, a mirror + /// rotation, a marquee, a corner widget, a pie widget, the Rotate All or Space widget, the brackets of type on a path, a mirror /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. @@ -728,6 +730,7 @@ impl Tool for SelectionTool { State::Corner(c) => c.adjusting(), State::Pie(d) => d.adjusting(), State::RotateAll(d) => d.adjusting(), + State::Space(d) => d.adjusting(), State::Bracket(b) => b.adjusting(), State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), @@ -891,6 +894,15 @@ impl Tool for SelectionTool { self.state = State::Idle; d.finish() } + (PointerKind::Drag, State::Space(mut d)) => { + let out = d.drag(cx, p, m.alt); + self.state = State::Space(d); + out + } + (PointerKind::Up, State::Space(d)) => { + self.state = State::Idle; + d.finish() + } (PointerKind::Drag, State::Bracket(mut b)) => { let out = b.drag(cx, p, m.cmd); self.state = State::Bracket(b); @@ -949,6 +961,7 @@ impl Tool for SelectionTool { State::Corner(c) => o.extend(c.overlays(cx)), State::Pie(d) => o.extend(d.overlays(cx)), State::RotateAll(d) => o.extend(d.overlays(cx)), + State::Space(d) => o.extend(d.overlays(cx)), State::Loaded { press: Some((start, cur)), .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))), _ => {} } @@ -997,6 +1010,7 @@ impl Tool for SelectionTool { State::Corner(_) => return Cursor::CornerRadius, State::Pie(_) => return Cursor::ArrowHollow, State::RotateAll(_) => return Cursor::Rotate, + State::Space(_) => return Cursor::ArrowHollow, State::Bracket(_) => return Cursor::PathBracket, State::Loaded { .. } => return Cursor::LoadedText, _ => {} @@ -1013,6 +1027,9 @@ impl Tool for SelectionTool { if over_rotate_all(cx, p) { return Cursor::Rotate; } + if over_space(cx, p) { + return Cursor::ArrowHollow; + } if over_bracket(cx, p) { return Cursor::PathBracket; } @@ -1355,7 +1372,7 @@ impl SelectionTool { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } - // 1. Live Corners widgets, pie widgets, the Rotate All widget and type on a path's brackets, then the + // 1. Live Corners widgets, pie widgets, the Rotate All and Space widgets and type on a path's brackets, then the // bounding-box handles of the current selection. if let Some(c) = CornerDrag::hit(cx, ev, false) { self.state = State::Corner(c); @@ -1369,6 +1386,10 @@ impl SelectionTool { self.state = State::RotateAll(d); return Some(vec![]); } + if let Some(d) = SpaceDrag::hit(cx, ev) { + self.state = State::Space(d); + return Some(vec![]); + } if let Some(b) = BracketDrag::hit(cx, ev) { self.state = State::Bracket(b); return Some(vec![]); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index f8c9b95f55..b98e186481 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -298,18 +298,33 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: rotate_all_widget(p, xf, tool, &st.doc, &st.selection); } -/// The Rotate All widget (Selection and Objects on Path tools, one Objects on Path group -/// selected): joined by a line to the first object's attachment point. It stays while dragged. +/// The Rotate All and Space widgets (Selection and Objects on Path tools, one Objects on Path +/// group selected). The Rotate All widget is joined by a line to the first object's attachment +/// point. It stays while dragged. fn rotate_all_widget(p: &egui::Painter, xf: &Xf, tool: &str, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { use vectorcraft_tools::objects_on_path::{ROTATE_ALL_RADIUS_PX, RotateAllWidget}; if !matches!(tool, "selection" | "objectsOnPath") { return; } - let Some(w) = RotateAllWidget::of(doc, selection, xf.zoom) else { return }; - let (on, c, color) = (xf.to_screen(w.pivot), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + if let Some(w) = RotateAllWidget::of(doc, selection, xf.zoom) { + let (on, c, color) = (xf.to_screen(w.pivot), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + p.line_segment([on, c], Stroke::new(1.0, color)); + p.circle_filled(c, ROTATE_ALL_RADIUS_PX, Color32::WHITE); + p.circle_stroke(c, ROTATE_ALL_RADIUS_PX, Stroke::new(1.0, color)); + } + space_widget(p, xf, doc, selection); +} + +/// The Space widget (beside the Rotate All widget, with two or more objects on the path): a square +/// joined by a line to the last object's attachment point. It stays while dragged. +fn space_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { + use vectorcraft_tools::objects_on_path::{SPACE_HALF_PX, SpaceWidget}; + let Some(w) = SpaceWidget::of(doc, selection, xf.zoom) else { return }; + let (on, c, color) = (xf.to_screen(w.last), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + let r = egui::Rect::from_center_size(c, vec2(2.0 * SPACE_HALF_PX, 2.0 * SPACE_HALF_PX)); p.line_segment([on, c], Stroke::new(1.0, color)); - p.circle_filled(c, ROTATE_ALL_RADIUS_PX, Color32::WHITE); - p.circle_stroke(c, ROTATE_ALL_RADIUS_PX, Stroke::new(1.0, color)); + p.rect_filled(r, 0.0, Color32::WHITE); + p.rect_stroke(r, 0.0, Stroke::new(1.0, color), StrokeKind::Inside); } /// Record where the Type tool's IME candidate window goes this pass, if it has an editor. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index efb608e74e..0c9462818e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4024,6 +4024,41 @@ fn a_selected_objects_on_path_group_shows_its_rotate_all_widget() { assert_eq!(widgets(&mut app), 0, "an object in the group, not the group"); } +/// A selected Objects on Path group of two or more objects shows its Space widget, a white square +/// beyond its last object, with the Selection and Objects on Path tools. +#[test] +fn a_selected_objects_on_path_group_shows_its_space_widget() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let line = id(app.session.execute("shape.line", &json!({"x1": 20, "y1": 200, "x2": 380, "y2": 200})).unwrap()); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 80, "y": 40, "width": 20, "height": 20})).unwrap()); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g = id(app.session.execute("object.objectsOnPath.attach", &json!({"path": line})).unwrap()); + let ctx = egui::Context::default(); + let widgets = |app: &mut VectorcraftApp| { + let side = 2.0 * vectorcraft_tools::objects_on_path::SPACE_HALF_PX; + shapes(app, &ctx) + .iter() + .filter(|s| matches!(s, Shape::Rect(r) if r.rect.width() == side && r.rect.height() == side && r.fill == Color32::WHITE)) + .count() + }; + app.select_tool("selection"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("objectsOnPath"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("directSelection"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(widgets(&mut app), 0, "an object in the group, not the group"); + // With one object on the path there is no space to set. + app.run("edit.clear", json!({"ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + assert_eq!(widgets(&mut app), 0, "one object"); +} + /// The shapes Type → Show Hidden Characters draws in one frame, seen through `xf`. fn hidden_chars(app: &mut VectorcraftApp, ctx: &egui::Context, xf: &Xf) -> Vec { let raw = egui::RawInput { screen_rect: Some(xf.rect), ..Default::default() }; diff --git a/docs/mcp.md b/docs/mcp.md index ab1a022a29..55a58ec79c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6055,12 +6055,22 @@ attaches nothing. The group stays live: after every edit its objects go back on its path. Editing the path moves them, an object moved on its own goes back to its place, an object moved into the group (`layer.move` with `place: "inside"`) joins the end of the path, an object moved out of it leaves, and art that replaces an object (`symbol.breakLink`) keeps its place. -`object.objectsOnPath.options {ids?, pivot?, rotate?}` changes Pivot and Rotate, and +`object.objectsOnPath.options {ids?, pivot?, rotate?, spacing?, start?}` changes Pivot, Rotate and Space, and `object.objectsOnPath.expand {ids?}` makes the groups plain groups. Both act on the groups that `ids` names (Objects on Path groups or objects in them), or on the groups of the selection when `ids` is not given. The native file keeps the group with an `objects_on_path` record; SVG, PDF and the other exports write the path and the objects as plain art. +Space sets the distance along the path between neighboring objects' attachment points. `spacing` takes points, 0 or +more, or `"auto"`, the default, which spreads the objects evenly with the last one at the end of an open path. `start` +is the distance in points along the path from its first anchor to the first object's attachment point (default 0). A +`spacing` larger than the path has room for is drawn smaller: on an open path the last object stops at the end, and on +a closed path the objects go no more than once around. The value is kept, so lengthening the path again brings the +objects back to it. On a closed path, `start` counts around from the first anchor. Pivot, Rotate, moving the group and +saving the file keep the Space. Scaling, rotating or shearing the group keeps the first and last objects where the +transform takes them on the new path, and sets `spacing` and `start` to match; a value that cannot be kept that way +scales as much as the path's length. + In the desktop app, double-clicking the Objects on Path tool (`tool.options {tool: "objectsOnPath"}`) opens Objects on Path Tool Options (dialog `objectsOnPathOptions`): the nine-point Pivot grid and the Rotate field (°). Save sets the tool's options (`tool.setOption {tool: "objectsOnPath", values: {pivot, rotate}}`), which the objects attached next @@ -6075,10 +6085,20 @@ counter-clockwise on the page: the drag previews `object.objectsOnPath.options { group's Rotate plus that angle and keeps it as one undo step on release. Shift turns in steps of 15°, and Escape cancels the drag. +With two or more objects in the group, the same tools show the Space widget, a square handle beyond the group's last +object, ahead along the path and joined by a line to its attachment point. Dragging it moves the last object along the +path as far as the pointer moves along the path, and previews +`object.objectsOnPath.options {ids: [group], spacing, start}` and keeps it as one undo step on release. The first +object stays where it is and the others move toward or away from it; on an open path the last object goes no further +than the end. With Alt (Option on macOS) held, the objects spread from both ends toward or away from the center of an +open path, or of the first anchor of a closed path, up to the whole path. With measurement labels on, the distance +between the objects shows next to the pointer in the document's units. Escape cancels the drag. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"objectsOnPath","values":{"pivot":7,"rotate":30}}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.attach","params":{"path":30,"ids":[12,15,18]}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"pivot":7,"rotate":15}}} +{"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"spacing":24,"start":0}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.expand","params":{}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 09e3842955..ed3f6b6cca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -978,7 +978,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Space, Move All and Select/Move widgets and Detach are missing. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Move All and Select/Move widgets and Detach are missing. + Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`. Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. From 84db6a54a0952ed5194453a964d962ae8af9ad97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:53:32 -0800 Subject: [PATCH 352/674] Type: discard queued font wheel turns after text selection changes --- crates/ui-egui/src/font_menu.rs | 15 ++++++++---- crates/ui-egui/tests/font_wheel.rs | 38 ++++++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 50 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 953be1a56b..e8fd10b4cc 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -11,7 +11,7 @@ //! filters as the remaining families. In the Character and Properties panels and the Control bar, //! the mouse wheel turned over the closed field applies the next family (or previous one) to the //! selected text, one undo step per notch. The menu's order at the first turn stays fixed until the -//! pointer leaves the field; steps stop at its first and last family. +//! pointer leaves the field or the text selection changes; steps stop at its first and last family. use std::collections::HashMap; use std::sync::Arc; @@ -287,7 +287,7 @@ struct MenuState { /// The height of the search field and filters last frame. header: f32, /// The families the wheel steps through, listed at its first notch over the closed field and - /// kept while the pointer stays on it: each step makes its family a recent one, which would + /// kept for that text selection while the pointer stays on it: each step makes its family a recent one, which would /// otherwise move it in the order. wheel_order: Option>, wheel_target: Option, @@ -451,15 +451,22 @@ fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { egui::Id::unique("font-wheel-fields").with(viewport) } -#[derive(Clone, Copy, PartialEq)] +#[derive(Clone, PartialEq)] struct WheelTarget { input: crate::state::InputGeneration, workspace: u64, + selection: Vec, + range: Option<(vectorcraft_doc::NodeId, usize, usize)>, } /// Pending turns and field rectangles belong to their input target and visible workspace. pub(crate) fn sync_wheel_target(app: &VectorcraftApp, ctx: &egui::Context, viewport: egui::ViewportId) { - let target = WheelTarget { input: app.input_generation(), workspace: app.ui.docking_generation }; + let target = WheelTarget { + input: app.input_generation(), + workspace: app.ui.docking_generation, + selection: app.session.active().map_or_else(Vec::new, |document| document.selection.objects.clone()), + range: crate::panels::character::text_editing(app), + }; let key = wheel_fields_id(viewport); let (previous, mut fields) = ctx.data(|d| (d.get_temp::(key.with("target")), d.get_temp::(key))); if previous.is_some_and(|old| old != target) { diff --git a/crates/ui-egui/tests/font_wheel.rs b/crates/ui-egui/tests/font_wheel.rs index 5c27c1db62..9e658a97b9 100644 --- a/crates/ui-egui/tests/font_wheel.rs +++ b/crates/ui-egui/tests/font_wheel.rs @@ -22,6 +22,44 @@ fn deselecting_type_leaves_the_missing_control_fields_wheel_available() { assert!(control_wheel_available_after("select.set", json!({"ids": []}))); } +#[test] +fn a_queued_font_wheel_does_not_restyle_a_new_object_selection() { + assert_queued_wheel_discarded_after_target_change(false); +} + +#[test] +fn a_queued_font_wheel_does_not_restyle_a_new_character_range() { + assert_queued_wheel_discarded_after_target_change(true); +} + +fn assert_queued_wheel_discarded_after_target_change(range: bool) { + let (ctx, mut app) = selected_type_with_control(); + let first = app.session.active().unwrap().selection.objects.first().unwrap().0; + let second = app.run("text.create", json!({"x": 30, "y": 120, "text": "Other text", "font": "Inter"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [first]})).unwrap(); + if range { + app.select_tool("type"); + app.session.set_tool_option("textSelection", &json!({"editing": first, "anchor": 0, "caret": 2})); + } + let mut texts = Vec::new(); + for _ in 0..8 { + texts = frame(&mut app, &ctx, vec![]); + } + let point = texts.iter().find(|(t, p)| t == "Inter" && p.y < 150.0).unwrap().1; + let mut raw = wheel_input(point); + app.raw_input_hook(&ctx, &mut raw); + assert!(!raw.events.iter().any(|e| matches!(e, Event::MouseWheel { .. })), "the original field captured its turn"); + if range { + app.session.set_tool_option("textSelection", &json!({"editing": first, "anchor": 2, "caret": 4})); + } else { + app.run("select.set", json!({"ids": [second]})).unwrap(); + } + let before = app.session.active().unwrap().history.undo.len(); + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + out.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.undo.len(), before, "the captured turn cannot restyle the new target"); +} + #[test] fn artboard_controls_leave_replaced_font_fields_wheel_available() { let (ctx, mut app) = selected_type_with_control(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b61a86b065..2bc6f55ab3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -885,7 +885,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) ("Kerning is the process of adding or subtracting space between specific pairs of characters."). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). -- **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field, so recent-font updates do not reshuffle later turns. That order follows the menu's saved font filters but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`. +- **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the menu's saved font filters but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in rectangular area type, rows and columns included. In area type of another shape, or with text wrap, such a paragraph is broken with the Single-line Composer. From f0e72fb11acc69904d7c865930b9eea56c350a09 Mon Sep 17 00:00:00 2001 From: Ahmed Gomaa Date: Mon, 2 Nov 2026 15:49:11 +0200 Subject: [PATCH 353/674] Selection: a click on a large compound path is culled by its control points Every click and hover measured each path and compound path along its curves to cull it (Node::reach_bounds_with), and a compound path was then assembled whole to test its outline and fill. For a compound path of thousands of members that took milliseconds per click. Hit testing now culls paths and compound paths by the box of their control points (which holds the curves), grown by their strokes' reach, so the box is never smaller than the reach box it replaces. A compound path's outline and fill are tested against only the members whose control box, grown by the tolerance, holds the point: a member outside that box is farther than the tolerance and winds zero times round the point. Painted strokes still follow the whole compound path (alignment, dashes, width profiles) and are measured along all of it, as before. Tests (crates/doc/src/hit/tests.rs): - a 2,000-member compound path hits exactly as the whole-path test did, at random points, on and next to anchors and on the edges of the members' boxes, for both fill rules, in Outline view and with Object Selection by Path Only; - wide strokes painting past the control points are still hit, for a path and a compound path; - the cull box holds the reach box for paths and compound paths. Measured in a debug test build (one run, machine not idle): a click on a 20,000-member compound path went from about 18 ms to about 1 ms. vectorcraft-cli perf was not rerun. --- crates/doc/src/hit.rs | 57 +++++++++- crates/doc/src/hit/tests.rs | 220 ++++++++++++++++++++++++++++++++++++ docs/gaps.md | 10 +- 3 files changed, 280 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index d20c1ffe4e..573d8fec43 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -577,7 +577,41 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols // (An envelope's content sits where it was, not where the envelope draws it.) edits_contents(c) || c.extras().shaper.is_some() && source_of(c, opt.scope) - || c.reach_bounds_with(symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) + || cull_reach(c, symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) +} + +/// A box round everything `c` can paint, for culling clicks: [`Node::reach_bounds_with`], except +/// that paths and compound paths are measured by their control points ([`PathData::control_bounds`], +/// which hold the curves) instead of along their curves, which a compound path of thousands of +/// members takes milliseconds to do on every click and hover. The box only rules points out, and it +/// is at least as large, so the same objects are hit. +/// +/// [`PathData::control_bounds`]: vectorcraft_geom::PathData::control_bounds +fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option { + let control = match &c.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Compound { children, .. } if children.iter().all(|m| m.path_data().is_some()) => { + children.iter().filter_map(|m| m.path_data().and_then(vectorcraft_geom::PathData::control_bounds)).reduce(|a, b| a.union(b)) + } + _ => return c.reach_bounds_with(symbols), + }; + let o = c.appearance.outset(); + control.map(|b| b.inflate(o, o)) +} + +/// The members of compound path `children` that a click at `p` within `tol` can touch, as one +/// path: those whose control points' box, grown by `tol`, holds `p` (edges included). A member +/// outside that box is farther than `tol` from `p` and winds zero times round it, so this path's +/// outline and fill answer a click as the whole compound path's do, without assembling it. +fn compound_members_near(children: &[std::sync::Arc], p: Point, tol: f64) -> vectorcraft_geom::BezPath { + let near = |b: Rect| b.x0 - tol <= p.x && p.x <= b.x1 + tol && b.y0 - tol <= p.y && p.y <= b.y1 + tol; + let mut bp = vectorcraft_geom::BezPath::new(); + for pd in children.iter().filter_map(|m| m.path_data()) { + if pd.control_bounds().is_some_and(near) { + bp.extend(pd.to_bezpath()); + } + } + bp } /// Is the first child of `n` the isolated container `scope`? @@ -710,12 +744,23 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } None } - NodeKind::Compound { rule, .. } => { - let bp = n.stroke_path()?; - if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { - return Some(k); + NodeKind::Compound { children, rule } => { + // Painted strokes follow the whole compound path (alignment, dashes, width profiles): + // they are measured along all of it, as before. + if !opt.outline && n.appearance.painted_strokes().next().is_some() { + let bp = n.stroke_path()?; + if n.appearance.stroke_hit(&bp, *rule, p, opt.tol) { + return Some(HitKind::Stroke); + } } - (!opt.outline && !opt.path_only && fill_contains(&bp, *rule, p)).then_some(HitKind::Fill) + // The outline and the fill only need the members near `p`. (Measured without + // `stroke_contains`'s box check: the box of the members near `p` is smaller than the + // whole path's, and its far edges would turn away points exactly `tol` away.) + let near = compound_members_near(children, p, opt.tol); + if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { + return Some(HitKind::Outline); + } + (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index c4d6c565e0..452055a8f2 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1120,3 +1120,223 @@ fn visible_sampling_reads_locked_art_and_layers_but_excludes_hidden_art() { d.node_mut(l).unwrap().visible = false; assert!(hit_test_visible(&d, p, HitOptions::default()).is_none()); } + +/// Deterministic xorshift in 0..1. +struct Rng(u64); +impl Rng { + fn next(&mut self) -> f64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % 1_000_000) as f64 / 1_000_000.0 + } +} + +/// A closed blob of `n` smooth anchors round `c` (radius about `r`), turning either way, with +/// handles long enough that its control points reach past its curves. +fn blob(rng: &mut Rng, c: Point, r: f64, n: usize, clockwise: bool) -> vectorcraft_geom::SubPath { + use vectorcraft_geom::{Anchor, Vec2}; + let anchors = (0..n) + .map(|i| { + let k = if clockwise { i as f64 } else { (n - i) as f64 }; + let a = k / n as f64 * std::f64::consts::TAU; + let rr = r * (0.6 + 0.8 * rng.next()); + let p = c + Vec2::new(a.cos(), a.sin()) * rr; + let t = Vec2::new(-a.sin(), a.cos()) * (if clockwise { 1.0 } else { -1.0 }) * rr * (0.2 + 1.3 * rng.next()); + Anchor::smooth(p, p + t) + }) + .collect(); + vectorcraft_geom::SubPath::new(anchors, true) +} + +/// A document with one compound path of `members` blobs (some of them holes), its id and the +/// members' paths. +fn compound_doc(members: usize, rule: vectorcraft_geom::FillRule, appearance: Appearance) -> (Document, NodeId, Vec) { + let mut d = Document::new(800.0, 800.0); + let l = d.layers[0].id; + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let mut paths = vec![]; + let mut children = vec![]; + for i in 0..members { + let c = Point::new(20.0 + rng.next() * 600.0, 20.0 + rng.next() * 600.0); + let r = 3.0 + rng.next() * 9.0; + let pd = vectorcraft_geom::PathData::single(blob(&mut rng, c, r, 3 + i % 4, i % 3 != 0)); + children.push(Arc::new(Node::path(d.alloc_id(), pd.clone(), Appearance::default()))); + paths.push(pd); + } + let id = d.alloc_id(); + let mut compound = Node::new(id, NodeKind::Compound { children, rule }); + compound.appearance = appearance.into(); + d.insert(Some(l), 0, compound).unwrap(); + (d, id, paths) +} + +/// What a click on compound path `n` gave before compound paths were culled by their control +/// points and their members near the click: the whole path assembled (`full`), culled by its +/// reach measured along the curves. +fn compound_hit_before(n: &Node, full: &vectorcraft_geom::BezPath, p: Point, opt: HitOptions) -> Option { + let NodeKind::Compound { rule, .. } = &n.kind else { return None }; + if !n.reach_bounds().is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + return None; + } + if !opt.outline && n.appearance.stroke_hit(full, *rule, p, opt.tol) { + return Some(HitKind::Stroke); + } + if stroke_contains(full, 0.0, opt.tol, p) { + return Some(HitKind::Outline); + } + (!opt.outline && !opt.path_only && fill_contains(full, *rule, p)).then_some(HitKind::Fill) +} + +/// The points a test clicks for `paths`: random ones over them and past them, and, for some +/// members, their anchors, points just over the tolerance from them, and the corners and edge +/// midpoints of their control and curve boxes, on them and grown by the tolerance. +fn probe_points(paths: &[vectorcraft_geom::PathData], tol: f64, random: usize, every: usize) -> Vec { + let all = paths.iter().filter_map(vectorcraft_geom::PathData::control_bounds).reduce(|a, b| a.union(b)).unwrap().inflate(30.0, 30.0); + let mut rng = Rng(7); + let mut pts: Vec = (0..random).map(|_| Point::new(all.x0 + rng.next() * all.width(), all.y0 + rng.next() * all.height())).collect(); + for pd in paths.iter().step_by(every) { + for a in pd.subpaths.iter().flat_map(|sp| &sp.anchors) { + pts.extend([a.p, Point::new(a.p.x + tol, a.p.y), Point::new(a.p.x, a.p.y - tol), Point::new(a.p.x + tol * 1.0001, a.p.y)]); + } + for b in [pd.control_bounds().unwrap(), pd.bounds().unwrap()] { + for b in [b, b.inflate(tol, tol)] { + let (cx, cy) = (b.center().x, b.center().y); + pts.extend( + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1), (cx, b.y0), (cx, b.y1), (b.x0, cy), (b.x1, cy)] + .map(|(x, y)| Point::new(x, y)), + ); + } + } + } + pts +} + +/// A compound path of thousands of members hits exactly as it did when it was assembled +/// whole for every click: at random points, on and next to anchors, and on the edges of the +/// members' boxes (control points' and curves', with and without the tolerance), for both fill +/// rules, in outline mode and with Object Selection by Path Only. +#[test] +fn culled_compound_hits_as_the_whole_path() { + use vectorcraft_geom::FillRule; + for (rule, opt) in [ + (FillRule::NonZero, HitOptions::default()), + (FillRule::EvenOdd, HitOptions { tol: 0.5, ..Default::default() }), + (FillRule::NonZero, HitOptions { outline: true, tol: 1.0, ..Default::default() }), + (FillRule::EvenOdd, HitOptions { path_only: true, ..Default::default() }), + ] { + let (d, id, paths) = compound_doc(2000, rule, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let n = d.node(id).unwrap(); + let full = n.stroke_path().unwrap(); + // The whole path's box grown by the tolerance. Before, a point on its far edges (right + // and bottom: `Rect::contains` leaves them out) never hit, even exactly `tol` from the + // outline; now it hits there as on the near edges. Those points are clicked too, and + // checked against the distance alone. + let far = vectorcraft_geom::Shape::bounding_box(&full).inflate(opt.tol, opt.tol); + let mut pts = probe_points(&paths, opt.tol, 200, 120); + let rightmost = paths.iter().filter_map(vectorcraft_geom::PathData::bounds).max_by(|a, b| a.x1.total_cmp(&b.x1)).unwrap(); + pts.push(Point::new(far.x1, rightmost.center().y)); + let (mut hits, mut kinds) = (0, HashSet::new()); + for p in pts { + let before = compound_hit_before(n, &full, p, opt); + let now = hit_test(&d, p, opt); + if p.x == far.x1 || p.y == far.y1 { + let outline = vectorcraft_geom::hit::distance_to_outline(&full, p) <= opt.tol; + assert_eq!(now.is_some(), outline || before.is_some(), "{rule:?} {opt:?} on the far edge at {p:?}"); + continue; + } + assert_eq!(now.as_ref().map(|h| (h.leaf, h.kind)), before.map(|k| (id, k)), "{rule:?} {opt:?} at {p:?}"); + hits += usize::from(before.is_some()); + kinds.extend(before.map(|k| format!("{k:?}"))); + } + // The points reach both hits and misses, and the outline as well as the fill. + assert!(hits > 100, "{rule:?} {opt:?}: {hits} hits"); + assert!(kinds.contains("Outline"), "{rule:?} {opt:?}: {kinds:?}"); + } +} + +/// A wide stroke paints far past a path's control points: clicks on it there still hit, for a +/// path and for a compound path (whose strokes are measured along all of it), exactly as when +/// they were culled by their reach measured along the curves. +#[test] +fn wide_strokes_hit_past_the_control_points() { + use vectorcraft_geom::{Anchor, PathData, SubPath}; + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 40.0); + // A zigzag 10 pt high whose 40 pt stroke reaches 20 pt (more at its mitred turns) past it. + let zig = PathData::single(SubPath::new( + [(100.0, 100.0), (110.0, 110.0), (120.0, 100.0), (130.0, 110.0)].map(|(x, y)| Anchor::corner(Point::new(x, y))).to_vec(), + false, + )); + let path = d.alloc_id(); + d.insert(Some(l), 0, Node::path(path, zig.clone(), stroke.clone())).unwrap(); + // A compound path of two small rings with the same stroke, further along. + let mut rng = Rng(3); + let members: Vec> = [Point::new(250.0, 250.0), Point::new(262.0, 250.0)] + .into_iter() + .map(|c| Arc::new(Node::path(d.alloc_id(), PathData::single(blob(&mut rng, c, 4.0, 4, true)), Appearance::default()))) + .collect(); + let compound = d.alloc_id(); + let mut node = Node::new(compound, NodeKind::Compound { children: members, rule: vectorcraft_geom::FillRule::NonZero }); + node.appearance = stroke.into(); + d.insert(Some(l), 9, node).unwrap(); + let symbols = d.symbol_boxes(); + let opt = HitOptions::default(); + for id in [path, compound] { + let n = d.node(id).unwrap(); + let full = n.stroke_path().unwrap(); + let control = match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds().unwrap(), + _ => n.children().unwrap().iter().filter_map(|m| m.path_data()?.control_bounds()).reduce(|a, b| a.union(b)).unwrap(), + }; + let (mut outside, mut checked) = (0, 0); + let area = control.inflate(40.0, 40.0); + for i in 0..=80 { + for j in 0..=80 { + let p = Point::new(area.x0 + area.width() * f64::from(i) / 80.0, area.y0 + area.height() * f64::from(j) / 80.0); + let before = match &n.kind { + NodeKind::Path { .. } => n + .reach_bounds_with(&symbols) + .is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) + .then(|| hit_leaf(n, p, opt, &symbols)) + .flatten(), + _ => compound_hit_before(n, &full, p, opt), + }; + let now = hit_test(&d, p, opt).filter(|h| h.leaf == id).map(|h| h.kind); + assert_eq!(now, before, "{id:?} at {p:?}"); + checked += 1; + outside += usize::from(before == Some(HitKind::Stroke) && !control.contains(p)); + } + } + assert!(outside > 50, "{id:?}: {outside} of {checked} points hit the stroke outside the control points' box"); + } +} + +/// The box a click is culled by holds the object's reach for paths and compound paths (it is +/// measured by their control points, which hold their curves, and grown by the same stroke reach), +/// so culling by it never turns away a click the reach let through. (Up to rounding: where a curve's +/// extreme is an anchor, the two boxes measure the same point in different ways.) +#[test] +fn cull_box_holds_the_reach_of_paths_and_compound_paths() { + const E: f64 = 1e-9; + let holds = + |outer: Rect, inner: Rect| outer.x0 - E <= inner.x0 && outer.y0 - E <= inner.y0 && inner.x1 <= outer.x1 + E && inner.y1 <= outer.y1 + E; + let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 12.0); + let (mut d, id, _) = compound_doc(200, vectorcraft_geom::FillRule::NonZero, stroke.clone()); + let path_id = d.alloc_id(); + let symbols = d.symbol_boxes(); + let n = d.node(id).unwrap(); + let mut checked = 0; + for node in std::iter::once(n).chain(n.children().unwrap().iter().map(|m| &**m)) { + let (cull, reach) = (cull_reach(node, &symbols).unwrap(), node.reach_bounds_with(&symbols).unwrap()); + assert!(holds(cull, reach), "{:?}: {cull:?} does not hold {reach:?}", node.id); + checked += 1; + } + // A stroked plain path, its handles reaching past its curves. + let mut rng = Rng(11); + let path = Node::path(path_id, vectorcraft_geom::PathData::single(blob(&mut rng, Point::new(50.0, 50.0), 20.0, 5, true)), stroke); + let (cull, reach) = (cull_reach(&path, &symbols).unwrap(), path.reach_bounds_with(&symbols).unwrap()); + assert!(holds(cull, reach), "{cull:?} does not hold {reach:?}"); + assert_eq!(checked, 201); +} diff --git a/docs/gaps.md b/docs/gaps.md index 7c00ad0b94..dc081640d5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; G12: Units › East Asian Type acts, with Q and Ha units; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (G15: clicks on paths and compound paths are culled by their control points; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -619,6 +619,13 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G15 Performance budgets and a GPU renderer +- **Improved (2026-11-02):** a click or hover culls paths and compound paths by the box of their control points + (grown by their strokes' reach) instead of measuring along their curves, and tests a compound path's outline and + fill against only the members whose control box, grown by the tolerance, holds the point; painted strokes are + still measured along the whole compound path. The same objects are hit (`crates/doc/src/hit/tests.rs`: a + 2,000-member compound path against the whole-path test for both fill rules, Outline view and Object Selection by + Path Only; wide strokes past the control points). A 20,000-member compound path went from about 18 ms to about + 1 ms a click in a debug test build (one run, not idle); `vectorcraft-cli perf` not rerun. - **Improved (#1257):** Craquelure, Mosaic Tiles and Stained Glass reuse squared distances during nearest-cell searches, with the original distance ordering retained near rounding/tie boundaries. A brute-force boundary regression and full-viewport pixel comparisons agree with the old result. `texture_drag_perf` reproduces a moved CMYK rounded rectangle at 190.07% and DPI 1.5; timings from a busy development machine are supporting evidence, with idle Windows drag QA still pending. - **Missing:** an idle-machine run of `vectorcraft-cli perf` at 50k paths (2026-10-11 at 25k paths, every budget met, 400% zoom 12.3 ms against 16 ms, measured; runs of 0.10.0 on Linux with 4 logical CPUs, reported in #1172 @@ -717,6 +724,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | | 2026-10-31 | minor | G12: Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; 4 Preferences options remain stored but not acted on. Estimate unchanged. | | 2026-11-01 | minor | G5: dynamic symbols (#4938): Symbol Options › Symbol Type, per-instance fill, stroke, opacity and blend for objects of a dynamic symbol's art that stay linked (redefining keeps them, Break Link bakes them, Reset and Static drop them; `symbol.instance.setAppearance`, `symbol.instance.reset`; `crates/engine/src/tests/dynamic_symbols.rs`); on-canvas Direct Selection of the parts and `.ai` round trip remain. Estimate 15–26 → 14–24 h. | From 1d011ab8adf2f1ba5282a1f7c3972e3fccc19ccd Mon Sep 17 00:00:00 2001 From: Ahmed Gomaa Date: Mon, 2 Nov 2026 15:55:52 +0200 Subject: [PATCH 354/674] Render: a compound path's members are assembled once and kept with the node A compound path was assembled from its members in every frame it was drawn, and Node::stroke_path grew its buffer by doubling, copying the path into ever larger buffers for a compound path of many anchors. The renderer's geometry cache was swept only once it held more than 1,024 entries, so while an object was dragged (a new node, and layer, in every frame) the old copies stayed alive with all their members. Now: - a compound path is drawn from the path the renderer keeps for it in its geometry cache, as a plain path already was, and is assembled only when the node changes; - Node::stroke_path sizes a compound path's buffer up front from its members' segment counts (the same elements, in the same order); - unused geometry entries are dropped after a few frames however few entries there are. Tests: - crates/render/src/tests/memory.rs: the second frame draws the kept path and the same pixels as the first and as a new renderer; after a five-frame move the renderer no longer holds the compound path drawn before it. The test fails without the renderer change. - crates/doc/src/node/tests.rs: a compound path's path is its members' paths in order (open, closed, empty and single-anchor members). Not timed; vectorcraft-cli perf was not rerun. --- crates/doc/src/node/ops.rs | 9 ++++-- crates/doc/src/node/tests.rs | 20 +++++++++++++ crates/render/src/renderer.rs | 8 ++++-- crates/render/src/renderer/nodes.rs | 27 ++++++++++-------- crates/render/src/tests/memory.rs | 44 +++++++++++++++++++++++++++++ docs/gaps.md | 8 +++++- 6 files changed, 99 insertions(+), 17 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 755cb51c4a..07899196c2 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -185,8 +185,13 @@ impl Node { match &self.kind { NodeKind::Path { path, .. } => Some(path.to_bezpath()), NodeKind::Compound { children, .. } => { - let mut bp = vectorcraft_geom::BezPath::new(); - children.iter().filter_map(|c| c.path_data()).for_each(|pd| bp.extend(pd.to_bezpath())); + // Sized up front: grown by doubling, the path of a compound path of hundreds of + // thousands of anchors is copied into ever larger buffers, up to tens of MB, on + // every call. + let subpaths = || children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths); + let elements = subpaths().filter(|sp| !sp.anchors.is_empty()).map(|sp| 1 + sp.segment_count() + usize::from(sp.closed)).sum(); + let mut bp = vectorcraft_geom::BezPath::from_vec(Vec::with_capacity(elements)); + subpaths().for_each(|sp| sp.to_bezpath_into(&mut bp)); Some(bp) } _ => None, diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 882018e1d1..1669de1a27 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -546,3 +546,23 @@ fn fields_before_the_type_are_buffered_within_the_value_budget() { assert!(with_buffered_value_budget(0, || read(&written)).is_ok(), "a saved object buffers nothing: {written}"); assert!(read(reordered).is_ok(), "no budget outside a read"); } + +/// A compound path's path is its members' paths one after another, open and closed, empty +/// members and single anchors included. +#[test] +fn compound_stroke_path_is_its_members_in_order() { + use vectorcraft_geom::{Anchor, PathData, SubPath}; + let open = PathData::single(SubPath::new([(0.0, 0.0), (5.0, 1.0), (9.0, 7.0)].map(|(x, y)| Anchor::corner(Point::new(x, y))).to_vec(), false)); + let lone = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(3.0, 3.0))], false)); + let members = + [shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), open, PathData::default(), lone, shapes::ellipse(Rect::new(10.0, 10.0, 20.0, 16.0))]; + let mut expected = vectorcraft_geom::BezPath::new(); + for pd in &members { + expected.extend(pd.to_bezpath()); + } + let children = members.iter().enumerate().map(|(i, pd)| Arc::new(Node::path(NodeId(i as u64 + 1), pd.clone(), Appearance::default()))).collect(); + let n = Node::new(NodeId(99), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::EvenOdd }); + let bp = n.stroke_path().unwrap(); + assert_eq!(bp.elements(), expected.elements()); + assert!(!bp.elements().is_empty()); +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 218ef06205..4d619e0454 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -172,9 +172,11 @@ impl Renderer { /// so the nodes they hold go with them). fn end_frame(&mut self) { let g = self.stamp; - if self.geom.len() > 1024 { - self.geom.retain(|_, e| g - e.stamp <= 3); - } + // Swept however few the entries: each keeps its node alive, and an object dragged or + // edited makes a new node (with its layer) in every frame. Kept until there were 1,024 of + // them, a drag left up to that many old copies of the object alive, each with all its + // members (and, for a compound path, its assembled path). + self.geom.retain(|_, e| g - e.stamp <= 3); if self.strokes.len() > 1024 { self.strokes.retain(|_, e| g - e.stamp <= 3); } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 25f6260914..79455cd75b 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -114,7 +114,16 @@ impl Renderer { /// The cached path of path or compound path `n` ([`Self::path_of`]) when the frame is in /// Outline view and `n` is `fx_owner`, else `None`. fn outline_path(&mut self, f: &Frame, n: &Node) -> Option> { - let owner = self.fx_owner.as_ref().filter(|o| f.opts.outline && std::ptr::eq(&***o, n)).cloned()?; + if !f.opts.outline { + return None; + } + self.owner_path(f, n) + } + + /// The cached path of path or compound path `n` ([`Self::path_of`]) when `n` is `fx_owner`, + /// else `None`. + fn owner_path(&mut self, f: &Frame, n: &Node) -> Option> { + let owner = self.fx_owner.as_ref().filter(|o| std::ptr::eq(&***o, n)).cloned()?; self.path_of(f.symbols, &owner) } @@ -470,17 +479,13 @@ impl Renderer { self.draw_shape(ctx, f, n, &bp, *rule); } } - NodeKind::Compound { children, rule } => { - if let Some(bp) = self.outline_path(f, n) { - return self.draw_shape(ctx, f, n, &bp, *rule); + NodeKind::Compound { rule, .. } => { + // Its members assembled once and kept with the node in `geom`, as plain paths are + // (`path_of`): a compound path of thousands of members is not assembled again in + // every frame. + if let Some(bp) = self.owner_path(f, n).or_else(|| n.stroke_path().map(Arc::new)) { + self.draw_shape(ctx, f, n, &bp, *rule); } - let mut bp = BezPath::new(); - for c in children { - if let Some(p) = c.path_data() { - bp.extend(p.to_bezpath()); - } - } - self.draw_shape(ctx, f, n, &bp, *rule); } NodeKind::Text(t) => self.draw_text(ctx, f, n, t), NodeKind::Image(im) => self.draw_image_in(ctx, f, im, None, images::image_tint(n, f.ink), n.extras().pixelated), diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 8b3648604c..f0c4b40e1f 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2378,3 +2378,47 @@ fn text_runs_draw_their_own_glyphs_from_the_shared_outlines() { } assert!(g.run(7).elements().is_empty()); } + +/// A compound path is drawn from the path the renderer keeps for it, as a plain path is: the next +/// frame draws the same path, and draws what a new renderer draws. +/// Once the compound path changes (each frame of a drag makes a new one), the entries of the old +/// one, which keep it alive, go after a few frames, however few entries the renderer holds. +#[test] +fn compound_paths_draw_from_kept_paths_and_let_old_ones_go() { + let _fonts = fonts_steady(); + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let members: Vec> = (0..30) + .map(|i| { + let x = f64::from(i % 6) * 15.0; + let y = f64::from(i / 6) * 15.0; + let p = vectorcraft_geom::shapes::ellipse(Rect::new(x, y, x + 10.0, y + 10.0)); + Arc::new(Node::path(d.alloc_id(), p, vectorcraft_doc::Appearance::default())) + }) + .collect(); + let id = d.alloc_id(); + let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: vectorcraft_geom::FillRule::EvenOdd }); + compound.appearance = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into(); + d.insert(Some(layer), 0, compound).unwrap(); + let opts = RenderOptions::default(); + let kept = |r: &Renderer, d: &Document| { + let n = d.layers[0].children().unwrap()[0].clone(); + r.geom.get(&(Arc::as_ptr(&n) as usize)).and_then(|e| e.path.clone()) + }; + let mut r = Renderer::new(); + let first = r.render(&d, 100, 100, Affine::IDENTITY, &opts).pixels; + let path = kept(&r, &d).expect("the compound path's path is kept"); + assert!(r.render(&d, 100, 100, Affine::IDENTITY, &opts).pixels == first); + assert!(kept(&r, &d).is_some_and(|p| Arc::ptr_eq(&p, &path)), "the second frame draws the kept path"); + assert!(first == Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts).pixels); + // Moved: a new compound path (and layer) in each frame. + let old = d.layers[0].children().unwrap()[0].clone(); + let mut moved = d.clone(); + for _ in 0..5 { + moved.node_mut(id).unwrap().transform(Affine::translate((1.0, 0.0)), false); + r.render(&moved, 100, 100, Affine::IDENTITY, &opts); + } + drop(d); + assert!(r.geom.len() < 1024); + assert_eq!(Arc::strong_count(&old), 1, "the renderer no longer keeps the compound path drawn before the move"); +} diff --git a/docs/gaps.md b/docs/gaps.md index dc081640d5..783dc97110 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (G15: clicks on paths and compound paths are culled by their control points; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (G15: a compound path's assembled path is kept between frames; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -619,6 +619,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G15 Performance budgets and a GPU renderer +- **Improved (2026-11-02):** the renderer keeps a compound path's assembled path with the node, as it keeps a plain + path's, instead of assembling its members again in every frame; the path is assembled into a buffer sized up front. + Unused geometry entries are dropped after a few frames however few there are (before, only past 1,024 entries), so + the copies a drag makes in every frame no longer stay alive with all their members + (`crates/render/src/tests/memory.rs`, `crates/doc/src/node/tests.rs`). Not timed; `vectorcraft-cli perf` not rerun. - **Improved (2026-11-02):** a click or hover culls paths and compound paths by the box of their control points (grown by their strokes' reach) instead of measuring along their curves, and tests a compound path's outline and fill against only the members whose control box, grown by the tolerance, holds the point; painted strokes are @@ -724,6 +729,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | | 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | | 2026-10-31 | minor | G12: Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; 4 Preferences options remain stored but not acted on. Estimate unchanged. | From af17c648c0c2386930c1d85719e95abb51d26c33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:38:17 +0700 Subject: [PATCH 355/674] Find Font: Change and Change All add no undo step when no text changes Squashed from #5204 onto main. --- crates/engine/src/cmd/fonts.rs | 154 +++++++++++++++++++++++++-------- 1 file changed, 117 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 8e68987f9f..585cd8a793 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec { "Replace Font", [], None, - "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}", + "{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); the type in the art of the symbols in scope changes too (all of the document's, or those the selected instances show, so every instance of them follows); text that is hidden or locked, in a hidden or locked group or layer (or group of a symbol's art), or on a locked artboard keeps its font; when no run changes (text already set in the new font, or none to change), the document and its undo history stay as they are → {runs: the runs changed, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}", has_doc, replace ), @@ -549,6 +549,16 @@ fn replace(s: &mut Session, p: &Value) -> Result { let matches = |st: &vectorcraft_doc::CharStyle| { st.font_family.eq_ignore_ascii_case(&ff) && fs.as_ref().is_none_or(|x| st.font_style.eq_ignore_ascii_case(x)) }; + // The style a matching run is set in after the change, or `None` when the run doesn't match or + // is already set in that family and style with no version or Variable Font settings. + let new_style = |st: &vectorcraft_doc::CharStyle| { + if !matches(st) { + return None; + } + // An explicit style, else the closest the new family has to the old one. + let style = ts.clone().or_else(|| db.face(&tf, &st.font_style).map(|f| f.style.clone())).unwrap_or_else(|| st.font_style.clone()); + (st.font_family != tf || st.font_style != style || st.font_version.is_some() || !st.font_axes.is_empty()).then_some(style) + }; // Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked // group or layer, or on a locked artboard. The text left in the font is counted. The type in // the art of the symbols in scope (all of them, or those the selection shows) changes too, @@ -564,54 +574,59 @@ fn replace(s: &mut Session, p: &Value) -> Result { (None, BTreeSet::new()) }; let uses = |t: &TextObject| t.runs.iter().any(|r| matches(&r.style)); - let (ids, skipped) = { + // Whether a run of `t` changes. + let changes = |t: &TextObject| t.runs.iter().any(|r| new_style(&r.style).is_some()); + let (ids, skipped, in_symbols) = { let d = &s.doc()?.doc; let editable = d.editable(); let (ids, other): (Vec, Vec) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id)); let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count(); - skipped += symbol_texts(d, symbols.as_ref()).into_iter().filter(|(t, open)| !open && uses(t)).count(); + let texts = symbol_texts(d, symbols.as_ref()); + skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count(); if !closed.is_empty() { skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count(); } - (ids, skipped) + // The text that changes: when none does, the document and its undo history stay as they are. + let ids: Vec = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect(); + let in_symbols = texts.iter().any(|(t, open)| *open && changes(t)); + (ids, skipped, in_symbols) }; // The fonts the replaced runs are set in, for the warning. let mut set = BTreeSet::new(); - let n = s.edit("Replace Font", |d, _| { - let mut n = 0; - let mut replace_in = |t: &mut TextObject| { - let mut changed = false; - for r in &mut t.runs { - if matches(&r.style) { - // An explicit style, else the closest the new family has to the old one. - let style = ts - .clone() - .or_else(|| db.face(&tf, &r.style.font_style).map(|f| f.style.clone())) - .unwrap_or_else(|| r.style.font_style.clone()); - r.style.font_family = tf.clone(); - r.style.font_style = style; - // Another font: none of the old one's versions or Variable Font settings. - r.style.font_version = None; - r.style.font_axes.clear(); - set.insert(font_of(&r.style)); - changed = true; - n += 1; + let n = if ids.is_empty() && !in_symbols { + 0 + } else { + s.edit("Replace Font", |d, _| { + let mut n = 0; + let mut replace_in = |t: &mut TextObject| { + let mut changed = false; + for r in &mut t.runs { + if let Some(style) = new_style(&r.style) { + r.style.font_family = tf.clone(); + r.style.font_style = style; + // Another font: none of the old one's versions or Variable Font settings. + r.style.font_version = None; + r.style.font_axes.clear(); + set.insert(font_of(&r.style)); + changed = true; + n += 1; + } + } + if changed { + vectorcraft_text::edit::normalize(&mut t.runs); + refresh_bounds(t); + } + }; + for id in &ids { + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + replace_in(t); } } - if changed { - vectorcraft_text::edit::normalize(&mut t.runs); - refresh_bounds(t); - } - }; - for id in &ids { - if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { - replace_in(t); - } - } - edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && uses(t), &mut replace_in); - drop(replace_in); - Ok(n) - })?; + edit_symbol_texts(d, symbols.as_ref(), &|t, open| open && changes(t), &mut replace_in); + drop(replace_in); + Ok(n) + })? + }; let mut out = json!({ "runs": n }); let mut warnings = Vec::new(); if skipped > 0 { @@ -889,6 +904,71 @@ mod tests { assert_eq!(r, json!({"runs": 2})); } + /// Replace Font adds no undo step when no run changes: only locked text uses the font, no text + /// uses it, or the text is already set in the new font and style. + #[test] + fn replace_font_that_changes_nothing_adds_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let serif = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap(); + let sans = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Sans", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [serif]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(r, json!({"runs": 0, "skipped": 1, "warning": REPLACE_SKIPPED})); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Nothing Uses This"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(r, json!({"runs": 0})); + let style = text(&s.doc().unwrap().doc, NodeId(sans)).unwrap().runs[0].style.font_style.clone(); + let r = + s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3", "style": style}})).unwrap(); + assert_eq!(r, json!({"runs": 0})); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(r, json!({"runs": 0})); + assert_eq!(steps(&s), before); + // A change is still one step. + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(steps(&s), before + 1); + assert_eq!(text_family(&s, sans), "Inter"); + } + + /// Change and Change All add no undo step when the type in a symbol's art already has the new + /// font, and a change to that type is still one step. + #[test] + fn replace_font_in_symbols_that_changes_nothing_adds_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Sans", "font": "Source Sans 3"})).unwrap()["id"].clone(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [id]})).unwrap(); + let mut on_layers = 0; + s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(on_layers, 0, "the type is only in the symbol"); + let family = |s: &Session| symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family.clone(); + let style = symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_style.clone(); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + // New Symbol selects the instance: Change (the selection) and Change All. + for selection_only in [true, false] { + for to in [json!({"family": "Source Sans 3"}), json!({"family": "Source Sans 3", "style": style})] { + let p = json!({"from": {"family": "Source Sans 3"}, "to": to, "selectionOnly": selection_only}); + assert_eq!(s.execute("text.replaceFont", &p).unwrap(), json!({"runs": 0}), "{p}"); + } + } + assert_eq!(steps(&s), before); + // A change is still one step, with the instance selected and without. + let r = + s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}, "selectionOnly": true})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(steps(&s), before + 1); + assert_eq!(family(&s), "Inter"); + let r = s.execute("text.replaceFont", &json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap(); + assert_eq!(r, json!({"runs": 1})); + assert_eq!(steps(&s), before + 2); + assert_eq!(family(&s), "Source Serif 4"); + } + /// The fonts of the symbols' art: Find Font lists them, and Change All replaces them, leaving /// hidden or locked type in the art as it is. #[test] From fbab0bdd433217dfb217d6bdf2dc9bb1530fc027 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:38:24 +0700 Subject: [PATCH 356/674] Type: Find Font's Replace With Font From lists the document's, recent or installed fonts Squashed from #5217 onto main. --- crates/ui-egui/src/app/commands.rs | 18 +- crates/ui-egui/src/find_font.rs | 312 +++++++++++++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/target-app-parity.md | 1 + 29 files changed, 369 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 632ef818b3..08e7960b3e 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -168,9 +168,21 @@ impl VectorcraftApp { if matches!(id, "dataset.select" | "dataset.next" | "dataset.prev") { self.ui.status.clear(); } - if matches!(id, "text.setStyle" | "text.setRangeStyle") - && let Some(font) = params.get("font").and_then(Value::as_str) - { + // A font applied with Character's font menu or Find Font's Change becomes the newest recent font. + // Find Font's Change records the family the text now carries (any name of it is stored as its + // own name), and only when it changed some text. + let applied = match id { + "text.setStyle" | "text.setRangeStyle" => params.get("font").and_then(Value::as_str).map(str::to_string), + "text.replaceFont" if v["runs"].as_u64().is_some_and(|n| n > 0) => { + let to = ¶ms["to"]; + to["family"].as_str().and_then(|family| { + let style = to["style"].as_str().unwrap_or("Regular"); + vectorcraft_text::FontDb::global().resolve(family, style).map(|(face, _)| face.family.clone()) + }) + } + _ => None, + }; + if let Some(font) = applied.as_deref() { let r = &mut self.ui.recent_fonts; r.retain(|f| !f.eq_ignore_ascii_case(font)); r.insert(0, font.to_string()); diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 5155542e01..af9a83af0b 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -1,6 +1,7 @@ //! Type → Find Font…: the fonts the document uses (missing ones marked), Find (select the text -//! using a font), Change / Change All to another installed font, and Find in Folder… (the missing -//! fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). +//! using a font), Change / Change All to another font from the list Replace With Font From shows +//! (the document's fonts, the recent fonts or every installed font), and Find in Folder… (the +//! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). use egui::Ui; use serde_json::{Value, json}; @@ -22,9 +23,90 @@ pub fn open_on_missing(app: &mut VectorcraftApp) { open_at(app, first.unwrap_or(0)); } -/// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen. +/// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen, and +/// System's font ([`system_family`]) to change to. fn open_at(app: &mut VectorcraftApp, selected: usize) { - app.ui.dialog = Some(Dialog::new("findFont", json!({ "selected": selected, "family": "Source Sans 3", "style": "", "selectionOnly": false }))); + app.ui.dialog = Some(Dialog::new( + "findFont", + json!({ "selected": selected, "family": system_family(), "style": "", "selectionOnly": false, "replaceFrom": "system" }), + )); +} + +/// The font System chooses: Source Sans 3 when it is installed, otherwise the font menu's first +/// family (none when the menu is empty). +fn system_family() -> String { + system_family_in(installed, &vectorcraft_text::FontDb::global().menu_family_list()) +} + +/// [`system_family`] for the installed check `is_installed` and the font menu `menu`. +fn system_family_in(is_installed: impl Fn(&str) -> bool, menu: &[String]) -> String { + const PREFERRED: &str = "Source Sans 3"; + if is_installed(PREFERRED) { PREFERRED.to_string() } else { menu.first().cloned().unwrap_or_default() } +} + +/// Replace With Font From's lists (the `replaceFrom` field): the document's fonts, the recent +/// fonts and every installed font. +const SOURCES: [&str; 3] = ["document", "recent", "system"]; +const SOURCE_LABELS: [&str; 3] = ["Document", "Recent", "System"]; + +/// The families Replace With Font From lists. `None` is System: the font menu, every installed +/// family. Document lists the families `text.fonts` names, once each, in its order; Recent lists +/// the font menu's recent families (newest first, Number of Recent Fonts at most) that are +/// installed. +fn replacement_families(app: &VectorcraftApp, source: &str, used: &[Value]) -> Option> { + let names: Vec = match source { + "document" => used.iter().filter_map(|f| f["family"].as_str()).map(str::to_string).collect(), + "recent" => { + let installed = vectorcraft_text::FontDb::global().menu_family_list(); + app.recent_fonts().iter().filter_map(|r| installed.iter().find(|f| f.eq_ignore_ascii_case(r)).cloned()).collect() + } + _ => return None, + }; + let mut out: Vec = vec![]; + for n in names { + if !out.iter().any(|o| o.eq_ignore_ascii_case(&n)) { + out.push(n); + } + } + Some(out) +} + +/// Is `family` installed: it resolves to a face of its own, as `text.replaceFont` requires. +fn installed(family: &str) -> bool { + !family.is_empty() + && vectorcraft_text::FontDb::global().resolve(family, "Regular").is_some_and(|(_, m)| m != vectorcraft_text::FontMatch::Missing) +} + +/// Can Change and Change All replace with the dialog's font: a family is chosen, it is installed, +/// and it is one of the list Replace With Font From shows (System's list is the font menu). +fn can_replace(d: &Dialog, families: Option<&[String]>) -> bool { + let family = d.str("family"); + match families { + Some(list) => can_replace_in(&family, installed, list), + None => can_replace_in(&family, installed, &vectorcraft_text::FontDb::global().menu_family_list()), + } +} + +/// [`can_replace`] for the installed check `is_installed` and the shown list `list`. +fn can_replace_in(family: &str, is_installed: impl Fn(&str) -> bool, list: &[String]) -> bool { + is_installed(family) && list.iter().any(|f| f.eq_ignore_ascii_case(family)) +} + +/// Show list `source` ([`SOURCES`]): the chosen family stays when the list has it and it is +/// installed, otherwise the list's first installed family (none when there is none) is chosen in +/// its closest style. System chooses [`system_family`]. +fn set_source(app: &VectorcraftApp, d: &mut Dialog, source: &str, used: &[Value]) { + d.fields.insert("replaceFrom".into(), json!(source)); + let families = replacement_families(app, source, used); + if can_replace(d, families.as_deref()) { + return; + } + let family = match families { + Some(l) => l.into_iter().find(|f| installed(f)), + None => Some(system_family()), + }; + d.fields.insert("family".into(), json!(family.unwrap_or_default())); + d.fields.insert("style".into(), json!("")); } fn fonts(app: &mut VectorcraftApp) -> Vec { @@ -81,13 +163,31 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } ui.add_space(10.0); widgets::subheader(ui, tl!("Replace With Font")); + let source = d.str("replaceFrom"); + ui.horizontal(|ui| { + widgets::field_label(ui, tl!("Replace With Font From")); + let at = SOURCES.iter().position(|s| *s == source).unwrap_or(2); + if let Some(i) = widgets::dropdown_named(ui, "ff-from", Some(tl!("Replace With Font From")), SOURCE_LABELS[at], &SOURCE_LABELS, 120.0) { + set_source(app, &mut d, SOURCES[i], &list); + } + }); + let families = replacement_families(app, &d.str("replaceFrom"), &list); let fam = d.str("family"); ui.horizontal(|ui| { - // Picks the font only: nothing is previewed on the document. - let pick = font_menu::font_menu(ui, "ff-family", &fam, 220.0, sample.as_deref(), font_menu::MenuLook::of(app)); - if let Some((f, style)) = font_menu::picked(app, pick) { - d.fields.insert("family".into(), json!(f)); - d.fields.insert("style".into(), json!(style.unwrap_or_default())); + if let Some(families) = &families { + // Font names are shown as they are. + let names: Vec<&str> = families.iter().map(String::as_str).collect(); + if let Some(i) = widgets::dropdown_names_named(ui, "ff-family-list", Some(tl!("Replace With Font")), &fam, &names, 220.0) { + d.fields.insert("family".into(), json!(families[i])); + d.fields.insert("style".into(), json!("")); + } + } else { + // Picks the font only: nothing is previewed on the document. + let pick = font_menu::font_menu(ui, "ff-family", &fam, 220.0, sample.as_deref(), font_menu::MenuLook::of(app)); + if let Some((f, style)) = font_menu::picked(app, pick) { + d.fields.insert("family".into(), json!(f)); + d.fields.insert("style".into(), json!(style.unwrap_or_default())); + } } let styles = vectorcraft_text::FontDb::global().styles(&d.str("family")); // "(closest)" is ours; the font's style names are shown as they are. @@ -101,15 +201,17 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); ui.add_space(14.0); + // An empty list (Recent before any font was applied) leaves nothing to change to. + let replace = sel < list.len() && can_replace(&d, families.as_deref()); ui.horizontal(|ui| { let has = sel < list.len(); if ui.add_enabled(has, egui::Button::new(tl!("Find"))).clicked() { act = Some("find"); } - if ui.add_enabled(has, egui::Button::new(tl!("Change"))).on_hover_text(tl!("In the selected objects")).clicked() { + if ui.add_enabled(replace, egui::Button::new(tl!("Change"))).on_hover_text(tl!("In the selected objects")).clicked() { act = Some("change"); } - if ui.add_enabled(has, egui::Button::new(tl!("Change All"))).clicked() { + if ui.add_enabled(replace, egui::Button::new(tl!("Change All"))).clicked() { act = Some("changeAll"); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -225,6 +327,194 @@ mod tests { crate::dialogs::cancel(&mut app); } + /// A document set in Inter and Source Serif 4 (Inter twice), with Inter the one recent font. + fn two_font_document() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Inter"), (40, "Source Serif 4"), (60, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + app.ui.recent_fonts = vec!["Inter".into()]; + app + } + + #[test] + fn replace_with_font_from_lists_the_document_s_recent_or_installed_fonts() { + let mut app = two_font_document(); + let used = fonts(&mut app); + let mut document = replacement_families(&app, "document", &used).unwrap(); + document.sort(); + assert_eq!(document, ["Inter", "Source Serif 4"]); + assert_eq!(replacement_families(&app, "recent", &used).unwrap(), ["Inter"]); + assert_eq!(replacement_families(&app, "system", &used), None, "System is the font menu of every installed family"); + open(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("replaceFrom"), "system"); + for source in SOURCES { + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, source, &used); + let listed = replacement_families(&app, source, &used); + assert!(can_replace(&d, listed.as_deref()), "{source}: {}", d.str("family")); + app.ui.dialog = Some(d); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(text.contains("Replace With Font From"), "{text}"); + } + } + + #[test] + fn change_all_replaces_with_a_font_from_the_document() { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "document", &used); + d.fields.insert("family".into(), json!("Inter")); + let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let families: Vec = fonts(&mut app).iter().map(|f| f["family"].clone()).collect(); + assert_eq!(families, [json!("Inter")]); + } + + /// A font applied with Change All becomes Recent's first family. + #[test] + fn change_all_adds_the_new_font_to_recent() { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Serif 4")); + let from = used.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let used = fonts(&mut app); + assert_eq!(replacement_families(&app, "recent", &used).unwrap(), ["Source Serif 4", "Inter"]); + } + + /// A Change All that changes no text (the font's only text is locked) leaves Recent as it was. + #[test] + fn a_change_all_that_changes_nothing_leaves_recent_unchanged() { + let mut app = two_font_document(); + app.run("select.font", json!({"family": "Source Serif 4"})).unwrap(); + app.run("object.lock", json!({})).unwrap(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Sans 3")); + let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone(); + assert_eq!(change(&mut app, &d, &from, true).unwrap()["runs"], 0); + assert_eq!(app.ui.recent_fonts, ["Inter"]); + } + + /// Change to another name of an installed family records the family's own name in Recent. + #[test] + fn change_records_the_family_s_own_name_in_recent() { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("SourceSerif4-Regular")); + let from = used.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + assert_eq!(change(&mut app, &d, &from, true).unwrap()["runs"], 2); + assert_eq!(app.ui.recent_fonts, ["Source Serif 4", "Inter"]); + } + + #[test] + fn an_empty_recent_list_leaves_nothing_to_change_to() { + let mut app = two_font_document(); + app.ui.recent_fonts.clear(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "recent", &used); + assert_eq!(replacement_families(&app, "recent", &used).unwrap(), Vec::::new()); + assert_eq!(d.str("family"), ""); + assert!(!can_replace(&d, Some(&[]))); + app.ui.dialog = Some(d); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(text.contains("Recent"), "{text}"); + assert_eq!(app.ui.status, ""); + } + + /// Document lists a missing family, but Change and Change All stay off for it, in every list. + #[test] + fn a_missing_document_font_is_listed_but_not_offered_to_change_to() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Missing Family"), (40, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + open(&mut app); + let used = fonts(&mut app); + let document = replacement_families(&app, "document", &used).unwrap(); + assert!(document.iter().any(|f| f == "Missing Family"), "{document:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Missing Family")); + set_source(&app, &mut d, "document", &used); + assert_eq!(d.str("family"), "Inter", "the first installed family is chosen"); + assert!(can_replace(&d, Some(&document))); + d.fields.insert("family".into(), json!("Missing Family")); + assert!(!can_replace(&d, Some(&document))); + assert!(!can_replace(&d, None), "System"); + set_source(&app, &mut d, "system", &used); + assert!(can_replace(&d, None), "System chooses an installed family: {}", d.str("family")); + // A document set only in a missing family leaves nothing to change to. + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi", "font": "Missing Family"})).unwrap(); + let used = fonts(&mut app); + set_source(&app, &mut d, "document", &used); + assert_eq!(d.str("family"), ""); + assert!(!can_replace(&d, replacement_families(&app, "document", &used).as_deref())); + } + + /// An empty Recent list clears the font; System then chooses an installed one again. + #[test] + fn system_after_an_empty_recent_list_chooses_an_installed_font() { + let mut app = two_font_document(); + app.ui.recent_fonts.clear(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "recent", &used); + assert_eq!(d.str("family"), ""); + set_source(&app, &mut d, "system", &used); + assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Source Sans 3", "")); + assert!(can_replace(&d, None)); + } + + /// The dialog opens on System's font: Source Sans 3 when it is installed, otherwise the font + /// menu's first family. + #[test] + fn the_dialog_opens_on_an_installed_font() { + let menu = ["Inter".to_string(), "Source Serif 4".to_string()]; + assert_eq!(system_family_in(|_| true, &menu), "Source Sans 3"); + assert_eq!(system_family_in(|f| f != "Source Sans 3", &menu), "Inter"); + assert_eq!(system_family_in(|_| false, &[]), ""); + let mut app = two_font_document(); + open(&mut app); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!(d.str("family"), system_family()); + assert!(can_replace(&d, None), "{}", d.str("family")); + } + + /// A family that is installed but left out of the font menu (a hidden `.` family that + /// Document lists) cannot be changed to from System. + #[test] + fn system_offers_only_the_font_menu_s_families() { + let menu = ["Inter".to_string()]; + assert!(can_replace_in("inter", |_| true, &menu)); + assert!(!can_replace_in(".Hidden", |_| true, &menu)); + assert!(!can_replace_in("Inter", |_| false, &menu)); + let hidden = vectorcraft_text::FontDb::global().family_list().iter().find(|f| f.starts_with('.') && installed(f)).cloned(); + if let Some(hidden) = hidden { + let mut app = two_font_document(); + open(&mut app); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!(hidden)); + assert!(!can_replace(&d, None), "{hidden}"); + set_source(&app, &mut d, "system", &used); + assert_eq!(d.str("family"), system_family()); + } + } + #[test] fn rows_flag_missing_fonts_substituted_styles_and_lacking_characters() { let row = |status: &str, glyphs: u64| json!({"status": status, "resolved": {"style": "W4"}, "missingGlyphs": glyphs}); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fe8c162df1..614054f41a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2640,6 +2640,8 @@ digits Malayalam Малаялам Replace Spine Замяна на оста Replace Symbol Замяна на символ Replace With Font Замяна с шрифт + Replace With Font From Замяна с шрифт от + System Система Replaces the saved preset of that name. Заменя записаната предварителна настройка с това име. Replace… Замяна… Require a password to open the document Изискване на парола за отваряне на документа diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 003a6189a5..a0b4e236db 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3918,6 +3918,8 @@ effect Regular Obično In the selected objects U odabranim objektima Find in Folder… Pronađi u folderu… Replace With Font Zamijeni fontom + Replace With Font From Zamijeni fontom iz + System Sistem — substituted by {style} — zamijenjeno stilom {style} — {n} characters from another font — {n} znakova iz drugog fonta All Scripts Sve skripte diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a28db5502e..2a1f0a518d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3340,6 +3340,8 @@ digits Malayalam Malaiàlam Replace Spine Reemplaça l’espina Replace Symbol Reemplaça el símbol Replace With Font Reemplaça per un tipus de lletra + Replace With Font From Reemplaça per un tipus de lletra de + System Sistema Replace “{name}”, the file this document was opened from? Voleu reemplaçar “{name}”, el fitxer amb què es va obrir aquest document? Replaces the saved preset of that name. Reemplaça el preajust desat amb aquest nom. Replace… Reemplaça… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f69545e1b6..b9e6fd7406 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3960,6 +3960,8 @@ effect Regular Pravidelný In the selected objects Ve vybraných objektech Find in Folder… Najít ve složce… Replace With Font Nahradit písmem + Replace With Font From Nahradit písmem z + System Systém — substituted by {style} — nahrazeno řezem {style} — {n} characters from another font — znaky z jiného písma: {n} All Scripts Všechny systémy písma diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d78046e91d..20a0a4dfec 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3680,6 +3680,8 @@ effect Regular Regular In the selected objects I de markerede objekter Find in Folder… Find i mappe… Replace With Font Erstat med skrifttype + Replace With Font From Erstat med skrifttype fra + System System — substituted by {style} — erstattet af {style} — {n} characters from another font — {n} tegn fra en anden skrifttype All Scripts Alle scripts diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index cde85a2c0b..94430d21ee 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2667,6 +2667,8 @@ digits Malayalam Malayalam Replace Spine Achse ersetzen Replace Symbol Symbol ersetzen Replace With Font Durch Schrift ersetzen + Replace With Font From Ersetzende Schrift aus + System System Replaces the saved preset of that name. Ersetzt die gespeicherte Vorgabe dieses Namens. Replace… Ersetzen… Require a password to open the document Kennwort zum Öffnen des Dokuments verlangen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1dbe39f0f2..0a7d2be71c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3263,6 +3263,8 @@ digits Malayalam Μαλαγιάλαμ Replace Spine Αντικατάσταση κεντρικής καμπύλης Replace Symbol Αντικατάσταση συμβόλου Replace With Font Αντικατάσταση με γραμματοσειρά + Replace With Font From Αντικατάσταση με γραμματοσειρά από + System Σύστημα Replaces the saved preset of that name. Αντικαθιστά την αποθηκευμένη προεπιλογή με αυτό το όνομα. Require a password to open the document Απαίτηση κωδικού για το άνοιγμα εγγράφου Reset Bounding Box Επαναφορά πλαισίου οριοθέτησης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ad27598386..4e5ba28d4e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2710,6 +2710,8 @@ digits Malayalam Malayálam Replace Spine Reemplazar eje Replace Symbol Reemplazar símbolo Replace With Font Reemplazar con fuente + Replace With Font From Reemplazar con fuente de + System Sistema Replaces the saved preset of that name. Reemplaza el preajuste guardado con ese nombre. Replace… Reemplazar… Require a password to open the document Solicitar una contraseña para abrir el documento diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 294c513871..c75f15ba54 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3879,6 +3879,8 @@ effect Regular Normaali In the selected objects Valituissa objekteissa Find in Folder… Etsi kansiosta… Replace With Font Korvaa fontilla + Replace With Font From Korvaavan fontin lähde + System Järjestelmä — substituted by {style} — korvattu tyylillä {style} — {n} characters from another font — {n} merkkiä toisesta fontista All Scripts Kaikki kirjoitusjärjestelmät diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f5e604a258..20b608bb4f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2702,6 +2702,8 @@ digits Malayalam Malayalam Replace Spine Remplacer la dorsale Replace Symbol Remplacer le symbole Replace With Font Remplacer par la police + Replace With Font From Remplacer par une police de + System Système Replaces the saved preset of that name. Remplace le paramètre prédéfini enregistré sous ce nom. Replace… Remplacer… Require a password to open the document Exiger un mot de passe pour ouvrir le document diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1ce300e5db..12e8b0ec1f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3236,6 +3236,8 @@ mark-style Japanese Japán Replace Spine Gerinc cseréje Replace Symbol Szimbólum cseréje Replace With Font Helyettesítő betűtípus + Replace With Font From Helyettesítő betűtípus forrása + System Rendszer Replace “{name}”, the file this document was opened from? Felülírod ezt a fájlt, amelyből a dokumentumot megnyitottad: „{name}”? Replaces the saved preset of that name. Felülírja az azonos nevű mentett előbeállítást. Replace… Csere… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 336e64182f..8e4aa69f2f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3680,6 +3680,8 @@ effect Regular Reguler In the selected objects Di objek yang dipilih Find in Folder… Temukan di folder… Replace With Font Ganti dengan font + Replace With Font From Ganti dengan font dari + System Sistem — substituted by {style} — digantikan oleh {style} — {n} characters from another font — {n} karakter dari font lain All Scripts Semua skrip diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 72d8ab51fe..6fd38b0f77 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2743,6 +2743,8 @@ digits Malayalam Malayalam Replace Spine Sostituisci dorsale Replace Symbol Sostituisci simbolo Replace With Font Sostituisci con font + Replace With Font From Sostituisci con font da + System Sistema Replaces the saved preset of that name. Sostituisce il preset salvato con quel nome. Replace… Sostituisci… Require a password to open the document Richiedi una password per aprire il documento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2fd494bd37..5096fef13c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2728,6 +2728,8 @@ mark-style Japanese 日本式 Replace Font フォントを置換 Replace Symbol シンボルを置き換え Replace With Font 置換するフォント + Replace With Font From 置換するフォントの一覧 + System システム Replace it with another file, or ignore it: its images keep showing the preview saved with the document. 別のファイルに置き換えるか、無視してください。無視した場合、画像にはドキュメントに保存されたプレビューが表示され続けます。 Replaces the saved preset of that name. 同じ名前の保存済みプリセットを置き換えます。 Replace… 置換… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3ab0c61b4f..5389e1f093 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3463,6 +3463,8 @@ effect Regular ჩვეულებრივი In the selected objects მონიშნულ ობიექტებში Find in Folder… საქაღალდეში ძებნა… Replace With Font ჩანაცვლება შრიფტით + Replace With Font From ჩანაცვლების შრიფტის წყარო + System სისტემა — substituted by {style} — ჩანაცვლებულია: {style} — {n} characters from another font — სხვა შრიფტის სიმბოლოები: {n} All Scripts ყველა დამწერლობა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7f95429201..8596570c74 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2717,6 +2717,8 @@ mark-style Japanese 일본식 Replace Font 글꼴 바꾸기 Replace Symbol 심볼 바꾸기 Replace With Font 바꿀 글꼴 + Replace With Font From 바꿀 글꼴 목록 + System 시스템 Replace it with another file, or ignore it: its images keep showing the preview saved with the document. 다른 파일로 바꾸거나 무시하세요. 무시하면 해당 이미지는 문서에 저장된 미리 보기로 계속 표시됩니다. Replaces the saved preset of that name. 같은 이름으로 저장된 사전 설정을 대체합니다. Replace… 바꾸기… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 65a015fd29..4cde5d4036 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3694,6 +3694,8 @@ effect Regular Regelmatig In the selected objects In de geselecteerde objecten Find in Folder… Zoeken in map… Replace With Font Vervangen door lettertype + Replace With Font From Vervangen door lettertype uit + System Systeem — substituted by {style} — vervangen door {style} — {n} characters from another font — {n} tekens van een ander lettertype All Scripts Alle scripts diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3eb6257e7a..52800ade00 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3800,6 +3800,8 @@ effect Regular Normalny In the selected objects W zaznaczonych obiektach Find in Folder… Znajdź w folderze… Replace With Font Zastąp czcionką + Replace With Font From Zastąp czcionką z + System System — substituted by {style} — zastąpiona przez {style} — {n} characters from another font — znaki z innej czcionki: {n} All Scripts Wszystkie skrypty diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 15bccd1f7a..8369f4d23f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2258,6 +2258,8 @@ digits Malayalam Malaiala Replace Spine Substituir Coluna Replace Symbol Substituir Símbolo Replace With Font Substituir Com Fonte + Replace With Font From Substituir Com Fonte De + System Sistema Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Substitua por outro arquivo, ou ignore-o: suas imagens continuam mostrando a pré-visualização salva com o documento. Replaces the saved preset of that name. Substitui o predefinido salvo com esse nome. Replace… Substituir… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ccf399ddfe..e6bf3f77ca 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2738,6 +2738,8 @@ digits Malayalam Малаялам Replace Spine Заменить остов Replace Symbol Заменить символ Replace With Font Заменить шрифтом + Replace With Font From Заменить шрифтом из + System Система Replaces the saved preset of that name. Заменяет сохранённый набор с таким именем. Replace… Заменить… Require a password to open the document Требовать пароль для открытия документа diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4ee641f804..f123510402 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2646,6 +2646,8 @@ digits Malayalam Malayalam Replace Spine Ersätt ryggrad Replace Symbol Ersätt symbol Replace With Font Ersätt med typsnitt + Replace With Font From Ersätt med typsnitt från + System System Replaces the saved preset of that name. Ersätter den sparade förinställningen med samma namn. Replace… Ersätt… Require a password to open the document Kräv lösenord för att öppna dokumentet diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cbf5bf629f..b198e1af18 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2517,6 +2517,8 @@ digits Malayalam Malayalam Replace Spine Omurgayı Değiştir Replace Symbol Sembolü Değiştir Replace With Font Yazı Tipiyle Değiştir + Replace With Font From Değiştirilecek Yazı Tipi Kaynağı + System Sistem Replaces the saved preset of that name. Bu adın kayıtlı ön ayarını değiştirir. Replace… Değiştir… Require a password to open the document Belgeyi açmak için parola gerektir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 037d980501..d468a63d71 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2735,6 +2735,8 @@ digits Malayalam Малаялам Replace Spine Замінити вісь Replace Symbol Замінити символ Replace With Font Замінити шрифтом + Replace With Font From Замінити шрифтом з + System Система Replaces the saved preset of that name. Замінює збережений набір із таким ім’ям. Replace… Замінити… Require a password to open the document Вимагати пароль для відкриття документа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index c4666f6ca0..9d4acddcbd 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3004,6 +3004,8 @@ mark-style Japanese Kiểu Nhật Replace Spine Thay thế trục Replace Symbol Thay thế ký hiệu Replace With Font Thay thế bằng phông chữ + Replace With Font From Thay thế bằng phông chữ từ + System Hệ thống Replace “{name}”, the file this document was opened from? Thay thế “{name}”, tệp mà tài liệu này được mở từ đó? Replaces the saved preset of that name. Thay thế thiết lập sẵn đã lưu có tên đó. Replace… Thay thế… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0a0bee4c15..0426b415f8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2613,6 +2613,8 @@ digits Malayalam 马拉雅拉姆数字 Replace Spine 替换脊线 Replace Symbol 替换符号 Replace With Font 替换为字体 + Replace With Font From 替换字体来源 + System 系统 Replaces the saved preset of that name. 替换同名已存预设。 Replace… 替换… Require a password to open the document 打开文档时需要密码 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b96f2a2a11..92a1a98087 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3595,6 +3595,8 @@ digits Malayalam 馬來亞拉姆數字 Replace Spine 取代脊線 Replace Symbol 取代符號 Replace With Font 取代為字體 + Replace With Font From 取代字體來源 + System 系統 Replaces the saved preset of that name. 取代同名的已儲存預設集。 Replace… 取代… Require a password to open the document 開啟文件時需要密碼 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2bc6f55ab3..755c57da56 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -885,6 +885,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) ("Kerning is the process of adding or subtracting space between specific pairs of characters."). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). +- **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, is the font menu of every installed family. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the menu's saved font filters but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). From 86deb546ada5ffe4555dce53967904113763f6a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:38:29 +0700 Subject: [PATCH 357/674] Variables: Import Data Sets reads every column as a variable and replaces the data sets Squashed from #5151 onto main. --- crates/engine/src/cmd/variablecmds.rs | 14 +- crates/engine/src/cmd/variablecmds/csv.rs | 127 +++---- crates/engine/src/tests/variables.rs | 384 ++++++++++++++-------- crates/ui-egui/src/i18n/tests.rs | 12 +- crates/ui-egui/src/panels/variables.rs | 17 +- crates/ui-egui/src/tests/picks.rs | 10 +- docs/mcp.md | 11 +- docs/target-app-parity.md | 2 +- 8 files changed, 335 insertions(+), 242 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 76d39ea56e..4806531cde 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -4,11 +4,11 @@ //! variable, anything to a `visibility` variable, a linked image to an `image` //! variable, or a graph root to a `graph` variable (CSV data), put a row of values in //! each dataset, and `dataset.select` swaps the whole document to that row in one undo -//! step. `dataset.import` / `dataset.export` move those rows as CSV (header: `name` -//! then variable names, which export writes with `#` before a visibility variable and `@` -//! before an image variable); import also reads tab-separated files, files without the -//! `name` column, and header cells that define new variables (`#` for visibility, `@` for -//! image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the +//! step. `dataset.import` / `dataset.export` move those rows as CSV (header: one +//! variable name per column, which export writes with `#` before a visibility variable and `@` +//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…, +//! also reads tab-separated files, and reads header cells that define new variables (`#` for +//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the //! text variables and data sets of a variable library, the XML file of the reference app's Save //! Variable Library, and `variable.saveLibrary` writes the text variables and data sets as one. //! Agents reach every command through `run_command`, like all engine commands. @@ -838,7 +838,7 @@ pub fn specs() -> Vec { "Import Data Sets…", ["Window", "Variables"], None, - "{path? | data? | dataBase64? | csv?} load datasets from CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: name, then variable names; one row per dataset; without the name column every header is a variable and the rows take the first free names Data Set 1, 2…). A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. Rows whose name already exists are replaced → {imported, updated, names, defined}", + "{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}", has_doc, dataset_import ), @@ -847,7 +847,7 @@ pub fn specs() -> Vec { "Export Data Sets…", ["Window", "Variables"], None, - "{path?} write every dataset as CSV (header: name, then one column per variable: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)", + "{path?} write every dataset as CSV (header: one column per variable and no dataset names: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)", has_doc, dataset_export ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 5a4ba5100e..31e46787f2 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -102,7 +102,8 @@ fn tab_separated(text: &str) -> bool { /// by commas, or by tabs when [`tab_separated`] says so. `"` quotes a cell (doubled inside), /// which may then hold separators and line breaks, as [`csv_escape`] writes them. An unquoted /// cell is trimmed. A quoted cell keeps what its quotes hold as written, spaces included, and -/// drops white space after the closing quote at the end of the cell. Blank lines are skipped. +/// drops white space after the closing quote at the end of the cell. A line whose cells are all +/// blank and unquoted is skipped; a quoted empty cell keeps its line as a row. fn parse_datasets_csv(text: &str, cmd: &str) -> Result> { let text = text.strip_prefix('\u{feff}').unwrap_or(text); let sep = if tab_separated(text) { '\t' } else { ',' }; @@ -132,7 +133,10 @@ fn parse_datasets_csv(text: &str, cmd: &str) -> Result> { Some('\n') | None if !in_quotes => { quoted.push(closed.is_some()); row.push(end_csv_cell(&mut cur, &mut closed)); - if row.iter().any(|c| !c.trim().is_empty()) { + if row.len() > MAX_CSV_COLS { + return Err(bad(cmd, format!("line {line}: more than {MAX_CSV_COLS} columns"))); + } + if row.iter().any(|c| !c.trim().is_empty()) || quoted.contains(&true) { rows.push((start, std::mem::take(&mut row), std::mem::take(&mut quoted))); // +1 for the header. if rows.len() > MAX_CSV_ROWS + 1 { @@ -174,8 +178,10 @@ fn end_csv_cell(cur: &mut String, closed: &mut Option) -> String { } fn csv_escape(s: &str) -> String { - // An empty string is quoted so that it reads back as an empty value, not as a missing one. - if s.is_empty() || s.contains([',', '"', '\n', '\r']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } + // An empty string is quoted so that it reads back as an empty value, not as a missing one. A + // tab is quoted so that a header of one variable whose name holds a tab isn't read as + // tab-separated. + if s.is_empty() || s.contains([',', '"', '\n', '\r', '\t']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } } /// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). An error names the @@ -240,8 +246,7 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { for (i, v) in vars.variables.iter().enumerate() { let header = export_header(v); let cell = header.trim(); - // Column 1 holds the dataset names. - let read = if cell.is_empty() { None } else { header_variable(cell, i + 2, &none, &mut defined, C).ok() }; + let read = if cell.is_empty() { None } else { header_variable(cell, i + 1, &none, &mut defined, C).ok() }; // The import refuses a header that names a variable an earlier column named. let Some((name, kind)) = read.filter(|(name, _)| seen.insert(name.clone())) else { refused.push(v.name.as_str()); @@ -260,30 +265,36 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { (refused, other) } -/// Build the CSV of every dataset (header `name` then each variable's [`export_header`] in -/// definition order). Refused when a variable's header is another variable's name, which the -/// import reads as that variable (a visibility variable `Show` next to a text variable `#Show`). +/// Build the CSV of every dataset: a header of each variable's [`export_header`] in definition +/// order, then one row per dataset. The dataset names are not written. Refused when a variable's +/// header is another variable's name, which the import reads as that variable (a visibility +/// variable `Show` next to a text variable `#Show`). A dataset with no value for any variable would +/// be a blank line, which the import skips, so its row gets a quoted empty cell: in the first column +/// whose variable isn't a text variable, where it reads back as no value, or else in the first +/// column, where it reads back as an empty text. fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result { let names: BTreeSet<&str> = vars.variables.iter().map(|v| v.name.as_str()).collect(); - let mut out = String::from("name"); + let mut header = Vec::with_capacity(vars.variables.len()); for v in &vars.variables { - let header = export_header(v); - if header != v.name && names.contains(header.as_str()) { - let (name, other) = (&v.name, &header); - return Err(bad(cmd, format!("the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them"))); + let cell = export_header(v); + if cell != v.name && names.contains(cell.as_str()) { + let (name, other) = (&v.name, &cell); + return Err(bad(cmd, format!("the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them"))); } - out.push(','); - out.push_str(&csv_escape(&header)); + header.push(csv_escape(&cell)); } + let mut out = header.join(","); out.push('\n'); + let keep = vars.variables.iter().position(|v| v.kind != VariableKind::Text).unwrap_or(0); for ds in &vars.datasets { - out.push_str(&csv_escape(&ds.name)); - for v in &vars.variables { - out.push(','); - if let Some(val) = ds.values.get(&v.name) { - out.push_str(&csv_escape(&value_to_cell(val))); - } + let mut row: Vec = + vars.variables.iter().map(|v| ds.values.get(&v.name).map(|val| csv_escape(&value_to_cell(val))).unwrap_or_default()).collect(); + if row.iter().all(String::is_empty) + && let Some(cell) = row.get_mut(keep) + { + *cell = csv_escape(""); } + out.push_str(&row.join(",")); out.push('\n'); } Ok(out) @@ -329,12 +340,11 @@ fn header_variable( } } -/// Import datasets from CSV. A first header cell `name` makes the first column the dataset -/// names; the other headers name variables, as [`header_variable`] reads them, and the -/// variables the document doesn't define yet are defined, unbound. Without the `name` column, -/// every header names a variable and the rows take the first free names "Data Set 1", "Data -/// Set 2" and so on. Two headers that name one variable are refused. Existing rows of the same -/// name are replaced; new names are appended. One undo step. +/// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it, +/// and the variables the document doesn't define yet are defined, unbound. Two headers that name +/// one variable are refused. The rows replace every dataset of the document and are named "Data +/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings +/// stay. One undo step, and none when the variables and datasets stay as they were. pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.import"; let (bytes, given_as_text) = datasets_csv_bytes(p, C)?; @@ -344,16 +354,10 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { let Some((_, header, _)) = rows.first() else { return Err(bad(C, "CSV is empty")); }; - let name_column = header.first().is_some_and(|h| h.trim().eq_ignore_ascii_case("name")); - let (kinds, existing_names) = { - let st = s.doc()?; - let kinds: BTreeMap = st.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect(); - let existing: BTreeSet = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); - (kinds, existing) - }; + let kinds: BTreeMap = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect(); let mut columns: Vec<(usize, String, VariableKind)> = Vec::new(); let mut defined: Vec = Vec::new(); - for (i, h) in header.iter().enumerate().skip(usize::from(name_column)) { + for (i, h) in header.iter().enumerate() { let cell = h.trim(); if cell.is_empty() { return Err(bad(C, format!("empty header in column {}", i + 1))); @@ -373,27 +377,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "CSV has a header but no data rows")); } let mut parsed: Vec = Vec::new(); - // The names of the rows read so far, and the last number given to a row without a name. - let (mut seen, mut number) = (BTreeSet::new(), 0usize); - for &(line, ref row, ref quoted) in rows.iter().skip(1) { - let raw_name = if name_column { row.first().map_or("", |c| c.trim()) } else { "" }; - let name = if raw_name.is_empty() { - // Same numbering as Capture Data Set when a row leaves the name blank or the file has - // no name column. The search starts after the last number given. - let (n, name) = (number + 1..) - .map(|n| (n, format!("Data Set {n}"))) - .find(|(_, n)| !seen.contains(n) && !existing_names.contains(n)) - .unwrap_or_else(|| (line, format!("Data Set {line}"))); - number = n; - name - } else if raw_name.chars().count() > MAX_NAME { - return Err(bad(C, format!("line {line}: `name` is longer than {MAX_NAME} characters"))); - } else { - raw_name.to_string() - }; - if !seen.insert(name.clone()) { - return Err(bad(C, format!("line {line}: dataset `{name}` appears twice"))); - } + for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() { + let name = format!("Data Set {}", n + 1); let mut values = BTreeMap::new(); for &(col, ref var, kind) in &columns { let cell = row.get(col).map(String::as_str).unwrap_or(""); @@ -406,26 +391,23 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { } let names: Vec = parsed.iter().map(|d| d.name.clone()).collect(); let new_variables: Vec = defined.iter().map(|v| v.name.clone()).collect(); + let deleted: Vec = s.doc()?.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); // The import is one undo step, and an import that leaves the variables and data sets as they - // were adds none. - let (imported, updated) = super::edit_variables(s, "Import Data Sets", |vars| { - vars.variables.extend(defined); - let (mut imported, mut updated) = (0usize, 0usize); - for row in parsed { - if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) { - *existing = row; - updated += 1; - } else { - vars.datasets.push(row); - imported += 1; - } + // were adds none, so the active data set stays when nothing changes. + super::edit_variables(s, "Import Data Sets", |vars| { + if defined.is_empty() && vars.datasets == parsed { + return Ok(()); } - Ok((imported, updated)) + vars.variables.extend(defined); + vars.datasets = parsed; + vars.active_dataset = None; + Ok(()) })?; - Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables})) + Ok(json!({"imported": names.len(), "names": names, "defined": new_variables, "deletedDataSets": deleted})) } -/// Export every dataset as CSV ([`datasets_to_csv`]). With `path`, write the file; else return +/// Export every dataset as CSV ([`datasets_to_csv`]: one column per variable, no dataset names). +/// With `path`, write the file; else return /// `{csv}`. The reply's `warning` names the variables whose column makes a document without them /// refuse the file, or else the variables it doesn't read back with their kind /// ([`kinds_a_new_document_loses`]); the app shows it in its status bar. @@ -439,7 +421,6 @@ pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result { if st.doc.variables.datasets.len() > MAX_CSV_ROWS { return Err(bad(C, format!("more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS}"))); } - // The name column comes first, so the import's column cap leaves room for this many variables. if st.doc.variables.variables.len() > MAX_CSV_COLS { return Err(bad(C, format!("more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS}"))); } diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 493871de2a..e6ef5e69dd 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -245,25 +245,26 @@ fn mismatched_and_missing_bindings_are_skipped_and_counted() { fn a_row_with_no_value_for_a_bound_variable_warns_that_nothing_was_applied() { let mut s = session(); let t = text(&mut s, "x"); - s.execute("dataset.import", &json!({"csv": "name,Name,Title\nA,Ann,Boss\nB,Bob,Chief\n"})).unwrap(); + s.execute("dataset.import", &json!({"csv": "Name,Title\nAnn,Boss\nBob,Chief\n"})).unwrap(); + let (a, b) = ("Data Set 1", "Data Set 2"); let warning = |row: &str| format!("nothing in data set {row} was applied: no object is bound to a variable it has a value for"); - let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap(); - assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(0), &json!(warning("A"))), "{v}"); + let v = s.execute("dataset.select", &json!({"name": a})).unwrap(); + assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(0), &json!(warning(a))), "{v}"); let v = s.execute("dataset.next", &json!({})).unwrap(); - assert_eq!(v["warning"], json!(warning("B")), "{v}"); + assert_eq!(v["warning"], json!(warning(b)), "{v}"); let v = s.execute("dataset.prev", &json!({})).unwrap(); - assert_eq!(v["warning"], json!(warning("A")), "{v}"); + assert_eq!(v["warning"], json!(warning(a)), "{v}"); assert_eq!(plain(&s, t), "x"); // A bound variable that the row has no value for still applies nothing. s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap(); s.execute("variable.bind", &json!({"variable": "Other", "ids": [t.0]})).unwrap(); - let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap(); - assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(1), &json!(warning("B"))), "{v}"); + let v = s.execute("dataset.select", &json!({"name": b})).unwrap(); + assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(1), &json!(warning(b))), "{v}"); // Bound to a variable with a value, the row applies it and gives no warning. s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap(); - let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + let v = s.execute("dataset.select", &json!({"name": a})).unwrap(); assert_eq!(v["applied"].as_u64(), Some(1), "{v}"); assert!(v.get("warning").is_none(), "{v}"); assert_eq!(plain(&s, t), "Boss"); @@ -271,7 +272,7 @@ fn a_row_with_no_value_for_a_bound_variable_warns_that_nothing_was_applied() { // Locked art is skipped, and its binding still counts as bound. s.execute("select.set", &json!({"ids": [t.0]})).unwrap(); s.execute("object.lock", &json!({})).unwrap(); - let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + let v = s.execute("dataset.select", &json!({"name": b})).unwrap(); assert_eq!(v["applied"].as_u64(), Some(0), "{v}"); assert!(v.get("warning").is_none(), "{v}"); } @@ -613,8 +614,8 @@ fn locked_variables_refuse_new_deleted_and_renamed_variables() { s.execute("variable.unbind", &json!({"ids": [r.0], "variable": "Show"})).unwrap(); s.execute("dataset.capture", &json!({})).unwrap(); s.execute("dataset.new", &json!({"name": "Bob", "values": {"Name": "Bob"}})).unwrap(); - s.execute("dataset.import", &json!({"csv": "name,Name\nCarol,Carol\n"})).unwrap(); - s.execute("dataset.select", &json!({"name": "Carol"})).unwrap(); + s.execute("dataset.import", &json!({"csv": "Name\nCarol\n"})).unwrap(); + s.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap(); assert_eq!(plain(&s, t), "Carol"); // Unlocking lets a variable be defined again; `locked` sets the state rather than toggling. @@ -1395,12 +1396,11 @@ fn datasets_csv_keeps_line_breaks_in_quoted_cells() { let value = "Line one, \"quoted\"\nLine two"; s.execute("dataset.new", &json!({"name": "A", "values": {"Name": value}})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap(); s.execute("dataset.import", &json!({"csv": csv})).unwrap(); let sets = &s.doc().unwrap().doc.variables.datasets; assert_eq!(sets.len(), 1); assert_eq!(sets[0].values.get("Name"), Some(&vectorcraft_doc::DataValue::Text(value.into()))); - assert!(s.execute("dataset.import", &json!({"csv": "name,Name\nX,\"open"})).is_err(), "unclosed quote"); + assert!(s.execute("dataset.import", &json!({"csv": "Name\n\"open"})).is_err(), "unclosed quote"); } /// An empty text value is not a missing value: it comes back from the exported CSV as an empty @@ -1413,23 +1413,45 @@ fn datasets_csv_keeps_an_empty_text_value() { s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); s.execute("dataset.new", &json!({"name": "A", "values": {"Name": ""}})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap(); s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - let value = s.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get("Name")).cloned(); - assert_eq!(value, Some(vectorcraft_doc::DataValue::Text(String::new()))); - s.execute("dataset.import", &json!({"csv": "name,Name\nB,\nC,\"\"\n"})).unwrap(); - let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned(); - assert_eq!(value("C"), Some(vectorcraft_doc::DataValue::Text(String::new()))); + let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned(); + assert_eq!(value(&s, "Data Set 1"), Some(vectorcraft_doc::DataValue::Text(String::new()))); + s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap(); + s.execute("dataset.import", &json!({"csv": "Name,Other\n,x\n\"\",y\n"})).unwrap(); + assert_eq!(value(&s, "Data Set 2"), Some(vectorcraft_doc::DataValue::Text(String::new()))); // Compatibility rule for files written before empty text was quoted: a bare empty cell stays "no value". - assert_eq!(value("B"), None); + assert_eq!(value(&s, "Data Set 1"), None); // A data set with no value for the variable exports a bare cell and stays without a value. - s.execute("dataset.new", &json!({"name": "D", "values": {}})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - assert!(csv.contains("\nD,\n"), "{csv:?}"); - s.execute("dataset.delete", &json!({"names": ["D"]})).unwrap(); + assert_eq!(csv, "Name,Other\n,x\n\"\",y\n"); s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned(); - assert_eq!(value("D"), None); + assert_eq!(value(&s, "Data Set 1"), None); +} + +/// A data set with no value for any variable exports as a row that imports back: a quoted empty +/// cell in the first column that isn't a text variable reads back as no value, and with only text +/// variables the first column reads back as an empty text. +#[test] +fn datasets_csv_keeps_a_data_set_without_values() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {}})).unwrap(); + s.execute("dataset.new", &json!({"name": "B", "values": {"Title": "x"}})).unwrap(); + let export = |s: &mut Session| s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + let csv = export(&mut s); + assert_eq!(csv, "Title\n\"\"\nx\n"); + let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"])); + let values = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).map(|d| d.values.clone()).unwrap(); + assert_eq!(values(&s, "Data Set 1").get("Title"), Some(&vectorcraft_doc::DataValue::Text(String::new()))); + + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("dataset.new", &json!({"name": "C", "values": {}})).unwrap(); + let csv = export(&mut s); + assert!(csv.ends_with("\n,\"\"\n"), "{csv:?}"); + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 3); + assert!(values(&s, "Data Set 3").is_empty()); } /// A quoted text cell keeps its leading and trailing spaces, so a padded value comes back from @@ -1442,25 +1464,28 @@ fn datasets_csv_keeps_spaces_in_quoted_cells() { s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); s.execute("dataset.new", &json!({"name": "A", "values": {"Name": " padded "}})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap(); s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - s.execute("dataset.import", &json!({"csv": "name,Name\nB, typed \nC,\" quoted \" \n"})).unwrap(); - let value = |name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned(); + let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Name")).cloned(); let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into())); - assert_eq!(value("A"), text_value(" padded ")); - assert_eq!(value("B"), text_value("typed")); - assert_eq!(value("C"), text_value(" quoted ")); + assert_eq!(value(&s, "Data Set 1"), text_value(" padded ")); + s.execute("dataset.import", &json!({"csv": "Name\n typed \n\" quoted \" \n"})).unwrap(); + assert_eq!(value(&s, "Data Set 1"), text_value("typed")); + assert_eq!(value(&s, "Data Set 2"), text_value(" quoted ")); } /// Export refuses a document with more data sets or variables than `dataset.import` reads, so /// every file it writes imports back: 1,000 data sets and 256 variables export and import, and -/// one more of either is refused. +/// one more of either is refused. The import refuses a line of 257 columns, the last one included. #[test] fn datasets_export_refuses_more_than_import_reads() { let mut s = session(); let header: Vec = (1..=256).map(|i| format!("V{i}")).collect(); + for wide in [format!("{},V257\nx\n", header.join(",")), format!("{}\nx{}\n", header.join(","), ",".repeat(256))] { + let err = s.execute("dataset.import", &json!({"csv": wide})).unwrap_err().to_string(); + assert!(err.contains("more than 256 columns"), "{err}"); + } let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect(); - s.execute("dataset.import", &json!({"csv": format!("name,{}\n{rows}", header.join(","))})).unwrap(); + s.execute("dataset.import", &json!({"csv": format!("{}\n{rows}", header.join(","))})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); s.execute("dataset.import", &json!({"csv": csv})).unwrap(); @@ -1488,59 +1513,102 @@ fn datasets_csv_reads_tab_separated_files() { s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); s.execute("variable.define", &json!({"name": "Last, First", "kind": "text"})).unwrap(); - let tsv = "name\tTitle\tShow\r\nA\tTwo words\ttrue\r\nB\t\"a, b\tc\"\tfalse\r\n"; + let tsv = "Title\tShow\r\nTwo words\ttrue\r\n\"a, b\tc\"\tfalse\r\n"; let imp = s.execute("dataset.import", &json!({"csv": tsv})).unwrap(); - assert_eq!(imp["names"], json!(["A", "B"])); - s.execute("dataset.import", &json!({"csv": "name,Title\nC,one\ttwo"})).unwrap(); - s.execute("dataset.import", &json!({"csv": "name\t\"Last, First\"\nD\tSmith, Jo"})).unwrap(); - let value = |name: &str, var: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get(var)).cloned(); + assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"])); + let value = |s: &Session, name: &str, var: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get(var)).cloned(); let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into())); - assert_eq!(value("A", "Title"), text_value("Two words")); - assert_eq!(value("A", "Show"), Some(vectorcraft_doc::DataValue::Visible(true))); - assert_eq!(value("B", "Title"), text_value("a, b\tc")); - assert_eq!(value("B", "Show"), Some(vectorcraft_doc::DataValue::Visible(false))); - assert_eq!(value("C", "Title"), text_value("one\ttwo")); - assert_eq!(value("D", "Last, First"), text_value("Smith, Jo")); - let unclosed = s.execute("dataset.import", &json!({"csv": "name\tTitle\t\"Show\nA\tx\ttrue"})).unwrap_err().to_string(); + assert_eq!(value(&s, "Data Set 1", "Title"), text_value("Two words")); + assert_eq!(value(&s, "Data Set 1", "Show"), Some(vectorcraft_doc::DataValue::Visible(true))); + assert_eq!(value(&s, "Data Set 2", "Title"), text_value("a, b\tc")); + assert_eq!(value(&s, "Data Set 2", "Show"), Some(vectorcraft_doc::DataValue::Visible(false))); + s.execute("dataset.import", &json!({"csv": "Title,Show\none\ttwo,true"})).unwrap(); + assert_eq!(value(&s, "Data Set 1", "Title"), text_value("one\ttwo")); + s.execute("dataset.import", &json!({"csv": "\"Last, First\"\tShow\nSmith, Jo\ttrue"})).unwrap(); + assert_eq!(value(&s, "Data Set 1", "Last, First"), text_value("Smith, Jo")); + // A file of one variable whose name holds a tab is exported with the name quoted, and reads back as one column. + let mut one = session(); + one.execute("variable.define", &json!({"name": "Tab\tName", "kind": "text"})).unwrap(); + one.execute("dataset.new", &json!({"name": "A", "values": {"Tab\tName": "v"}})).unwrap(); + let csv = one.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + assert_eq!(csv, "\"Tab\tName\"\nv\n"); + let imp = one.execute("dataset.import", &json!({"csv": csv})).unwrap(); + assert_eq!(imp["defined"], json!([]), "{imp}"); + assert_eq!(value(&one, "Data Set 1", "Tab\tName"), text_value("v")); + let unclosed = s.execute("dataset.import", &json!({"csv": "Title\t\"Show\nx\ttrue"})).unwrap_err().to_string(); assert!(unclosed.contains("unclosed quote"), "{unclosed}"); } -/// Without a `name` column every header cell is a variable, and the rows take the first free -/// names Data Set 1, 2 and so on. A first header cell `name`, in any case, still holds the names. +/// Every header cell is a variable, whatever its case: a file laid out as the set-up page shows +/// (`Name,Age`) defines and fills `Name`, and `name` and `NAME` are variables too. The rows are +/// named Data Set 1, 2 and so on, in file order. #[test] -fn datasets_csv_without_a_name_column_numbers_the_rows() { +fn datasets_csv_reads_every_header_cell_as_a_variable() { let mut s = session(); - s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); - s.execute("dataset.new", &json!({"name": "Data Set 2", "values": {"Title": "kept"}})).unwrap(); - let imp = s.execute("dataset.import", &json!({"csv": "Title\nx\ny\n"})).unwrap(); - assert_eq!((imp["imported"].as_u64(), imp["updated"].as_u64()), (Some(2), Some(0))); - assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 3"])); - let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("Title")).cloned(); - let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into())); - assert_eq!(value(&s, "Data Set 1"), text_value("x")); - assert_eq!(value(&s, "Data Set 2"), text_value("kept")); - assert_eq!(value(&s, "Data Set 3"), text_value("y")); - let named = s.execute("dataset.import", &json!({"csv": "NAME,Title\nData Set 1,z"})).unwrap(); - assert_eq!((named["imported"].as_u64(), named["updated"].as_u64()), (Some(0), Some(1))); - assert_eq!(value(&s, "Data Set 1"), text_value("z")); + let t = text(&mut s, "x"); + let imp = s.execute("dataset.import", &json!({"csv": "Name,Age\nBill Tucker,36\nJo Lee,41\n"})).unwrap(); + assert_eq!((imp["imported"].as_u64(), &imp["defined"]), (Some(2), &json!(["Name", "Age"])), "{imp}"); + assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"])); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap(); + assert_eq!(plain(&s, t), "Jo Lee"); + for header in ["name", "NAME"] { + let imp = s.execute("dataset.import", &json!({"csv": format!("{header},Age\nx,1\n")})).unwrap(); + assert_eq!((&imp["defined"], &imp["names"]), (&json!([header]), &json!(["Data Set 1"])), "{header}: {imp}"); + } + let value = |s: &Session, var: &str| s.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned(); + assert_eq!(value(&s, "NAME"), Some(vectorcraft_doc::DataValue::Text("x".into()))); } -/// An error about a row's values or name gives the file line the row starts on, counting blank -/// lines and line breaks inside quoted cells. +/// An import replaces every data set of the document, as Load Variable Library does, and clears +/// the active data set. The document's variables stay with their bindings, including those the +/// file has no column for, which then have no value in any data set. Undo brings the data sets back. +#[test] +fn datasets_csv_import_replaces_the_data_sets() { + let mut s = session(); + let t = text(&mut s, "x"); + let r = rect(&mut s); + s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap(); + for (name, title) in [("First", "a"), ("Data Set 2", "b"), ("Data Set 3", "c")] { + s.execute("dataset.new", &json!({"name": name, "values": {"Title": title, "Show": true}})).unwrap(); + } + s.execute("dataset.select", &json!({"name": "First"})).unwrap(); + let imp = s.execute("dataset.import", &json!({"csv": "Title\ny\nz\n"})).unwrap(); + assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"])); + assert_eq!(imp["deletedDataSets"], json!(["First", "Data Set 2", "Data Set 3"])); + let vars = &s.doc().unwrap().doc.variables; + let sets: Vec<_> = vars.datasets.iter().map(|d| (d.name.as_str(), d.values.get("Title").cloned(), d.values.get("Show").cloned())).collect(); + let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into())); + assert_eq!(sets, [("Data Set 1", text_value("y"), None), ("Data Set 2", text_value("z"), None)]); + assert_eq!(vars.active_dataset, None); + let listed = s.execute("variable.list", &json!({})).unwrap(); + assert_eq!(listed["variables"], json!([{"name": "Title", "kind": "text", "bindings": 1}, {"name": "Show", "kind": "visibility", "bindings": 1}])); + s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap(); + assert_eq!(plain(&s, t), "z"); + + // The first undo takes back the selection, the second the import. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let vars = &s.doc().unwrap().doc.variables; + let names: Vec<&str> = vars.datasets.iter().map(|d| d.name.as_str()).collect(); + assert_eq!((names, vars.active_dataset.as_deref()), (vec!["First", "Data Set 2", "Data Set 3"], Some("First"))); +} + +/// An error about a row's values gives the file line the row starts on, counting blank lines and +/// line breaks inside quoted cells. #[test] fn datasets_csv_row_errors_name_the_file_line() { let mut s = session(); s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); - let blank_line = error(&mut s, "name,Show\n\nX,maybe"); + let blank_line = error(&mut s, "Show\n\nmaybe"); assert!(blank_line.contains("line 3:"), "{blank_line}"); - let line_break = error(&mut s, "name,Title,Show\nA,\"one\ntwo\",true\nB,x,maybe"); + let line_break = error(&mut s, "Title,Show\n\"one\ntwo\",true\nx,maybe"); assert!(line_break.contains("line 4:"), "{line_break}"); - let twice = error(&mut s, "name,Title\nA,x\n\nA,y"); - assert!(twice.contains("line 4:"), "{twice}"); - let long = error(&mut s, &format!("name,Title\n\n{},x", "n".repeat(256))); - assert!(long.contains("line 3:") && long.contains("longer than 255"), "{long}"); } /// A refused cell's error gives its line and why the value was refused: a visibility value that @@ -1551,10 +1619,10 @@ fn datasets_csv_cell_errors_say_why() { s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); - let maybe = error(&mut s, "name,Show\nX,maybe"); + let maybe = error(&mut s, "Show\nmaybe"); let want = "line 2: value for `Show` must be true or false"; assert!(matches!(&maybe, EngineError::BadParams { msg, .. } if msg == want), "{maybe}"); - let long = error(&mut s, &format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000))); + let long = error(&mut s, &format!("Sales\n\"{}\"", "1,".repeat(140_000))); let want = "line 2: value for `Sales` is longer than 262144 bytes"; assert!(matches!(&long, EngineError::BadParams { msg, .. } if msg == want), "{long}"); assert!(s.doc().unwrap().doc.variables.datasets.is_empty()); @@ -1567,10 +1635,10 @@ fn datasets_csv_cell_errors_say_why() { #[test] fn datasets_csv_header_prefixes_define_variables() { let mut s = session(); - let csv = "name,#Shown,@Photo,Title\nA,true,a.png,x"; + let csv = "#Shown,@Photo,Title\ntrue,a.png,x"; let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); assert_eq!(imp["defined"], json!(["Shown", "Photo", "Title"])); - assert_eq!((imp["imported"].as_u64(), imp["names"].clone()), (Some(1), json!(["A"]))); + assert_eq!((imp["imported"].as_u64(), imp["names"].clone()), (Some(1), json!(["Data Set 1"]))); let listed = s.execute("variable.list", &json!({})).unwrap(); assert_eq!( listed["variables"], @@ -1580,23 +1648,23 @@ fn datasets_csv_header_prefixes_define_variables() { {"name": "Title", "kind": "text", "bindings": 0}, ]) ); - let value = |s: &Session, var: &str| s.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned(); + let value = |s: &Session, var: &str| s.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned(); assert_eq!(value(&s, "Shown"), Some(vectorcraft_doc::DataValue::Visible(true))); assert_eq!(value(&s, "Photo"), Some(vectorcraft_doc::DataValue::Image("a.png".into()))); assert_eq!(value(&s, "Title"), Some(vectorcraft_doc::DataValue::Text("x".into()))); - let again = s.execute("dataset.import", &json!({"csv": "name\t#Shown\t@Photo\tTitle\nA\tfalse\tb.png\ty"})).unwrap(); - assert_eq!((again["updated"].as_u64(), again["defined"].clone()), (Some(1), json!([]))); + let again = s.execute("dataset.import", &json!({"csv": "#Shown\t@Photo\tTitle\nfalse\tb.png\ty"})).unwrap(); + assert_eq!((again["imported"].as_u64(), again["defined"].clone()), (Some(1), json!([]))); assert_eq!(value(&s, "Shown"), Some(vectorcraft_doc::DataValue::Visible(false))); let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); - let other_kind = error(&mut s, "name,New,#Title\nB,n,true"); + let other_kind = error(&mut s, "Shown,New,#Title\ntrue,n,true"); assert!(other_kind.contains("column 3:") && other_kind.contains("text variable"), "{other_kind}"); let twice = error(&mut s, "Fresh,@Fresh\nn,f.png"); assert!(twice.contains("column 2:") && twice.contains("text variable"), "{twice}"); - let bare = error(&mut s, "name,#\nB,true"); + let bare = error(&mut s, "Title,#\nx,true"); assert!(bare.contains("column 2:") && bare.contains("names no variable"), "{bare}"); - let long = error(&mut s, &format!("name,@{}\nB,b.png", "n".repeat(256))); + let long = error(&mut s, &format!("Title,@{}\nx,b.png", "n".repeat(256))); assert!(long.contains("column 2:") && long.contains("longer than 255"), "{long}"); assert_eq!(s.doc().unwrap().doc.variables.variables.len(), 3, "a failed import defines nothing"); @@ -1620,11 +1688,10 @@ fn datasets_csv_exact_names_win_over_prefixes() { let values = json!({"#Shown": "hello", "@Photo": true, "%Chart": ",Q\nX,3", "Shown": "s.png"}); s.execute("dataset.new", &json!({"name": "A", "values": values})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - assert!(csv.starts_with("name,#Shown,#@Photo,%Chart,@Shown\n"), "{csv}"); - s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap(); + assert!(csv.starts_with("#Shown,#@Photo,%Chart,@Shown\n"), "{csv}"); let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); assert_eq!((imp["imported"].as_u64(), imp["defined"].clone()), (Some(1), json!([]))); - let value = |var: &str| s.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned(); + let value = |var: &str| s.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned(); assert_eq!(value("#Shown"), Some(vectorcraft_doc::DataValue::Text("hello".into()))); assert_eq!(value("@Photo"), Some(vectorcraft_doc::DataValue::Visible(true))); assert_eq!(value("%Chart"), Some(vectorcraft_doc::DataValue::Graph(",Q\nX,3".into()))); @@ -1644,7 +1711,7 @@ fn datasets_csv_export_marks_visibility_and_image_columns() { } s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Ann", "Show": false, "Photo": "a.png"}})).unwrap(); let out = s.execute("dataset.export", &json!({})).unwrap(); - assert_eq!(out["csv"], "name,Name,#Show,@Photo\nA,Ann,false,a.png\n"); + assert_eq!(out["csv"], "Name,#Show,@Photo\nAnn,false,a.png\n"); assert!(out.get("warning").is_none(), "{out}"); let mut fresh = session(); @@ -1653,7 +1720,8 @@ fn datasets_csv_export_marks_visibility_and_image_columns() { let listed = fresh.execute("variable.list", &json!({})).unwrap(); let kinds: Vec<_> = listed["variables"].as_array().unwrap().iter().map(|v| v["kind"].clone()).collect(); assert_eq!(kinds, [json!("text"), json!("visibility"), json!("image")]); - let value = |var: &str| fresh.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned(); + let value = |var: &str| fresh.doc().unwrap().doc.variables.dataset("Data Set 1").and_then(|d| d.values.get(var)).cloned(); + assert_eq!(value("Name"), Some(vectorcraft_doc::DataValue::Text("Ann".into()))); assert_eq!(value("Show"), Some(vectorcraft_doc::DataValue::Visible(false))); assert_eq!(value("Photo"), Some(vectorcraft_doc::DataValue::Image("a.png".into()))); @@ -1662,7 +1730,48 @@ fn datasets_csv_export_marks_visibility_and_image_columns() { } let out = s.execute("dataset.export", &json!({})).unwrap(); assert_eq!(out["warning"], "a new document won't read these variables back with their kind: `#Tag`, `Chart`, `@Note`"); - assert!(out["csv"].as_str().unwrap().starts_with("name,Name,#Show,@Photo,#Tag,Chart,@Note\n"), "{out}"); + assert!(out["csv"].as_str().unwrap().starts_with("Name,#Show,@Photo,#Tag,Chart,@Note\n"), "{out}"); +} + +/// A file `dataset.export` writes has no column of data set names, and `dataset.import` reads +/// every column as a variable, so the file imports back to the same data sets: the same variables +/// with their kinds, and each data set's values in order, a data set without values included, named +/// Data Set 1, 2 and so on. In a document whose data sets already have those names and values, the +/// import changes nothing. +#[test] +fn datasets_csv_export_imports_back_to_the_same_data_sets() { + let mut s = session(); + for (name, kind) in [("Name", "text"), ("Show", "visibility"), ("Photo", "image")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Ann, Jr.", "Show": true, "Photo": "a.png"}})).unwrap(); + s.execute("dataset.new", &json!({"name": "B", "values": {"Show": false}})).unwrap(); + s.execute("dataset.new", &json!({"name": "C", "values": {}})).unwrap(); + s.execute("dataset.new", &json!({"name": "D", "values": {"Name": "", "Photo": "d.png"}})).unwrap(); + let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + assert!(csv.starts_with("Name,#Show,@Photo\n"), "{csv}"); + let before = s.doc().unwrap().doc.variables.clone(); + + let mut fresh = session(); + fresh.execute("dataset.import", &json!({"csv": csv})).unwrap(); + let vars = fresh.doc().unwrap().doc.variables.clone(); + assert_eq!(vars.variables, before.variables, "the same variables, with their kinds"); + let values = |v: &vectorcraft_doc::Variables| v.datasets.iter().map(|d| d.values.clone()).collect::>(); + assert_eq!(values(&vars), values(&before), "the same values in every data set"); + let names: Vec<&str> = vars.datasets.iter().map(|d| d.name.as_str()).collect(); + assert_eq!(names, ["Data Set 1", "Data Set 2", "Data Set 3", "Data Set 4"]); + + // Exporting the imported data sets writes the same file, and importing it changes nothing: no + // undo step, and the active data set stays. + let again = fresh.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + assert_eq!(again, csv); + fresh.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap(); + let vars = fresh.doc().unwrap().doc.variables.clone(); + assert!(vars.active_dataset.is_some()); + let undo = fresh.doc().unwrap().history.undo.len(); + fresh.execute("dataset.import", &json!({"csv": again})).unwrap(); + assert_eq!(fresh.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(fresh.doc().unwrap().doc.variables, vars); } /// The export's `warning` names the variables whose column a document without the variables @@ -1719,7 +1828,7 @@ fn datasets_csv_export_refuses_a_header_that_names_another_variable() { fn datasets_csv_refuses_graph_data_file_columns() { let mut s = session(); let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); - let named = error(&mut s, "name,Title,%Sales\nA,x,sales.txt"); + let named = error(&mut s, "Name,Title,%Sales\nA,x,sales.txt"); assert!(named.contains("column 3:") && named.contains("`%Sales`"), "{named}"); let unnamed = error(&mut s, "%Sales\tTitle\nsales.txt\tx"); assert!(unnamed.contains("column 1:") && unnamed.contains("`%Sales`"), "{unnamed}"); @@ -1735,10 +1844,10 @@ fn datasets_csv_refuses_two_columns_for_one_variable() { s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap(); let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); for (csv, first, second, var) in [ - ("name,City,City\nR,Paris,Rome", 2, 3, "City"), - ("name,City,City\nR,Paris,", 2, 3, "City"), + ("Title,City,City\nR,Paris,Rome", 2, 3, "City"), + ("Title,City,City\nR,Paris,", 2, 3, "City"), ("City,Title,City\nParis,x,Rome", 1, 3, "City"), - ("name,Shown,#Shown\nR,true,false", 2, 3, "Shown"), + ("Title,Shown,#Shown\nR,true,false", 2, 3, "Shown"), ("Title\t@Photo\t@ Photo\nx\ta.png\tb.png", 2, 3, "Photo"), ] { let err = error(&mut s, csv); @@ -1757,21 +1866,22 @@ fn locked_variables_refuse_header_cells_that_define_variables() { s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap(); s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); s.execute("variable.lock", &json!({"locked": true})).unwrap(); - for csv in ["name,#Shown,Title,New\nA,true,x,n", "@Photo\nb.png", "name,#Fresh\nA,true"] { + for csv in ["#Shown,Title,New\ntrue,x,n", "@Photo\nb.png", "Title,#Fresh\nx,true"] { let e = s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); assert!(matches!(&e, EngineError::Disabled(cmd, why) if cmd == "dataset.import" && why == "variables are locked"), "{csv}: {e}"); } let vars = &s.doc().unwrap().doc.variables; assert!(vars.variables.len() == 2 && vars.datasets.is_empty(), "a refused import defines and imports nothing"); - let imp = s.execute("dataset.import", &json!({"csv": "name,#Shown,Title\nA,true,x"})).unwrap(); + let imp = s.execute("dataset.import", &json!({"csv": "#Shown,Title\ntrue,x"})).unwrap(); assert_eq!((imp["imported"].as_u64(), imp["defined"].clone()), (Some(1), json!([]))); s.execute("variable.lock", &json!({"locked": false})).unwrap(); - let imp = s.execute("dataset.import", &json!({"csv": "name,New\nB,n"})).unwrap(); + let imp = s.execute("dataset.import", &json!({"csv": "New\nn"})).unwrap(); assert_eq!(imp["defined"], json!(["New"])); } -/// Import / export datasets as CSV: header `name` then variables; round-trip keeps values. +/// Import / export datasets as CSV: one column per variable and no dataset names; round-trip keeps +/// the values in order, and the rows come back as Data Set 1, 2. #[test] fn datasets_csv_round_trips_and_rejects_bad_input() { let dir = Folder::new("vars-csv"); @@ -1795,28 +1905,27 @@ fn datasets_csv_round_trips_and_rejects_bad_input() { let exported = s.execute("dataset.export", &json!({})).unwrap(); let csv = exported["csv"].as_str().unwrap().to_string(); - assert!(csv.starts_with("name,Name,#Show,@Photo\n"), "{csv}"); + assert!(csv.starts_with("Name,#Show,@Photo\n"), "{csv}"); assert!(csv.contains("Alice") && csv.contains("Bob") && csv.contains("false"), "{csv}"); - // Clear rows, import again, apply B. - s.execute("dataset.delete", &json!({"names": ["A", "B"]})).unwrap(); + // Import again, which replaces A and B, and apply the second row. let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - assert_eq!((imp["imported"].as_u64(), imp["updated"].as_u64()), (Some(2), Some(0))); - s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!((imp["imported"].as_u64(), &imp["deletedDataSets"]), (Some(2), &json!(["A", "B"]))); + s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap(); assert_eq!(plain(&s, t), "Bob"); assert!(!s.doc().unwrap().doc.node(r).unwrap().visible); assert_eq!(image(&s, img).link.as_ref().map(|l| l.path.as_str()), Some(blue_path.as_str())); - // Re-import updates in place and defines nothing; a bad visibility value is an error. + // Re-import replaces the rows and defines nothing; a bad visibility value is an error. let again = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - assert_eq!((again["imported"].as_u64(), again["updated"].as_u64()), (Some(0), Some(2))); + assert_eq!((again["imported"].as_u64(), &again["deletedDataSets"]), (Some(2), &json!(["Data Set 1", "Data Set 2"]))); assert_eq!(again["defined"], json!([])); - assert!(s.execute("dataset.import", &json!({"csv": "name,Show\nX,maybe"})).is_err()); + assert!(s.execute("dataset.import", &json!({"csv": "Show\nmaybe"})).is_err()); let out = dir.file("sets.csv"); s.execute("dataset.export", &json!({"path": out})).unwrap(); let from_file = s.execute("dataset.import", &json!({"path": out})).unwrap(); - assert_eq!(from_file["updated"].as_u64(), Some(2)); + assert_eq!(from_file["names"], json!(["Data Set 1", "Data Set 2"])); // One undo undoes the last import's replacements. s.execute("edit.undo", &json!({})).unwrap(); @@ -1831,17 +1940,17 @@ fn datasets_csv_reads_windows_1252_files() { let import = |s: &mut Session, bytes: &[u8]| s.execute("dataset.import", &json!({"dataBase64": vectorcraft_format::base64_encode(bytes)})); let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("City")).cloned(); let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into())); - let imp = import(&mut s, b"name,City\r\nA,Jos\xe9\r\nB,\x80 5 \x96 \x93Caf\xe9\x94\r\n").unwrap(); - assert_eq!(imp["names"], json!(["A", "B"])); - assert_eq!(value(&s, "A"), text_value("José")); - assert_eq!(value(&s, "B"), text_value("€ 5 – “Café”")); - import(&mut s, "name,City\nC,José\n".as_bytes()).unwrap(); - assert_eq!(value(&s, "C"), text_value("José")); - import(&mut s, "\u{feff}name,City\nD,Zoë\n".as_bytes()).unwrap(); - assert_eq!(value(&s, "D"), text_value("Zoë")); - let e = import(&mut s, b"\xef\xbb\xbfname,City\nE,Jos\xe9\n").unwrap_err().to_string(); + let imp = import(&mut s, b"City\r\nJos\xe9\r\n\x80 5 \x96 \x93Caf\xe9\x94\r\n").unwrap(); + assert_eq!(imp["names"], json!(["Data Set 1", "Data Set 2"])); + assert_eq!(value(&s, "Data Set 1"), text_value("José")); + assert_eq!(value(&s, "Data Set 2"), text_value("€ 5 – “Café”")); + import(&mut s, "City\nJosé\n".as_bytes()).unwrap(); + assert_eq!(value(&s, "Data Set 1"), text_value("José")); + import(&mut s, "\u{feff}City\nZoë\n".as_bytes()).unwrap(); + assert_eq!(value(&s, "Data Set 1"), text_value("Zoë")); + let e = import(&mut s, b"\xef\xbb\xbfCity\nJos\xe9\n").unwrap_err().to_string(); assert!(e.contains("CSV is not UTF-8"), "{e}"); - assert_eq!(value(&s, "E"), None); + assert_eq!(value(&s, "Data Set 1"), text_value("Zoë")); } /// A CSV that starts with a UTF-16 byte-order mark is read as UTF-16, and @@ -1858,24 +1967,24 @@ fn datasets_csv_reads_utf16_files() { let units = text.encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() }); bom.iter().copied().chain(units).collect() }; - import(&mut s, &utf16(b"\xff\xfe", "name\tCity\r\nA\tZoë 😀\r\n", true)).unwrap(); - assert_eq!(value(&s, "A"), text_value("Zoë 😀")); - import(&mut s, &utf16(b"\xfe\xff", "name,City\nB,José\n", false)).unwrap(); - assert_eq!(value(&s, "B"), text_value("José")); - let mut odd = utf16(b"\xff\xfe", "name,City\nC,x\n", true); + import(&mut s, &utf16(b"\xff\xfe", "City\r\nZoë 😀\r\n", true)).unwrap(); + assert_eq!(value(&s, "Data Set 1"), text_value("Zoë 😀")); + import(&mut s, &utf16(b"\xfe\xff", "City\nJosé\n", false)).unwrap(); + assert_eq!(value(&s, "Data Set 1"), text_value("José")); + let mut odd = utf16(b"\xff\xfe", "City\nx\n", true); odd.push(b'y'); let e = import(&mut s, &odd).unwrap_err().to_string(); assert!(e.contains("CSV is not UTF-16"), "{e}"); - let e = import(&mut s, &[b"\xff\xfe".as_slice(), "name,City\nD,".as_bytes(), b"\x00\xd8"].concat()).unwrap_err().to_string(); + let e = import(&mut s, &[b"\xff\xfe".as_slice(), "City\nAB,".as_bytes(), b"\x00\xd8"].concat()).unwrap_err().to_string(); assert!(e.contains("CSV is not UTF-16"), "{e}"); - let e = import(&mut s, &utf16(b"", "name,City\nE,x\n", true)).unwrap_err().to_string(); + let e = import(&mut s, &utf16(b"", "City\nx\n", true)).unwrap_err().to_string(); assert!(e.contains("CSV holds NUL bytes"), "{e}"); - assert_eq!((value(&s, "C"), value(&s, "D"), value(&s, "E")), (None, None, None)); - s.execute("dataset.new", &json!({"name": "F", "values": {"City": "a\u{0}b"}})).unwrap(); + assert_eq!(value(&s, "Data Set 1"), text_value("José"), "a refused file changes nothing"); + s.execute("dataset.set", &json!({"name": "Data Set 1", "values": {"City": "a\u{0}b"}})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - s.execute("dataset.delete", &json!({"names": ["F"]})).unwrap(); + s.execute("dataset.delete", &json!({"names": ["Data Set 1"]})).unwrap(); s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - assert_eq!(value(&s, "F"), text_value("a\u{0}b")); + assert_eq!(value(&s, "Data Set 1"), text_value("a\u{0}b")); } /// A data set of [`library`]: its name, and each variable's name with its paragraphs. @@ -1993,31 +2102,30 @@ fn a_variable_library_replaces_every_variable_and_data_set() { } /// An import or a library load that leaves the variables and data sets as they were (the same CSV -/// imported again, a row rewritten with its own values, the same library loaded again) records no -/// undo step: the step to redo stays, and the document stays unmodified. An import or load that -/// changes something is still one undo step. +/// imported again, the same rows tab-separated, the file Export Data Sets writes, the same library +/// loaded again) records no undo step: the step to redo stays, and the document stays unmodified. +/// An import or load that changes something is still one undo step. #[test] fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() { let mut s = session(); let t = text(&mut s, "Alice"); - let csv = "name,Name,#Shown\nA,Ann,true\nB,Bob,false\n"; + let csv = "Name,#Shown\nAnn,true\nBob,false\n"; s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - for csv in [csv, "name\tName\t#Shown\nB\tBob\tfalse\n", "Name,#Shown\nAnn,true\n"] { + let exported = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + for csv in [csv, "Name\t#Shown\nAnn\ttrue\nBob\tfalse\n", exported.as_str()] { super::select_with_a_step_to_redo(&mut s, &[t]); let before = super::history(&s); assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); let r = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); - if csv.starts_with("name") { - assert_eq!((super::history(&s), r["imported"].clone()), (before, json!(0)), "{csv}"); - } else { - // Without a name column the row is a new data set, which is a change. - assert_eq!((super::history(&s), r["imported"].clone()), ((before.0 + 1, 0, true), json!(1)), "{csv}"); - } + assert_eq!((super::history(&s), r["imported"].clone()), (before, json!(2)), "{csv}"); + } + // A file with one of the two rows replaces both data sets with one, which is a change. + for csv in ["Name,#Shown\nAnn,true\n", "Name\nCy\n"] { + super::select_with_a_step_to_redo(&mut s, &[t]); + let undo = super::history(&s).0; + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + assert_eq!(super::history(&s), (undo + 1, 0, true), "{csv}"); } - super::select_with_a_step_to_redo(&mut s, &[t]); - let undo = super::history(&s).0; - s.execute("dataset.import", &json!({"csv": "name,Name\nB,Cy\n"})).unwrap(); - assert_eq!(super::history(&s), (undo + 1, 0, true)); let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["Ann"])]), ("B", &[("Name", &["Bob"])])]); s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ae1a4f708e..bb2de38d61 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1792,8 +1792,8 @@ fn dataset_import_repeated_column_error_is_translated() { use vectorcraft_engine::{EngineError, Session}; let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); - let e = s.execute("dataset.import", &json!({"csv": "name,City,City\nR,Paris,Rome"})).unwrap_err(); - let want = "columns 2 and 3 both name the variable `City`"; + let e = s.execute("dataset.import", &json!({"csv": "City,City\nParis,Rome"})).unwrap_err(); + let want = "columns 1 and 2 both name the variable `City`"; assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); let e = e.to_string(); for code in COMPLETE_MESSAGES { @@ -1842,8 +1842,8 @@ fn dataset_export_limit_errors_are_translated() { use vectorcraft_engine::{EngineError, Session}; let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); - let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect(); - s.execute("dataset.import", &json!({"csv": format!("name,V1\n{rows}")})).unwrap(); + let rows = "x\n".repeat(1000); + s.execute("dataset.import", &json!({"csv": format!("V1\n{rows}")})).unwrap(); s.execute("dataset.new", &json!({"name": "Set 1001"})).unwrap(); let mut errors = vec![]; let e = s.execute("dataset.export", &json!({})).unwrap_err(); @@ -1906,8 +1906,8 @@ fn dataset_import_cell_errors_are_translated() { s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); let mut errors = vec![]; for (csv, want) in [ - ("name,Show\nX,maybe".to_string(), "line 2: value for `Show` must be true or false"), - (format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000)), "line 2: value for `Sales` is longer than 262144 bytes"), + ("Show\nmaybe".to_string(), "line 2: value for `Show` must be true or false"), + (format!("Sales\n\"{}\"", "1,".repeat(140_000)), "line 2: value for `Sales` is longer than 262144 bytes"), ] { let e = s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index ab89d2faf8..87aa5cd13f 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -429,23 +429,24 @@ mod tests { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); let t = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "x"})).unwrap()["id"].as_u64().unwrap(); - app.run("dataset.import", json!({"csv": "name,Name\nA,Ann\nB,Bob\n"})).unwrap(); + app.run("dataset.import", json!({"csv": "Name\nAnn\nBob\n"})).unwrap(); + let (a, b) = ("Data Set 1", "Data Set 2"); let message = |row: &str| format!("nothing in data set {row} was applied: no object is bound to a variable it has a value for"); - app.run("dataset.select", json!({"name": "A"})).unwrap(); - assert_eq!(app.ui.status, message("A")); + app.run("dataset.select", json!({"name": a})).unwrap(); + assert_eq!(app.ui.status, message(a)); app.run("dataset.next", json!({})).unwrap(); - assert_eq!(app.ui.status, message("B")); + assert_eq!(app.ui.status, message(b)); app.run("dataset.prev", json!({})).unwrap(); - assert_eq!(app.ui.status, message("A")); + assert_eq!(app.ui.status, message(a)); app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap(); - app.run("dataset.select", json!({"name": "B"})).unwrap(); + app.run("dataset.select", json!({"name": b})).unwrap(); assert_eq!(app.ui.status, ""); // Stepping to a data set that applies clears the message as well. for step in ["dataset.next", "dataset.prev"] { app.run("variable.unbind", json!({"variable": "Name", "ids": [t]})).unwrap(); - app.run("dataset.select", json!({"name": "A"})).unwrap(); - assert_eq!(app.ui.status, message("A")); + app.run("dataset.select", json!({"name": a})).unwrap(); + assert_eq!(app.ui.status, message(a)); app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap(); app.run(step, json!({})).unwrap(); assert_eq!(app.ui.status, "", "{step}"); diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 8608b7813f..574bb07b51 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -238,8 +238,8 @@ fn load_profile_asks_off_the_ui_thread() { } /// The Variables panel menu's Import Data Sets… and Export Data Sets… ask off the UI thread: the -/// data sets in the file picked are loaded, and the header and data set `B` are written to the -/// path the dialog answers. +/// data sets in the file picked are loaded, and the header and the data set's row are written to +/// the path the dialog answers. #[test] fn variables_panel_data_sets_ask_off_the_ui_thread() { let (mut app, shown, _) = app(); @@ -250,20 +250,20 @@ fn variables_panel_data_sets_ask_off_the_ui_thread() { } std::fs::create_dir_all(&dir).unwrap(); let (csv, out) = (dir.join("sets.csv"), dir.join("out.csv")); - std::fs::write(&csv, "name,Name\nB,y\n").unwrap(); + std::fs::write(&csv, "Name\ny\n").unwrap(); let sets = |app: &VectorcraftApp| app.session.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect::>(); click(&mut app, "Import Data Sets…", crate::panels::variables::menu); assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)])); shown.answer(&[&csv.to_string_lossy()]); poll(&mut app); - assert_eq!(sets(&app), ["B"], "{}", app.ui.status); + assert_eq!(sets(&app), ["Data Set 1"], "{}", app.ui.status); click(&mut app, "Export Data Sets…", crate::panels::variables::menu); assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)])); shown.answer(&[&out.to_string_lossy()]); poll(&mut app); - assert_eq!(std::fs::read_to_string(&out).ok().as_deref(), Some("name,Name\nB,y\n"), "{}", app.ui.status); + assert_eq!(std::fs::read_to_string(&out).ok().as_deref(), Some("Name\ny\n"), "{}", app.ui.status); let _ = std::fs::remove_dir_all(dir); } diff --git a/docs/mcp.md b/docs/mcp.md index 55a58ec79c..6878e137b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1684,10 +1684,13 @@ already walks Image Trace. Short agent entry points: renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv}` / - `dataset.export {path?}` (CSV: `name`, then one column per variable). `dataset.import` also reads tab-separated - files, and files whose first header cell isn't `name`: every header cell is then a variable, and the rows take the - first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file - line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the + `dataset.export {path?}` (CSV: one column per variable, and no column of data set names). `dataset.import` also + reads tab-separated files. Every header cell is a variable, whatever its case (`name` and `Name` included), as the + [set-up page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/set-up-data-source-files.html) + describes the first row: "Specify your data field name in the first row of your spreadsheet." The rows replace every + data set of the document and are named `Data Set 1`, `Data Set 2` and so on, in file order; the document's variables + and their bindings stay, and the reply's `deletedDataSets` lists the data sets that were replaced. An import error + about a row's values gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image variable's as `@Photo`, and a text or graph variable's as its name alone. Its reply's `warning` names the variables diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 755c57da56..7d526a04a8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -572,7 +572,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone; every command, like the rest, is drivable over MCP and the CLI. - - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones, and files without a `name` column, whose rows take the first free names Data Set 1, Data Set 2 and so on. An import error about a row's values or name gives the file line the row starts on. + - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones. Every header cell is a variable, and the rows replace the document's data sets as Data Set 1, Data Set 2 and so on. An import error about a row's values gives the file line the row starts on. - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every variable is deleted with its bindings and values, and every data set is deleted; then the library's text variables are defined, unbound, and its data sets take the text of each value's `p` elements, one paragraph each. Variables of other kinds are left out with a warning that names their kinds. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's text variables and data sets as a variable library's XML file, which Load Variable Library reads back with the same text variables, data set names and text values. Variables of other kinds are left out with a warning that names their kinds. From e1ea0ecad1cd4a2555fbf863c80584f824f21cea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:38:36 +0700 Subject: [PATCH 358/674] Type: the caret, a click and the arrow keys reach the characters inside a ligature Squashed from #5225 onto main. --- crates/engine/src/tests/textedit.rs | 22 + crates/text/src/fontdb/face.rs | 66 +++ crates/text/src/layout.rs | 84 +++- crates/text/src/layout/driver.rs | 2 + crates/text/src/layout/ruby.rs | 3 + crates/text/src/layout/vertical.rs | 14 + crates/text/src/lib.rs | 132 +++++- crates/text/src/test_fonts.rs | 189 +++++++++ crates/text/src/tests.rs | 1 + crates/text/src/tests/bidi.rs | 3 + crates/text/src/tests/ligature_carets.rs | 498 +++++++++++++++++++++++ docs/target-app-parity.md | 1 + 12 files changed, 997 insertions(+), 18 deletions(-) create mode 100644 crates/text/src/tests/ligature_carets.rs diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index c6c3587b49..2cdf299ce8 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1257,6 +1257,28 @@ fn type_tool_selection_replace_and_delete() { assert_eq!(obj(&s, id).plain_text(), " "); } +/// A Type tool click inside a ligature (Source Serif 4's fi) puts the caret between its +/// characters, and Shift+Right from there selects the i alone. +#[test] +fn type_tool_click_reaches_the_inside_of_a_ligature() { + let mut s = session(); + let v = ViewInfo::default(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "fin", "size": 40, "font": "Source Serif 4"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.select_tool("type", v).unwrap(); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let g = lay.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph"); + let (_, f) = g.carets[0]; + let p = t.xf * (g.origin + vectorcraft_geom::Vec2::new(g.advance * f + 0.2, -10.0)); + click(&mut s, p.x, p.y); + assert_eq!(s.tool_options()["caret"], json!(1), "between the f and the i"); + key(&mut s, ToolKey::Right, Mods { shift: true, ..Default::default() }); + assert_eq!((s.tool_options()["start"].as_u64(), s.tool_options()["end"].as_u64()), (Some(1), Some(2))); + s.tool_text("I", v).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "fIn"); +} + #[test] fn character_panel_flow_styles_the_selected_range_while_editing() { let mut s = session(); diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 0df8c2e333..506c3b1bf1 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -239,6 +239,72 @@ impl FontFace { .map(|a| a as f64) .unwrap_or(self.upem * 0.5) } + /// The coordinates of the carets inside ligature glyph `gid`, in font units, in the order the + /// font lists them: the font's ligature caret list (`GDEF` `LigCaretList`, + /// ), one between each two + /// characters the glyph stands for, each an x in horizontal text and a y (up from the baseline) + /// in vertical text. A coordinate with a variation index (format 3 in a variable font) takes its + /// delta from the `GDEF` item variation store at the face's location; a device table's + /// adjustments for pixel sizes are not applied. `None` when the font lists no carets for the + /// glyph, lists a number other than `count`, gives one by a contour point, or gives one a + /// variation index whose delta can't be read. + fn ligature_caret_coordinates(&self, gid: u32, count: usize) -> Option> { + use skrifa::raw::TableProvider; + use skrifa::raw::tables::gdef::CaretValue; + use skrifa::raw::tables::layout::DeviceOrVariationIndex; + use skrifa::raw::tables::variations::DeltaSetIndex; + let font = self.skrifa()?; + let gdef = font.gdef().ok()?; + let list = gdef.lig_caret_list()?.ok()?; + let index = list.coverage().ok()?.get(GlyphId::new(gid))?; + let glyph = list.lig_glyphs().get(usize::from(index)).ok()?; + if usize::from(glyph.caret_count()) != count { + return None; + } + let carets = glyph + .caret_values() + .iter() + .map(|c| match c.ok()? { + CaretValue::Format1(v) => Some(f64::from(v.coordinate())), + CaretValue::Format3(v) => { + let coordinate = f64::from(v.coordinate()); + if v.device_offset().is_null() { + return Some(coordinate); + } + match v.device().ok()? { + DeviceOrVariationIndex::Device(_) => Some(coordinate), + DeviceOrVariationIndex::VariationIndex(ix) => { + let store = gdef.item_var_store()?.ok()?; + let index = DeltaSetIndex { outer: ix.delta_set_outer_index(), inner: ix.delta_set_inner_index() }; + Some(coordinate + store.compute_delta(index, self.location.coords()).ok()?.to_f64()) + } + } + } + CaretValue::Format2(_) => None, + }) + .collect::>>()?; + (!carets.is_empty()).then_some(carets) + } + /// The caret positions inside ligature glyph `gid` set across, in font units from its left + /// edge, left to right: the x coordinates of the font's ligature caret list. `None` when the + /// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour + /// point, or gives positions that are not increasing inside the glyph's advance. + pub fn ligature_carets(&self, gid: u32, count: usize) -> Option> { + let carets = self.ligature_caret_coordinates(gid, count)?; + let advance = self.advance(gid); + let inside = carets.iter().all(|x| *x > 0.0 && *x < advance) && carets.windows(2).all(|w| w[0] < w[1]); + inside.then_some(carets) + } + /// The caret positions inside ligature glyph `gid` standing upright in vertical type, in font + /// units down from the top of its cell, top to bottom: the y coordinates of the font's ligature + /// caret list, for a cell `cell` long whose top is `top` above the baseline. `None` when the + /// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour + /// point, or gives positions that are not increasing inside the cell. + pub fn vertical_ligature_carets(&self, gid: u32, count: usize, top: f64, cell: f64) -> Option> { + let carets = self.ligature_caret_coordinates(gid, count)?; + let inside = carets.iter().all(|y| *y < top && *y > top - cell) && carets.windows(2).all(|w| w[0] < w[1]); + inside.then(|| carets.iter().rev().map(|y| top - y).collect()) + } /// Glyph `gid` set upright in vertical type, from the font's vertical metrics: (its advance down /// the column, the height above the baseline of its vertical origin, the top of its cell), in /// font units. The origin is the `VORG` table's, else the glyph's top plus its top side bearing. diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 67b5c3c7c7..cbdd41725c 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -37,7 +37,7 @@ use breaking::tab_advance; #[cfg(test)] use breaking::{break_line, candidates}; pub use driver::{decorations, fit_first_line, layout, layout_with, scaled}; -use vertical::{TcyStyle, stands_upright, tate_chu_yoko, upright_cell, upright_centre, whole_character_widths}; +use vertical::{TcyStyle, stands_upright, tate_chu_yoko, upright_cell, upright_centre, upright_extent, whole_character_widths}; const EPS: f64 = 1e-6; @@ -47,6 +47,60 @@ fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool { prev.zip(g).is_some_and(|(a, b)| a.len > 0 && b.len > 0 && a.byte == b.byte) } +/// The caret stops inside glyph `g` when it alone stands for several characters (grapheme clusters) +/// of `text`, a ligature ([`PositionedGlyph::carets`]); `rtl` when its logical leading edge is its +/// right edge; `upright` when it stands upright in vertical type, its carets then down its cell +/// ([`upright_extent`]). Empty for a glyph of one character. +fn ligature_carets(text: &str, g: &SGlyph, rtl: bool, upright: bool) -> Vec<(usize, f64)> { + use unicode_segmentation::UnicodeSegmentation; + let Some(s) = text.get(g.byte..g.byte + g.len).filter(|_| g.len > 1) else { return Vec::new() }; + let starts: Vec = s.grapheme_indices(true).skip(1).map(|(i, _)| g.byte + i).collect(); + if starts.is_empty() { + return Vec::new(); + } + let parts = starts.len() + 1; + let from_font = if upright { + let (cell, top) = upright_extent(g); + g.face + .vertical_ligature_carets(g.gid, starts.len(), top, cell) + .filter(|c| c.len() == starts.len() && cell > 0.0) + .map(|c| c.into_iter().map(|d| d / cell).collect::>()) + } else { + let advance = g.face.advance(g.gid); + g.face + .ligature_carets(g.gid, starts.len()) + .filter(|c| c.len() == starts.len() && advance > 0.0) + .map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::>()) + }; + let mut at = from_font.unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect()); + at.sort_by(f64::total_cmp); + starts.into_iter().zip(at).collect() +} + +/// Does glyph `g`, standing upright in vertical type, take a cell of its own down the column? Every +/// glyph with an advance does, including one whose tracking or kerning makes its advance zero or +/// negative; a glyph without a font advance (a mark) does not. +fn takes_cell(g: &SGlyph) -> bool { + g.adv > 0.0 || g.face.advance(g.gid) > 0.0 +} + +/// Clear the caret stops of each glyph that shares its cluster with another glyph: only a glyph +/// that alone stands for its characters is a ligature. +fn keep_lone_ligature_carets(glyphs: &mut [PositionedGlyph]) { + if glyphs.iter().all(|g| g.carets.is_empty()) { + return; + } + let mut count: std::collections::HashMap<(usize, usize), usize> = std::collections::HashMap::new(); + for g in glyphs.iter().filter(|g| g.len > 0) { + *count.entry((g.byte, g.len)).or_default() += 1; + } + for g in glyphs.iter_mut().filter(|g| !g.carets.is_empty()) { + if count.get(&(g.byte, g.len)).is_some_and(|n| *n > 1) { + g.carets.clear(); + } + } +} + struct Ctx<'a> { on_path: bool, db: &'a FontDb, @@ -278,7 +332,7 @@ impl Ctx<'_> { // the middle of its own cell, not of its advance (tracking and justification add // space after the cell, and must not push the glyph off the centre line). let em = self.style_at(g.byte).size; - let cell = if g.adv > 0.0 { upright_cell(g) } else { advance }; + let cell = if takes_cell(g) { upright_cell(g) } else { advance }; // A leading space taken off moves it up the column after the turn (moving the // turning point instead would move it across the column too). let turn = Affine::translate((-g.lead, 0.0)) @@ -300,6 +354,29 @@ impl Ctx<'_> { p }; let font_id = g.face.id(); + // Its own width along the baseline: its font advance through its size, scale and the glyph + // scaling `pre` adds. In vertical type, an upright glyph's own length down the column is + // its cell with the Proportional Metrics change to it, and a tate-chu-yoko glyph takes its + // advance, as an inline graphic does. + let upright = self.vertical && g.inline.is_none() && g.tcy.is_none() && takes_cell(g) && stands_upright(g); + let width = if g.inline.is_some() || (self.vertical && g.tcy.is_some()) { + advance + } else if upright { + let proportional = g.vpal.filter(|_| g.face.vertical_glyph(g.gid).is_some()).map_or(0.0, |a| a.advance); + Some(upright_cell(g) + proportional).filter(|w| w.is_finite() && *w > 0.0).unwrap_or(advance) + } else { + let [a, b, ..] = pre.as_coeffs(); + Some(g.face.advance(g.gid) * g.sx * a.hypot(b)).filter(|w| w.is_finite()).unwrap_or(advance) + }; + // Where its own width starts along its advance: the shaper's placement, a leading space + // taken off and right-to-left manual kerning move the glyph along the line. An upright or + // tate-chu-yoko glyph in vertical type starts its cell at the start of its advance. + let width_start = if g.inline.is_none() && !upright && !(self.vertical && g.tcy.is_some()) { + let [a, b, ..] = pre.as_coeffs(); + Some((g.kern_shift + g.dx - g.lead) * a.hypot(b)).filter(|s| s.is_finite()).unwrap_or(0.0) + } else { + 0.0 + }; if let Some(art) = g.inline.as_ref().and_then(|ib| ib.art) { self.out.inlines.push(InlineGlyph { run: g.run, byte: g.byte, glyph: self.out.glyphs.len(), xf: m, bounds: m.transform_rect_bbox(art) }); } @@ -323,6 +400,9 @@ impl Ctx<'_> { bend: None, unturned, pivot, + carets: if g.inline.is_some() { Vec::new() } else { ligature_carets(self.text, g, g.level.is_rtl() && !self.vertical, upright) }, + width, + width_start, }); } diff --git a/crates/text/src/layout/driver.rs b/crates/text/src/layout/driver.rs index 0b76f2c5ac..01fef17656 100644 --- a/crates/text/src/layout/driver.rs +++ b/crates/text/src/layout/driver.rs @@ -5,6 +5,7 @@ use super::ruby::ruby_layout; use super::vertical::{EM_CENTER, QUARTER_TURN, align_vertically, finish_bounds}; use super::{ Affine, BezPath, CharStyle, Ctx, FontDb, LayoutOptions, OtFeatures, Point, Rect, Shape, TextKind, TextLayout, TextObject, VerticalAlign, + keep_lone_ligature_carets, }; /// Lay out a text object into text-space glyph outlines (default [`LayoutOptions`]). @@ -305,6 +306,7 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout cx.out.vertical = true; cx.out.line_xf = line_xf; } + keep_lone_ligature_carets(&mut cx.out.glyphs); finish_bounds(&mut cx.out); cx.out } diff --git a/crates/text/src/layout/ruby.rs b/crates/text/src/layout/ruby.rs index 59ce52c4ca..1cf34e24ce 100644 --- a/crates/text/src/layout/ruby.rs +++ b/crates/text/src/layout/ruby.rs @@ -369,5 +369,8 @@ fn ruby_glyph(g: &PositionedGlyph, m: Affine, run: usize, byte: usize, line: usi bend: None, unturned: Affine::IDENTITY, pivot: m * g.origin, + carets: Vec::new(), + width: 0.0, + width_start: 0.0, } } diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index e571953d8b..8f01a5d32b 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -206,6 +206,20 @@ pub(super) fn upright_cell(g: &SGlyph) -> f64 { } } +/// An upright glyph's cell in font units, as [`upright_cell`] and [`upright_centre`] place it before +/// its size: (its length down the column, the height of its top above the baseline). From the +/// font's vertical metrics, else at least one em long, centred on the ideographic em box. +pub(super) fn upright_extent(g: &SGlyph) -> (f64, f64) { + match g.face.vertical_glyph(g.gid) { + Some((advance, origin)) => (advance, origin), + None => { + let em = g.face.units_per_em(); + let cell = g.face.advance(g.gid).max(em); + (cell, EM_CENTER * em + cell * 0.5) + } + } +} + /// Height above the baseline (line space) of the centre of an upright glyph's `cell`, the point it /// turns about: from the font's vertical metrics, the cell hanging from the glyph's vertical origin; /// else the centre of the ideographic em box ([`EM_CENTER`] of the size `em`). diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index a1b77e02aa..bafaf70af0 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -149,6 +149,25 @@ pub struct PositionedGlyph { /// Font units: `xf * pivot` is the point its Character Rotation turns it about, its pen /// position on the baseline moved by its baseline shift. pub pivot: Point, + /// A ligature (one glyph that alone stands for several characters, grapheme clusters, of the + /// text): the caret stop between each two of them, in logical order, as the byte offset of the + /// later character and how far the caret stands along the glyph's own width ([`Self::width`]) + /// from its logical leading edge, 0 to 1. The font's ligature carets + /// ([`FontFace::ligature_carets`], or [`FontFace::vertical_ligature_carets`] for a glyph + /// standing upright in vertical type) when it lists one for each stop, else the width divided + /// equally among the characters. Empty for any other glyph. + pub carets: Vec<(usize, f64)>, + /// The glyph's own width along its advance in text space: its font advance at its size, + /// Horizontal Scale and glyph scaling, without the tracking, kerning, justification space and + /// kashida that [`Self::advance`] includes after it (to its right in horizontal type). The + /// advance itself in vertical type. + pub width: f64, + /// How far right of the left end of its advance the glyph's own width ([`Self::width`]) starts, + /// in text space: the font's placement of the glyph (`GPOS` x placement), less a leading space + /// taken off, plus the manual kerning of right-to-left text, which moves the glyph right so that + /// the space it adds lies on the glyph's left. 0 for a glyph standing upright or set across the + /// column in vertical type, and for an inline graphic. + pub width_start: f64, } /// How a glyph on a path is bent along it: a point of its pen space (x along its advance from its @@ -167,6 +186,57 @@ pub struct GlyphBend { } impl PositionedGlyph { + /// The glyph's caret stops in logical order: its first byte, its ligature carets + /// ([`Self::carets`]) and its end, each with how far along its own width ([`Self::width`]) from + /// its logical leading edge the caret stands, 0 to 1. + fn width_stops(&self) -> impl Iterator + '_ { + std::iter::once((self.byte, 0.0)).chain(self.carets.iter().copied()).chain(std::iter::once((self.byte + self.len, 1.0))) + } + /// The glyph's caret stops in logical order, each with its distance in text space from the + /// logical leading edge of a span `extent` long that holds the glyph (its advance, or its + /// cluster's): 0 at its first byte and `extent` at its end. A ligature caret stands at its place + /// in the glyph's own width ([`Self::width`]), which starts [`Self::width_start`] right of the + /// glyph's left edge; the rest of the space the advance adds lies to the right of that width, + /// after the last ligature caret left to right, and before the first one right to left. + /// Negative kerning or tracking makes the advance shorter than the width, or zero or negative, + /// and a ligature caret then stands past the end of the advance. + fn stops_along(&self, extent: f64) -> impl Iterator + '_ { + let (width, start) = if self.width > 0.0 && self.width.is_finite() { + (self.width, if self.width_start.is_finite() { self.width_start } else { 0.0 }) + } else { + (extent, 0.0) + }; + let ends = (self.byte, self.byte + self.len); + self.width_stops().map(move |(b, f)| { + if b == ends.0 { + (b, 0.0) + } else if b == ends.1 { + (b, extent) + } else if self.rtl { + (b, extent - start - (1.0 - f) * width) + } else { + (b, start + f * width) + } + }) + } + /// The distance in text space from the logical leading edge of a span `extent` long that holds + /// the glyph (its advance, or its cluster's) to the caret for byte `byte`: 0 at its first byte, + /// `extent` at its end, a ligature caret's place at that caret's byte ([`Self::stops_along`], + /// which can lie outside 0 to `extent`), and in proportion to the bytes between two stops. + pub fn caret_offset(&self, byte: usize, extent: f64) -> f64 { + if byte <= self.byte || self.len == 0 { + return 0.0; + } + let mut from = (self.byte, 0.0); + for (b, d) in self.stops_along(extent).skip(1) { + if byte <= b { + let span = b.saturating_sub(from.0).max(1) as f64; + return from.1 + (d - from.1) * (byte - from.0) as f64 / span; + } + from = (b, d); + } + extent + } /// The glyph's colour bitmap, and the transform from its pixels to text space. pub fn placed_image(&self) -> Option<(&Arc, Affine)> { self.image.as_ref().map(|i| (i, self.xf * i.xf)) @@ -436,7 +506,8 @@ fn cluster_extent(layout: &TextLayout, glyphs: &[PositionedGlyph], i: usize) -> } /// Caret for byte offset `byte`, as a (top, bottom) segment in text space. In horizontal type, a -/// cluster drawn with several glyphs is measured whole ([`cluster_extent`]). +/// cluster drawn with several glyphs is measured whole ([`cluster_extent`]). Inside a ligature the +/// caret stands at its caret stops ([`PositionedGlyph::carets`]). pub fn caret_position(layout: &TextLayout, byte: usize) -> (Point, Point) { let Some(line) = layout.lines.get(layout.line_of(byte)) else { return (Point::ZERO, Point::ZERO); @@ -444,12 +515,12 @@ pub fn caret_position(layout: &TextLayout, byte: usize) -> (Point, Point) { let glyphs = &layout.glyphs[line.glyph_start..line.glyph_end]; let (pos, angle) = if let Some(i) = glyphs.iter().position(|g| g.byte <= byte && g.byte + g.len > byte) { let g = &glyphs[i]; - let frac = if byte <= g.byte { 0.0 } else { (byte - g.byte) as f64 / g.len.max(1) as f64 }; let (origin, advance) = match cluster_extent(layout, glyphs, i) { Some((left, right)) => (Point::new(left, g.origin.y), right - left), None => (g.origin, g.advance), }; - (origin + dir(g.angle) * (advance * if g.rtl { 1.0 - frac } else { frac }), g.angle) + let off = g.caret_offset(byte, advance); + (origin + dir(g.angle) * if g.rtl { advance - off } else { off }, g.angle) } else if let Some(g) = glyphs.iter().max_by_key(|g| g.byte + g.len) { (g.origin + dir(g.angle) * if g.rtl { 0.0 } else { g.advance }, g.angle) } else { @@ -464,11 +535,16 @@ pub fn caret_position(layout: &TextLayout, byte: usize) -> (Point, Point) { /// Byte offset nearest to the text-space point `p` (for clicking/dragging with the Type tool). pub fn hit_byte(layout: &TextLayout, p: Point) -> usize { if layout.on_path { - let best = layout.glyphs.iter().enumerate().min_by(|(_, a), (_, b)| { - let ca = a.origin + dir(a.angle) * (a.advance * 0.5); - let cb = b.origin + dir(b.angle) * (b.advance * 0.5); - (p - ca).hypot2().total_cmp(&(p - cb).hypot2()) - }); + // The distance from `p` to a glyph's middle, or to one of its inner ligature caret stops + // when that is nearer (a stop can lie past the glyph's advance). + let near = |g: &PositionedGlyph| { + let along = dir(g.angle); + let mid = (p - (g.origin + along * (g.advance * 0.5))).hypot2(); + (g.stops_along(g.advance).filter(|(b, _)| *b != g.byte && *b != g.byte + g.len)) + .map(|(_, d)| (p - (g.origin + along * if g.rtl { g.advance - d } else { d })).hypot2()) + .fold(mid, f64::min) + }; + let best = layout.glyphs.iter().enumerate().min_by(|(_, a), (_, b)| near(a).total_cmp(&near(b))); let Some((i, g)) = best else { return layout.lines.first().map_or(0, |l| l.start) }; // `first` and `last` are the first and last glyphs of the cluster. A click before the middle of // the cluster, measured along the first glyph's direction, goes to the cluster's start. @@ -476,6 +552,14 @@ pub fn hit_byte(layout: &TextLayout, p: Point) -> usize { let first = layout.glyphs[..=i].iter().rev().take_while(same).last().unwrap_or(g); let last = layout.glyphs[i..].iter().take_while(same).last().unwrap_or(g); let along = dir(first.angle); + if !g.carets.is_empty() { + // A ligature: the nearest of its caret stops, measured along it from its logical + // leading edge in text space, within the span its stops cover. + let (lo, hi) = g.stops_along(g.advance).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), (_, d)| (lo.min(d), hi.max(d))); + let t = (p - g.origin).dot(along); + let at = (if g.rtl { g.advance - t } else { t }).max(lo).min(hi); + return g.stops_along(g.advance).min_by(|a, b| (a.1 - at).abs().total_cmp(&(b.1 - at).abs())).map_or(g.byte, |s| s.0); + } let span = (last.origin + dir(last.angle) * last.advance - first.origin).dot(along); return if ((p - first.origin).dot(along) < span * 0.5) != g.rtl { g.byte } else { g.byte + g.len }; } @@ -517,7 +601,8 @@ pub fn byte_in_line(layout: &TextLayout, li: usize, x: f64) -> usize { // a consonant and its reph) has one caret stop at each end of its glyphs taken together. The // tatweels of a kashida have no source length or advance and come after the glyphs of the // letter after the kashida in the text; they belong to that letter's cluster. A list marker's - // glyphs (no source length, an advance) are a cluster of their own. + // glyphs (no source length, an advance) are a cluster of their own. A ligature also has a stop + // at each of its caret stops. let mut clusters: Vec<(f64, f64, &PositionedGlyph)> = Vec::with_capacity(glyphs.len()); for g in glyphs { let left = layout.logical_point(g.origin).x; @@ -529,7 +614,7 @@ pub fn byte_in_line(layout: &TextLayout, li: usize, x: f64) -> usize { } let nearest = clusters .iter() - .flat_map(|&(left, right, g)| if g.rtl { [(right, g.byte), (left, g.byte + g.len)] } else { [(left, g.byte), (right, g.byte + g.len)] }) + .flat_map(|&(left, right, g)| g.stops_along(right - left).map(move |(b, d)| (if g.rtl { right - d } else { left + d }, b))) .min_by(|a, b| (a.0 - x).abs().total_cmp(&(b.0 - x).abs())); nearest.map_or(line.start, |(_, byte)| byte) } @@ -562,9 +647,9 @@ fn x_in_line(layout: &TextLayout, li: usize, byte: usize) -> f64 { let glyphs = &layout.glyphs[line.glyph_start..line.glyph_end]; if let Some(i) = glyphs.iter().position(|g| g.byte <= byte && g.byte + g.len > byte) { let g = &glyphs[i]; - let frac = if byte <= g.byte { 0.0 } else { (byte - g.byte) as f64 / g.len.max(1) as f64 }; let (left, advance) = cluster_extent(layout, glyphs, i).map_or((layout.logical_point(g.origin).x, g.advance), |(l, r)| (l, r - l)); - return left + advance * if g.rtl { 1.0 - frac } else { frac }; + let off = g.caret_offset(byte, advance); + return left + if g.rtl { advance - off } else { off }; } glyphs.iter().max_by_key(|g| g.byte + g.len).map_or(line.x0, |g| layout.logical_point(g.origin).x + if g.rtl { 0.0 } else { g.advance }) } @@ -592,13 +677,25 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4 if a == b { return out; } + // The part of glyph `g` that the selection covers, as distances in text space from its left + // (its start along a path), the smaller first: all of its advance, or the characters of a + // ligature that are selected. A ligature caret past a shortened advance lies outside it. + let covered = |g: &PositionedGlyph| { + if g.len == 0 { + return (g.advance.min(0.0), g.advance.max(0.0)); + } + let (fa, fb) = (g.caret_offset(a.max(g.byte), g.advance), g.caret_offset(b.min(g.byte + g.len), g.advance)); + let (f0, f1) = if g.rtl { (g.advance - fb, g.advance - fa) } else { (fa, fb) }; + (f0.min(f1), f0.max(f1)) + }; if layout.on_path { // A list marker's glyphs stand for no characters. - for g in layout.glyphs.iter().filter(|g| g.byte >= a && g.byte < b && g.len > 0) { + for g in layout.glyphs.iter().filter(|g| g.byte < b && g.byte + g.len > a && g.len > 0) { let li = &layout.lines[0]; let d = dir(g.angle); let up = Vec2::new(d.y, -d.x); - let (p0, p1) = (g.origin, g.origin + d * g.advance); + let (f0, f1) = covered(g); + let (p0, p1) = (g.origin + d * f0, g.origin + d * f1); out.push([p0 + up * li.ascent, p1 + up * li.ascent, p1 - up * li.descent, p0 - up * li.descent]); } return out; @@ -609,7 +706,8 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4 for (_, g) in glyphs { let Some(l) = layout.lines.get(g.line) else { continue }; let p = layout.logical_point(g.origin); - let (x0, x1) = (p.x, p.x + g.advance); + let (f0, f1) = covered(g); + let (x0, x1) = (p.x + f0, p.x + f1); out.push( [ Point::new(x0, l.baseline - l.ascent), @@ -636,6 +734,8 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4 let last = layout.glyphs[l.glyph_start..l.glyph_end].last().map_or(l.x1, |g| layout.logical_point(g.origin).x + g.advance); xb = last.max(l.x1) + (l.ascent + l.descent) * 0.25; } + // A ligature caret past the ligature's shortened advance stands right of the glyph's end. + let (xa, xb) = (xa.min(xb), xa.max(xb)); if xb - xa <= 1e-9 { continue; } @@ -678,7 +778,7 @@ fn caret_horizontal_filtered(layout: &TextLayout, byte: usize, right: bool, vali (layout.logical_point(caret_position(layout, b).0).x, if rtl { -(b as f64) } else { b as f64 }) }; let (x, order) = stop(byte); - let mut stops: Vec<_> = glyphs.iter().flat_map(|g| [g.byte, g.byte + g.len]).collect(); + let mut stops: Vec<_> = glyphs.iter().flat_map(|g| g.width_stops().map(|(b, _)| b)).collect(); stops.sort_unstable(); stops.dedup(); stops diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index a4e0fcde6a..2a6072762c 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -489,6 +489,195 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option> { Some(builder.build()) } +/// The family of [`ligature_caret_font`]. +pub const LIGATURE_CARET_FAMILY: &str = "Carettest Sans"; + +/// The glyph [`ligature_caret_font`]'s `liga` gives for f + i: W, wider than either letter. +pub const LIGATURE_CARET_GLYPH: char = 'W'; + +/// A test-only cmap over bundled Source Sans 3 for f, i and the space, whose `GSUB` `liga` joins f + +/// i into [`LIGATURE_CARET_GLYPH`]. With `caret`, a `GDEF` ligature caret list puts that glyph's one +/// caret at x = `caret` font units; without it the font has no `GDEF` table. `None` when it can't be +/// built. +pub fn ligature_caret_font(caret: Option) -> Option> { + use write_fonts::tables::cmap::Cmap; + use write_fonts::tables::gdef::{CaretValue, Gdef, LigCaretList, LigGlyph}; + use write_fonts::tables::gsub::{Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SubstitutionLookup, SubstitutionLookupList}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mapping = [('f', 'f'), ('i', 'i'), (' ', ' ')]; + let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; + let family = LIGATURE_CARET_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Carettest Sans Regular"), (6, "CarettestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let ligature = gid(LIGATURE_CARET_GLYPH)?; + let subst = LigatureSubstFormat1::new( + CoverageFormat1::new(vec![gid('f')?]).into(), + vec![LigatureSet::new(vec![Ligature::new(ligature, vec![gid('i')?])])], + ); + let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"liga"), Feature::new(None, vec![0]))]); + let lookups = SubstitutionLookupList::new(vec![SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![subst]))]); + let langsys = || Script::new(Some(LangSys::new(vec![0])), vec![]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), langsys()), ScriptRecord::new(Tag::new(b"latn"), langsys())]); + builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?; + if let Some(x) = caret { + let carets = LigCaretList::new(CoverageFormat1::new(vec![ligature]).into(), vec![LigGlyph::new(vec![CaretValue::format_1(x)])]); + builder.add_table(&Gdef::new(None, None, Some(carets), None)).ok()?; + } + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GDEF") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`vertical_ligature_caret_font`]. +pub const VERTICAL_LIGATURE_CARET_FAMILY: &str = "Vertical Carettest Sans"; + +/// [`ligature_caret_font`] with its one caret at y = `caret` font units, as family +/// [`VERTICAL_LIGATURE_CARET_FAMILY`], with vertical metrics (`vhea`, `vmtx` and `VORG`): every glyph +/// one em down the column with its vertical origin at 0.88 em. `None` when it can't be built. +pub fn vertical_ligature_caret_font(caret: i16) -> Option> { + let base = ligature_caret_font(Some(caret))?; + let font = skrifa::FontRef::new(&base).ok()?; + let n = font.maxp().ok()?.num_glyphs(); + let be16 = |v: &mut Vec, x: i16| v.extend_from_slice(&x.to_be_bytes()); + // vmtx: (advance height, top side bearing) for every glyph; VORG gives the origin. + let mut vmtx = Vec::with_capacity(4 * usize::from(n)); + for _ in 0..n { + vmtx.extend_from_slice(&1000_u16.to_be_bytes()); + be16(&mut vmtx, 0); + } + // vhea 1.1: ascent/descent of the em box across the column, then the metrics' count. + let mut vhea = Vec::with_capacity(36); + vhea.extend_from_slice(&0x0001_1000_u32.to_be_bytes()); + for x in [500, -500, 0] { + be16(&mut vhea, x); + } + vhea.extend_from_slice(&1000_u16.to_be_bytes()); + for x in [0, 0, 1000, 1, 0, 0, 0, 0, 0, 0, 0] { + be16(&mut vhea, x); + } + vhea.extend_from_slice(&n.to_be_bytes()); + // VORG 1.0: the default origin and no glyph that differs. + let mut vorg = Vec::new(); + for x in [1, 0, 880, 0] { + be16(&mut vorg, x); + } + let family = VERTICAL_LIGATURE_CARET_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Vertical Carettest Sans Regular"), (6, "VerticalCarettestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + builder.add_raw(Tag::new(b"vhea"), vhea); + builder.add_raw(Tag::new(b"vmtx"), vmtx); + builder.add_raw(Tag::new(b"VORG"), vorg); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`variable_ligature_caret_font`]. +pub const VARIABLE_LIGATURE_CARET_FAMILY: &str = "Varicaret Sans"; + +/// [`ligature_caret_font`] as a variable font of family [`VARIABLE_LIGATURE_CARET_FAMILY`]: one +/// weight axis (400–700, default 400) with the named instances Regular (400) and Bold (700), and a +/// `GDEF` ligature caret list whose one caret is a format 3 value at x = `caret` font units with a +/// variation index into the `GDEF` item variation store that moves it by `delta` at 700. `None` +/// when it can't be built. +pub fn variable_ligature_caret_font(caret: i16, delta: i16) -> Option> { + use write_fonts::tables::gdef::{CaretValue, Gdef, LigCaretList, LigGlyph}; + use write_fonts::tables::layout::{CoverageFormat1, DeviceOrVariationIndex}; + use write_fonts::tables::variations::{ItemVariationData, ItemVariationStore, RegionAxisCoordinates, VariationRegion, VariationRegionList}; + use write_fonts::types::GlyphId16; + + let base = ligature_caret_font(None)?; + let font = skrifa::FontRef::new(&base).ok()?; + let ligature = GlyphId16::new(source_sans_gid(LIGATURE_CARET_GLYPH)?); + let value = CaretValue::format_3(caret, DeviceOrVariationIndex::variation_index(0, 0)); + let carets = LigCaretList::new(CoverageFormat1::new(vec![ligature]).into(), vec![LigGlyph::new(vec![value])]); + let mut gdef = Gdef::new(None, None, Some(carets), None); + let region = VariationRegion::new(vec![RegionAxisCoordinates::new(F2Dot14::from_f32(0.0), F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0))]); + // One delta set of one 16-bit delta for the one region. + let data = ItemVariationData::new(1, 1, vec![0], delta.to_be_bytes().to_vec()); + gdef.item_var_store = Some(ItemVariationStore::new(VariationRegionList::new(1, vec![region]), vec![Some(data)])).into(); + let axis = VariationAxisRecord { + axis_tag: Tag::new(b"wght"), + min_value: Fixed::from_i32(400), + default_value: Fixed::from_i32(400), + max_value: Fixed::from_i32(700), + flags: 0, + axis_name_id: NameId::new(256), + }; + let instance = |name: u16, wght: i32| InstanceRecord { + subfamily_name_id: NameId::new(name), + flags: 0, + coordinates: vec![Fixed::from_i32(wght)], + post_script_name_id: None, + }; + let fvar = Fvar::new(AxisInstanceArrays::new(vec![axis], vec![instance(257, 400), instance(258, 700)])); + let family = VARIABLE_LIGATURE_CARET_FAMILY; + let name = name_table(&[ + (1, family), + (2, "Regular"), + (4, "Varicaret Sans Regular"), + (6, "VaricaretSans-Regular"), + (256, "Weight"), + (257, "Regular"), + (258, "Bold"), + ])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + builder.add_table(&gdef).ok()?.add_table(&fvar).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// [`ligature_caret_font`] with its one caret at x = `caret` font units and a `GPOS` `kern` single +/// adjustment that places the ligature glyph `x` font units right of its pen position. `None` when +/// it can't be built. +pub fn placed_ligature_caret_font(caret: i16, x: i16) -> Option> { + use write_fonts::tables::gpos::{Gpos, PositionLookup, PositionLookupList, SinglePos, ValueRecord}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + let base = ligature_caret_font(Some(caret))?; + let font = skrifa::FontRef::new(&base).ok()?; + let ligature = GlyphId16::new(source_sans_gid(LIGATURE_CARET_GLYPH)?); + let pos = SinglePos::format_1(CoverageFormat1::new(vec![ligature]).into(), ValueRecord::new().with_x_placement(x)); + let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"kern"), Feature::new(None, vec![0]))]); + let lookups = PositionLookupList::new(vec![PositionLookup::Single(Lookup::new(Default::default(), vec![pos]))]); + let langsys = || Script::new(Some(LangSys::new(vec![0])), vec![]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), langsys()), ScriptRecord::new(Tag::new(b"latn"), langsys())]); + let mut builder = FontBuilder::new(); + builder.add_table(&Gpos::new(scripts, features, lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`pair_kerning_font`]. pub const PAIR_KERNING_FAMILY: &str = "Pairtest Sans"; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index db28b20138..3f86a85bdc 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -15,6 +15,7 @@ mod hang; mod inline; mod joiners; mod justify; +mod ligature_carets; mod path_joins; mod ruby; mod scripts; diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index 7e49312979..d7cd584013 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -165,6 +165,9 @@ fn lines_of_clusters(lines: &[&[(usize, usize, f64)]], rtl: bool) -> TextLayout bend: None, unturned: Affine::IDENTITY, pivot: Point::new(x, baseline), + carets: Vec::new(), + width: advance, + width_start: 0.0, }); x += advance; } diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs new file mode 100644 index 0000000000..ee42864c58 --- /dev/null +++ b/crates/text/src/tests/ligature_carets.rs @@ -0,0 +1,498 @@ +//! Caret stops inside ligatures: the caret, a click, arrow keys and the selection reach each +//! character a ligature glyph stands for, at the font's ligature carets (`GDEF`) or, without them, +//! at the glyph's advance divided equally. + +use kurbo::{BezPath, Point, Vec2}; +use vectorcraft_doc::{CharStyle, TextKind, TextObject}; +use vectorcraft_geom::PathData; + +use crate::test_fonts::{ + LIGATURE_CARET_FAMILY, LIGATURE_CARET_GLYPH, VARIABLE_LIGATURE_CARET_FAMILY, VERTICAL_LIGATURE_CARET_FAMILY, lam_alef_family, lam_alef_font, + ligature_caret_font, placed_ligature_caret_font, source_sans_gid, variable_ligature_caret_font, vertical_ligature_caret_font, +}; +use crate::*; + +/// A database of the bundled fonts and `font`. +fn db_with(font: Option>) -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(font.expect("the test font builds")), 1); + db +} + +fn point(text: &str, family: &str) -> TextObject { + TextObject::point(Point::ZERO, text, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() }) +} + +/// The caret's x for byte `b`. +fn caret_x(l: &TextLayout, b: usize) -> f64 { + caret_position(l, b).0.x +} + +/// The x of a click at `at` (0 to 1) along glyph `g`'s advance from its left, on its baseline. +fn along(g: &PositionedGlyph, at: f64) -> Point { + Point::new(g.origin.x + g.advance * at, g.origin.y) +} + +/// A font whose caret list for a ligature holds a number of carets other than the one asked for +/// gives none. +#[test] +fn a_caret_list_of_another_length_gives_no_carets() { + let db = db_with(ligature_caret_font(Some(150))); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); + assert_eq!(face.ligature_carets(gid, 1), Some(vec![150.0])); + assert_eq!(face.ligature_carets(gid, 2), None); + assert_eq!(face.ligature_carets(gid, 0), None); +} + +/// A variable font's ligature caret with a variation index moves with the face's axis settings: by +/// none at the default weight, by the whole delta at the weight its region peaks at. +#[test] +fn a_variable_ligature_caret_takes_its_delta() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(variable_ligature_caret_font(150, 100).expect("the test font builds")), 2, "Regular and Bold"); + let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); + let regular = db.face(VARIABLE_LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let bold = db.face(VARIABLE_LIGATURE_CARET_FAMILY, "Bold").expect("the test font is added"); + assert_eq!(regular.ligature_carets(gid, 1), Some(vec![150.0])); + assert_eq!(bold.ligature_carets(gid, 1), Some(vec![250.0])); +} + +/// The font's ligature caret is where the caret, a click, arrow keys and the selection stop inside +/// the ligature, not the middle of the glyph. +#[test] +fn the_font_ligature_caret_places_the_inner_stop() { + let db = db_with(ligature_caret_font(Some(150))); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); + let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY)); + assert_eq!(l.glyphs.len(), 1, "f + i is one glyph: {:?}", l.glyphs); + let g = &l.glyphs[0]; + assert_eq!((g.gid, g.len), (gid, 2)); + let at = 150.0 / face.advance(gid); + assert!(at < 0.4, "the caret is well left of the middle: {at}"); + assert_eq!(g.carets.len(), 1); + assert_eq!(g.carets[0].0, 1); + assert!((g.carets[0].1 - at).abs() < 1e-9, "{:?} against {at}", g.carets); + assert!((caret_x(&l, 1) - g.advance * at).abs() < 1e-6); + // A click left or right of the caret goes to it rather than to either end. + assert_eq!(hit_byte(&l, along(g, at * 0.4)), 0); + assert_eq!(hit_byte(&l, along(g, at * 1.4)), 1); + assert_eq!(hit_byte(&l, along(g, 0.9)), 2); + // Arrow keys stop at it both ways, and the f alone is selected up to it. + assert_eq!(caret_horizontal(&l, 0, true), 1); + assert_eq!(caret_horizontal(&l, 1, true), 2); + assert_eq!(caret_horizontal(&l, 2, false), 1); + let q = selection_quads(&l, 0, 1); + assert_eq!(q.len(), 1); + assert!((q[0][1].x - q[0][0].x - g.advance * at).abs() < 1e-6, "{q:?}"); +} + +/// The font's placement of a ligature (`GPOS` x placement) moves its caret with the glyph. +#[test] +fn a_placed_ligature_keeps_its_caret_on_the_glyph() { + let at = |font: Option>| { + let db = db_with(font); + let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY)); + let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph").clone(); + (caret_x(&l, 1) - g.origin.x, g.outline.bounding_box().x0 - g.origin.x, g.width_start, hit_byte(&l, Point::new(caret_x(&l, 1) + 1.0, 0.0))) + }; + let (caret, ink, start, _) = at(ligature_caret_font(Some(150))); + let (placed_caret, placed_ink, placed_start, hit) = at(placed_ligature_caret_font(150, 100)); + // 100 units at 100 pt in a 1000-unit em. + assert!(start.abs() < 1e-9 && (placed_start - 10.0).abs() < 1e-9, "{start} {placed_start}"); + assert!((placed_ink - ink - 10.0).abs() < 1e-6, "the glyph moves right: {placed_ink} against {ink}"); + assert!((placed_caret - caret - 10.0).abs() < 1e-6, "the caret moves with it: {placed_caret} against {caret}"); + assert_eq!(hit, 1); +} + +/// A ligature whose font lists no carets for it divides its advance equally among its characters. +#[test] +fn a_ligature_without_font_carets_is_divided_equally() { + let db = db_with(ligature_caret_font(None)); + let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY)); + assert_eq!(l.glyphs.len(), 1); + let g = &l.glyphs[0]; + assert_eq!(g.carets, vec![(1, 0.5)]); + assert!((caret_x(&l, 1) - g.advance * 0.5).abs() < 1e-6); + assert_eq!(hit_byte(&l, along(g, 0.4)), 1); + assert_eq!(hit_byte(&l, along(g, 0.2)), 0); + // A caret value outside the glyph is not used either. + let db = db_with(ligature_caret_font(Some(-20))); + let l = layout(&db, &point("fi", LIGATURE_CARET_FAMILY)); + assert_eq!(l.glyphs[0].carets, vec![(1, 0.5)]); +} + +/// Tracking adds space after a ligature's own width: the font's caret stays where the font puts it +/// in the glyph, and the caret, a click and the selection use that place, left to right and right +/// to left. +#[test] +fn tracking_does_not_move_a_ligature_caret() { + let db = db_with(ligature_caret_font(Some(150))); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let mut t = point("fi", LIGATURE_CARET_FAMILY); + t.runs[0].style.tracking = 50.0; + let l = layout(&db, &t); + assert_eq!(l.glyphs.len(), 1, "f + i stays one glyph at this tracking: {:?}", l.glyphs); + let g = &l.glyphs[0]; + let k = 100.0 / face.units_per_em(); + let width = face.advance(g.gid) * k; + assert!((g.width - width).abs() < 1e-9, "{} against {width}", g.width); + assert!((g.advance - width - 5.0).abs() < 1e-9, "the advance takes in 5 pt of tracking: {}", g.advance); + let x = g.origin.x + 150.0 * k; + assert!((caret_x(&l, 1) - x).abs() < 1e-6, "{} against {x}", caret_x(&l, 1)); + assert_eq!(hit_byte(&l, Point::new(g.origin.x + 150.0 * k * 0.45, -10.0)), 0); + assert_eq!(hit_byte(&l, Point::new(x + 0.3, -10.0)), 1); + let q = selection_quads(&l, 0, 1); + assert_eq!(q.len(), 1); + assert!((q[0][1].x - x).abs() < 1e-6, "{q:?}"); + // Right to left the tracking lies to the glyph's right, before its first character: the stop + // between lam and alef stays in the middle of the glyph's own width. + let db = db_with(lam_alef_font(b"rlig")); + let mut t = point("\u{0644}\u{0627}", lam_alef_family(b"rlig")); + t.runs[0].style.tracking = 50.0; + let l = layout(&db, &t); + let g = l.glyphs.iter().find(|g| g.len == 4).expect("lam + alef is one glyph"); + assert!(g.rtl && g.advance > g.width + 4.0, "{} {}", g.advance, g.width); + let mid = g.origin.x + g.width * 0.5; + assert!((caret_x(&l, 2) - mid).abs() < 1e-6, "{} against {mid}", caret_x(&l, 2)); + let q = selection_quads(&l, 2, 4); + assert_eq!(q.len(), 1, "{q:?}"); + let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x)); + assert!((x0 - g.origin.x).abs() < 1e-6 && (x1 - mid).abs() < 1e-6, "{q:?}"); +} + +/// Negative kerning can end a ligature's advance before its font caret: the caret still stands at +/// the font's place, a click at the advance's end goes to the end of the ligature, and the last +/// character's selection runs between the two. +#[test] +fn negative_kerning_keeps_a_ligature_caret_past_the_advance() { + let db = db_with(ligature_caret_font(Some(150))); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let k = 100.0 / face.units_per_em(); + let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); + let width = face.advance(gid) * k; + // Kerning (thousandths of an em at 100 pt, a tenth of a point each) that leaves an advance of + // half the distance to the font caret. + let kern = (150.0 * k * 0.5 - width) * 10.0; + let mut t = point("fi", LIGATURE_CARET_FAMILY); + t.runs[0].style.kerning = Some(kern); + let l = layout(&db, &t); + assert_eq!(l.glyphs.len(), 1, "f + i stays one glyph with this kerning: {:?}", l.glyphs); + let g = &l.glyphs[0]; + assert!((g.width - width).abs() < 1e-9, "{} against {width}", g.width); + assert!((g.advance - 150.0 * k * 0.5).abs() < 1e-6, "the advance ends before the caret: {}", g.advance); + let x = g.origin.x + 150.0 * k; + let end = g.origin.x + g.advance; + assert!((caret_x(&l, 1) - x).abs() < 1e-6, "{} against {x}", caret_x(&l, 1)); + assert!((caret_x(&l, 2) - end).abs() < 1e-6, "{} against {end}", caret_x(&l, 2)); + assert_eq!(hit_byte(&l, Point::new(end, -10.0)), 2); + assert_eq!(hit_byte(&l, Point::new(x + 0.3, -10.0)), 1); + let q = selection_quads(&l, 1, 2); + assert_eq!(q.len(), 1, "{q:?}"); + let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x)); + assert!((x0 - end).abs() < 1e-6 && (x1 - x).abs() < 1e-6, "{q:?}"); + // On a path, a click at the advance's end goes to the end of the ligature as well. + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((1000.0, 0.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let l = layout(&db, &t); + let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph"); + let d = Vec2::new(g.angle.cos(), g.angle.sin()); + assert_eq!(hit_byte(&l, g.origin + d * g.advance), 2); + assert_eq!(hit_byte(&l, g.origin + d * (g.width * 150.0 / face.advance(gid) + 0.3)), 1); +} + +/// On a path, a ligature whose negative kerning ends its advance before its font caret is followed +/// by an i that covers the caret: a click at the caret goes to the caret, not to the i. +#[test] +fn a_click_at_a_ligature_caret_past_the_advance_on_a_path_reaches_it() { + let db = db_with(ligature_caret_font(Some(150))); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let k = 100.0 / face.units_per_em(); + let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph")); + let width = face.advance(gid) * k; + let kern = (150.0 * k * 0.5 - width) * 10.0; + let mut t = point("fii", LIGATURE_CARET_FAMILY); + crate::edit::style_range(&mut t.runs, 0, 2, |st| st.kerning = Some(kern)); + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((1000.0, 0.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let l = layout(&db, &t); + let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph"); + let i = l.glyphs.iter().find(|h| h.byte == 2).expect("the second i"); + let d = Vec2::new(g.angle.cos(), g.angle.sin()); + let caret = g.origin + d * (g.width * 150.0 / face.advance(gid)); + let mid = |h: &PositionedGlyph| h.origin + d * (h.advance * 0.5); + assert!((caret - mid(i)).hypot() < (caret - mid(g)).hypot(), "the i's middle is nearer the caret than the ligature's"); + assert_eq!(hit_byte(&l, caret + d * 0.3), 1); +} + +/// Tracking of -1000 (one em to the left) leaves Source Serif 4's fi ligature, with standard +/// ligatures turned on explicitly, an advance of zero or less: the caret, a click and the selection +/// still reach the i at its place in the glyph's own width, across and on a path. +#[test] +fn a_ligature_without_advance_keeps_its_inner_stop() { + let db = FontDb::with_font_dirs(vec![]); + let mut t = point("fi", "Source Serif 4"); + t.runs[0].style.tracking = -1000.0; + t.runs[0].style.features = vec!["liga".into()]; + let l = layout(&db, &t); + let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph"); + assert!(g.advance <= 0.0 && g.width > 0.0, "{} {}", g.advance, g.width); + let &[(1, f)] = g.carets.as_slice() else { panic!("one inner stop: {:?}", g.carets) }; + let x = g.origin.x + g.width * f; + let end = g.origin.x + g.advance; + assert!((caret_x(&l, 1) - x).abs() < 1e-6, "{} against {x}", caret_x(&l, 1)); + assert!((caret_x(&l, 2) - end).abs() < 1e-6, "{} against {end}", caret_x(&l, 2)); + assert_eq!(hit_byte(&l, Point::new(x + 0.3, -10.0)), 1); + assert_eq!(hit_byte(&l, Point::new(g.origin.x + 0.3, -10.0)), 0); + let q = selection_quads(&l, 0, 1); + assert_eq!(q.len(), 1, "{q:?}"); + let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x)); + assert!((x0 - g.origin.x).abs() < 1e-6 && (x1 - x).abs() < 1e-6, "{q:?} against {} {x}", g.origin.x); + assert_eq!(caret_horizontal(&l, 0, true), 1); + // On a path, a click past the inner stop goes to it, and the f alone is selected up to it. + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((1000.0, 0.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let l = layout(&db, &t); + let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph"); + assert!(g.advance <= 0.0, "{}", g.advance); + let d = Vec2::new(g.angle.cos(), g.angle.sin()); + assert_eq!(hit_byte(&l, g.origin + d * (g.width * f + 0.3)), 1); + assert_eq!(hit_byte(&l, g.origin + d * 0.3), 0); + let q = selection_quads(&l, 0, 1); + assert_eq!(q.len(), 1, "{q:?}"); + assert!(((q[0][1] - q[0][0]).hypot() - g.width * f).abs() < 1e-6, "{q:?}"); +} + +/// Bundled Source Serif 4's fi ligature has a caret stop that a click and the arrow keys reach. +#[test] +fn source_serif_fi_and_ffi_have_inner_stops() { + let db = FontDb::with_font_dirs(vec![]); + for (s, stops) in [("fi", vec![1]), ("ffi", vec![1, 2])] { + let l = layout(&db, &point(s, "Source Serif 4")); + let lone: Vec<&PositionedGlyph> = l.glyphs.iter().filter(|g| g.len == s.len()).collect(); + if lone.is_empty() { + // The font has no ligature for these letters (ffi in some versions). + assert_ne!(s, "fi", "{:?}", l.glyphs); + continue; + } + let g = lone[0]; + assert_eq!(g.carets.iter().map(|c| c.0).collect::>(), stops, "{s}"); + for &(b, f) in &g.carets { + let x = g.origin.x + g.advance * f; + assert_eq!(hit_byte(&l, Point::new(x + 0.01, -10.0)), b, "{s} byte {b}"); + assert!((caret_x(&l, b) - x).abs() < 1e-6); + } + let mut b = 0; + let mut seen = vec![]; + while b < s.len() { + b = caret_horizontal(&l, b, true); + seen.push(b); + } + assert_eq!(seen[..stops.len()], stops[..], "{s}"); + } +} + +/// A right-to-left ligature (lam + alef, two bytes each) has its stop between the two characters, +/// never inside a character, and its first character is on its right. +#[test] +fn a_right_to_left_ligature_stops_between_its_characters() { + let db = db_with(lam_alef_font(b"rlig")); + let l = layout(&db, &point("\u{0644}\u{0627}", lam_alef_family(b"rlig"))); + let g = l.glyphs.iter().find(|g| g.len == 4).expect("lam + alef is one glyph"); + assert!(g.rtl); + assert_eq!(g.carets, vec![(2, 0.5)]); + // Right of the middle is the lam, left of it the alef. + assert_eq!(hit_byte(&l, along(g, 0.9)), 0); + assert_eq!(hit_byte(&l, along(g, 0.6)), 2); + assert_eq!(hit_byte(&l, along(g, 0.1)), 4); + assert!((caret_x(&l, 2) - (g.origin.x + g.advance * 0.5)).abs() < 1e-6); + assert!(caret_x(&l, 0) > caret_x(&l, 2) && caret_x(&l, 2) > caret_x(&l, 4)); + // The lam alone is selected on the right half. + let q = selection_quads(&l, 0, 2); + assert_eq!(q.len(), 1, "{q:?}"); + let (x0, x1) = (q[0][0].x.min(q[0][1].x), q[0][0].x.max(q[0][1].x)); + assert!((x0 - (g.origin.x + g.advance * 0.5)).abs() < 1e-6 && (x1 - (g.origin.x + g.advance)).abs() < 1e-6, "{q:?}"); + // Arrow keys (visual stops) take the inner stop: right to left, left goes forward. + assert_eq!(caret_horizontal_cluster(&l, "\u{0644}\u{0627}", 0, false), 2); + assert_eq!(caret_horizontal_cluster(&l, "\u{0644}\u{0627}", 2, false), 4); +} + +/// Right to left, manual kerning moves a ligature right and puts its space on the left: the inner +/// stop moves with the glyph, and the click, the caret and the selection of each character follow. +#[test] +fn manual_kerning_moves_a_right_to_left_ligature_stop_with_the_glyph() { + let db = db_with(lam_alef_font(b"rlig")); + let at = |kern: f64| { + let mut t = point("\u{0644}\u{0627}", lam_alef_family(b"rlig")); + t.runs[0].style.kerning = Some(kern); + let l = layout(&db, &t); + let g = l.glyphs.iter().find(|g| g.len == 4).expect("lam + alef is one glyph").clone(); + assert!(g.rtl); + (l, g) + }; + let (plain, p) = at(0.0); + let (kerned, k) = at(100.0); + // 100/1000 em at 100 pt. + assert!((k.width_start - 10.0).abs() < 1e-9 && (k.advance - p.advance - 10.0).abs() < 1e-9, "{} {} {}", k.width_start, k.advance, p.advance); + let ink = |g: &PositionedGlyph| g.outline.bounding_box().x0; + assert!((ink(&k) - k.origin.x - (ink(&p) - p.origin.x) - 10.0).abs() < 1e-6, "the glyph moves right"); + let mid = k.origin.x + 10.0 + k.width * 0.5; + assert!((caret_x(&kerned, 2) - ink(&k) - (caret_x(&plain, 2) - ink(&p))).abs() < 1e-6, "the stop moves with the glyph"); + assert!((caret_x(&kerned, 2) - mid).abs() < 1e-6, "{} against {mid}", caret_x(&kerned, 2)); + assert_eq!(hit_byte(&kerned, Point::new(mid + 1.0, k.origin.y)), 2); + assert_eq!(hit_byte(&kerned, Point::new(mid + 4.0, k.origin.y)), 2); + assert_eq!(hit_byte(&kerned, Point::new(k.origin.x + k.advance - 1.0, k.origin.y)), 0); + let q = selection_quads(&kerned, 0, 2); + assert_eq!(q.len(), 1, "{q:?}"); + let x0 = q[0][0].x.min(q[0][1].x); + assert!((x0 - mid).abs() < 1e-6, "the lam alone is selected right of the stop: {q:?}"); +} + +/// A letter with a combining mark is one character: a glyph for it has no inner stop. +#[test] +fn a_letter_and_its_mark_has_no_inner_stop() { + let db = FontDb::with_font_dirs(vec![]); + let l = layout(&db, &point("e\u{0301}", "Source Sans 3")); + assert!(l.glyphs.iter().all(|g| g.carets.is_empty()), "{:?}", l.glyphs); +} + +/// On a path, a click on either half of the ligature goes to its nearer stop, and the selection of +/// one character covers its part of the glyph. +#[test] +fn a_ligature_on_a_path_has_its_inner_stop() { + let db = db_with(ligature_caret_font(None)); + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((1000.0, 0.0)); + let mut t = point("fi", LIGATURE_CARET_FAMILY); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let l = layout(&db, &t); + assert!(l.on_path); + let g = l.glyphs.iter().find(|g| g.len == 2).expect("f + i is one glyph"); + assert_eq!(g.carets, vec![(1, 0.5)]); + let at = |f: f64| g.origin + Vec2::new(g.angle.cos(), g.angle.sin()) * (g.advance * f); + assert_eq!(hit_byte(&l, at(0.1)), 0); + assert_eq!(hit_byte(&l, at(0.4)), 1); + assert_eq!(hit_byte(&l, at(0.95)), 2); + let q = selection_quads(&l, 1, 2); + assert_eq!(q.len(), 1); + assert!(((q[0][1] - q[0][0]).hypot() - g.advance * 0.5).abs() < 1e-6, "{q:?}"); +} + +/// In vertical type, the inner stop of a turned Latin ligature lies down the column between its +/// ends. +#[test] +fn a_ligature_in_vertical_type_has_its_inner_stop() { + let db = db_with(ligature_caret_font(None)); + let mut t = point("fi", LIGATURE_CARET_FAMILY); + t.vertical = true; + let l = layout(&db, &t); + let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + assert_eq!(g.carets, vec![(1, 0.5)]); + let y = |b| caret_position(&l, b).0.y; + assert!(y(0) < y(1) && y(1) < y(2), "{} {} {}", y(0), y(1), y(2)); + let mid = caret_position(&l, 1); + assert_eq!(hit_byte(&l, mid.0.midpoint(mid.1) + Vec2::new(0.0, 0.01)), 1); +} + +/// In vertical type, tracking adds space after a turned ligature's own width as it does across: +/// the font's caret stays the same distance down the column from the ligature's start, and the +/// last character's selection runs from it to the end of the advance. +#[test] +fn tracking_does_not_move_a_ligature_caret_in_vertical_type() { + let db = db_with(ligature_caret_font(Some(150))); + let face = db.face(LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let k = 100.0 / face.units_per_em(); + let at = |tracking: f64| { + let mut t = point("fi", LIGATURE_CARET_FAMILY); + t.vertical = true; + t.runs[0].style.tracking = tracking; + let l = layout(&db, &t); + let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + let width = face.advance(g.gid) * k; + assert!((g.width - width).abs() < 1e-9, "{} against {width}", g.width); + let y = |b| caret_position(&l, b).0.y; + let q = selection_quads(&l, 1, 2); + assert_eq!(q.len(), 1, "{q:?}"); + let ys = q[0].map(|p| p.y); + let (y0, y1) = (ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)); + assert!((y0 - y(1)).abs() < 1e-6 && (y1 - y(2)).abs() < 1e-6, "{q:?} {} {}", y(1), y(2)); + (y(1) - y(0), y(2) - y(0), g.advance) + }; + let (plain, plain_end, _) = at(0.0); + let (tracked, tracked_end, advance) = at(50.0); + assert!((plain - 150.0 * k).abs() < 1e-6, "{plain} against {}", 150.0 * k); + assert!((tracked - plain).abs() < 1e-6, "{tracked} against {plain}"); + assert!((tracked_end - advance).abs() < 1e-6 && (tracked_end - plain_end - 5.0).abs() < 1e-6, "{tracked_end} {plain_end} {advance}"); +} + +/// A ligature standing upright in vertical type (Standard Vertical Roman Alignment) takes its font +/// caret as a y coordinate: the stop lies that far below the top of its cell, which runs from its +/// vertical origin (0.88 em) one em down the column. A caret above the cell is not used. +#[test] +fn an_upright_ligature_takes_its_caret_down_its_cell() { + let at = |caret: i16| { + let db = db_with(vertical_ligature_caret_font(caret)); + let mut t = point("fi", VERTICAL_LIGATURE_CARET_FAMILY); + t.vertical = true; + t.runs[0].style.standard_vertical_roman = true; + let l = layout(&db, &t); + let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + let face = db.face(VERTICAL_LIGATURE_CARET_FAMILY, "Regular").expect("the test font is added"); + let cell = 1000.0 * 100.0 / face.units_per_em(); + assert!((g.width - cell).abs() < 1e-9, "the glyph stands upright, one em down the column: {} against {cell}", g.width); + let &[(1, f)] = g.carets.as_slice() else { panic!("one inner stop: {:?}", g.carets) }; + let y = |b| caret_position(&l, b).0.y; + assert!(((y(1) - y(0)) - g.width * f).abs() < 1e-6, "{} {} against {f}", y(0), y(1)); + f + }; + // 0.88 em at the top: y = 280 is 600 units down, y = -50 is 930 units down. + assert!((at(280) - 0.6).abs() < 1e-9, "{}", at(280)); + assert!((at(-50) - 0.93).abs() < 1e-9, "{}", at(-50)); + assert!((at(900) - 0.5).abs() < 1e-9, "{}", at(900)); +} + +/// Tracking that makes an upright ligature's advance negative leaves it upright: it keeps its +/// caret down its cell, and its cell starts where it does without tracking, with or without the +/// font's vertical metrics. +#[test] +fn an_upright_ligature_with_a_negative_advance_keeps_its_cell() { + let at = |font: Option>, family: &str, tracking: f64| { + let db = db_with(font); + let mut t = point("fi", family); + t.vertical = true; + t.runs[0].style.standard_vertical_roman = true; + t.runs[0].style.tracking = tracking; + // Ligatures turned on by name stay on at any tracking. + t.runs[0].style.features = vec!["+liga".into()]; + let l = layout(&db, &t); + let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) }; + let face = db.face(family, "Regular").expect("the test font is added"); + assert!(tracking == 0.0 || g.advance <= 0.0, "the tracking makes the advance negative: {}", g.advance); + let cell = 1000.0 * 100.0 / face.units_per_em(); + assert!((g.width - cell).abs() < 1e-9, "the glyph stands upright, one em down the column: {} against {cell}", g.width); + let y = |b| caret_position(&l, b).0.y; + let &[(1, f)] = g.carets.as_slice() else { panic!("one inner stop: {:?}", g.carets) }; + assert!(((y(1) - y(0)) - g.width * f).abs() < 1e-6, "{} {} against {f}", y(0), y(1)); + (f, g.outline.bounding_box().y0 - y(0)) + }; + let vertical = |tracking| at(vertical_ligature_caret_font(280), VERTICAL_LIGATURE_CARET_FAMILY, tracking); + let (f, top) = vertical(0.0); + assert!((f - 0.6).abs() < 1e-9, "{f}"); + let (tracked, tracked_top) = vertical(-1500.0); + assert!((tracked - f).abs() < 1e-9, "the caret is read down the cell: {tracked} against {f}"); + assert!((tracked_top - top).abs() < 1e-6, "{tracked_top} against {top}"); + let plain = |tracking| at(ligature_caret_font(None), LIGATURE_CARET_FAMILY, tracking); + let (f, top) = plain(0.0); + assert!((f - 0.5).abs() < 1e-9, "{f}"); + let (tracked, tracked_top) = plain(-1500.0); + assert!((tracked - f).abs() < 1e-9, "{tracked} against {f}"); + assert!((tracked_top - top).abs() < 1e-6, "the cell starts where it does without tracking: {tracked_top} against {top}"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7d526a04a8..bccb007687 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -764,6 +764,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While a drag rotates the view, a dial at the center of the canvas shows the angle. - **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation). While a Type tool edits type, a click that lands on no type ends the editing without making new type, and that tool stays active; the next click makes new type (#2871, #2854). + Inside a ligature (one glyph for several characters, such as fi), the Type tool's caret, clicks, arrow keys and selection stop between its characters, at the font's ligature carets ([OpenType GDEF ligature caret list](https://learn.microsoft.com/en-us/typography/opentype/spec/gdef)) or, when the font does not list one valid caret for each stop, at the glyph's width divided equally. Duplicate Artboards, the Artboard tool's Alt-drag and Paste give the new artboard an id that no other artboard has, also when an artboard's id is the largest possible value (#1718). Deleting the copy or the original then leaves the other's guides. - **Touch Type:** a click with the Touch Type tool (Shift+T) selects one character and shows a box around it. Dragging the box or its lower-left handle moves the character. The upper-left handle scales it vertically, the lower-right handle scales it horizontally, the upper-right handle scales it proportionally, and the upper-middle handle rotates it. Each drag is one undo step that sets the character's kerning, baseline shift, scales or rotation, and the type stays editable (`text.touchType`; behavior reference: [Touch Type tool](https://web.archive.org/web/20261007185617/https://helpx.adobe.com/illustrator/using/tool-techniques/touch-type-tool.html), [Add text with the Type, Area Type, and Touch Type tools](https://web.archive.org/web/20260926095922/https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-text-illustrator-text-tools.html)). A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. From f62e502f1cc69ec165ff29e4022c1067a008b9ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:38:42 +0700 Subject: [PATCH 359/674] .ai import: version 7 pattern definitions come in as pattern swatches Squashed from #5189 onto main. --- crates/engine/tests/import_fuzz.rs | 34 +++ crates/eps/src/import/ai/legacy_text.rs | 3 + crates/eps/src/import/ai/read.rs | 12 +- crates/eps/src/import/ai/read/directives.rs | 226 ++++++++++++++++++- crates/eps/src/import/ai/read/ops.rs | 60 ++++- crates/eps/src/import/ai/style.rs | 14 +- crates/eps/src/import/ai/tests.rs | 229 +++++++++++++++++++- crates/eps/src/import/tests_illustrator.rs | 26 +++ docs/file-format-parity.md | 4 +- 9 files changed, 584 insertions(+), 24 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index bd9069bd20..d3f0c8cc8c 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3601,6 +3601,40 @@ proptest! { } } +/// A pattern's definition in the version 7 form (§3.4): a layer whose `_ &` fills the tile's box, +/// and one whose tile string has CR-separated lines, comments and escapes. +const LEGACY_PATTERN: &str = "%AI3_BeginPattern: (P)\n(P) 0 0 10 10 [\n%AI3_Tile\n(0 O 0 R 0 0 0 0.5 k) @ _ &\n\ + (0 O 1 R 0 0 0 1 \\(Ink\\) 0 X) @ (\r%AI6_BeginPatternLayer\r1 w u\r0 5 m\\r10 5 L\rS\rU\r%AI6_EndPatternLayer\r) &\n] E\n%AI3_EndPattern\n"; + +/// [`NAMED_PROLOG_AI`] with `pattern` in its setup, filling the square. +fn legacy_pattern_ai(pattern: &str) -> String { + NAMED_PROLOG_AI + .replace("%AI5_Begin_NonPrinting", &format!("{pattern}%AI5_Begin_NonPrinting")) + .replace("\n10 10 m\n", "\n(P) 5 5 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n10 10 m\n") + .replace("10 10 L\nS\n", "10 10 L\nB\n") +} + +/// The fixture, as it is, opens with the pattern filling the square. +#[test] +fn the_legacy_pattern_fixture_opens_with_its_pattern() { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", legacy_pattern_ai(LEGACY_PATTERN).as_bytes()).unwrap(); + assert_eq!(l.doc.pattern("P").map(|p| p.art.len()), Some(2), "{:?}", l.warnings); + let square = &l.doc.layers[0].children().unwrap()[0]; + assert!(matches!(square.appearance.fill().map(|f| &f.paint), Some(vectorcraft_color::Paint::Pattern { .. }))); +} + +proptest! { + #![proptest_config(config())] + + /// That `.ai` with its pattern's definition damaged (its strings, `@`, `&`, `_`, the list's + /// brackets and its `E`): read, without the pattern where it can't be read whole, or refused. + #[test] + fn ps_form_ai_legacy_pattern_never_panics(cut in 0usize..500, edits in prop::collection::vec((0usize..500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '\r', '(', ')', '\\', '[', ']', '%', '@', '&', '_', 'E', 'u', 'U', 'q', 'Q', 'm', 'f', 'S', 'k', 'X'])), 0..12)) { + let text = legacy_pattern_ai(&mutate_text(LEGACY_PATTERN, cut, &edits)); + survive("PostScript-form .ai with a damaged version 7 pattern", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + /// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or /// anything else. fn arb_layer_operand() -> impl Strategy { diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 3c0d4cf43f..17590b3203 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -127,6 +127,9 @@ impl Reader<'_> { /// `type To`: a text object begins. pub(super) fn begin_text(&mut self, vals: &[V], hidden: bool) { self.end_path_quietly(); + if self.pattern.is_some() { + self.unreadable("type in a pattern", false); + } let kind = nums::<1>(vals).map_or(0, |[k]| k as i64); self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() }); } diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 2dfee6f2c4..93cc0af6b3 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -52,9 +52,13 @@ //! lines and `1 (style) XW`: the drawn look is kept, named after the object. //! - Patterns: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury` (the tile, in the pattern's //! space, y up), the tile's art (on `%_` lines in newer files), `E`, `%AI3_EndPattern`; each is -//! read by a reader of its own and becomes a pattern swatch. A fill or stroke with one: +//! read by a reader of its own and becomes a pattern swatch. In the version 7 form (§3.4) a list +//! of layers follows the tile, `[ (colors) @ (tile) & … ] E`, each layer's tile read from its +//! string with the colors' state (`_ &`: the tile's box filled). A fill or stroke with one: //! `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`), the matrix -//! taking the pattern's space to art space (the other operands are what it is made of). +//! taking the pattern's space to art space (the other operands are what it is made of). With a +//! pattern defined in the version 7 form, the other operands are applied in order (§5.4.1) before +//! the initial matrix. //! //! - Type in the legacy format (version 7 specification §15): `type To` … `TO`, read by //! [`legacy_text`]. @@ -327,6 +331,9 @@ struct Reader<'a> { pattern: Option, /// The tile (y down) of each pattern read, by name. pattern_tiles: HashMap, + /// The patterns read from a definition in the version 7 form, whose fills apply their other + /// operands before the matrix (see [`Reader::pattern_paint`]). + v7_patterns: HashSet, /// The legacy text object being read (`To` … `TO`), and the modal type attributes. text: Option, type_state: legacy_text::TypeState, @@ -431,6 +438,7 @@ impl<'a> Reader<'a> { ruler_units: None, pattern: None, pattern_tiles: HashMap::new(), + v7_patterns: HashSet::new(), text: None, type_state: legacy_text::TypeState::default(), graph: None, diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index be4f6214c8..ed838b51b6 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,6 +1,7 @@ use super::art::{four, sane, two}; use super::types::{ - FLIP, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED, + FLIP, GState, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, + VERSIONED_UNENDED, }; use super::{Arc, Node, PatternDef, Reader, Rect, Tok, V, marker}; @@ -82,10 +83,14 @@ impl<'a> Reader<'a> { return Ok(()); } let m = marker(line); - // A pattern's definition (one inside another's isn't read). - if m == "BeginPattern" && self.pattern.is_none() { + // A pattern's definition. One inside another's isn't read, and the outer tile is then incomplete. + if m == "BeginPattern" { let section = self.section("EndPattern")?; - self.define_pattern(section); + if self.pattern.is_some() { + self.unsupported.insert("patterns inside patterns".into()); + } else { + self.define_pattern(section); + } return Ok(()); } if m == "BeginSymbol" { @@ -322,6 +327,11 @@ impl<'a> Reader<'a> { if self.pattern_tiles.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS { return; } + match legacy_pattern(section) { + Legacy::No => {} + Legacy::Malformed => return, + Legacy::Yes(def) => return self.define_legacy_pattern(&def), + } let mut sub = Reader::new(section); sub.subreader_depth = self.subreader_depth + 1; sub.pattern = Some(PatternHead::default()); @@ -339,6 +349,98 @@ impl<'a> Reader<'a> { && sub.unread.is_empty() && sub.hidden_unread.is_empty() && sub.frames.len() == 1; + self.keep_pattern(sub, whole, false); + } + + /// A definition in the version 7 form ([`legacy_pattern`]), read layer by layer into one group: + /// each layer's colors (`@`) set the state its tile string (`&`) is read with, or the fill of the + /// tile's box (`_ &`). Each layer starts from the state the definition starts with. + fn define_legacy_pattern(&mut self, def: &LegacyPattern) { + let mut sub = Reader::new(b""); + sub.subreader_depth = self.subreader_depth + 1; + sub.pattern = Some(PatternHead { taken: true, name: def.name.clone(), tile: Some(def.tile) }); + sub.gradients = std::mem::take(&mut self.gradients); + sub.nodes = self.nodes; + sub.template = self.template; + let mut read = sub.open(Kind::Group, false); + for layer in &def.layers { + if read.is_err() { + break; + } + read = sub.pattern_layer(layer, def.tile); + } + self.nodes = sub.nodes; + self.gradients = std::mem::take(&mut sub.gradients); + let whole = read.is_ok() + && sub.unsupported.is_empty() + && sub.unknown.is_empty() + && sub.unread.is_empty() + && sub.hidden_unread.is_empty() + && sub.frames.len() == 1; + self.keep_pattern(sub, whole, true); + } + + /// One layer of a definition in the version 7 form, read into the definition's group. + fn pattern_layer(&mut self, layer: &'a LegacyLayer, tile: Rect) -> Result<(), String> { + self.gs = GState::default(); + self.pending_fill = None; + self.pending_stroke = None; + self.pending_unread_fill = false; + self.pending_unread_stroke = false; + self.instance = None; + self.end_path_quietly(); + // The color part has the overprint and the colors only. + let mut lex = super::Lexer::new(&layer.color); + while let Some(t) = lex.next_token() { + match t.tok { + Tok::Num(_) | Tok::Str(_) | Tok::Hex(_) => {} + Tok::Word(w) if LAYER_COLOR_OPS.contains(&w) => {} + _ => return Err("a pattern layer's colors hold something else".into()), + } + } + self.run_string(&layer.color)?; + match &layer.tile { + Some(art) => self.run_string(art)?, + None => { + let corner = |x: f64, y: f64| [V::Num(x), V::Num(y)]; + self.path_op("m", &corner(tile.x0, tile.y0))?; + for (x, y) in [(tile.x0, tile.y1), (tile.x1, tile.y1), (tile.x1, tile.y0)] { + self.path_op("L", &corner(x, y))?; + } + self.paint("f", false, false)?; + } + } + // A path the layer leaves unpainted paints nothing. + self.end_path_quietly(); + Ok(()) + } + + /// Run this reader on one of a pattern layer's strings, which must end everything it starts. + fn run_string(&mut self, bytes: &'a [u8]) -> Result<(), String> { + let depth = self.frames.len(); + self.lex = super::Lexer::new(bytes); + let read = self.run(); + let open = self.done + || self.frames.len() != depth + || self.stack.iter().any(|v| matches!(v, V::Mark)) + || !self.marks.is_empty() + || self.text.is_some() + || self.raster.is_some() + || self.place.is_some() + || self.mesh.is_some() + || self.gradient_def.is_some(); + self.stack.clear(); + self.marks.clear(); + read?; + if open { + return Err("a pattern layer doesn't end what it starts".into()); + } + Ok(()) + } + + /// Keep the pattern `sub` read, when it read it `whole`, as a pattern swatch; `v7` when it was + /// defined in the version 7 form. + fn keep_pattern(&mut self, mut sub: Reader<'_>, whole: bool, v7: bool) { let (Some(head), Some(frame)) = (sub.pattern.take(), sub.frames.pop()) else { return }; let Some(tile) = head.tile.filter(|t| whole && sane(*t) && t.width() > 0.0 && t.height() > 0.0 && !frame.children.is_empty()) else { return; @@ -349,6 +451,11 @@ impl<'a> Reader<'a> { if self.pattern_tiles.insert(def.name.clone(), def.tile).is_some() { self.doc.patterns.retain(|p| p.name != def.name); } + if v7 { + self.v7_patterns.insert(def.name.clone()); + } else { + self.v7_patterns.remove(&def.name); + } self.doc.patterns.push(def); for (key, blob) in sub.doc.images { self.doc.images.entry(key).or_insert(blob); @@ -404,6 +511,117 @@ impl<'a> Reader<'a> { } } +/// The operators a pattern layer's colors (`@`) may hold: overprint, gray, process and custom colors. +const LAYER_COLOR_OPS: &[&[u8]] = &[b"O", b"R", b"g", b"G", b"k", b"K", b"x", b"X"]; + +/// The longest string a pattern layer may have (the format's limit, 64K bytes). +const MAX_LAYER_STRING: usize = 65_535; + +/// Most layers in one pattern's definition. +const MAX_LAYERS: usize = 65_536; + +/// A pattern's definition in the version 7 form: its head, then a list of layers painted in order, +/// the first the lowest. +struct LegacyPattern { + name: String, + /// The tile in the pattern's space (y up). + tile: Rect, + layers: Vec, +} + +/// `(colors) @ (tile) &`, or `(colors) @ _ &` (no tile: the tile's box is filled with the colors' fill). +struct LegacyLayer { + color: Vec, + tile: Option>, +} + +enum Legacy { + /// Another form: the definition's art follows its head as operators. + No, + /// The version 7 form, which can't be read. + Malformed, + Yes(LegacyPattern), +} + +/// The next token that isn't a comment; `Err` at a pattern's definition inside this one. +fn next_operand<'s>(lex: &mut super::Lexer<'s>) -> Result>, ()> { + while let Some(t) = lex.next_token() { + match t.tok { + Tok::Comment(c) if marker(&String::from_utf8_lossy(c)) == "BeginPattern" => return Err(()), + Tok::Comment(_) => {} + _ => return Ok(Some(t)), + } + } + Ok(None) +} + +/// A pattern's definition in the version 7 form: `(name) llx lly urx ury [`, then for each layer +/// `(colors) @` and `(tile) &` or `_ &`, then `] E` (version 7 specification §3.4). It is that form +/// when a `[` that isn't on a `%_` line follows the head. +fn legacy_pattern(section: &[u8]) -> Legacy { + let mut lex = super::Lexer::new(section); + let mut next = || next_operand(&mut lex).ok().flatten().map(|t| (t.tok, t.hidden)); + let name = match next() { + Some((Tok::Str(s), _)) => super::obj::text(&s), + _ => return Legacy::No, + }; + let mut tile = [0.0; 4]; + for v in &mut tile { + match next() { + Some((Tok::Num(n), _)) => *v = n, + _ => return Legacy::No, + } + } + if !matches!(next(), Some((Tok::Word(b"["), false))) { + return Legacy::No; + } + let [x0, y0, x1, y1] = tile; + let mut layers = vec![]; + let string = |t: Option<(Tok, bool)>| match t { + Some((Tok::Str(s) | Tok::Hex(s), _)) if s.len() <= MAX_LAYER_STRING => Some(s), + _ => None, + }; + let word = |t: Option<(Tok, bool)>, w: &[u8]| matches!(t, Some((Tok::Word(x), _)) if x == w); + loop { + // Before the first layer, anything but a string or `] E` is the newer form's art (`[]0 d`). + let first = layers.is_empty(); + let color = match next() { + Some((Tok::Word(b"]"), _)) if !first => break, + Some((Tok::Word(b"]"), _)) => { + return match next() { + Some((Tok::Word(b"E"), _)) => Legacy::Yes(LegacyPattern { name, tile: Rect::new(x0, y0, x1, y1), layers }), + _ => Legacy::No, + }; + } + t @ Some((Tok::Str(_) | Tok::Hex(_), _)) => match string(t) { + Some(s) => s, + None => return Legacy::Malformed, + }, + _ if first => return Legacy::No, + _ => return Legacy::Malformed, + }; + if !word(next(), b"@") { + return Legacy::Malformed; + } + let tile = match next() { + Some((Tok::Word(b"_"), _)) => None, + t => match string(t) { + Some(s) => Some(s), + None => return Legacy::Malformed, + }, + }; + if !word(next(), b"&") || layers.len() >= MAX_LAYERS { + return Legacy::Malformed; + } + layers.push(LegacyLayer { color, tile }); + } + // `] E` ends the definition: nothing but comments may follow it. + if !word(next(), b"E") || !matches!(next_operand(&mut lex), Ok(None)) { + return Legacy::Malformed; + } + Legacy::Yes(LegacyPattern { name, tile: Rect::new(x0, y0, x1, y1), layers }) +} + /// How many custom colors the header may define. pub(super) const MAX_CUSTOM_COLORS: usize = 1000; diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 88f1325686..f5ce513844 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -402,7 +402,8 @@ impl<'a> Reader<'a> { /// `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`: the stroke's): /// the pattern swatch `name`, its space taken to art space by the matrix. A pattern this hasn't - /// read can't be drawn. + /// read can't be drawn. For a pattern defined in the version 7 form, the other operands are + /// applied in order before the initial matrix ([`pattern_controls`]). fn pattern_paint(&mut self, w: &str, vals: &[V]) { // In the setup it paints nothing (and the art's space isn't fixed yet). if self.frames.is_empty() { @@ -413,7 +414,16 @@ impl<'a> Reader<'a> { self.unread_pattern(w); return; }; - let matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None }); + let mut matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None }); + if name.as_ref().is_some_and(|n| self.v7_patterns.contains(n)) { + let controls: Vec = + vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect(); + let Some(controls) = pattern_controls(&controls) else { + self.unread_pattern(w); + return; + }; + matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * controls); + } let Some(xf) = pattern_xf(self.space(), matrix, tile) else { self.unread_pattern(w); return; @@ -596,11 +606,14 @@ impl<'a> Reader<'a> { return; } // A style read here: the object, painted as it says. - if let Some(mut appearance) = self - .styles - .get(&style) - .and_then(|st| styled(object, look, st, &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, space })) - { + if let Some(mut appearance) = self.styles.get(&style).and_then(|st| { + styled( + object, + look, + st, + &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, v7_patterns: &self.v7_patterns, space }, + ) + }) { // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). let k = space.determinant().abs().sqrt(); if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { @@ -694,10 +707,33 @@ fn pattern_xf(space: Affine, matrix: Option, tile: Rect) -> Option= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite())).then_some(xf) } -/// What a style's fills paint with: the file's gradients and pattern tiles, and art space → the document. +/// A pattern fill's `x y scaleX scaleY angle reflect axis shear shearAxis` as one transform of the +/// pattern's space, applied before its initial matrix: the shear (by `shear` degrees along the line +/// at `shearAxis` degrees), the reflection about the line at `axis` degrees when `reflect` isn't +/// 0, the counterclockwise rotation by `angle` degrees, the scale, then the move to `x y`. `None` +/// unless there are nine finite numbers. +fn pattern_controls(n: &[f64]) -> Option { + let &[x, y, sx, sy, angle, reflect, axis, shear, shear_axis] = n else { return None }; + if !n.iter().all(|v| v.is_finite()) { + return None; + } + let turn = |deg: f64| Affine::rotate(deg.to_radians()); + let reflection = if reflect != 0.0 { turn(axis) * Affine::scale_non_uniform(1.0, -1.0) * turn(-axis) } else { Affine::IDENTITY }; + let shearing = if shear != 0.0 { + turn(shear_axis) * Affine::new([1.0, 0.0, shear.to_radians().tan(), 1.0, 0.0, 0.0]) * turn(-shear_axis) + } else { + Affine::IDENTITY + }; + let xf = Affine::translate((x, y)) * Affine::scale_non_uniform(sx, sy) * turn(angle) * reflection * shearing; + xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf) +} + +/// What a style's fills paint with: the file's gradients and pattern tiles, the patterns defined in +/// the version 7 form, and art space → the document. struct StylePaints<'a> { gradients: &'a HashMap, patterns: &'a HashMap, + v7_patterns: &'a HashSet, space: Affine, } @@ -778,11 +814,15 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p }; AppearanceItem::Fill(FillLayer::new(paint)) } - StyleItem::Pattern { name, matrix } => match placed.get(&format!("{PATTERN_KEY}{name}")) { + StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{name}")) { Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())), None => { let tile = paints.patterns.get(name).copied()?; - let xf = pattern_xf(paints.space, matrix.and_then(|m| paint::affine(&m)), tile)?; + let mut matrix = matrix.and_then(|m| paint::affine(&m)); + if paints.v7_patterns.contains(name) { + matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?); + } + let xf = pattern_xf(paints.space, matrix, tile)?; AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: name.clone(), xf })) } }, diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 0437145185..db143d9f62 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -133,10 +133,12 @@ pub(super) enum StyleItem { name: Option, angle: f64, }, - /// A fill with pattern swatch `name`, its space taken to art space by `matrix`. + /// A fill with pattern swatch `name`, its space taken to art space by `matrix`; `controls`, the + /// numbers before the matrix, apply first when the pattern was defined in the version 7 form. Pattern { name: String, matrix: Option<[f64; 6]>, + controls: Vec, }, Stroke { paint: Paint, @@ -199,8 +201,8 @@ struct Filter { gradient: bool, /// The gradient's swatch and angle (`Bg`). gradient_of: Option<(Option, f64)>, - /// `(name) … [matrix] p`. - pattern: Option<(String, Option<[f64; 6]>)>, + /// `(name) … [matrix] p`, and the numbers between the name and the matrix. + pattern: Option<(String, Option<[f64; 6]>, Vec)>, /// `mode opacity … Xy`. xy: Option<(usize, f32)>, /// `… isolate knockout … Xy`. @@ -518,8 +520,10 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V]) { } _ => None, }); + let controls: Vec = + vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect(); if let Some(name) = name { - f.pattern = Some((name, matrix)); + f.pattern = Some((name, matrix, controls)); } } _ => {} @@ -998,7 +1002,7 @@ fn paint_item(f: &Filter) -> Result, ()> { match f.name.as_str() { FILL if !f.paints.1 => Ok(None), FILL => match (&f.pattern, &f.gradient_of, &f.fill) { - (Some((name, matrix)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix })), + (Some((name, matrix, controls)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix, controls: controls.clone() })), (None, Some((name, angle)), _) => Ok(Some(StyleItem::Gradient { name: name.clone(), angle: *angle })), (None, None, _) if f.gradient => Ok(Some(StyleItem::Gradient { name: None, angle: 0.0 })), (None, None, Some(p)) => Ok(Some(StyleItem::Fill(p.clone()))), diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 13316561d3..9ca955eb9a 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use kurbo::{Point, Rect}; +use kurbo::{Affine, Point, Rect}; use vectorcraft_color::gradient::GradientKind; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Guide, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; @@ -525,7 +525,7 @@ fn a_gradient_in_a_patterns_definition_is_placed_from_the_canvas() { /// has that isn't read, where it shows. Its definition costs nothing else. #[test] fn a_pattern_it_cant_read_is_an_error_only_where_it_fills() { - let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L S\n) &\n] E\n%AI3_EndPattern\n\ + let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L frobnicate S\n) &\n] E\n%AI3_EndPattern\n\ %AI3_BeginPattern: (Odd)\n(Odd) 0 0 8 8\n%_U\nE\n%AI3_EndPattern\n%AI3_BeginPattern: (Flat)\n(Flat) 0 0 8 0\n%_0 0 m\n%_8 0 L\n%_S\nE\n%AI3_EndPattern\n"; let s = read_ok(&format!("{unread}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); assert!(s.doc.patterns.is_empty() && s.doc.swatches.iter().all(|w| !matches!(w.paint, Paint::Pattern { .. }))); @@ -565,6 +565,231 @@ fn a_pattern_painting_with_an_unread_pattern_is_not_kept() { } } +/// A pattern's definition inside another's isn't read, so the outer one isn't kept either. +#[test] +fn a_pattern_with_a_definition_inside_it_isnt_kept() { + let tile = rect_path(0.0, 0.0, 8.0, 8.0).replace('\n', "\n%_"); + let inner = "%AI3_BeginPattern: (In)\n(In) 0 0 1 1\n%_0 0 m\n%_1 1 L\n%_S\nE\n%AI3_EndPattern\n"; + let def = format!("%AI3_BeginPattern: (Out)\n(Out) 0 0 8 8\n{inner}%_{tile}f\nE\n%AI3_EndPattern\n"); + let s = read_ok(&format!("{def}{}", layer(""))); + assert!(s.doc.patterns.is_empty(), "{:?}", s.doc.patterns.iter().map(|p| &p.name).collect::>()); + // Without the definition inside it, it is kept. + let s = read_ok(&format!("{}{}", def.replace(inner, ""), layer(""))); + assert!(s.doc.pattern("Out").is_some()); +} + +/// A definition whose art follows its head as operators is still read when that art starts with a +/// dash array (`[]0 d`) off `%_` lines, which isn't a version 7 layer list. +#[test] +fn a_pattern_whose_art_starts_with_a_dash_array_is_read() { + let def = format!("%AI3_BeginPattern: (Dash)\n(Dash) 0 0 8 8 []0 d\n{}f\nE\n%AI3_EndPattern\n", rect_path(0.0, 0.0, 8.0, 8.0)); + let s = read_ok(&format!("{def}{}", layer(""))); + assert_eq!(s.doc.pattern("Dash").map(|p| p.art.len()), Some(1)); +} + +/// Editing data in the version 7 form: `%AI5_FileFormat 2.0`, the art size around the template +/// box's center (an artboard 200 by 100 from the origin), `setup` (pattern definitions), then `body`. +fn pattern_stream7(setup: &str, body: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 2.0\n%AI5_ArtSize: 200 100\n%AI3_TemplateBox: 100 50 100 50\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n{setup}%%EndSetup\n{body}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n" + ) +} + +/// One layer named `name` with the version 7 form's ten operands before `Lb`, holding `art`. +fn pattern_layer7(name: &str, art: &str) -> String { + format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n({name}) Ln\n0 A\n{art}LB\n%AI5_EndLayer--\n") +} + +/// A definition of `name` in the version 7 form: its 20-point tile, then `layers`, the layer list. +fn pattern7(name: &str, layers: &str) -> String { + format!("%AI3_BeginPattern: ({name})\n({name}) 0 0 20 20 [\n%AI3_Tile\n{layers}] E\n%AI3_EndPattern\n") +} + +fn pattern_read7(setup: &str, body: &str) -> Structure { + match read(pattern_stream7(setup, body).as_bytes()) { + Ok(s) => s, + Err(e) => panic!("{e}"), + } +} + +/// A definition in the version 7 form (§3.4): each layer's colors (`@`) paint its tile's art (`&`), +/// the first layer the lowest. The operator lines in the strings end in CR, and each layer starts +/// from the definition's state, so the second layer's stroke doesn't take the first one's width. +#[test] +fn version_7_pattern_layers_paint_in_order_with_their_own_colors() { + let layers = "(0 O 0 R 1 0 0 0 k\r1 0 0 0 K) @\n(\r%AI6_BeginPatternLayer\r0 J 0 j 3 w 4 M []0 d\r2 2 m\r9 2 L\r9 9 L\r2 9 L\rf\r%AI6_EndPatternLayer\r) &\n\ + (0 O 1 R 0 0 0 1 k\r0 0 0 1 K) @\n(\r2 12 m\r18 12 L\rS\r) &\n"; + let fill_with = format!("(Grid) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0)); + let s = pattern_read7(&pattern7("Grid", layers), &pattern_layer7("Art", &fill_with)); + assert!(s.unread.is_empty() && s.warnings.is_empty(), "{:?} {:?}", s.unread, s.warnings); + let def = s.doc.pattern("Grid").unwrap(); + assert_eq!(def.tile, Rect::new(0.0, -20.0, 20.0, 0.0), "the tile, y down"); + assert_eq!(def.art.len(), 2, "one path for each layer"); + let (square, line) = (&def.art[0], &def.art[1]); + assert_eq!(square.geometric_bounds(), Some(Rect::new(2.0, -9.0, 9.0, -2.0))); + assert_eq!(fill(square).color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0))); + assert!(square.appearance.stroke().is_none()); + assert!(line.appearance.fill().is_none()); + let stroke = line.appearance.stroke().unwrap(); + assert_eq!(stroke.paint.color(), Some(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert_eq!(stroke.width, 1.0, "the first layer's width stays with it"); + assert!(stroke.overprint); + assert!(matches!(fill(&art(&s.doc)[0]), Paint::Pattern { pattern, .. } if pattern == "Grid")); +} + +/// `_ &` fills the tile's box with the layer's fill color, without a stroke (§3.4). +#[test] +fn a_version_7_patterns_underbar_fills_the_tile_box() { + let layers = "(0 O 0 R 0 1 0 0 k 0 0 0 1 K) @ _ &\n(0 0 0 1 k 0 0 0 1 K) @ (2 2 m 18 18 L S) &\n"; + let s = pattern_read7(&pattern7("Back", layers), &pattern_layer7("Art", "")); + let def = s.doc.pattern("Back").unwrap(); + let back = &def.art[0]; + assert_eq!(back.geometric_bounds(), Some(def.tile)); + assert_eq!(fill(back).color(), Some(Color::cmyk(0.0, 1.0, 0.0, 0.0))); + assert!(back.appearance.stroke().is_none()); + assert!(def.art[1].appearance.stroke().is_some()); +} + +/// A layer's strings are read with their escapes undone: `\r`, `\n`, an octal tab, a backslash at +/// a line's end, and escaped parentheses around a custom color's name. +#[test] +fn a_version_7_patterns_strings_are_read_with_their_escapes_undone() { + let layers = "(0 O 0 R 0 0 0 1 \\(Ink \\(A\\)\\) 0 x) @\n(2 2 m\\r9 2 L\\n9 9 L\\0112 9 \\\nL f) &\n"; + let s = pattern_read7(&pattern7("Ink", layers), &pattern_layer7("Art", "")); + let def = s.doc.pattern("Ink").unwrap(); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(2.0, -9.0, 9.0, -2.0))); + assert!(s.doc.swatch("Ink (A)").is_some(), "{:?}", s.doc.swatches.iter().map(|w| &w.name).collect::>()); +} + +/// A definition in the version 7 form that can't be read whole isn't kept, and a fill with it is +/// something the file has that isn't read: an operator it doesn't know, type, a definition inside +/// it, colors with other operators, a layer without its tile or its `&`, a string longer than the +/// format allows, an `E`, a group or an array a layer doesn't end, more than 65,536 layers, a list +/// without its `]` or its `E`, anything after its `E`. +#[test] +fn a_version_7_pattern_it_cant_read_whole_isnt_kept() { + let line = "(0 0 m 8 8 L S) &\n"; + let long = format!("(0 g) @ ({}0 0 m 8 8 L S) &\n", " ".repeat(65_536)); + let open = "%AI3_BeginPattern: (P)\n(P) 0 0 20 20 [\n(0 g) @ (0 0 m 8 8 L S) &\n"; + let defs = [ + pattern7("P", "(0 g) @ (0 0 m 8 8 L frobnicate S) &\n"), + pattern7("P", "(0 g) @ (0 To 1 0 0 1 2 2 0 Tp TP (a) Tx TO) &\n"), + pattern7("P", "(0 g) @ (\r%AI3_BeginPattern: (In)\r(In) 0 0 1 1\rE\r%AI3_EndPattern\r0 0 m 8 8 L S) &\n"), + pattern7("P", &format!("%AI3_BeginPattern: (In)\n(In) 0 0 1 1 [\n] E\n%AI3_EndPattern\n(0 g) @ {line}")), + pattern7("P", &format!("(0 g 0 0 m) @ {line}")), + pattern7("P", "(0 g) @\n"), + pattern7("P", "(0 g) @ _\n"), + pattern7("P", &long), + pattern7("P", "(0 g) @ (0 0 m 8 8 L S E) &\n"), + pattern7("P", "(0 g) @ (u 0 0 m 8 8 L S) &\n"), + pattern7("P", "(0 g) @ (0 0 m 8 8 L S [) &\n"), + pattern7("P", "(0 g) @ ([ 0 0 m 8 8 L S) &\n"), + pattern7("P", &"(0 g) @ _ &\n".repeat(65_537)), + format!("{open}E\n%AI3_EndPattern\n"), + format!("{open}]\n%AI3_EndPattern\n"), + format!("{open}] E\n0 0 m 8 8 L S\n%AI3_EndPattern\n"), + ]; + let fill_with = format!("(P) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0)); + for (i, def) in defs.iter().enumerate() { + assert!(pattern_read7(def, &pattern_layer7("Art", "")).doc.patterns.is_empty(), "case {i}"); + assert_unread(&pattern_read7(def, &pattern_layer7("Art", &fill_with)), "pattern fills"); + } + // The same definition, whole, is kept. + let s = pattern_read7(&pattern7("P", &format!("(0 g) @ {line}")), &pattern_layer7("Art", &fill_with)); + assert!(s.doc.pattern("P").is_some() && s.unread.is_empty()); +} + +/// With a pattern defined in the version 7 form, a fill's other operands are applied in order +/// before its initial matrix (§5.4.1): the shear along its axis, the reflection about the line at +/// its angle, the rotation, the scale, then the offset. Identity ones move the tiles by the offset +/// alone. `P` places a stroke's tiles the same way. +#[test] +fn a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear() { + let def = pattern7("Grid", "(0 g) @ _ &\n"); + // The operands, and the pattern's space → art space they make (a b c d e f). + let cases = [ + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, 15.0]), + ("25 30 1.5 .75 30 1 45 10 0 [1 0 0 1 0 0]", [-0.75, 0.649519, 1.166793, 0.489528, 25.0, 30.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, -0.353553, 1.035276, 0.353553, -5.0, 7.0]), + ("3 -4 1.2 .8 20 1 30 12 25 [.8 .1 -.2 1.1 4 -6]", [-0.028557, 0.816531, 1.054026, 0.117492, 7.2, -10.1]), + ]; + // Art space → the document (the artboard is 100 high), and a tile's art (y down from its top + // left) → the pattern's space. + let space = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let tile = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 20.0]); + for (ops, want) in cases { + for (op, paint) in [("p", "f"), ("P", "S")] { + let s = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) {ops} {op}\n{}{paint}\n", rect_path(10.0, 10.0, 90.0, 90.0)))); + let node = &art(&s.doc)[0]; + let p = if op == "p" { fill(node) } else { node.appearance.stroke().unwrap().paint.clone() }; + let Paint::Pattern { xf, .. } = p else { panic!("{ops} {op}: {p:?}") }; + let got = (space.inverse() * xf * tile.inverse()).as_coeffs(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{ops} {op}: {got:?}"); + } + } + // The tiles' corners: with identity operands but the offset, the tile's top left (0, 20) is at + // (10, 35) in art space; with the last ones, its lower right (20, 0) is at (6.628860, 6.230623). + let placed = |ops: &str| { + let s = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) {ops} p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0)))); + let Paint::Pattern { xf, .. } = fill(&art(&s.doc)[0]) else { panic!() }; + xf + }; + assert_eq!(placed(cases[0].0) * Point::ZERO, Point::new(10.0, 65.0)); + assert!((placed(cases[3].0) * Point::new(20.0, 20.0)).distance(Point::new(6.628860, 93.769377)) < 1e-5); + // Without its nine operands, a fill with the pattern isn't read. + let r = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) 0 0 1 1 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0)))); + assert_unread(&r, "pattern fills"); +} + +/// With a pattern defined in the newer form (art on `%_` lines), the matrix alone places the tiles +/// (#1025): the other operands don't move them, and a fill without all nine is still read. +#[test] +fn a_newer_pattern_fill_is_placed_by_its_matrix_alone() { + let placed = |ops: &str| { + let s = read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {ops} p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0))))); + assert!(s.unread.is_empty() && s.warnings.is_empty(), "{ops}: {:?} {:?}", s.unread, s.warnings); + let Paint::Pattern { xf, .. } = fill(&art(&s.doc)[0]) else { panic!("{ops}: {:?}", fill(&art(&s.doc)[0])) }; + xf + }; + let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); + assert_eq!(plain * Point::ZERO, Point::new(0.0, 92.0)); + assert_eq!(placed("25 30 1.5 .75 30 1 45 10 0 [1 0 0 1 0 0]"), plain); + assert_eq!(placed("0 0 1 1 0 0 0 0 [1 0 0 1 0 0]"), plain); +} + +/// An art style `Tiled` whose fill is `(name) {ops} p`. +fn tiled_style(name: &str, ops: &str) -> String { + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Tiled) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n({name}) {ops} p\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// A fill set through an art style on a text object places the tiles as a `p` fill with the same +/// operands does: with the other operands before the matrix for a pattern defined in the version 7 +/// form, by the matrix alone for one defined in the newer form. +#[test] +fn a_style_pattern_fill_is_placed_as_a_direct_one() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + // The text object's drawn look (without a pattern to take the placement from), then the object. + let look = "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nU\n"; + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let ops = "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"; + for (name, def) in [("Grid", pattern7("Grid", "(0 g) @ _ &\n")), ("Dots", DOTS.to_string())] { + let styled = read_ok(&format!("{}{def}{}", tiled_style(name, ops), layer(&format!("{look}{own}1 (Tiled) XW\n")))); + let direct = read_ok(&format!("{def}{}", layer(&format!("({name}) {ops} p\n{rect}f\n")))); + let xf = |s: &Structure| match fill(&art(&s.doc)[0]) { + Paint::Pattern { xf, .. } => xf, + p => panic!("{name}: {p:?} {:?} {:?}", s.unread, s.warnings), + }; + let (got, want) = (xf(&styled).as_coeffs(), xf(&direct).as_coeffs()); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{name}: {got:?} {want:?}"); + } +} + #[test] fn compound_paths_and_clipping() { let art_ = format!( diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 9d748f459f..d4ae4db83e 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -3,6 +3,7 @@ use std::sync::Arc; +use kurbo::Point; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::clipnest::MAX_NEST; use vectorcraft_doc::{LayerColor, LineCap, Node, NodeKind}; @@ -123,6 +124,31 @@ fn a_postscript_ai_that_names_its_prolog_without_including_it_opens_with_its_lay assert_eq!(tree(d.layers[1].children().unwrap()), "p"); } +/// A `.ai` in PostScript form with a pattern defined in the version 7 form (§3.4): the layer keeps +/// its name, and the pattern is a swatch that fills the path from its offset. +#[test] +fn a_postscript_ai_with_a_version_7_pattern_fills_with_it() { + let pattern = "%AI3_BeginPattern: (Stripes)\n(Stripes) 0 0 10 10 [\n%AI3_Tile\n(0 O 0 R 0 0 0 0.5 k) @ _ &\n\ + (0 O 0 R 0 0 0 1 K) @ (\r1 w\r0 5 m\r10 5 L\rS\r) &\n] E\n%AI3_EndPattern\n"; + let setup = "Adobe_IllustratorA_AI3 /initialize get exec\n"; + let style = "0 i 1 J 1 j 0.8 w 4 M []0 d\n0 D\n"; + let src = NAMED_PROLOG + .replace(setup, &format!("{setup}{pattern}")) + .replace(style, &format!("{style}(Stripes) 5 5 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n")) + .replace("10 10 L\nS\n", "10 10 L\nB\n"); + let r = import(src.as_bytes()).unwrap(); + assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings); + let d = &r.document; + assert_eq!(d.layers[0].name.as_deref(), Some("SECTION::Cut")); + assert!(matches!(&d.swatch("Stripes").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Stripes")); + assert_eq!(d.pattern("Stripes").unwrap().art.len(), 2); + let square = &d.layers[0].children().unwrap()[0]; + let Some(Paint::Pattern { pattern, xf }) = square.appearance.fill().map(|f| f.paint.clone()) else { panic!("{:?}", square.appearance) }; + assert_eq!(pattern, "Stripes"); + // The tile's top left, (0, 10) in its space, is at (5, 15) in art space: 85 down the 100-point page. + assert_eq!(xf * Point::ZERO, Point::new(5.0, 85.0)); +} + /// A `.ai` in PostScript form with a graph on each of two layers (version 7 specification §17): its /// data on `%_` lines, then its drawn art in a group, each object followed by `%_… Go`. fn graphs_on_layers() -> String { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 92d6f79d22..6f02703ca5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -104,7 +104,9 @@ private editing data. VectorCraft: without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. Graphs (`%_Gs` … `%_GS`) come in as their drawn art, as plain groups, paths and type, without their data or settings, with a note. without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, with its paragraphs' letter - and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). + and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). Its patterns in + the version 7 form (a list of `@` and `&` layers, `_ &` for the tile's background) open as pattern swatches, + with a fill's offset, scale, rotation, reflection and shear applied before its matrix. - Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. From a870da6c7d3fc686a15ca018c12b90b4cb826c87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:38:47 +0700 Subject: [PATCH 360/674] =?UTF-8?q?.ai=20import:=20Effect=20=E2=80=BA=20Pa?= =?UTF-8?q?thfinder=20on=20a=20group=20opens=20as=20a=20live=20effect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Squashed from #5150 onto main. --- crates/effects/src/group/tests.rs | 17 +++ crates/engine/tests/import_fuzz.rs | 51 +++++++++ crates/eps/src/import/ai/read/ops.rs | 5 +- crates/eps/src/import/ai/style.rs | 79 ++++++++++++-- crates/eps/src/import/ai/style/tests.rs | 138 ++++++++++++++++++++++++ crates/eps/src/import/ai/tests.rs | 74 +++++++++++++ crates/eps/src/import/tests_native.rs | 53 +++++++++ docs/target-app-parity.md | 1 + 8 files changed, 406 insertions(+), 12 deletions(-) diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 7c9f649c7a..b67279bbb4 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -103,6 +103,23 @@ fn shape_modes_follow_the_pathfinder_panel() { assert_eq!(div.len(), 3); } +/// Divide and Outline draw no piece of a member without fill or stroke, the same as when such +/// pieces are left out. +#[test] +fn divide_and_outline_draw_nothing_for_unpainted_members() { + let unpainted = + Arc::new(Node::path(NodeId(2), shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0))); + for effect in ["pathfinder.divide", "pathfinder.outline"] { + let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unpainted.clone()]); + g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true }); + let out = pathfinder_children(&g, None).unwrap(); + assert!(out.iter().any(|n| n.id == NodeId(1)) && out.iter().any(|n| n.id == NodeId(2)), "{effect}: {out:#?}"); + for n in out.iter().filter(|n| n.id == NodeId(2)) { + assert!(n.appearance.items.iter().all(|i| i.paint().is_none()), "{effect}: {n:#?}"); + } + } +} + /// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either /// side of x = 100. fn type_h() -> Node { diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index d3f0c8cc8c..5b858b5f78 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3940,6 +3940,10 @@ fn arb_ai_token() -> impl Strategy { "(Fill Style Filter) 0 0 /Filter ,", "(Adobe Outer Glow) 1 0 /Filter ,", "(Adobe Drop Shadow) 1 0 /Filter ,", + "(Adobe Pathfinder) 1 0 /Filter ,", + "0 /Int (Command) ,", + "0.5 /Real (Mix) ,", + "(Op) /UnicodeString (DisplayString) ,", "(Adobe Transform) 1 0 /Filter ,", "(Adobe Free Distort) 1 0 /Filter ,", "(Adobe Punk and Bloat) 1 0 /Filter ,", @@ -4150,6 +4154,53 @@ proptest! { survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?; } + /// A group with an Effect › Pathfinder style whose dictionary is hostile: any `Command`, keys of + /// any type and value (missing, repeated, unknown, not finite), shown or hidden, the style cut + /// short anywhere; in editing data, an EPS and a `.ai`. A `Command` other than 0 never becomes + /// a live effect. + #[test] + fn ai_pathfinder_styles_never_panic( + command in prop_oneof![(-3i64..16).prop_map(|c| c.to_string()), arb_num()], + keys in prop::collection::vec( + ( + prop::sample::select(vec!["Mix", "Precision", "RemovePoints", "ExtractUnpainted", "ConvertCustom", "TrapTint", "TrapThickness", "Command", "Extra"]), + prop::sample::select(vec!["Int", "Real", "Bool", "String"]), + arb_num(), + ), + 0..16, + ), + hidden in any::(), + cut in 0usize..4_000, + ) { + use vectorcraft_testkit::ai; + let dict: String = keys.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); + let styles = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(PF) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Pathfinder) 1 0 /Filter ,\n{} /Visible ,\n/Dictionary : /NotRecorded ,\n{command} /Int (Command) ,\n{dict}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n", + u8::from(!hidden) + ); + let styles: String = styles.chars().take(cut.max(1)).collect(); + let group = "0 Ae\nu\n1 0 0 1 0 0 Xa\n10 10 m\n10 60 L\n80 60 L\n80 10 L\nf\nU\n\ + %_0 Ae\n%_u\n%_1 0 0 1 0 0 Xa\n%_10 10 m\n%_10 50 L\n%_50 50 L\n%_50 10 L\n%_f\n%_0 0 1 0 0 0 1 Xa\n%_40 20 m\n%_40 60 L\n%_80 60 L\n%_80 20 L\n%_f\n%_U\n1 (PF) XW\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", group))); + let live = command.parse::().is_ok_and(|c| c == 0.0); + let check = |d: Option| { + if let Some(d) = &d + && !live + { + d.walk(|n| assert!(!n.appearance.effects.iter().any(|e| e.id.starts_with("pathfinder.")), "Command {command}: {:?}", n.appearance.effects)); + } + d + }; + survive("hostile Pathfinder style", || check(Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0)))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("hostile Pathfinder style in an EPS", || check(vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc)))?; + let file = ai::ai(data.as_bytes(), ai::page_pdf()); + survive("hostile Pathfinder style in a .ai", || check(vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc)))?; + } + /// Art styles with Offset Path, Outline Object and Outline Stroke, in any order, shown or hidden, /// whose dictionaries hold any of Offset Path's entries and unknown ones, as any kind, with any /// value (huge, tiny, not a number, a string), repeated or left out, on the whole object, a fill diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index f5ce513844..de12631eba 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -776,7 +776,8 @@ fn placed_paints(look: &Node, out: &mut HashMap, depth: usize) { const PATTERN_KEY: &str = "\u{1}pattern "; /// `object`'s appearance with style `st`, its drawn look `look`: `None` when the style isn't one -/// this reads, or asks a group for fills or strokes. +/// this reads, asks a group for fills or strokes, or has Pathfinder effects on anything but a group +/// with no fills or strokes. fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, paints: &StylePaints) -> Option { use crate::import::ai::style::StyleItem; // A text object's slot (an empty group standing for it) takes the style as the type will. @@ -784,6 +785,8 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p if !st.plain || (!slot && !st.simple) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) + || (st.pathfinder + && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) { return None; } diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index db143d9f62..13abd50d27 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -35,13 +35,15 @@ //! A style is *plain* when every filter in it is one read here: fills and strokes (in a colour; fills //! with a pattern or gradient too), each with its own transparency and effects, and the effects of //! [`effect`]. Such objects are read as themselves with an appearance of those fills, strokes and -//! effects; others keep their drawn look. +//! effects; others keep their drawn look. Effect › Pathfinder effects (`(Adobe Pathfinder)` in the +//! object's chain) are read on a group with no fills or strokes of its own, which keeps its members. use std::collections::HashMap; use serde_json::json; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::{Dash, Effect, Knockout, LineCap, LineJoin, WidthProfile}; +use vectorcraft_effects::is_pathfinder; use super::lex::{Lexer, Tok}; use super::obj::V; @@ -68,6 +70,7 @@ const ZIG_ZAG: &str = "Adobe Zigzag"; // brand-ok: the filter's name in the file const GAUSSIAN: &str = "Adobe PSL Gaussian Blur"; // brand-ok: the filter's name in the files const BAS_RELIEF: &str = "PSAdapter_plugin_BsRl"; const SHAPE_EFFECTS: &str = "Adobe Shape Effects"; // brand-ok: the filter's name in the files +const PATHFINDER: &str = "Adobe Pathfinder"; // brand-ok: the filter's name in the files const CHAIN: &str = "Chain Style Filter"; const STACK: &str = "Stack Style Filter"; @@ -101,6 +104,28 @@ pub(super) fn warp_style(n: i64) -> Option<&'static str> { id.strip_prefix("warp.") } +/// The keys of an Effect › Pathfinder › Add filter's dictionary besides `DisplayString`, each with +/// the kind and the one value read: `Command` 0 is Add, and the rest are its Pathfinder Options, +/// Soft Mix and Trap settings +/// (https://community.adobe.com/questions-652/liveeffect-xml-effect-is-added-under-the-object-795137). +/// `Precision` is in microns, as the SDK's `AIOptions` gives it +/// (https://ai-sdk-2020.84.nz/html/struct_a_i_options.html). +const PATHFINDER_ADD: [(&str, Kind, f64); 13] = [ + ("Command", Kind::Int, 0.0), + ("ConvertCustom", Kind::Bool, 1.0), + ("ExtractUnpainted", Kind::Bool, 1.0), + ("Mix", Kind::Real, 0.5), + ("Precision", Kind::Real, 10.0), + ("RemovePoints", Kind::Bool, 0.0), + ("TrapAspect", Kind::Real, 1.0), + ("TrapConvertCustom", Kind::Bool, 0.0), + ("TrapMaxTint", Kind::Real, 1.0), + ("TrapReverse", Kind::Bool, 0.0), + ("TrapThickness", Kind::Real, 0.25), + ("TrapTint", Kind::Real, 0.4), + ("TrapTintTolerance", Kind::Real, 0.05), +]; + /// A plain style's paint, as the object comes in. #[derive(Clone, Debug, Default, PartialEq)] pub(super) struct ArtStyle { @@ -108,7 +133,8 @@ pub(super) struct ArtStyle { pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, - /// Feather, Round Corners, Scribble, Convert to Shape and the Path effects (Offset Path, Outline Object, Outline Stroke) on the object: what any object is read with. Type takes the other plain styles too (its drawn look + /// Feather, Round Corners, Scribble, Convert to Shape and the Path effects (Offset Path, Outline Object, Outline Stroke) on the object + /// (and Pathfinder effects when it has no fills or strokes): what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, /// Its fills and strokes, bottom first. @@ -122,6 +148,8 @@ pub(super) struct ArtStyle { /// The object's own opacity, blend mode, isolation and knockout (its blend filter), when the /// style has them. pub transparency: Option<(f32, BlendMode, bool, Knockout)>, + /// [`Self::effects`] holds Effect › Pathfinder effects, which only a group is read with. + pub pathfinder: bool, } #[derive(Clone, Debug, PartialEq)] @@ -187,6 +215,8 @@ struct Filter { params: HashMap, /// How each key of its dictionary is written. kinds: HashMap, + /// A key of its dictionary is written more than once. + repeated: bool, /// Its dictionary's arrays (`/Array : v /Real , … ; (key) ,`), by key. arrays: HashMap>, fill: Option, @@ -218,6 +248,7 @@ impl Default for Filter { compound: false, params: HashMap::new(), kinds: HashMap::new(), + repeated: false, arrays: HashMap::new(), fill: None, stroke: None, @@ -360,7 +391,8 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { } b"Array" => dict_array = Some(vec![]), b"Int" | b"Real" | b"Bool" => { - let value = operands.iter().rev().find_map(V::num); + // The number right before the type: an earlier one isn't this value. + let value = operands.last().and_then(V::num); operands.clear(); if let Some(a) = dict_array.as_mut() { a.extend(value); @@ -380,7 +412,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { Some(value) => f.params.insert(key.clone(), value), None => f.params.remove(&key), }; - f.kinds.insert(key, kind); + f.repeated |= f.kinds.insert(key, kind).is_some(); } continue; } @@ -419,7 +451,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { None => entry.map(|k| (k, Kind::Other)), }; if let (Some((key, kind)), Some(f)) = (key, filters.last_mut()) { - f.kinds.insert(key, kind); + f.repeated |= f.kinds.insert(key, kind).is_some(); } } if let Some(f) = filters.last_mut() { @@ -991,11 +1023,26 @@ fn effect(f: &Filter, under: Under) -> Option { // Its settings are in a Photoshop plug-in's binary block: the effect's defaults stand in. BAS_RELIEF => ("sketch.basRelief", json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"})), SHAPE_EFFECTS => return shape_effect(f), + PATHFINDER => return pathfinder_effect(f), _ => return None, }; Some(Effect { id: id.into(), params, visible: f.visible }) } +/// Effect › Pathfinder › Add, when every key of [`PATHFINDER_ADD`] is there with its kind and value +/// and the only other key is the `DisplayString` text, each written once. `None` for anything else, +/// which keeps the drawn look. +fn pathfinder_effect(f: &Filter) -> Option { + let known = f.kinds.iter().all(|(key, kind)| (key == "DisplayString" && *kind == Kind::Other) || PATHFINDER_ADD.iter().any(|(k, ..)| k == key)); + if !known || f.repeated || !f.arrays.is_empty() || f.fill.is_some() || f.stroke.is_some() || f.gradient || f.pattern.is_some() { + return None; + } + if !PATHFINDER_ADD.iter().all(|(key, kind, value)| f.kinds.get(*key) == Some(kind) && f.params.get(*key) == Some(value)) { + return None; + } + Some(Effect { id: "pathfinder.add".into(), params: json!({}), visible: f.visible }) +} + /// The fill or stroke basic filter `f` paints, `Ok(None)` when it paints nothing, `Err` when it /// paints in a way this doesn't read. fn paint_item(f: &Filter) -> Result, ()> { @@ -1096,9 +1143,9 @@ impl Builder<'_> { } } // Convert to Shape on one fill or stroke isn't read yet: what it draws there is - // the drawn look's. + // the drawn look's. A fill's or stroke's own Pathfinder effect isn't read either. _ => match effect(c, under) { - Some(e) if !e.id.starts_with("convertToShape.") => look.effects.push(e), + Some(e) if !e.id.starts_with("convertToShape.") && !is_pathfinder(&e.id) => look.effects.push(e), _ => self.plain = false, }, } @@ -1136,6 +1183,7 @@ fn style(filters: &[Filter]) -> ArtStyle { let mut st = ArtStyle { plain: true, ..ArtStyle::default() }; let Some(root) = filters.iter().position(|f| f.parent.is_none()) else { return st }; let mut b = Builder { filters, plain: true }; + let chained = filters[root].compound && filters[root].name == CHAIN; let top = if filters[root].compound { b.children(root) } else { vec![root] }; for id in top { let f = &filters[id]; @@ -1155,12 +1203,19 @@ fn style(filters: &[Filter]) -> ArtStyle { st.transparency = Some((opacity, super::read::blend_mode(mode), isolate, knockout)); } } + // The object's Pathfinder effects are read only in its own chain. _ => match effect(f, ANYTHING) { - Some(e) => st.effects.push(e), - None => b.plain = false, + Some(e) if chained || !is_pathfinder(&e.id) => st.effects.push(e), + _ => b.plain = false, }, } } + st.pathfinder = st.effects.iter().any(|e| is_pathfinder(&e.id)); + // A group's Pathfinder effects are drawn before its other effects: one listed after another + // effect keeps the drawn look. + if st.effects.iter().skip_while(|e| is_pathfinder(&e.id)).any(|e| is_pathfinder(&e.id)) { + b.plain = false; + } st.plain = b.plain; let count = |stroke: bool| st.items.iter().filter(|i| matches!(i, StyleItem::Stroke { .. }) == stroke).count(); st.simple = st.plain @@ -1183,8 +1238,10 @@ fn style(filters: &[Filter]) -> ArtStyle { | "path.offsetPath" | "path.outlineObject" | "path.outlineStroke" - ) - }); + ) || is_pathfinder(&e.id) + }) + // Pathfinder effects on a group with no fills or strokes of its own (`styled` checks the group). + && (!st.pathfinder || st.items.is_empty()); st } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 444f5c4fd9..2815f589c5 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -471,6 +471,58 @@ fn an_effect_not_read_here_keeps_the_drawn_look() { assert!(!art_styles(data.as_bytes())["Odd"].plain); } +/// The dictionary of an Effect › Pathfinder filter with `Command` `command` and `Mix` `mix`, and +/// the other options at the values the effect reads. +fn pathfinder_keys(command: &str, mix: &str) -> String { + format!( + "0 /Bool (RemovePoints) ,\n{mix} /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n{command} /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n\ + 1 /Real (TrapAspect) ,\n0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n\ + (Op) /UnicodeString (DisplayString) ,\n0 /Bool (TrapConvertCustom) ,\n0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n" + ) +} + +/// The style `Group`: the object's chain holding `effects`, a stack whose fill and stroke paint +/// nothing, and the object's transparency. +fn group_style(effects: &[String]) -> ArtStyle { + let stack = compound( + "Stack Style Filter", + &[ + basic("Stroke Style Filter", "/StrokeStyle : 0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n"), + basic("Conduit Filter", ""), + basic( + "Fill Style Filter", + "/FillStyle : 0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n/Def ;\n (FillStyle) ,\n0 /Bool (UseEvenOdd) ,\n", + ), + ], + ); + let mut kids = effects.to_vec(); + kids.extend([stack, blend(0, 1.0)]); + let data = format!("/KnownStyle :\n(Group) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &kids)); + art_styles(data.as_bytes()).remove("Group").unwrap_or_default() +} + +fn pathfinder(keys: &str) -> String { + basic("Adobe Pathfinder", keys) +} + +#[test] +fn pathfinder_add_is_read_as_its_effect() { + // GUARDS: an `Adobe Pathfinder` filter made the style not plain, so a group with it came in as its drawn look. + let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5"))]); + assert!(st.plain && st.simple && st.pathfinder, "{st:?}"); + assert!(st.items.is_empty(), "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{st:?}") }; + assert_eq!((e.id.as_str(), &e.params, e.visible), ("pathfinder.add", &json!({}), true)); +} + +#[test] +fn pathfinder_commands_other_than_add_keep_the_drawn_look() { + for command in 1..=12 { + let st = group_style(&[pathfinder(&pathfinder_keys(&command.to_string(), "0.5"))]); + assert!(!st.plain && !st.pathfinder && st.effects.is_empty(), "{command}: {st:?}"); + } +} + fn stroke(paint: &str) -> String { basic("Stroke Style Filter", &format!("/StrokeStyle : 0 1 0 0 0 Xy\n0 J 0 j 2 w 10 M []0 d0 XR\n{paint}\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n")) } @@ -519,6 +571,92 @@ fn offset_path_on_the_object_is_read_with_its_settings() { } } +#[test] +fn a_hidden_pathfinder_effect_comes_in_hidden() { + let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5")).replacen("1 /Visible", "0 /Visible", 1)]); + assert!(st.simple, "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{st:?}") }; + assert_eq!((e.id.as_str(), e.visible), ("pathfinder.add", false)); +} + +#[test] +fn pathfinder_effects_keep_their_order_among_the_objects_effects() { + let offset = basic("Adobe Offset Path", "3 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n"); + let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5")), offset.clone()]); + assert!(st.plain, "{st:?}"); + assert_eq!(ids(&st.effects), ["pathfinder.add", "path.offsetPath"]); + // GUARDS: an effect before the Pathfinder effect was read too, and the group drew the Pathfinder + // effect first, which isn't what the file draws. + let st = group_style(&[offset, pathfinder(&pathfinder_keys("0", "0.5"))]); + assert!(!st.plain, "{st:?}"); +} + +#[test] +fn pathfinder_settings_this_does_not_read_keep_the_drawn_look() { + let add = pathfinder_keys("0", "0.5"); + let cases = [ + ("no Command", add.replace("0 /Int (Command) ,\n", "")), + ("Trap", add.replace("0 /Int (Command)", "12 /Int (Command)")), + ("unknown Command", add.replace("0 /Int (Command)", "40 /Int (Command)")), + ("negative Command", add.replace("0 /Int (Command)", "-1 /Int (Command)")), + ("fractional Command", add.replace("0 /Int (Command)", "2.5 /Int (Command)")), + ("huge Command", add.replace("0 /Int (Command)", "1e999 /Int (Command)")), + ("Command as a real", add.replace("0 /Int (Command)", "0 /Real (Command)")), + ("Command without a number", add.replace("0 /Int (Command)", "(zero) /Int (Command)")), + // A number before the string isn't its value. + ("Command with a string after a number", add.replace("0 /Int (Command)", "3 (zero) /Int (Command)")), + ("Command twice", add.clone() + "1 /Int (Command) ,\n"), + // GUARDS: the last of a repeated key was read, so a Trap command followed by Add was read as Add. + ("Command twice, Add last", add.replace("0 /Int (Command)", "12 /Int (Command) ,\n0 /Int (Command)")), + ("Command twice, both Add", add.replace("0 /Int (Command)", "0 /Int (Command) ,\n0 /Int (Command)")), + ("an option twice, the read value last", add.replace("10 /Real (Precision)", "5 /Real (Precision) ,\n10 /Real (Precision)")), + ("unknown key", add.clone() + "1 /Int (Extra) ,\n"), + ("unknown string", add.clone() + "(x) /String (Extra) ,\n"), + ("an array", add.clone() + "/Array :\n1 /Real ,\n; (Extra) ,\n"), + ("many strings", add.clone() + &(0..40).map(|i| format!("(x) /String (DisplayString{i}) ,\n")).collect::()), + ("missing option", add.replace("0.25 /Real (TrapThickness) ,\n", "")), + ("missing Mix", add.replace("0.5 /Real (Mix) ,\n", "")), + ("option of the wrong type", add.replace("10 /Real (Precision)", "10 /Int (Precision)")), + ("other Precision", add.replace("10 /Real (Precision)", "5 /Real (Precision)")), + ("huge Precision", add.replace("10 /Real (Precision)", "1e999 /Real (Precision)")), + ("Remove Redundant Points", add.replace("0 /Bool (RemovePoints)", "1 /Bool (RemovePoints)")), + ("unpainted art kept", add.replace("1 /Bool (ExtractUnpainted)", "0 /Bool (ExtractUnpainted)")), + ("other trap tint", add.replace("0.4 /Real (TrapTint)", "0.25 /Real (TrapTint)")), + ("Mix on Add", add.replace("0.5 /Real (Mix)", "0.3 /Real (Mix)")), + ("Mix as a bool", add.replace("0.5 /Real (Mix)", "1 /Bool (Mix)")), + ]; + for (case, keys) in cases { + let st = group_style(&[pathfinder(&keys)]); + assert!(!st.plain && !st.pathfinder && st.effects.is_empty(), "{case}: {st:?}"); + } +} + +#[test] +fn a_pathfinder_effect_outside_the_objects_chain_keeps_the_drawn_look() { + let pf = pathfinder(&pathfinder_keys("0", "0.5")); + // On a fill of its own. + let item = compound("Chain Style Filter", &[pf.clone(), fill("0 0 0 1 0 0 0 Xa")]); + let data = + format!("/KnownStyle :\n(Item) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + let st = &art_styles(data.as_bytes())["Item"]; + assert!(!st.plain, "{st:?}"); + // In a style that isn't an object's chain. + let data = format!("/KnownStyle :\n(Bare) /Name ,\n/ActiveStyle :\n{pf}"); + let st = &art_styles(data.as_bytes())["Bare"]; + assert!(!st.plain && st.effects.is_empty(), "{st:?}"); +} + +#[test] +fn a_pathfinder_effect_with_fills_of_its_own_keeps_the_drawn_look() { + let stack = compound("Stack Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Conduit Filter", "")]); + let data = format!( + "/KnownStyle :\n(Filled) /Name ,\n/ActiveStyle :\n{}", + compound("Chain Style Filter", &[pathfinder(&pathfinder_keys("0", "0.5")), stack]) + ); + let st = &art_styles(data.as_bytes())["Filled"]; + assert!(st.pathfinder && !st.simple, "{st:?}"); +} + #[test] fn outline_object_and_outline_stroke_are_read_with_no_settings() { // GUARDS: `Adobe Outline Type` and `Adobe Outline Stroke` weren't read, so the style kept its drawn look. diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9ca955eb9a..6b1e8622d0 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3248,6 +3248,80 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +/// An art style section with style `PF`: an Effect › Pathfinder filter with `Command` `command` +/// and `Mix` `mix` in the object's chain, over a fill and stroke that paint nothing. +fn pathfinder_styles(command: u32, mix: f64) -> String { + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(PF) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Pathfinder) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + 0 /Bool (RemovePoints) ,\n{mix} /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n{command} /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n\ + 1 /Real (TrapAspect) ,\n0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n\ + (Op) /UnicodeString (DisplayString) ,\n0 /Bool (TrapConvertCustom) ,\n0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n\ + ; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// A group of a red and a blue square with style `PF`: its drawn look (one path of their area), +/// then the group on `%_` lines. +fn pathfinder_group() -> String { + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (PF) XW\n", + rect_path(0.0, 0.0, 15.0, 10.0), + hidden(RED, 0.0), + hidden("0 0 1 0 0 0 1 Xa\n", 5.0) + ) +} + +#[test] +fn a_group_with_a_pathfinder_effect_keeps_its_members_and_the_effect() { + // GUARDS: the style was not read, and the group came in as its drawn look: one path, with no effect. + let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&pathfinder_group()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let members = a[0].children().cloned().unwrap_or_default(); + assert_eq!(members.len(), 2, "the squares, not the look: {a:#?}"); + assert!(members.iter().all(|m| matches!(m.kind, NodeKind::Path { .. })), "{members:#?}"); + assert_eq!((fill(&members[0]).color(), fill(&members[1]).color()), (Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0)))); + let effects: Vec<_> = a[0].appearance.effects.iter().map(|e| (e.id.as_str(), e.visible)).collect(); + assert_eq!(effects, [("pathfinder.add", true)]); + assert!(a[0].appearance.items.is_empty(), "{:?}", a[0].appearance); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +#[test] +fn a_pathfinder_style_this_does_not_read_keeps_the_drawn_look() { + // Another command (Intersect, Trap), and a Precision other than the one read. + let other = pathfinder_styles(0, 0.5).replace("10 /Real (Precision)", "5 /Real (Precision)"); + for styles in [pathfinder_styles(1, 0.5), pathfinder_styles(12, 0.5), other] { + let r = read_ok(&format!("{styles}{}", layer(&pathfinder_group()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let look = a[0].children().cloned().unwrap_or_default(); + assert_eq!(look.len(), 1, "the look's one path: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{:?}", a[0].appearance); + } +} + +#[test] +fn a_path_with_a_pathfinder_effect_keeps_its_drawn_look() { + // Effect › Pathfinder doesn't apply to a lone path: its style stays the drawn look's. + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (PF) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the look, not the path: {a:#?}"); + let mut effects = 0; + r.doc.walk(|n| effects += n.appearance.effects.len()); + assert_eq!(effects, 0); +} + #[test] fn an_object_with_convert_to_shape_comes_in_as_itself_with_the_effect_live() { // GUARDS: `Adobe Shape Effects` wasn't read, so the object came in as its drawn look. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 29a45ae195..daeea4826a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3459,6 +3459,59 @@ fn type_with_a_stacked_art_style_comes_in_as_type_with_that_appearance() { check(&r.document, &r.warnings); } +/// An art style section with style `Add`: Effect › Pathfinder › Add in the object's chain, over a +/// fill and stroke that paint nothing. +fn pathfinder_add_style() -> String { + let basic = |name: &str, body: &str| { + format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n") + }; + let compound = |name: &str, kids: &[String]| format!("/CompoundFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat()); + let add = basic( + "Adobe Pathfinder", + "0 /Bool (RemovePoints) ,\n0.5 /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n0 /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n1 /Real (TrapAspect) ,\n\ + 0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n0 /Bool (TrapConvertCustom) ,\n\ + 0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n", + ); + let stack = compound( + "Stack Style Filter", + &[ + basic("Stroke Style Filter", "/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n"), + basic("Conduit Filter", ""), + basic("Fill Style Filter", "/FillStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (FillStyle) ,\n"), + ], + ); + format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Add) /Name ,\n/ActiveStyle :\n{}%AI9_EndArtStyles\n", compound("Chain Style Filter", &[add, stack])) +} + +#[test] +fn type_in_a_group_with_a_pathfinder_effect_stays_type() { + // GUARDS: the group's style was not read, and the group came in as its drawn look, the type's + // outlines and the square, which can't be retyped. + let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + // The look: the square, and the area round where the type lies (its anchor is at (58.5, 61.5)), + // in the square's yellow. + let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf"; + let look = format!("u\n{}\n{drawing}\nU\n9 () XW\n", square(10, 10)); + let own: String = format!("0 Ae\nu\n{}{}\nU\n", text_object(0), square(10, 10)).lines().map(|l| format!("%_{l}\n")).collect(); + let art = native_with_text(&(pathfinder_add_style() + &layer("Art", true, &format!("{look}{own}1 (Add) XW\n"))), &doc); + let check = |d: &Document, notes: &[String]| { + assert_eq!(kinds(&d.layers[0]), ["group[2]"], "{notes:?}"); + let group = &d.layers[0].children().unwrap()[0]; + let mut kinds = kinds(group); + kinds.sort_unstable(); + assert_eq!(kinds, ["path", "text"], "{notes:?}"); + assert_eq!(text_of(group).iter().map(|t| t.plain_text()).collect::>(), ["Hi"]); + let effects: Vec<_> = group.appearance.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(effects, ["pathfinder.add"], "{notes:?}"); + assert!(!notes.iter().any(|w| w.contains("drawn look")), "{notes:?}"); + }; + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + check(&d, ¬es); + let page = format!("{}\n0 0 1 0 setcmykcolor 54 56 moveto 100 56 lineto 100 80 lineto 54 80 lineto closepath fill", page_square(10, 10)); + let r = import(&eps(&page, &art)).unwrap(); + check(&r.document, &r.warnings); +} + /// An art style section with style `Bent`: a blue fill over the characters, and effect `name`, its /// dictionary holding `keys`, on the whole object. fn whole_object_style(name: &str, keys: &str) -> String { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bccb007687..15d40489a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1113,6 +1113,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304). In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`). + A `.ai` opened from its editing data keeps Effect › Pathfinder on a group with no fills or strokes of its own as a live effect, with the group's members editable: Add, shown or hidden, in its order among the group's effects. The other operations, Pathfinder Options values other than the ones the reader accepts, and the effect on a path, on type, or on a fill or stroke open as the drawn look (`crates/eps/src/import/ai/style.rs`, `pathfinder_effect`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). A `.ai` or PDF whose editing data holds a readable variable library opens with its variable definitions, data-set rows, text, visibility and linked-file values, active row and lock in the Variables panel, whether its layers are read or it comes in as its PDF part; graph values and malformed entries are skipped with a note, and objects aren't bound yet (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data keeps each artboard's center mark, cross hairs, video safe areas and video ruler pixel aspect ratio, and the file's Document Raster Effects Settings; the author comes from the header's `%%For` (the editing data's, else an EPS's own) when the file's File Info gives none, the header's custom colors that no swatch has come in as spot swatches, a named color the file defines takes the place of a default swatch of that name when the file has no palette, and an older file's `%%TemplateBox` places its artboard. A value of another type or out of range keeps its default (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). From 58faa73909886f55ab83511472749b10459f7ae0 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 16:39:05 +0700 Subject: [PATCH 361/674] .ai import: drop the SDK mirror citation from the Pathfinder Add keys --- crates/eps/src/import/ai/style.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 13abd50d27..e1947bfdaf 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -108,8 +108,6 @@ pub(super) fn warp_style(n: i64) -> Option<&'static str> { /// the kind and the one value read: `Command` 0 is Add, and the rest are its Pathfinder Options, /// Soft Mix and Trap settings /// (https://community.adobe.com/questions-652/liveeffect-xml-effect-is-added-under-the-object-795137). -/// `Precision` is in microns, as the SDK's `AIOptions` gives it -/// (https://ai-sdk-2020.84.nz/html/struct_a_i_options.html). const PATHFINDER_ADD: [(&str, Kind, f64); 13] = [ ("Command", Kind::Int, 0.0), ("ConvertCustom", Kind::Bool, 1.0), From 2380e889bc33d25c34fc4277dc5124e1d03ef8e1 Mon Sep 17 00:00:00 2001 From: "Prin.Ing" <267065148+Prin-Ing@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:27:29 +0000 Subject: [PATCH 362/674] Group flattened multi-line transparent type by line Fixes #5252 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/flatten/apply.rs | 56 +++++++++++++++++++++++++- crates/engine/src/tests/flatten.rs | 27 +++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index cccd82ecc8..e4113b47b1 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -26,6 +26,40 @@ pub(super) struct Flat { /// Where its image goes, and the image (once rendered). pub(super) area: Option, raster: Option, + /// When the group is one block of type over several lines: its lines, to group the regions by. + lines: Option, +} + +/// The lines of a block of type: document space → its line space, where each line spans a band +/// across the lines (its ascent above the baseline to its descent below). +struct Lines { + to_lines: Affine, + bands: Vec<(f64, f64)>, +} + +impl Lines { + /// The lines of `n` when it is type laid out in two lines or more (not on a path). + fn of(n: &Node) -> Option { + let NodeKind::Text(t) = &n.kind else { return None }; + if t.xf.determinant().abs() < 1e-12 { + return None; + } + let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + if layout.on_path { + return None; + } + let bands: Vec<(f64, f64)> = layout.lines.iter().filter(|l| l.x1 > l.x0).map(|l| (l.baseline - l.ascent, l.baseline + l.descent)).collect(); + let to_lines = if layout.vertical { layout.line_xf.inverse() * t.xf.inverse() } else { t.xf.inverse() }; + (bands.len() > 1).then_some(Lines { to_lines, bands }) + } + + /// The line nearest to the middle of `path`. + fn line_of(&self, path: &PathData) -> usize { + let Some(b) = path.bounds() else { return 0 }; + let y = (self.to_lines * b.center()).y; + let away = |&(lo, hi): &(f64, f64)| if y < lo { lo - y } else { (y - hi).max(0.0) }; + self.bands.iter().enumerate().min_by(|a, b| away(a.1).total_cmp(&away(b.1))).map_or(0, |(i, _)| i) + } } /// Where a group's image goes. @@ -97,7 +131,11 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: } None => None, }; - out.flat.push(Flat { roots: ids, regions, area, raster }); + let lines = match g.as_slice() { + [i] => Lines::of(&art[*i]), + _ => None, + }; + out.flat.push(Flat { roots: ids, regions, area, raster, lines }); } Ok(out) } @@ -366,7 +404,10 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan children.push(Arc::new(raster_node(d, r))); rasterized += 1; } + // Type over several lines gives a group per line. + let mut by_line: Vec>> = f.lines.as_ref().map_or(vec![], |l| vec![vec![]; l.bands.len()]); for (path, fill) in f.regions { + let line = f.lines.as_ref().map(|l| l.line_of(&path)); let mut n = shape_node(d, path, None); n.appearance = Appearance { items: vec![AppearanceItem::Fill(FillLayer { overprint: fill.overprint, ..FillLayer::new(fill.paint) })], @@ -374,9 +415,20 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan } .into(); n.opacity = fill.alpha.min(1.0); - children.push(Arc::new(n)); + match line.and_then(|i| by_line.get_mut(i)) { + Some(l) => l.push(Arc::new(n)), + None => children.push(Arc::new(n)), + } vector += 1; } + by_line.retain(|l| !l.is_empty()); + if by_line.len() > 1 { + for l in by_line { + children.push(Arc::new(Node::group(d.alloc_id(), l))); + } + } else { + children.extend(by_line.into_iter().flatten()); + } let g = Node::group(d.alloc_id(), children); ids.push(g.id); if one_pass { diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index e2b9b4f6ad..d4671c11e3 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -381,6 +381,33 @@ fn outlined_type_keeps_its_underline() { assert!(b.y1 > 151.0, "{b:?}"); } +/// Flattening transparent type that runs over several lines gives a group per line, each holding +/// that line's regions (#5252). +#[test] +fn flattening_multiline_transparent_text_gives_one_group_per_line() { + let _settings = settings_lock(); + let mut s = session(); + let text = + run(&mut s, "text.create", json!({"x": 10, "y": 40, "text": "First line\nSecond line\nThird line", "size": 24}))["id"].as_u64().unwrap(); + run(&mut s, "transparency.set", json!({"ids": [text], "opacity": 50})); + let NodeKind::Text(t) = &node(&s, text).kind else { panic!("type") }; + let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let baselines: Vec = layout.baselines().iter().map(|(a, _)| (t.xf * *a).y).collect(); + assert_eq!(baselines.len(), 3, "{baselines:?}"); + let before = picture(&s); + let (ids, vector, _) = flatten(&mut s, json!({"ids": [text]})); + assert_eq!(ids.len(), 1); + assert!(vector > 0); + let g = node(&s, ids[0]); + let lines: Vec<&std::sync::Arc> = g.children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Group { .. })).collect(); + assert_eq!(lines.len(), 3, "expected one group per line, got {} children", g.children().unwrap().len()); + for (line, y) in lines.iter().zip(&baselines) { + let b = line.geometric_bounds().unwrap(); + assert!(b.y0 > y - 24.0 && b.y1 < y + 10.0, "line at baseline {y} has bounds {b:?}"); + assert_regions_match(&s, &before, line.id.0, 2, "line"); + } +} + #[test] fn outlined_type_keeps_its_gradient_on_the_outlines_its_transform_effect_moves() { let _settings = settings_lock(); From 7db34d9ee05d62d58bd4d1011f68f7682a7acbb8 Mon Sep 17 00:00:00 2001 From: JonRC Date: Tue, 3 Nov 2026 07:11:43 -0300 Subject: [PATCH 363/674] Fix #5342: `eexec` skips in the file it is given `eexec` dropped its file operand and skipped the encrypted part of a font program to `cleartomark` in the program's own file. With `currentfile eexec` inside a file run with `cvx exec`, the program goes on in that file, so the skip searched the outer file instead and failed or skipped the wrong text. Ghostscript's eps2write runs each embedded Type 1 font program that way, so an EPS with one did not open. `eexec` now skips in its operand, through the same file reading as the other data operators: the program's own file or the file being run. A string operand skips in the file being read, as before. --- crates/eps/src/import/data/ops.rs | 28 ++++++++++++++++++++++------ crates/eps/src/import/tests.rs | 12 +++++++++--- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index a39d56081f..c5c588557c 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -435,10 +435,11 @@ impl Interp<'_> { Ok(out) } - /// `eexec`: an encrypted font program follows. It is skipped (type is drawn in the app's - /// fonts, by name): the font dictionary it would complete is defined as it is. + /// `file eexec`: an encrypted font program follows in `file`. It is skipped there, up to the + /// `cleartomark` that ends it (type is drawn in the app's fonts, by name): the font + /// dictionary it would complete is defined as it is. fn eexec(&mut self) -> Res { - self.pop()?; + let src = self.pop()?; if let Some(Obj::Dict(d)) = self.stack.last().cloned() { let name = d.borrow().get(&Key::name("FontName")).cloned(); if let Some(k) = name.and_then(|n| n.key()) { @@ -446,9 +447,24 @@ impl Interp<'_> { self.fonts.borrow_mut().insert(k, Obj::Dict(d)); } } - let rest = self.lex.data(); - let at = find(rest, b"cleartomark").ok_or(PsError::Ps("ioerror", "eexec".into()))?; - self.lex.advance(at); + // `currentfile eexec`: the program's own file or the file being run. A string operand + // skips in the file being read. + let f = match src { + Obj::File { stream, .. } => stream, + _ => self.running.last().cloned().unwrap_or_else(|| Rc::new(RefCell::new(Stream::Current))), + }; + self.materialize(&f)?; + let missing = || PsError::Ps("ioerror", "eexec".into()); + match &mut *f.borrow_mut() { + Stream::Buf { data, pos, .. } => { + let at = find(data.get(*pos..).unwrap_or_default(), b"cleartomark").ok_or_else(missing)?; + *pos += at; + } + _ => { + let at = find(self.lex.data(), b"cleartomark").ok_or_else(missing)?; + self.lex.advance(at); + } + } self.push(Obj::Mark) } diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 20593f0e6e..52c098bb05 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -717,14 +717,20 @@ fn type_42_fonts_set_type_at_their_size() { } } +/// The encrypted part of a font program is skipped up to its `cleartomark` in the file it is in: +/// the program's own file, or a file being run (`cvx exec`), as Ghostscript's `eps2write` runs +/// each Type 1 font it embeds. #[test] fn embedded_font_programs_are_skipped() { let body = "/MyFont 10 dict begin /FontName /MyFont def /FontMatrix [0.001 0 0 0.001 0 0] def currentdict end currentfile eexec\n\ 0123456789abcdef garbage that is encrypted\n0000000000000000000000000000000000000000000000000000000000000000\ncleartomark\n\ /MyFont findfont 10 scalefont setfont 10 10 moveto (x) show"; - let r = read(body); - let NodeKind::Text(t) = &objects(&r.document)[0].kind else { panic!("{:?}", r.warnings) }; - assert_eq!(t.runs[0].style.font_family, "My Font"); + for program in [body.to_string(), format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{body}\nendstream\n")] { + let r = read(&program); + let NodeKind::Text(t) = &objects(&r.document)[0].kind else { panic!("{program}: {:?}", r.warnings) }; + assert_eq!(t.runs[0].style.font_family, "My Font"); + assert!(r.warnings.is_empty(), "{program}: {:?}", r.warnings); + } } /// A document with what the writer writes in its own ways: gradients, type, an image with From 4e75f135e9194908414f60dde0fcc8d869297a94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 04:50:29 -0800 Subject: [PATCH 364/674] Docs: consolidate assessment target metadata --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 15d40489a6..a76d8e44ab 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; Units › East Asian Type acts, with Q and Ha units; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence From d13660e8bc70317c2212410cd5cf50b046e22d0f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 04:54:22 -0800 Subject: [PATCH 365/674] Tests: isolate font wheel picking from missing-glyph protection --- crates/ui-egui/src/tests/font_menu.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 624c32c7ea..fa80c359d9 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -206,6 +206,9 @@ fn a_press_outside_the_menu_ends_the_preview_at_once() { /// A document with point type in Inter, selected; its id. fn selected_inter(app: &mut VectorcraftApp) -> u64 { app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + // These tests exercise font picking, including system fonts without Latin glyphs. Missing + // glyph protection would intentionally keep the sample text in its previous font. + app.run("prefs.set", json!({"key": "missingGlyphProtection", "value": false})).unwrap(); let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Gagaku", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); if !crate::panel_docking::showing(&app.ui, "character") { From d11764c11751897ad076d9db327c6e144e71cac4 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:54:57 +0530 Subject: [PATCH 366/674] Fix #5236: Edit Original opens linked files in a chosen app MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Preferences › File Handling › Edit Original With picks the app Links panel › Edit Original opens a linked file in: System Default (as before), PhotoCraft (found in /Applications or ~/Applications on macOS, on the PATH elsewhere) or Other Application, with a path field and Choose…. The desktop host's new `open_file_with` service starts only an application (an .app bundle on macOS, an .exe on Windows, an executable file elsewhere), with the path as its only argument and never through a shell. Edit Original still refuses control requests. Co-Authored-By: Claude Opus 5.5 --- apps/vectorcraft/src/host_services.rs | 143 +++++++++++++++++++++++ crates/engine/src/cmd/prefscmds.rs | 2 + crates/engine/src/prefs.rs | 5 + crates/ui-egui/src/io.rs | 4 +- crates/ui-egui/src/io/export.rs | 10 ++ crates/ui-egui/src/panels/links.rs | 2 +- crates/ui-egui/src/panels/tests_links.rs | 42 +++++++ crates/ui-egui/src/prefs_dialog.rs | 84 +++++++++++++ crates/ui-egui/src/prefs_dialog/tests.rs | 27 +++++ crates/ui-egui/src/services.rs | 7 ++ docs/control-protocol.md | 4 + docs/mcp.md | 4 +- 12 files changed, 331 insertions(+), 3 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index e25332b61a..e23cea2434 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -300,6 +300,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { reveal: Some(Box::new(reveal)), // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. open_file: Some(Box::new(open_file)), + // Edit Original with Preferences › File Handling › Edit Original With set (#5236). + open_file_with: Some(Box::new(open_file_with)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] @@ -334,3 +336,144 @@ fn open_file(path: &str) -> Result<(), String> { c.arg(path); c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}")) } + +/// Edit Original with Preferences › File Handling › Edit Original With set (#5236): open `path` in +/// `app` (`photocraft`, or an application's path). The app must be an application ([`check_app`]); +/// it gets the path as its only argument and is never started through a shell. +fn open_file_with(app: &str, path: &str) -> Result<(), String> { + explorer_safe(path)?; + let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from); + let app = resolve_app(app, home.as_deref(), std::env::var_os("PATH").as_deref())?; + check_app(&app)?; + #[cfg(target_os = "macos")] + let mut c = { + let mut c = std::process::Command::new("open"); + c.arg("-a").arg(&app).arg(path); + c + }; + #[cfg(not(target_os = "macos"))] + let mut c = { + let mut c = std::process::Command::new(&app); + c.arg(path); + c + }; + c.spawn().map(|_| ()).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) +} + +/// The application Edit Original With names: PhotoCraft where it is installed for `photocraft` +/// ([`photocraft_candidates`]), else the path as given. +pub(crate) fn resolve_app(app: &str, home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Result { + if app.trim().eq_ignore_ascii_case("photocraft") { + return photocraft_candidates(home, path_var) + .into_iter() + .find(|p| check_app(p).is_ok()) + .ok_or_else(|| "PhotoCraft isn't installed: choose another app in Preferences › File Handling › Edit Original With".to_string()); + } + Ok(std::path::PathBuf::from(app.trim())) +} + +/// Where PhotoCraft may be installed: the Applications folders on macOS, else a `photocraft` +/// program on the `PATH`. +pub(crate) fn photocraft_candidates(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Vec { + if cfg!(target_os = "macos") { + let mut v = vec![std::path::PathBuf::from("/Applications/PhotoCraft.app")]; + v.extend(home.map(|h| h.join("Applications/PhotoCraft.app"))); + return v; + } + let name = if cfg!(windows) { "photocraft.exe" } else { "photocraft" }; + path_var.map(|p| std::env::split_paths(p).map(|dir| dir.join(name)).collect()).unwrap_or_default() +} + +/// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on +/// Windows, an executable file elsewhere? Anything else (a document, a folder, a script on +/// Windows) is refused, so the preference can only ever open an installed app. +pub(crate) fn check_app(app: &std::path::Path) -> Result<(), String> { + let ext = app.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + let ok = if cfg!(target_os = "macos") { + ext == "app" && app.is_dir() + } else if cfg!(windows) { + ext == "exe" && app.is_file() + } else { + executable_file(app) + }; + if ok { Ok(()) } else { Err(format!("{} isn't an application Edit Original can open files in", app.display())) } +} + +#[cfg(unix)] +fn executable_file(p: &std::path::Path) -> bool { + use std::os::unix::fs::PermissionsExt as _; + std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) +} + +#[cfg(not(unix))] +fn executable_file(p: &std::path::Path) -> bool { + p.is_file() +} + +#[cfg(test)] +mod open_with_tests { + use super::{check_app, photocraft_candidates, resolve_app}; + + /// A fresh, empty folder under the system's temporary folder. + fn scratch(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + /// #5236: Edit Original With only ever starts an application, never a document, a folder or a + /// missing path. + #[test] + fn only_applications_are_started() { + let d = scratch("check"); + let doc = d.join("notes.txt"); + std::fs::write(&doc, "hi").unwrap(); + assert!(check_app(&doc).is_err(), "a document"); + assert!(check_app(&d).is_err(), "a folder"); + assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path"); + if cfg!(target_os = "macos") { + let app = d.join("Editor.app"); + std::fs::create_dir_all(&app).unwrap(); + assert!(check_app(&app).is_ok(), "an .app bundle"); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + use std::os::unix::fs::PermissionsExt as _; + let tool = d.join("editor"); + std::fs::write(&tool, "#!/bin/sh\n").unwrap(); + assert!(check_app(&tool).is_err(), "not executable yet"); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(check_app(&tool).is_ok(), "an executable file"); + } + let _ = std::fs::remove_dir_all(&d); + } + + /// `photocraft` is looked for where PhotoCraft installs; any other value is taken as a path. + #[test] + fn photocraft_is_found_where_it_installs() { + let d = scratch("find"); + assert_eq!(resolve_app("/Apps/Other.app", None, None).unwrap(), std::path::PathBuf::from("/Apps/Other.app")); + if cfg!(target_os = "macos") { + let candidates = photocraft_candidates(Some(&d), None); + assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app")); + assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}"); + std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap(); + assert!(resolve_app("PhotoCraft", Some(&d), None).unwrap().ends_with("PhotoCraft.app")); + } else { + let bin = d.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let path_var = std::env::join_paths([&bin]).unwrap(); + assert!(resolve_app("photocraft", None, Some(&path_var)).is_err(), "not installed"); + let exe = bin.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" }); + std::fs::write(&exe, "").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + assert_eq!(resolve_app("photocraft", None, Some(&path_var)).unwrap(), exe); + } + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 6950eeaace..d1aff0ca58 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -372,6 +372,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("newArtBasic", "General", "Appearance Panel", "New Art Has Basic Appearance", bool), // File Handling (continued) p!("templatesFolder", "File Handling", "Files", "Templates Folder", text), + // "" (the system's default app), `photocraft` or an application's path (#5236). + p!("editOriginalApp", "File Handling", "Files", "Edit Original With", text), p!("appendConverted", "File Handling", "Files", "Mark Older Files as [Converted] When Opened", bool), // Native saves (`document.save {compress}`) p!("useCompression", "File Handling", "Files", "Use Compression", bool), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index db3ee7e752..46c3d111ff 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -253,6 +253,10 @@ pub struct Prefs { // File Handling (continued) /// Where Save as Template and New from Template start ("" = `Documents/VectorCraft Templates`). pub templates_folder: String, + /// The app Links panel › Edit Original opens a linked file in (#5236): "" = the system's + /// default app for the file, `photocraft` = PhotoCraft wherever it is installed, else the path + /// of an application. + pub edit_original_app: String, /// Open older native files as " [Converted]" so Save asks for a new name. pub append_converted: bool, /// File Handling → Use Compression: native saves are gzip-compressed (`document.save @@ -464,6 +468,7 @@ impl Default for Prefs { pdf_presets: vec![], screen_export_presets: vec![], templates_folder: String::new(), + edit_original_app: String::new(), append_converted: true, use_compression: false, web_export_presets: vec![], diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 89c102f358..38a67400a0 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -18,7 +18,9 @@ mod open; mod save; pub use export::{EXPORT_CANCELLED, cancel_exports, export, export_for_screens, export_pdf, hide_exports, reveal, save_command_output}; -pub(crate) use export::{export_files, exported_with_notes, file_url, open_in_app, reveal_path, run_to_file, save_command_output_named}; +pub(crate) use export::{ + export_files, exported_with_notes, file_url, open_in_app, open_original, reveal_path, run_to_file, save_command_output_named, +}; pub(crate) use open::{EXPORT_PRESETS, import_presets, opened}; pub use open::{ MAX_RECENT_FILES, OpensAs, ask_revert, install_module, install_plugin, new_from_template, note_recent, open_bytes, open_dialog, open_document, diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 60c7656dda..592d60ec00 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -217,6 +217,16 @@ pub(crate) fn open_in_app(app: &mut VectorcraftApp, path: &str) -> Result<(), St app.services.open_file.as_mut().ok_or("no app to open files here")?(path) } +/// Edit Original: open `path` in the app Preferences › File Handling › Edit Original With names +/// (#5236), or in the system's default app for it when that is System Default (""). +pub(crate) fn open_original(app: &mut VectorcraftApp, path: &str) -> Result<(), String> { + let with = app.session.prefs.edit_original_app.trim().to_string(); + if with.is_empty() { + return open_in_app(app, path); + } + app.services.open_file_with.as_mut().ok_or("no app to open files in here")?(&with, path) +} + /// File → Export for Screens with `document.exportForScreens` params: the files go into `folder`; /// without one the web downloads them (the ZIP, or each file) and the other frontends get them /// back as base64. With `openLocation`, the file manager shows the first file written. When an diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 9e751cf1f5..9fc91f5068 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -227,7 +227,7 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Re } else { app.refuse_automation("links.editOriginal")?; openable_original(&path)?; - crate::io::open_in_app(app, &path)?; + crate::io::open_original(app, &path)?; } Ok(json!({ "path": path })) } diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 98e1dd250e..fb323122c2 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -168,6 +168,48 @@ fn edit_original_and_show_in_folder_hand_the_file_to_the_system() { assert!(app.run("links.editOriginal", json!({"id": linked})).is_err()); } +/// #5236: Preferences › File Handling › Edit Original With picks the app Edit Original opens the +/// file in: System Default ("") hands it to the system's default app as before, PhotoCraft or an +/// application's path to that app. +#[test] +fn edit_original_opens_the_file_in_the_chosen_app() { + /// What each open asked for: (the app, `None` for the system's default, and the path). + type Opened = Rc, String)>>>; + let dir = Folder::new("with"); + let (mut app, linked, _) = app(&dir); + let opened: Opened = Rc::default(); + let (o, w) = (opened.clone(), opened.clone()); + app.services.open_file = Some(Box::new(move |p: &str| { + o.borrow_mut().push((None, p.to_string())); + Ok(()) + })); + app.services.open_file_with = Some(Box::new(move |with: &str, p: &str| { + w.borrow_mut().push((Some(with.to_string()), p.to_string())); + Ok(()) + })); + let path = app.run("links.editOriginal", json!({"id": linked})).unwrap()["path"].as_str().unwrap().to_string(); + for value in ["photocraft", "/Applications/Example.app"] { + app.run("prefs.set", json!({"key": "editOriginalApp", "value": value})).unwrap(); + app.run("links.editOriginal", json!({"id": linked})).unwrap(); + } + app.run("prefs.set", json!({"key": "editOriginalApp", "value": ""})).unwrap(); + app.run("links.editOriginal", json!({"id": linked})).unwrap(); + assert_eq!( + *opened.borrow(), + [ + (None, path.clone()), + (Some("photocraft".into()), path.clone()), + (Some("/Applications/Example.app".into()), path.clone()), + (None, path.clone()), + ] + ); + // An app the host can't open in (the web) is an error, not the default app instead. + app.run("prefs.set", json!({"key": "editOriginalApp", "value": "photocraft"})).unwrap(); + app.services.open_file_with = None; + assert!(app.run("links.editOriginal", json!({"id": linked})).is_err()); + assert_eq!(opened.borrow().len(), 4); +} + /// Edit Original hands only regular image and document files to the system's default app. #[test] fn edit_original_opens_image_and_document_files_only() { diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index b91c149f45..03ee49be9e 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -176,6 +176,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); let (mut ok, mut cancel, mut reset) = (false, false, false); + d.fields.insert(CAN_PICK_APP.into(), json!(crate::picks::can(app, &crate::picks::PickRequest::Open(app_pick())))); let cat = d.str("__category"); let cat = PREF_CATEGORIES.iter().find(|c| **c == cat).copied().unwrap_or(PREF_CATEGORIES[0]); crate::dialogs::modal::show(ctx, tl!("Preferences"), egui::Id::unique("dialog-preferences"), -20.0, 20, |ui| { @@ -242,6 +243,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { d.fields.insert(k, v); } } + if d.fields.remove(CHOOSE_APP).is_some() { + choose_app(app, &mut d); + } app.ui.dialog = Some(d); if cancel { app.ui.dialog = None; @@ -380,6 +384,7 @@ fn category_fields(ui: &mut egui::Ui, d: &mut Dialog, cat: &str) { } }); } + PrefKind::Text if sp.key == "editOriginalApp" => edit_original_row(ui, d, sp.key, sp.label, &v), PrefKind::Text => { labeled(ui, sp.label, |ui| { let mut s = v.as_str().unwrap_or("").to_string(); @@ -410,6 +415,85 @@ fn choice_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, opts: & }); } +/// File Handling › Edit Original With (#5236): System Default (""), PhotoCraft (`photocraft`) or +/// Other Application, which shows a field for the application's path. +fn edit_original_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, v: &Value) { + const OPTIONS: [&str; 3] = ["System Default", "PhotoCraft", "Other Application"]; + let cur = v.as_str().unwrap_or("").trim().to_string(); + let photocraft = cur.eq_ignore_ascii_case("photocraft"); + // Other Application with no path typed yet is still System Default: remember the choice. + let chose_other = egui::Id::unique("prefs-edit-original-other"); + let mut other = !photocraft && (!cur.is_empty() || ui.ctx().data(|m| m.get_temp::(chose_other)).unwrap_or(false)); + let at = if photocraft { + 1 + } else if other { + 2 + } else { + 0 + }; + labeled(ui, label, |ui| { + if let Some(i) = widgets::dropdown(ui, key, OPTIONS[at], &OPTIONS, 260.0) { + other = i == 2; + ui.ctx().data_mut(|m| m.insert_temp(chose_other, other)); + let new = match i { + 0 => String::new(), + 1 => "photocraft".to_string(), + _ if photocraft => String::new(), + _ => cur.clone(), + }; + d.fields.insert(key.into(), json!(new)); + } + }); + if other { + let can_pick = d.bool(CAN_PICK_APP); + labeled(ui, "Application Path", |ui| { + let mut s = if photocraft { String::new() } else { cur.clone() }; + let width = if can_pick { 186.0 } else { 260.0 }; + let field = egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(width); + let hint = if cfg!(target_os = "macos") { "/Applications/Example.app" } else { "" }; + if ui.add(field.hint_text(hint)).changed() { + d.fields.insert(key.into(), json!(s)); + } + // The open dialog runs from `show`, which has the app ([`choose_app`]). + if can_pick && widgets::flat_button(ui, tl!("Choose…"), 68.0).clicked() { + d.fields.insert(CHOOSE_APP.into(), json!(true)); + } + }); + } +} + +/// UI-only dialog fields for Edit Original With's Choose… button: whether the host shows an open +/// dialog, and that the button was clicked this frame. +const CAN_PICK_APP: &str = "__canPickApp"; +const CHOOSE_APP: &str = "__chooseApp"; + +/// The open dialog Edit Original With's Choose… shows: applications (`.app` bundles in +/// Applications on macOS, `.exe` files on Windows, any file elsewhere). +fn app_pick() -> crate::FilePick { + let filters: Vec = if cfg!(target_os = "macos") { + vec![("Applications".into(), vec!["app".into()])] + } else if cfg!(windows) { + vec![("Programs".into(), vec!["exe".into()])] + } else { + vec![] + }; + let folder = cfg!(target_os = "macos").then(|| "/Applications".to_string()); + crate::FilePick { name: String::new(), folder, filters } +} + +/// Edit Original With › Choose…: the picked application into the dialog's `editOriginalApp`. Shown +/// off the UI thread, the answer fills the dialog as it is then ([`crate::picks::in_dialog`]). +fn choose_app(app: &mut VectorcraftApp, d: &mut Dialog) { + let r = crate::picks::in_dialog(app, d, |app, d| { + if let Some(path) = crate::picks::open(app, &app_pick()) { + d.fields.insert("editOriginalApp".into(), json!(path)); + } + Ok(()) + }); + // Picking a file doesn't fail. + let _ = r; +} + fn bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { // The app's outlined checkbox (it translates `label`): egui's own has no border at rest. let on = d.bool(key); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 80fb23a176..32dee4b4ba 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -391,3 +391,30 @@ fn hyphenation_exceptions_dialog_ok_reaches_the_hyphenator() { assert!(vectorcraft_text::hyphen::hyphen_points("typography").is_empty()); assert_eq!(vectorcraft_text::hyphen::hyphen_points("happen"), vec![3]); } + +/// #5236: File Handling › Edit Original With offers System Default, PhotoCraft and Other +/// Application, whose Choose… puts the picked application into the preference. +#[test] +fn edit_original_with_takes_a_chosen_application() { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Edit Original With") && text.contains("System Default"), "{text}"); + let asked: std::rc::Rc>> = Default::default(); + let seen = asked.clone(); + a.services.pick_open = Some(Box::new(move |p: &crate::FilePick| { + seen.borrow_mut().push(p.clone()); + Some("/Applications/Editor.app".into()) + })); + let mut d = a.ui.dialog.clone().unwrap(); + choose_app(&mut a, &mut d); + assert_eq!(d.str("editOriginalApp"), "/Applications/Editor.app"); + let pick = asked.borrow()[0].clone(); + if cfg!(target_os = "macos") { + assert_eq!((pick.folder.as_deref(), pick.filters[0].1.clone()), (Some("/Applications"), vec!["app".to_string()])); + } + // OK saves it; the dialog's own fields (`__…`) are not preferences. + a.ui.dialog = Some(d); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.edit_original_app, "/Applications/Editor.app"); +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 45f363eda1..7e00322bcc 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -65,6 +65,9 @@ pub(crate) fn browsable_url(url: &str) -> Result<(), String> { /// Shows a file in the system file manager, or opens it in its app. pub type RevealFn = Box Result<(), String>>; +/// Opens a file in a chosen app: `(app, path)`. +pub type OpenWithFn = Box Result<(), String>>; + /// Platform services injected by the host app (desktop or web). #[derive(Default)] pub struct Services { @@ -116,6 +119,10 @@ pub struct Services { /// Open a file (or a folder) in the system's default app for it (desktop: Edit Original, Show /// Package). Without it (the web) those answer with an error. pub open_file: Option, + /// Open a file in a chosen app (desktop: Edit Original with Preferences › File Handling › Edit + /// Original With set): `(app, path)`, where `app` is `photocraft` or an application's path. + /// Without it (the web) Edit Original with an app set answers with an error. + pub open_file_with: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, and diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3da08ad0f9..8c624dcb57 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -668,6 +668,10 @@ one undo step. The Links panel (`window.panel {panel: "links"}`) shows `links.li `links.info`; `links.editOriginal` and `links.reveal` (Edit › Edit Original, Show in Folder) hand the linked file to the system and return `{path}`. Edit Original opens only a regular file whose extension is a format `document.open` reads, and answers a control request with an error unless the file is a placed document (which opens in a tab). +The preference `editOriginalApp` (Preferences › File Handling › Edit Original With, #5236) picks the app: `""` (System +Default, the system's default app for the file), `"photocraft"` (PhotoCraft where it is installed) or an application's +path. The app must be an application (an `.app` bundle on macOS, an `.exe` on Windows, an executable file elsewhere), +and gets the file's path as its only argument. Package: File → Package… (`ui.packageDialog`) opens the `package` dialog for a saved document (a document never saved gets a `confirm` dialog whose OK runs `file.saveAs`). Fields: `folder` (the location), `name` (the package folder), diff --git a/docs/mcp.md b/docs/mcp.md index 6878e137b4..2befc0205d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4216,7 +4216,9 @@ file is missing stays linked: relink it first); `links.unembed {id, path}` write clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and `links.reveal` open the linked file in its app or show it in its folder (desktop). Edit Original runs only from the app's window, -except for a placed document, which opens in a tab. +except for a placed document, which opens in a tab. The preference `editOriginalApp` (Preferences › File Handling › +Edit Original With) picks the app Edit Original opens the file in: `""` (the system's default app), `"photocraft"` or an +application's path (#5236). ```json {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} From 695cc04e06904254db1531de41570d70a33d43b4 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:28:25 +0530 Subject: [PATCH 367/674] Fix #5236: Edit Original With keeps its Other choice in the dialog and paths with spaces The Other Application choice (before a path is typed) is a `__` field of the Preferences dialog instead of egui memory, so a dialog opened again or reset starts at System Default. The path field shows the stored value untrimmed, so spaces can be typed. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/prefs_dialog.rs | 19 ++++++++++++------- crates/ui-egui/src/prefs_dialog/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 03ee49be9e..97be221468 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -242,6 +242,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { for (k, v) in Prefs::default().to_json().as_object().cloned().unwrap_or_default() { d.fields.insert(k, v); } + d.fields.remove(CHOSE_OTHER_APP); } if d.fields.remove(CHOOSE_APP).is_some() { choose_app(app, &mut d); @@ -419,11 +420,13 @@ fn choice_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, opts: & /// Other Application, which shows a field for the application's path. fn edit_original_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, v: &Value) { const OPTIONS: [&str; 3] = ["System Default", "PhotoCraft", "Other Application"]; - let cur = v.as_str().unwrap_or("").trim().to_string(); + // The field shows the value as stored, spaces included (the host trims it when it opens). + let raw = v.as_str().unwrap_or("").to_string(); + let cur = raw.trim().to_string(); let photocraft = cur.eq_ignore_ascii_case("photocraft"); - // Other Application with no path typed yet is still System Default: remember the choice. - let chose_other = egui::Id::unique("prefs-edit-original-other"); - let mut other = !photocraft && (!cur.is_empty() || ui.ctx().data(|m| m.get_temp::(chose_other)).unwrap_or(false)); + // Other Application with no path typed yet is still System Default: the dialog remembers the + // choice in a field of its own, which a new dialog and Reset Preferences start without. + let mut other = !photocraft && (!cur.is_empty() || d.bool(CHOSE_OTHER_APP)); let at = if photocraft { 1 } else if other { @@ -434,12 +437,12 @@ fn edit_original_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, labeled(ui, label, |ui| { if let Some(i) = widgets::dropdown(ui, key, OPTIONS[at], &OPTIONS, 260.0) { other = i == 2; - ui.ctx().data_mut(|m| m.insert_temp(chose_other, other)); + d.fields.insert(CHOSE_OTHER_APP.into(), json!(other)); let new = match i { 0 => String::new(), 1 => "photocraft".to_string(), _ if photocraft => String::new(), - _ => cur.clone(), + _ => raw.clone(), }; d.fields.insert(key.into(), json!(new)); } @@ -447,7 +450,7 @@ fn edit_original_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, if other { let can_pick = d.bool(CAN_PICK_APP); labeled(ui, "Application Path", |ui| { - let mut s = if photocraft { String::new() } else { cur.clone() }; + let mut s = if photocraft { String::new() } else { raw.clone() }; let width = if can_pick { 186.0 } else { 260.0 }; let field = egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(width); let hint = if cfg!(target_os = "macos") { "/Applications/Example.app" } else { "" }; @@ -466,6 +469,8 @@ fn edit_original_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, /// dialog, and that the button was clicked this frame. const CAN_PICK_APP: &str = "__canPickApp"; const CHOOSE_APP: &str = "__chooseApp"; +/// UI-only dialog field: Other Application was chosen, though no path is typed yet. +const CHOSE_OTHER_APP: &str = "__choseOtherApp"; /// The open dialog Edit Original With's Choose… shows: applications (`.app` bundles in /// Applications on macOS, `.exe` files on Windows, any file elsewhere). diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 32dee4b4ba..143adc6e6f 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -418,3 +418,25 @@ fn edit_original_with_takes_a_chosen_application() { confirm(&mut a).unwrap(); assert_eq!(a.session.prefs.edit_original_app, "/Applications/Editor.app"); } + +/// #5327 review: choosing Other Application before a path is typed is remembered by the dialog +/// itself, so a dialog opened again (or reset) starts at System Default, and a stored path keeps +/// its spaces. +#[test] +fn edit_original_with_other_is_the_dialogs_own_choice() { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + assert!(!a.ui.dialog.as_ref().unwrap().bool(CHOSE_OTHER_APP), "a new dialog starts without the choice"); + let shown = |a: &mut VectorcraftApp| crate::tests_labels::painted_text(a, |a, ui| show(a, ui.ctx())).contains("Application Path"); + assert!(!shown(&mut a), "System Default shows no path field"); + a.ui.dialog.as_mut().unwrap().fields.insert(CHOSE_OTHER_APP.into(), json!(true)); + assert!(shown(&mut a), "Other Application with no path yet shows the field"); + a.ui.dialog = None; + open(&mut a, Some("File Handling")); + assert!(!shown(&mut a), "opened again: System Default"); + // A path with spaces is kept as typed. + let path = "/Applications/Visual Studio Code.app"; + a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalApp".into(), json!(path)); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.edit_original_app, path); +} From 7c5670b7978537f00f1c205388c4da6b4975a224 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:46:48 +0530 Subject: [PATCH 368/674] Fix #5236: report a failed open -a, and keep Other Application while its path is cleared macOS: wait for `open -a` (it returns once Launch Services has the request) and report its error, such as a folder named .app that isn't a bundle; other platforms still start the editor without waiting. A saved or typed path also sets the dialog's Other Application choice, so clearing it to type another keeps the field. Co-Authored-By: Claude Opus 5.5 --- apps/vectorcraft/src/host_services.rs | 14 ++++++++++++++ crates/ui-egui/src/prefs_dialog.rs | 5 +++++ crates/ui-egui/src/prefs_dialog/tests.rs | 5 +++++ 3 files changed, 24 insertions(+) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index e23cea2434..4004050ff6 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -357,6 +357,20 @@ fn open_file_with(app: &str, path: &str) -> Result<(), String> { c.arg(path); c }; + // macOS: `open` returns once Launch Services has the request, so waiting for it is brief and + // reports an app it can't open (a folder named `.app` that isn't a bundle). Elsewhere the + // editor itself runs: waiting would last until it closes. + #[cfg(target_os = "macos")] + { + let out = c.output().map_err(|e| format!("can't open {path} in {}: {e}", app.display()))?; + if out.status.success() { + return Ok(()); + } + let why = String::from_utf8_lossy(&out.stderr).trim().to_string(); + let why = if why.is_empty() { out.status.to_string() } else { why }; + Err(format!("can't open {path} in {}: {why}", app.display())) + } + #[cfg(not(target_os = "macos"))] c.spawn().map(|_| ()).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 97be221468..ef18c3ec58 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -427,6 +427,11 @@ fn edit_original_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, // Other Application with no path typed yet is still System Default: the dialog remembers the // choice in a field of its own, which a new dialog and Reset Preferences start without. let mut other = !photocraft && (!cur.is_empty() || d.bool(CHOSE_OTHER_APP)); + // A path (saved or typed) also counts as the choice, so clearing it to type another keeps the + // field. + if other && !d.bool(CHOSE_OTHER_APP) { + d.fields.insert(CHOSE_OTHER_APP.into(), json!(true)); + } let at = if photocraft { 1 } else if other { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 143adc6e6f..c2557aedec 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -434,6 +434,11 @@ fn edit_original_with_other_is_the_dialogs_own_choice() { a.ui.dialog = None; open(&mut a, Some("File Handling")); assert!(!shown(&mut a), "opened again: System Default"); + // A saved path counts as the choice: clearing it to type another keeps the field. + a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalApp".into(), json!("/Applications/Old.app")); + assert!(shown(&mut a)); + a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalApp".into(), json!("")); + assert!(shown(&mut a), "the path cleared: still Other Application"); // A path with spaces is kept as typed. let path = "/Applications/Visual Studio Code.app"; a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalApp".into(), json!(path)); From 79c8d1a7e02190ce0f60e6d75445303ba1031631 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:56:29 +0530 Subject: [PATCH 369/674] Fix #5236: cap the wait for open -a at two seconds A stalled `open -a` no longer holds the window: Edit Original waits at most two seconds for its exit status (enough to report an app it can't open), then leaves the launch running and reaps it on a thread of its own. Co-Authored-By: Claude Opus 5.5 --- apps/vectorcraft/src/host_services.rs | 39 ++++++++++++++++++++------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 4004050ff6..2568ae03ba 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -357,18 +357,39 @@ fn open_file_with(app: &str, path: &str) -> Result<(), String> { c.arg(path); c }; - // macOS: `open` returns once Launch Services has the request, so waiting for it is brief and - // reports an app it can't open (a folder named `.app` that isn't a bundle). Elsewhere the - // editor itself runs: waiting would last until it closes. + // macOS: `open` returns once Launch Services has the request, so a short wait reports an app + // it can't open (a folder named `.app` that isn't a bundle). The wait is capped so a stalled + // `open` never holds the window: past it, the launch is left to run. Elsewhere the editor + // itself runs: waiting would last until it closes. #[cfg(target_os = "macos")] { - let out = c.output().map_err(|e| format!("can't open {path} in {}: {e}", app.display()))?; - if out.status.success() { - return Ok(()); + const WAIT: std::time::Duration = std::time::Duration::from_secs(2); + let fail = |why: String| format!("can't open {path} in {}: {why}", app.display()); + let mut child = c.stderr(std::process::Stdio::piped()).spawn().map_err(|e| fail(e.to_string()))?; + let started = std::time::Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) if status.success() => return Ok(()), + Ok(Some(status)) => { + let mut why = String::new(); + if let Some(mut err) = child.stderr.take() { + // Best effort: without its message the exit status says why. + let _ = std::io::Read::read_to_string(&mut err, &mut why); + } + let why = why.trim().to_string(); + return Err(fail(if why.is_empty() { status.to_string() } else { why })); + } + Ok(None) if started.elapsed() < WAIT => std::thread::sleep(std::time::Duration::from_millis(20)), + Ok(None) => { + // Reaped off the UI thread once it ends. + std::thread::spawn(move || { + let _ = child.wait(); + }); + return Ok(()); + } + Err(e) => return Err(fail(e.to_string())), + } } - let why = String::from_utf8_lossy(&out.stderr).trim().to_string(); - let why = if why.is_empty() { out.status.to_string() } else { why }; - Err(format!("can't open {path} in {}: {why}", app.display())) } #[cfg(not(target_os = "macos"))] c.spawn().map(|_| ()).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) From d7aa1c561f9a98ced3595576ec1537aa9834c0e5 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:18:32 +0530 Subject: [PATCH 370/674] Fix #5236: Edit Original is one checkbox, Use System Defaults for Edit Original MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per review on #5327: Preferences › File Handling › Edit Original With (an app path and Choose…) becomes the checkbox Use System Defaults for Edit Original, on by default. Off, Edit Original opens a raster image in the app that made it, PhotoCraft, looked for only where it installs; any other file, or no PhotoCraft, goes to the system's default app. The preference is a boolean, so prefs.set over control or MCP can no longer name an executable. The label has a row in all 26 catalogs. Co-Authored-By: Claude Opus 5.5 --- apps/vectorcraft/src/host_services.rs | 52 ++++++------- crates/engine/src/cmd/prefscmds.rs | 4 +- crates/engine/src/prefs.rs | 10 +-- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/io/export.rs | 18 +++-- crates/ui-egui/src/panels/tests_links.rs | 54 +++++++------- crates/ui-egui/src/prefs_dialog.rs | 94 ------------------------ crates/ui-egui/src/prefs_dialog/tests.rs | 55 ++------------ crates/ui-egui/src/services.rs | 12 +-- docs/control-protocol.md | 8 +- docs/mcp.md | 6 +- 36 files changed, 113 insertions(+), 226 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 2568ae03ba..2ed5f55308 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -300,8 +300,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { reveal: Some(Box::new(reveal)), // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. open_file: Some(Box::new(open_file)), - // Edit Original with Preferences › File Handling › Edit Original With set (#5236). - open_file_with: Some(Box::new(open_file_with)), + // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). + open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] @@ -337,14 +337,14 @@ fn open_file(path: &str) -> Result<(), String> { c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}")) } -/// Edit Original with Preferences › File Handling › Edit Original With set (#5236): open `path` in -/// `app` (`photocraft`, or an application's path). The app must be an application ([`check_app`]); -/// it gets the path as its only argument and is never started through a shell. -fn open_file_with(app: &str, path: &str) -> Result<(), String> { +/// Edit Original with Preferences › File Handling › Use System Defaults for Edit Original off +/// (#5236): open the raster image `path` in PhotoCraft, found only where it installs +/// ([`find_photocraft`]); `Ok(false)` when it isn't installed. PhotoCraft gets the path as its only +/// argument and is never started through a shell. +fn open_in_photocraft(path: &str) -> Result { explorer_safe(path)?; let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from); - let app = resolve_app(app, home.as_deref(), std::env::var_os("PATH").as_deref())?; - check_app(&app)?; + let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) }; #[cfg(target_os = "macos")] let mut c = { let mut c = std::process::Command::new("open"); @@ -369,7 +369,7 @@ fn open_file_with(app: &str, path: &str) -> Result<(), String> { let started = std::time::Instant::now(); loop { match child.try_wait() { - Ok(Some(status)) if status.success() => return Ok(()), + Ok(Some(status)) if status.success() => return Ok(true), Ok(Some(status)) => { let mut why = String::new(); if let Some(mut err) = child.stderr.take() { @@ -385,26 +385,19 @@ fn open_file_with(app: &str, path: &str) -> Result<(), String> { std::thread::spawn(move || { let _ = child.wait(); }); - return Ok(()); + return Ok(true); } Err(e) => return Err(fail(e.to_string())), } } } #[cfg(not(target_os = "macos"))] - c.spawn().map(|_| ()).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) + c.spawn().map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display())) } -/// The application Edit Original With names: PhotoCraft where it is installed for `photocraft` -/// ([`photocraft_candidates`]), else the path as given. -pub(crate) fn resolve_app(app: &str, home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Result { - if app.trim().eq_ignore_ascii_case("photocraft") { - return photocraft_candidates(home, path_var) - .into_iter() - .find(|p| check_app(p).is_ok()) - .ok_or_else(|| "PhotoCraft isn't installed: choose another app in Preferences › File Handling › Edit Original With".to_string()); - } - Ok(std::path::PathBuf::from(app.trim())) +/// PhotoCraft where it is installed: the first of [`photocraft_candidates`] that is an application. +pub(crate) fn find_photocraft(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Option { + photocraft_candidates(home, path_var).into_iter().find(|p| check_app(p).is_ok()) } /// Where PhotoCraft may be installed: the Applications folders on macOS, else a `photocraft` @@ -421,7 +414,7 @@ pub(crate) fn photocraft_candidates(home: Option<&std::path::Path>, path_var: Op /// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on /// Windows, an executable file elsewhere? Anything else (a document, a folder, a script on -/// Windows) is refused, so the preference can only ever open an installed app. +/// Windows) found where PhotoCraft installs is not taken for it. pub(crate) fn check_app(app: &std::path::Path) -> Result<(), String> { let ext = app.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); let ok = if cfg!(target_os = "macos") { @@ -447,7 +440,7 @@ fn executable_file(p: &std::path::Path) -> bool { #[cfg(test)] mod open_with_tests { - use super::{check_app, photocraft_candidates, resolve_app}; + use super::{check_app, find_photocraft, photocraft_candidates}; /// A fresh, empty folder under the system's temporary folder. fn scratch(name: &str) -> std::path::PathBuf { @@ -457,8 +450,8 @@ mod open_with_tests { d } - /// #5236: Edit Original With only ever starts an application, never a document, a folder or a - /// missing path. + /// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing + /// path. #[test] fn only_applications_are_started() { let d = scratch("check"); @@ -484,22 +477,21 @@ mod open_with_tests { let _ = std::fs::remove_dir_all(&d); } - /// `photocraft` is looked for where PhotoCraft installs; any other value is taken as a path. + /// PhotoCraft is looked for only where it installs. #[test] fn photocraft_is_found_where_it_installs() { let d = scratch("find"); - assert_eq!(resolve_app("/Apps/Other.app", None, None).unwrap(), std::path::PathBuf::from("/Apps/Other.app")); if cfg!(target_os = "macos") { let candidates = photocraft_candidates(Some(&d), None); assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app")); assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}"); std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap(); - assert!(resolve_app("PhotoCraft", Some(&d), None).unwrap().ends_with("PhotoCraft.app")); + assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app")); } else { let bin = d.join("bin"); std::fs::create_dir_all(&bin).unwrap(); let path_var = std::env::join_paths([&bin]).unwrap(); - assert!(resolve_app("photocraft", None, Some(&path_var)).is_err(), "not installed"); + assert!(find_photocraft(None, Some(&path_var)).is_none(), "not installed"); let exe = bin.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" }); std::fs::write(&exe, "").unwrap(); #[cfg(unix)] @@ -507,7 +499,7 @@ mod open_with_tests { use std::os::unix::fs::PermissionsExt as _; std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); } - assert_eq!(resolve_app("photocraft", None, Some(&path_var)).unwrap(), exe); + assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe)); } let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index d1aff0ca58..ad24afacbc 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -372,8 +372,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("newArtBasic", "General", "Appearance Panel", "New Art Has Basic Appearance", bool), // File Handling (continued) p!("templatesFolder", "File Handling", "Files", "Templates Folder", text), - // "" (the system's default app), `photocraft` or an application's path (#5236). - p!("editOriginalApp", "File Handling", "Files", "Edit Original With", text), + // Off: raster images open in PhotoCraft where it is installed (#5236). + p!("editOriginalSystemDefaults", "File Handling", "Files", "Use System Defaults for Edit Original", bool), p!("appendConverted", "File Handling", "Files", "Mark Older Files as [Converted] When Opened", bool), // Native saves (`document.save {compress}`) p!("useCompression", "File Handling", "Files", "Use Compression", bool), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 46c3d111ff..5deb00ddde 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -253,10 +253,10 @@ pub struct Prefs { // File Handling (continued) /// Where Save as Template and New from Template start ("" = `Documents/VectorCraft Templates`). pub templates_folder: String, - /// The app Links panel › Edit Original opens a linked file in (#5236): "" = the system's - /// default app for the file, `photocraft` = PhotoCraft wherever it is installed, else the path - /// of an application. - pub edit_original_app: String, + /// File Handling → Use System Defaults for Edit Original (#5236): Links panel › Edit Original + /// opens a linked file in the system's default app for it; off, in the app that made it + /// (PhotoCraft for a raster image, where it is installed; the system's app otherwise). + pub edit_original_system_defaults: bool, /// Open older native files as " [Converted]" so Save asks for a new name. pub append_converted: bool, /// File Handling → Use Compression: native saves are gzip-compressed (`document.save @@ -468,7 +468,7 @@ impl Default for Prefs { pdf_presets: vec![], screen_export_presets: vec![], templates_folder: String::new(), - edit_original_app: String::new(), + edit_original_system_defaults: true, append_converted: true, use_compression: false, web_export_presets: vec![], diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 614054f41a..d64cd51179 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1799,6 +1799,7 @@ font-technology Variable Променливи Manually Ръчно Mark as trapped Маркиране като прехванато Mark Older Files as [Converted] When Opened Маркиране на по-стари файлове като [Конвертирани] при отваряне + Use System Defaults for Edit Original Системни настройки по подразбиране за „Редактиране на оригинал“ Marker… Маркер… Marks Маркери Marks and Bleed Маркери и изтичане diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a0b4e236db..7e29b19084 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3560,6 +3560,7 @@ theme Appearance Izgled List Preferences Izlistaj postavke Manually Ručno Mark Older Files as [Converted] When Opened Označi starije datoteke kao [Pretvoreno] pri otvaranju + Use System Defaults for Edit Original Koristi sistemske zadane postavke za Uredi original Match User Interface Brightness Uskladi sa svjetlinom korisničkog interfejsa Light Gray Svijetlosiva Medium Gray Srednje siva diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2a1f0a518d..2c9ea12679 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2330,6 +2330,7 @@ digits Malayalam Malaiàlam Manually Manualment Mark as trapped Marca com a reventat Mark Older Files as [Converted] When Opened Marca els fitxers antics com a [Convertit] en obrir-los + Use System Defaults for Edit Original Utilitza els valors per defecte del sistema per a Edita l’original Marker… Marcador… Marks Marques Marks and Bleed Marques i sangrat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b9e6fd7406..dede785a75 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3601,6 +3601,7 @@ theme Appearance Motiv List Preferences Vypsat předvolby Manually Ručně Mark Older Files as [Converted] When Opened Při otevření označit starší soubory jako [Converted] + Use System Defaults for Edit Original Pro Upravit originál použít výchozí aplikace systému Match User Interface Brightness Odpovídat jasu uživatelského rozhraní Light Gray Světle šedá Medium Gray Středně šedá diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 20a0a4dfec..6d307f60f1 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3328,6 +3328,7 @@ theme Appearance Udseende List Preferences Oplist indstillinger Manually Manuelt Mark Older Files as [Converted] When Opened Markér ældre filer som [konverteret] ved åbning + Use System Defaults for Edit Original Anvend systemets standarder til Redigér original Match User Interface Brightness Match lysstyrken i brugergrænsefladen Light Gray Lysegrå Medium Gray Mellemgrå diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 94430d21ee..f1aece5390 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1861,6 +1861,7 @@ file-filter Templates Vorlagen Manually Manuell Mark as trapped Als überfüllt kennzeichnen Mark Older Files as [Converted] When Opened Ältere Dateien beim Öffnen als [Konvertiert] kennzeichnen + Use System Defaults for Edit Original Systemstandards für „Original bearbeiten“ verwenden Marker… Markierung… Marks Marken Marks and Bleed Marken und Anschnitt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 0a7d2be71c..56e14d395d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2651,6 +2651,7 @@ theme Appearance Εμφάνιση Manually Χειροκίνητα Mark as trapped Σήμανση ως επικαλυπτόμενου Mark Older Files as [Converted] When Opened Σήμανση παλαιότερων αρχείων ως [Μετατράπηκε] κατά το άνοιγμα + Use System Defaults for Edit Original Χρήση προεπιλογών συστήματος για την Επεξεργασία πρωτοτύπου Marker… Δείκτης… Marks Σημάδια Marks and Bleed Σημάδια και ξάκρισμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4e5ba28d4e..84b860be9f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1864,6 +1864,7 @@ font-technology Variable Variables Manually Manualmente Mark as trapped Marcar como reventado Mark Older Files as [Converted] When Opened Marcar archivos antiguos como [Convertido] al abrirlos + Use System Defaults for Edit Original Usar valores predeterminados del sistema para Editar original Marker… Marcador… Marks Marcas Marks and Bleed Marcas y sangrado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index c75f15ba54..14d0957e02 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3525,6 +3525,7 @@ theme Appearance Ulkoasu List Preferences Luettele asetukset Manually Manuaalisesti Mark Older Files as [Converted] When Opened Merkitse vanhemmat tiedostot [Muunnettu] avattaessa + Use System Defaults for Edit Original Käytä järjestelmän oletuksia toiminnossa Muokkaa alkuperäistä Match User Interface Brightness Sovita käyttöliittymän kirkkauteen Light Gray Vaaleanharmaa Medium Gray Keskiharmaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20b608bb4f..0e8434dc4e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1858,6 +1858,7 @@ font-technology Variable Variables Manually Manuellement Mark as trapped Marquer comme grossi-maigri Mark Older Files as [Converted] When Opened Marquer les anciens fichiers comme [Converti] à l’ouverture + Use System Defaults for Edit Original Utiliser les applications par défaut du système pour Modifier l’original Marker… Marqueur… Marks Repères Marks and Bleed Repères et fond perdu diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 12e8b0ec1f..e3fee02cb5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2351,6 +2351,7 @@ file-filter Templates Sablonok Manually Kézzel Mark as trapped Megjelölés csapdázottként Mark Older Files as [Converted] When Opened Régebbi fájlok megjelölése [Átalakítva] címkével megnyitáskor + Use System Defaults for Edit Original Rendszer alapértelmezéseinek használata az Eredeti szerkesztéséhez Marker… Jelölő… Marks Jelek Marks and Bleed Jelek és kifutó diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8e4aa69f2f..06cf4da3aa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3328,6 +3328,7 @@ theme Appearance Tampilan List Preferences Daftarkan preferensi Manually Secara manual Mark Older Files as [Converted] When Opened Tandai file lama sebagai [Converted] saat dibuka + Use System Defaults for Edit Original Gunakan default sistem untuk Edit asli Match User Interface Brightness Sesuaikan dengan kecerahan antarmuka pengguna Light Gray Abu-abu terang Medium Gray Abu-abu sedang diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6fd38b0f77..742624e12d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1893,6 +1893,7 @@ file-filter Templates Modelli Manually Manualmente Mark as trapped Contrassegna come sottoposto a trapping Mark Older Files as [Converted] When Opened Contrassegna i file meno recenti come [Convertito] all'apertura + Use System Defaults for Edit Original Usa le impostazioni predefinite di sistema per Modifica originale Marker… Indicatore… Marks Segni Marks and Bleed Segni e abbondanza diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5096fef13c..1584618d11 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2094,6 +2094,7 @@ digits Malayalam マラヤーラム数字 Manage Workspaces ワークスペースを管理 Manually 手動 Mark Older Files as [Converted] When Opened 古いファイルを開くときに[変換]と表示 + Use System Defaults for Edit Original 「オリジナルを編集」にシステムのデフォルトを使用 Mark as trapped トラップ済みとしてマーク Marks トンボ Match User Interface Brightness ユーザーインターフェイスの明るさに合わせる diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5389e1f093..fabc4a3694 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3138,6 +3138,7 @@ theme Appearance იერსახე List Preferences პარამეტრების სია Manually ხელით Mark Older Files as [Converted] When Opened ძველი ფაილების მარკირება როგორც [გარდაქმნილი] გახსნისას + Use System Defaults for Edit Original სისტემის ნაგულისხმევის გამოყენება ორიგინალის რედაქტირებისთვის Match User Interface Brightness ინტერფეისის სიკაშკაშესთან შესაბამისობა Light Gray ღია ნაცრისფერი Medium Gray საშუალო ნაცრისფერი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8596570c74..7376f14d85 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2084,6 +2084,7 @@ digits Malayalam 말라얄람어 Manage Workspaces 작업 영역 관리 Manually 수동 Mark Older Files as [Converted] When Opened 열 때 이전 파일을 [Converted]로 표시 + Use System Defaults for Edit Original 원본 편집에 시스템 기본값 사용 Mark as trapped 트래핑됨으로 표시 Marks 표시 Match User Interface Brightness 사용자 인터페이스 밝기에 맞춤 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4cde5d4036..c2670658d3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3342,6 +3342,7 @@ theme Appearance Vormgeving List Preferences Voorkeuren weergeven Manually Handmatig Mark Older Files as [Converted] When Opened Oudere bestanden bij het openen markeren als [geconverteerd] + Use System Defaults for Edit Original Systeemstandaarden gebruiken voor Origineel bewerken Match User Interface Brightness Aanpassen aan helderheid van gebruikersinterface Light Gray Lichtgrijs Medium Gray Middelgrijs diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 52800ade00..10ebc96bd0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3464,6 +3464,7 @@ theme Appearance Wygląd List Preferences Wyświetl preferencje Manually Ręcznie Mark Older Files as [Converted] When Opened Oznaczaj starsze pliki jako [Przekonwertowane] przy otwieraniu + Use System Defaults for Edit Original Używaj ustawień domyślnych systemu dla polecenia Edytuj oryginał Match User Interface Brightness Dopasuj do jasności interfejsu Light Gray Jasnoszary Medium Gray Średnio szary diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8369f4d23f..f43b74b971 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1585,6 +1585,7 @@ Manage Workspaces… Gerenciar Espaços de Trabalho… Manually Manualmente Mark Older Files as [Converted] When Opened Marcar Arquivos Antigos como [Convertido] Ao Abrir + Use System Defaults for Edit Original Usar Padrões do Sistema para Editar Original Mark as trapped Marcar como sobreimpresso Marker… Marcador… Marks Marcas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e6bf3f77ca..0a42894b63 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1890,6 +1890,7 @@ file-filter Templates Шаблоны Manually Вручную Mark as trapped Пометить как треппинг Mark Older Files as [Converted] When Opened Помечать старые файлы как [Преобразованные] при открытии + Use System Defaults for Edit Original Использовать системные значения по умолчанию для «Редактировать оригинал» Marker… Маркер… Marks Метки Marks and Bleed Метки и вылет diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f123510402..214b19aed4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1805,6 +1805,7 @@ font-technology Variable Variabla Manually Manuellt Mark as trapped Märk som överfyllt Mark Older Files as [Converted] When Opened Märk äldre filer som [Konverterad] när de öppnas + Use System Defaults for Edit Original Använd systemets standardinställningar för Redigera original Marker… Markör… Marks Märken Marks and Bleed Märken och utfall diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b198e1af18..cdf14d3f5a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1699,6 +1699,7 @@ font-technology Variable Değişken Manually Manuel olarak Mark as trapped Sıkışmış olarak işaretle Mark Older Files as [Converted] When Opened Eski Dosyaları Açıldığında [Dönüştürülmüş] Olarak İşaretle + Use System Defaults for Edit Original Orijinali Düzenle için Sistem Varsayılanlarını Kullan Marker… işaretleyici… Marks İşaretler Marks and Bleed İşaretler ve Taşma Payı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d468a63d71..112ed58400 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1887,6 +1887,7 @@ file-filter Templates Шаблони Manually Вручну Mark as trapped Позначити як трепінг Mark Older Files as [Converted] When Opened Помічати старі файли як [Перетворені] при відкритті + Use System Defaults for Edit Original Використовувати системні типові програми для «Редагувати оригінал» Marker… Маркер… Marks Мітки Marks and Bleed Мітки та виліт diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9d4acddcbd..05b1dda5c7 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2172,6 +2172,7 @@ digits Hindi Hindi Manually Thủ công Mark as trapped Đánh dấu đã chồng màu Mark Older Files as [Converted] When Opened Đánh dấu tệp cũ là [Đã chuyển đổi] khi mở + Use System Defaults for Edit Original Dùng mặc định hệ thống cho Chỉnh sửa bản gốc Marker… Ký hiệu đánh dấu… Marks Dấu in Marks and Bleed Dấu in và chảy tràn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0426b415f8..336057c436 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1774,6 +1774,7 @@ file-filter Templates 模板 Manually 手动 Mark as trapped 标示为已陷印 Mark Older Files as [Converted] When Opened 打开旧文件时标记为 [已转换] + Use System Defaults for Edit Original “编辑原稿”使用系统默认设置 Marker… 标记… Marks 标记 Marks and Bleed 标记和出血 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 92a1a98087..4ddbf0f694 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2728,6 +2728,7 @@ file-filter Templates 範本 Manually 手動 Mark as trapped 標示為已陷印 Mark Older Files as [Converted] When Opened 開啟舊檔時標示為 [已轉換] + Use System Defaults for Edit Original 「編輯原稿」使用系統預設值 Marker… 標記… Marks 標記 Marks and Bleed 標記與出血 diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 592d60ec00..f323231511 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -217,14 +217,20 @@ pub(crate) fn open_in_app(app: &mut VectorcraftApp, path: &str) -> Result<(), St app.services.open_file.as_mut().ok_or("no app to open files here")?(path) } -/// Edit Original: open `path` in the app Preferences › File Handling › Edit Original With names -/// (#5236), or in the system's default app for it when that is System Default (""). +/// Edit Original: open `path` in the system's default app for it, or with Preferences › File +/// Handling › Use System Defaults for Edit Original off, in the app that made it (#5236): PhotoCraft +/// for a raster image where it is installed. Any other file, or no PhotoCraft, uses the system's app. pub(crate) fn open_original(app: &mut VectorcraftApp, path: &str) -> Result<(), String> { - let with = app.session.prefs.edit_original_app.trim().to_string(); - if with.is_empty() { - return open_in_app(app, path); + let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); + let raster = vectorcraft_engine::cmd::fileio::readable_format(&ext).is_some_and(|f| f.raster); + if !app.session.prefs.edit_original_system_defaults + && raster + && let Some(open) = app.services.open_in_photocraft.as_mut() + && open(path)? + { + return Ok(()); } - app.services.open_file_with.as_mut().ok_or("no app to open files in here")?(&with, path) + open_in_app(app, path) } /// File → Export for Screens with `document.exportForScreens` params: the files go into `folder`; diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index fb323122c2..215cf7148a 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -1,7 +1,7 @@ //! The Links panel, its flyout, Link Info, Edit Original / Show in Folder, the Placement Options //! dialog and the Properties panel's image section, drawn headless. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use serde_json::json; @@ -168,44 +168,40 @@ fn edit_original_and_show_in_folder_hand_the_file_to_the_system() { assert!(app.run("links.editOriginal", json!({"id": linked})).is_err()); } -/// #5236: Preferences › File Handling › Edit Original With picks the app Edit Original opens the -/// file in: System Default ("") hands it to the system's default app as before, PhotoCraft or an -/// application's path to that app. +/// #5236: with Preferences › File Handling › Use System Defaults for Edit Original off, Edit +/// Original opens a raster image in the app that made it, PhotoCraft, and falls back to the +/// system's default app when PhotoCraft isn't installed or the file isn't a raster image. #[test] -fn edit_original_opens_the_file_in_the_chosen_app() { - /// What each open asked for: (the app, `None` for the system's default, and the path). - type Opened = Rc, String)>>>; +fn edit_original_opens_raster_images_in_photocraft_without_system_defaults() { + /// What each open asked for: (`true` for PhotoCraft, the path). + type Opened = Rc>>; let dir = Folder::new("with"); let (mut app, linked, _) = app(&dir); let opened: Opened = Rc::default(); - let (o, w) = (opened.clone(), opened.clone()); + let installed = Rc::new(Cell::new(true)); + let (o, w, i) = (opened.clone(), opened.clone(), installed.clone()); app.services.open_file = Some(Box::new(move |p: &str| { - o.borrow_mut().push((None, p.to_string())); + o.borrow_mut().push((false, p.to_string())); Ok(()) })); - app.services.open_file_with = Some(Box::new(move |with: &str, p: &str| { - w.borrow_mut().push((Some(with.to_string()), p.to_string())); - Ok(()) + app.services.open_in_photocraft = Some(Box::new(move |p: &str| { + if i.get() { + w.borrow_mut().push((true, p.to_string())); + } + Ok(i.get()) })); + // On (the default): the system's app. let path = app.run("links.editOriginal", json!({"id": linked})).unwrap()["path"].as_str().unwrap().to_string(); - for value in ["photocraft", "/Applications/Example.app"] { - app.run("prefs.set", json!({"key": "editOriginalApp", "value": value})).unwrap(); - app.run("links.editOriginal", json!({"id": linked})).unwrap(); - } - app.run("prefs.set", json!({"key": "editOriginalApp", "value": ""})).unwrap(); + app.run("prefs.set", json!({"key": "editOriginalSystemDefaults", "value": false})).unwrap(); app.run("links.editOriginal", json!({"id": linked})).unwrap(); - assert_eq!( - *opened.borrow(), - [ - (None, path.clone()), - (Some("photocraft".into()), path.clone()), - (Some("/Applications/Example.app".into()), path.clone()), - (None, path.clone()), - ] - ); - // An app the host can't open in (the web) is an error, not the default app instead. - app.run("prefs.set", json!({"key": "editOriginalApp", "value": "photocraft"})).unwrap(); - app.services.open_file_with = None; + installed.set(false); + app.run("links.editOriginal", json!({"id": linked})).unwrap(); + installed.set(true); + // A file that isn't a raster image goes to the system's app. + crate::io::open_original(&mut app, "/Art/plan.emf").unwrap(); + assert_eq!(*opened.borrow(), [(false, path.clone()), (true, path.clone()), (false, path), (false, "/Art/plan.emf".to_string())]); + // PhotoCraft failing to open it is said, not hidden behind the system's app. + app.services.open_in_photocraft = Some(Box::new(|_: &str| Err("PhotoCraft didn't start".to_string()))); assert!(app.run("links.editOriginal", json!({"id": linked})).is_err()); assert_eq!(opened.borrow().len(), 4); } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index ef18c3ec58..b91c149f45 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -176,7 +176,6 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); let (mut ok, mut cancel, mut reset) = (false, false, false); - d.fields.insert(CAN_PICK_APP.into(), json!(crate::picks::can(app, &crate::picks::PickRequest::Open(app_pick())))); let cat = d.str("__category"); let cat = PREF_CATEGORIES.iter().find(|c| **c == cat).copied().unwrap_or(PREF_CATEGORIES[0]); crate::dialogs::modal::show(ctx, tl!("Preferences"), egui::Id::unique("dialog-preferences"), -20.0, 20, |ui| { @@ -242,10 +241,6 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { for (k, v) in Prefs::default().to_json().as_object().cloned().unwrap_or_default() { d.fields.insert(k, v); } - d.fields.remove(CHOSE_OTHER_APP); - } - if d.fields.remove(CHOOSE_APP).is_some() { - choose_app(app, &mut d); } app.ui.dialog = Some(d); if cancel { @@ -385,7 +380,6 @@ fn category_fields(ui: &mut egui::Ui, d: &mut Dialog, cat: &str) { } }); } - PrefKind::Text if sp.key == "editOriginalApp" => edit_original_row(ui, d, sp.key, sp.label, &v), PrefKind::Text => { labeled(ui, sp.label, |ui| { let mut s = v.as_str().unwrap_or("").to_string(); @@ -416,94 +410,6 @@ fn choice_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, opts: & }); } -/// File Handling › Edit Original With (#5236): System Default (""), PhotoCraft (`photocraft`) or -/// Other Application, which shows a field for the application's path. -fn edit_original_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, v: &Value) { - const OPTIONS: [&str; 3] = ["System Default", "PhotoCraft", "Other Application"]; - // The field shows the value as stored, spaces included (the host trims it when it opens). - let raw = v.as_str().unwrap_or("").to_string(); - let cur = raw.trim().to_string(); - let photocraft = cur.eq_ignore_ascii_case("photocraft"); - // Other Application with no path typed yet is still System Default: the dialog remembers the - // choice in a field of its own, which a new dialog and Reset Preferences start without. - let mut other = !photocraft && (!cur.is_empty() || d.bool(CHOSE_OTHER_APP)); - // A path (saved or typed) also counts as the choice, so clearing it to type another keeps the - // field. - if other && !d.bool(CHOSE_OTHER_APP) { - d.fields.insert(CHOSE_OTHER_APP.into(), json!(true)); - } - let at = if photocraft { - 1 - } else if other { - 2 - } else { - 0 - }; - labeled(ui, label, |ui| { - if let Some(i) = widgets::dropdown(ui, key, OPTIONS[at], &OPTIONS, 260.0) { - other = i == 2; - d.fields.insert(CHOSE_OTHER_APP.into(), json!(other)); - let new = match i { - 0 => String::new(), - 1 => "photocraft".to_string(), - _ if photocraft => String::new(), - _ => raw.clone(), - }; - d.fields.insert(key.into(), json!(new)); - } - }); - if other { - let can_pick = d.bool(CAN_PICK_APP); - labeled(ui, "Application Path", |ui| { - let mut s = if photocraft { String::new() } else { raw.clone() }; - let width = if can_pick { 186.0 } else { 260.0 }; - let field = egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(width); - let hint = if cfg!(target_os = "macos") { "/Applications/Example.app" } else { "" }; - if ui.add(field.hint_text(hint)).changed() { - d.fields.insert(key.into(), json!(s)); - } - // The open dialog runs from `show`, which has the app ([`choose_app`]). - if can_pick && widgets::flat_button(ui, tl!("Choose…"), 68.0).clicked() { - d.fields.insert(CHOOSE_APP.into(), json!(true)); - } - }); - } -} - -/// UI-only dialog fields for Edit Original With's Choose… button: whether the host shows an open -/// dialog, and that the button was clicked this frame. -const CAN_PICK_APP: &str = "__canPickApp"; -const CHOOSE_APP: &str = "__chooseApp"; -/// UI-only dialog field: Other Application was chosen, though no path is typed yet. -const CHOSE_OTHER_APP: &str = "__choseOtherApp"; - -/// The open dialog Edit Original With's Choose… shows: applications (`.app` bundles in -/// Applications on macOS, `.exe` files on Windows, any file elsewhere). -fn app_pick() -> crate::FilePick { - let filters: Vec = if cfg!(target_os = "macos") { - vec![("Applications".into(), vec!["app".into()])] - } else if cfg!(windows) { - vec![("Programs".into(), vec!["exe".into()])] - } else { - vec![] - }; - let folder = cfg!(target_os = "macos").then(|| "/Applications".to_string()); - crate::FilePick { name: String::new(), folder, filters } -} - -/// Edit Original With › Choose…: the picked application into the dialog's `editOriginalApp`. Shown -/// off the UI thread, the answer fills the dialog as it is then ([`crate::picks::in_dialog`]). -fn choose_app(app: &mut VectorcraftApp, d: &mut Dialog) { - let r = crate::picks::in_dialog(app, d, |app, d| { - if let Some(path) = crate::picks::open(app, &app_pick()) { - d.fields.insert("editOriginalApp".into(), json!(path)); - } - Ok(()) - }); - // Picking a file doesn't fail. - let _ = r; -} - fn bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { // The app's outlined checkbox (it translates `label`): egui's own has no border at rest. let on = d.bool(key); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c2557aedec..2e47115056 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -392,56 +392,17 @@ fn hyphenation_exceptions_dialog_ok_reaches_the_hyphenator() { assert_eq!(vectorcraft_text::hyphen::hyphen_points("happen"), vec![3]); } -/// #5236: File Handling › Edit Original With offers System Default, PhotoCraft and Other -/// Application, whose Choose… puts the picked application into the preference. +/// #5236: File Handling › Use System Defaults for Edit Original is a checkbox, on by default, and +/// OK saves it off. #[test] -fn edit_original_with_takes_a_chosen_application() { +fn use_system_defaults_for_edit_original_is_a_checkbox() { let mut a = VectorcraftApp::new(Session::new(), Default::default()); + assert!(a.session.prefs.edit_original_system_defaults, "on by default"); open(&mut a, Some("File Handling")); let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); - assert!(text.contains("Edit Original With") && text.contains("System Default"), "{text}"); - let asked: std::rc::Rc>> = Default::default(); - let seen = asked.clone(); - a.services.pick_open = Some(Box::new(move |p: &crate::FilePick| { - seen.borrow_mut().push(p.clone()); - Some("/Applications/Editor.app".into()) - })); - let mut d = a.ui.dialog.clone().unwrap(); - choose_app(&mut a, &mut d); - assert_eq!(d.str("editOriginalApp"), "/Applications/Editor.app"); - let pick = asked.borrow()[0].clone(); - if cfg!(target_os = "macos") { - assert_eq!((pick.folder.as_deref(), pick.filters[0].1.clone()), (Some("/Applications"), vec!["app".to_string()])); - } - // OK saves it; the dialog's own fields (`__…`) are not preferences. - a.ui.dialog = Some(d); + assert!(text.contains("Use System Defaults for Edit Original"), "{text}"); + assert!(a.ui.dialog.as_ref().unwrap().bool("editOriginalSystemDefaults")); + a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalSystemDefaults".into(), json!(false)); confirm(&mut a).unwrap(); - assert_eq!(a.session.prefs.edit_original_app, "/Applications/Editor.app"); -} - -/// #5327 review: choosing Other Application before a path is typed is remembered by the dialog -/// itself, so a dialog opened again (or reset) starts at System Default, and a stored path keeps -/// its spaces. -#[test] -fn edit_original_with_other_is_the_dialogs_own_choice() { - let mut a = VectorcraftApp::new(Session::new(), Default::default()); - open(&mut a, Some("File Handling")); - assert!(!a.ui.dialog.as_ref().unwrap().bool(CHOSE_OTHER_APP), "a new dialog starts without the choice"); - let shown = |a: &mut VectorcraftApp| crate::tests_labels::painted_text(a, |a, ui| show(a, ui.ctx())).contains("Application Path"); - assert!(!shown(&mut a), "System Default shows no path field"); - a.ui.dialog.as_mut().unwrap().fields.insert(CHOSE_OTHER_APP.into(), json!(true)); - assert!(shown(&mut a), "Other Application with no path yet shows the field"); - a.ui.dialog = None; - open(&mut a, Some("File Handling")); - assert!(!shown(&mut a), "opened again: System Default"); - // A saved path counts as the choice: clearing it to type another keeps the field. - a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalApp".into(), json!("/Applications/Old.app")); - assert!(shown(&mut a)); - a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalApp".into(), json!("")); - assert!(shown(&mut a), "the path cleared: still Other Application"); - // A path with spaces is kept as typed. - let path = "/Applications/Visual Studio Code.app"; - a.ui.dialog.as_mut().unwrap().fields.insert("editOriginalApp".into(), json!(path)); - confirm(&mut a).unwrap(); - assert_eq!(a.session.prefs.edit_original_app, path); + assert!(!a.session.prefs.edit_original_system_defaults); } diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 7e00322bcc..3d35247880 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -65,8 +65,8 @@ pub(crate) fn browsable_url(url: &str) -> Result<(), String> { /// Shows a file in the system file manager, or opens it in its app. pub type RevealFn = Box Result<(), String>>; -/// Opens a file in a chosen app: `(app, path)`. -pub type OpenWithFn = Box Result<(), String>>; +/// Opens a file in a fixed app; `Ok(false)` when that app isn't installed. +pub type OpenInFn = Box Result>; /// Platform services injected by the host app (desktop or web). #[derive(Default)] @@ -119,10 +119,10 @@ pub struct Services { /// Open a file (or a folder) in the system's default app for it (desktop: Edit Original, Show /// Package). Without it (the web) those answer with an error. pub open_file: Option, - /// Open a file in a chosen app (desktop: Edit Original with Preferences › File Handling › Edit - /// Original With set): `(app, path)`, where `app` is `photocraft` or an application's path. - /// Without it (the web) Edit Original with an app set answers with an error. - pub open_file_with: Option, + /// Open a file in PhotoCraft where it is installed (desktop: Edit Original of a raster image + /// with Preferences › File Handling › Use System Defaults for Edit Original off); `Ok(false)` + /// when it isn't. Without it Edit Original uses `open_file`. + pub open_in_photocraft: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, and diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c624dcb57..b7f63de17a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -668,10 +668,10 @@ one undo step. The Links panel (`window.panel {panel: "links"}`) shows `links.li `links.info`; `links.editOriginal` and `links.reveal` (Edit › Edit Original, Show in Folder) hand the linked file to the system and return `{path}`. Edit Original opens only a regular file whose extension is a format `document.open` reads, and answers a control request with an error unless the file is a placed document (which opens in a tab). -The preference `editOriginalApp` (Preferences › File Handling › Edit Original With, #5236) picks the app: `""` (System -Default, the system's default app for the file), `"photocraft"` (PhotoCraft where it is installed) or an application's -path. The app must be an application (an `.app` bundle on macOS, an `.exe` on Windows, an executable file elsewhere), -and gets the file's path as its only argument. +The preference `editOriginalSystemDefaults` (Preferences › File Handling › Use System Defaults for Edit Original, on +by default, #5236) opens the file in the system's default app for it; off, in the app that made it: a raster image in +PhotoCraft, looked for only where it installs (the Applications folders on macOS, the `PATH` elsewhere), and any other +file, or a raster image without PhotoCraft installed, in the system's default app. Package: File → Package… (`ui.packageDialog`) opens the `package` dialog for a saved document (a document never saved gets a `confirm` dialog whose OK runs `file.saveAs`). Fields: `folder` (the location), `name` (the package folder), diff --git a/docs/mcp.md b/docs/mcp.md index 2befc0205d..bbd4451f5b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4216,9 +4216,9 @@ file is missing stays linked: relink it first); `links.unembed {id, path}` write clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and `links.reveal` open the linked file in its app or show it in its folder (desktop). Edit Original runs only from the app's window, -except for a placed document, which opens in a tab. The preference `editOriginalApp` (Preferences › File Handling › -Edit Original With) picks the app Edit Original opens the file in: `""` (the system's default app), `"photocraft"` or an -application's path (#5236). +except for a placed document, which opens in a tab. With the preference `editOriginalSystemDefaults` (Preferences › +File Handling › Use System Defaults for Edit Original, on by default) off, Edit Original opens a raster image in the app +that made it, PhotoCraft, where it is installed, and anything else in the system's default app (#5236). ```json {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} From 46f1ddf170bc43b59805b28401646e4ad4c629da Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:16:46 +0530 Subject: [PATCH 371/674] Fix #5236: find PhotoCraft where its Windows installer puts it Per CodeRabbit on #5327: on Windows Edit Original looked for photocraft.exe only on the PATH, but PhotoCraft's MSI installs it to ArtCraft\PhotoCraft under %LOCALAPPDATA%\Programs (per user, the default) or Program Files (for everyone), neither on the PATH. Look first at the path the installer registers under App Paths (HKCU, then HKLM; `reg query`, as i18n reads the locale, which also covers a folder chosen in setup), then those two default folders, then the PATH. Each candidate must still be an .exe. Co-Authored-By: Claude Opus 5.5 --- apps/vectorcraft/src/host_services.rs | 109 +++++++++++++++++++++++++- docs/control-protocol.md | 5 +- 2 files changed, 108 insertions(+), 6 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 2ed5f55308..fc54c504b8 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -400,8 +400,8 @@ pub(crate) fn find_photocraft(home: Option<&std::path::Path>, path_var: Option<& photocraft_candidates(home, path_var).into_iter().find(|p| check_app(p).is_ok()) } -/// Where PhotoCraft may be installed: the Applications folders on macOS, else a `photocraft` -/// program on the `PATH`. +/// Where PhotoCraft may be installed: the Applications folders on macOS; on Windows where its +/// installer puts it ([`windows_candidates`]); else a `photocraft` program on the `PATH`. pub(crate) fn photocraft_candidates(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Vec { if cfg!(target_os = "macos") { let mut v = vec![std::path::PathBuf::from("/Applications/PhotoCraft.app")]; @@ -409,7 +409,73 @@ pub(crate) fn photocraft_candidates(home: Option<&std::path::Path>, path_var: Op return v; } let name = if cfg!(windows) { "photocraft.exe" } else { "photocraft" }; - path_var.map(|p| std::env::split_paths(p).map(|dir| dir.join(name)).collect()).unwrap_or_default() + let on_path = path_var.map(|p| std::env::split_paths(p).map(|dir| dir.join(name)).collect()).unwrap_or_default(); + if cfg!(windows) { + let folders: Vec = [ + std::env::var_os("LOCALAPPDATA").map(|d| std::path::PathBuf::from(d).join("Programs")), + std::env::var_os("ProgramW6432").map(std::path::PathBuf::from), + std::env::var_os("ProgramFiles").map(std::path::PathBuf::from), + ] + .into_iter() + .flatten() + .collect(); + return windows_candidates(registered_photocraft(), &folders, on_path); + } + on_path +} + +/// Windows: PhotoCraft's installer puts it in `ArtCraft\PhotoCraft` under a folder of +/// `program_folders` (for the current user `%LOCALAPPDATA%\Programs`, for everyone Program Files) +/// and registers its path under App Paths, which also covers a folder chosen in setup. So: the +/// `registered` paths first, then those folders, then `on_path`. +pub(crate) fn windows_candidates( + registered: Vec, + program_folders: &[std::path::PathBuf], + on_path: Vec, +) -> Vec { + let mut v = registered; + for f in program_folders { + let p = f.join("ArtCraft").join("PhotoCraft").join("photocraft.exe"); + if !v.contains(&p) { + v.push(p); + } + } + v.extend(on_path); + v +} + +/// The paths PhotoCraft's installer registers under App Paths, for the current user and then for +/// everyone (`reg query`, so no extra dependency; a hidden console window). +#[cfg(windows)] +fn registered_photocraft() -> Vec { + use std::os::windows::process::CommandExt as _; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + // reg.exe by its full path, so nothing named `reg` in the app's folder or on PATH runs instead. + let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()); + ["HKCU", "HKLM"] + .into_iter() + .filter_map(|hive| { + let key = format!(r"{hive}\Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe"); + let out = std::process::Command::new(root.join("System32").join("reg.exe")) + .args(["query", &key, "/ve"]) + .creation_flags(CREATE_NO_WINDOW) + .output() + .ok()?; + registered_path(&String::from_utf8_lossy(&out.stdout)) + }) + .collect() +} + +#[cfg(not(windows))] +fn registered_photocraft() -> Vec { + Vec::new() +} + +/// The path in `reg query … /ve` output like +/// ` (Default) REG_SZ C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub(crate) fn registered_path(text: &str) -> Option { + text.lines().find_map(|l| l.split_once("REG_SZ")).map(|(_, v)| v.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from) } /// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on @@ -440,7 +506,7 @@ fn executable_file(p: &std::path::Path) -> bool { #[cfg(test)] mod open_with_tests { - use super::{check_app, find_photocraft, photocraft_candidates}; + use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates}; /// A fresh, empty folder under the system's temporary folder. fn scratch(name: &str) -> std::path::PathBuf { @@ -503,4 +569,39 @@ mod open_with_tests { } let _ = std::fs::remove_dir_all(&d); } + + /// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it + /// registers, then `ArtCraft\PhotoCraft` in the per-user and per-machine program folders, then + /// the `PATH`. + #[test] + fn windows_looks_where_the_photocraft_installer_puts_it() { + use std::path::PathBuf; + let registered = vec![PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe")]; + let folders = [PathBuf::from("C:/Users/me/AppData/Local/Programs"), PathBuf::from("C:/Program Files"), PathBuf::from("C:/Program Files")]; + let on_path = vec![PathBuf::from("C:/bin/photocraft.exe")]; + let exe = |f: &str| PathBuf::from(f).join("ArtCraft").join("PhotoCraft").join("photocraft.exe"); + assert_eq!( + windows_candidates(registered, &folders, on_path), + [ + PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe"), + exe("C:/Users/me/AppData/Local/Programs"), + exe("C:/Program Files"), + PathBuf::from("C:/bin/photocraft.exe"), + ] + ); + } + + /// The registered path is read from `reg query … /ve` output, spaces and quotes included; + /// no value, no path. + #[test] + fn the_registered_path_is_read_from_reg_query() { + let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\photocraft.exe\r\n (Default) REG_SZ C:\\Program Files\\ArtCraft\\PhotoCraft\\photocraft.exe\r\n"; + assert_eq!(registered_path(out), Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe"))); + assert_eq!( + registered_path(" (Standard) REG_SZ \"C:\\A B\\photocraft.exe\""), + Some(std::path::PathBuf::from(r"C:\A B\photocraft.exe")) + ); + assert_eq!(registered_path("ERROR: The system was unable to find the specified registry key or value."), None); + assert_eq!(registered_path(" (Default) REG_SZ "), None); + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b7f63de17a..cdb7471df1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -670,8 +670,9 @@ the system and return `{path}`. Edit Original opens only a regular file whose ex reads, and answers a control request with an error unless the file is a placed document (which opens in a tab). The preference `editOriginalSystemDefaults` (Preferences › File Handling › Use System Defaults for Edit Original, on by default, #5236) opens the file in the system's default app for it; off, in the app that made it: a raster image in -PhotoCraft, looked for only where it installs (the Applications folders on macOS, the `PATH` elsewhere), and any other -file, or a raster image without PhotoCraft installed, in the system's default app. +PhotoCraft, looked for only where it installs (the Applications folders on macOS; on Windows the path its installer +registers under App Paths, then `ArtCraft\PhotoCraft` in the per-user and per-machine program folders, then the `PATH`; +the `PATH` elsewhere), and any other file, or a raster image without PhotoCraft installed, in the system's default app. Package: File → Package… (`ui.packageDialog`) opens the `package` dialog for a saved document (a document never saved gets a `confirm` dialog whose OK runs `file.saveAs`). Fields: `folder` (the location), `name` (the package folder), From f3a9114e558dc690367fe6a13e0e26e7db6a5840 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 19:58:28 +0700 Subject: [PATCH 372/674] Edit Original: the PhotoCraft lookup test holds where PhotoCraft is installed --- apps/vectorcraft/src/host_services.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index fc54c504b8..81a20e601c 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -557,7 +557,11 @@ mod open_with_tests { let bin = d.join("bin"); std::fs::create_dir_all(&bin).unwrap(); let path_var = std::env::join_paths([&bin]).unwrap(); - assert!(find_photocraft(None, Some(&path_var)).is_none(), "not installed"); + // On Windows an installed PhotoCraft (registered, or in a program folder) comes first, so + // there only the `PATH` candidate is checked. + if !cfg!(windows) { + assert!(find_photocraft(None, Some(&path_var)).is_none(), "not installed"); + } let exe = bin.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" }); std::fs::write(&exe, "").unwrap(); #[cfg(unix)] @@ -565,7 +569,12 @@ mod open_with_tests { use std::os::unix::fs::PermissionsExt as _; std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); } - assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe)); + if cfg!(windows) { + assert_eq!(photocraft_candidates(None, Some(&path_var)).last(), Some(&exe)); + assert!(check_app(&exe).is_ok()); + } else { + assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe)); + } } let _ = std::fs::remove_dir_all(&d); } From 8850b923ce707778affc515080eb17a6d8902fed Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:20:18 +0530 Subject: [PATCH 373/674] Fix #4924: Text Tweaker ramps or randomises one character attribute letter by letter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A built-in Type Tools add-on (Object › Plug-ins › Type Tools › Text Tweaker…, `addon.type.textTweaker`): size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight go from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets them, while the text stays live. One undo step, a dialog with Preview, catalog rows in all 26 languages, docs/mcp.md and the parity docs. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/engine/src/cmd/addons.rs | 2 + crates/engine/src/cmd/addons/typetools.rs | 165 +++++++++++++++ .../engine/src/cmd/addons/typetools/tests.rs | 195 ++++++++++++++++++ crates/engine/src/cmd/textedit.rs | 8 +- crates/engine/tests/command_sweep.rs | 6 + crates/ui-egui/src/addons.rs | 2 + crates/ui-egui/src/addons/typetools.rs | 96 +++++++++ crates/ui-egui/src/addons/typetools/tests.rs | 62 ++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 10 + crates/ui-egui/src/i18n/bs.tsv | 10 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/menus/invoke.rs | 1 + docs/mcp.md | 27 +++ docs/target-app-parity.md | 7 +- 39 files changed, 830 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/addons/typetools.rs create mode 100644 crates/engine/src/cmd/addons/typetools/tests.rs create mode 100644 crates/ui-egui/src/addons/typetools.rs create mode 100644 crates/ui-egui/src/addons/typetools/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index bce1cab0c4..7aa720205e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Progress log row for the Type Tools add-on's Text Tweaker, #4924; headline numbers unchanged; previously: font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -138,6 +138,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. +- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. - 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. @@ -215,6 +216,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | | 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | | 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 21d73cc4f8..02f8864423 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -7,6 +7,7 @@ mod color; mod document; mod pathtools; mod pen; +mod typetools; use super::CommandSpec; @@ -18,5 +19,6 @@ pub fn specs() -> Vec { v.extend(document::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); + v.extend(typetools::specs()); v } diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs new file mode 100644 index 0000000000..0cd8e21ea1 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -0,0 +1,165 @@ +//! Type Tools (`addon.type.*`), a built-in add-on: Text Tweaker gives one character attribute to +//! the selected characters letter by letter, from a start value to an end value along a shape +//! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as +//! the Character panel sets them (`text.setRangeStyle`), in its units and ranges +//! (). Its submenu +//! (Object › Plug-ins › Type Tools) and dialog are the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_doc::{NodeId, TextRun}; +use vectorcraft_text::edit; + +use super::super::menucmds::whole_or; +use super::super::object::choice; +use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; +use super::super::typecmd::refresh_bounds; +use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use crate::{EngineError, Result, Session}; + +/// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its +/// default start and end. +type Attribute = (&'static str, (f64, f64), (f64, f64)); + +/// The attributes Text Tweaker sets. +pub const ATTRIBUTES: [Attribute; 8] = [ + ("size", (0.1, 1296.0), (12.0, 36.0)), + ("baselineShift", (-1296.0, 1296.0), (0.0, 12.0)), + ("rotation", (-360.0, 360.0), (0.0, 30.0)), + ("hScale", (1.0, 10000.0), (100.0, 150.0)), + ("vScale", (1.0, 10000.0), (100.0, 150.0)), + ("tracking", (-1000.0, 10000.0), (0.0, 200.0)), + ("leading", (0.1, 5000.0), (12.0, 36.0)), + ("strokeWidth", (0.0, 1000.0), (0.0, 2.0)), +]; +/// The shapes the values follow from the first character to the last. +pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"]; +/// The most characters one run changes. +const MAX_CHARS: usize = 100_000; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.type.textTweaker", + "Text Tweaker", + ["Object", "Plug-ins", "Type Tools"], + None, + "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", + has_selection, + text_tweaker + )] +} + +/// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the +/// random shape. +fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 { + let t = if n > 1 { i as f64 / (n - 1) as f64 } else { 0.0 }; + match shape { + "ease" => t * t * (3.0 - 2.0 * t), + "bow" => (std::f64::consts::PI * t).sin(), + "spike" => 1.0 - (2.0 * t - 1.0).abs(), + "random" => random, + _ => t, + } +} + +/// A random number from 0 to 1. +fn unit(rng: &mut Rng) -> f64 { + (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64 +} + +fn text_tweaker(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.type.textTweaker"; + let attribute = choice(p, C, "attribute", &ATTRIBUTES.map(|a| a.0))?.unwrap_or("size"); + let Some(&(key, (lo, hi), (from0, to0))) = ATTRIBUTES.iter().find(|a| a.0 == attribute) else { + return Err(bad(C, format!("unknown attribute `{attribute}`"))); + }; + let mut ends = [0.0; 2]; + for (end, (k, default)) in ends.iter_mut().zip([("from", from0), ("to", to0)]) { + let v = number_or(p, k, default, C)?; + if !(lo..=hi).contains(&v) { + return Err(bad(C, format!("`{k}` must be from {lo} to {hi} for {key}"))); + } + *end = v; + } + let [from, to] = ends; + let shape = choice(p, C, "shape", &SHAPES)?.unwrap_or("straight"); + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let skip = switch_or(p, "skipSpaces", true, C)?; + let setup = s.doc()?.doc.setup.clone(); + // At a caret, all of the object's text. + let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?; + // Each object's changed characters: (byte, its change), worked out before the edit. + let mut plans: Vec<(NodeId, Vec<(usize, CharChange)>)> = vec![]; + let mut count = 0; + for (id, a, b, _) in ranges { + let t = text_ref(s, id)?; + let text = t.plain_text(); + let chars: Vec = + text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect(); + count += chars.len(); + if count > MAX_CHARS { + return Err(bad(C, format!("too many characters: at most {MAX_CHARS}"))); + } + let n = chars.len(); + let mut changes = Vec::with_capacity(n); + for (i, at) in chars.into_iter().enumerate() { + let random = if shape == "random" { unit(&mut rng) } else { 0.0 }; + let value = from + (to - from) * amount(shape, i, n, random); + let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?; + change.localize(&t, C)?; + changes.push((at, change)); + } + if !changes.is_empty() { + plans.push((id, changes)); + } + } + if plans.is_empty() { + return Ok(json!({ "count": 0, "ids": [] })); + } + let ids: Vec = plans.iter().map(|(id, _)| id.0).collect(); + s.edit("Text Tweaker", |d, _| { + for (id, changes) in &plans { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + t.runs = tweak(std::mem::take(&mut t.runs), changes); + refresh_bounds(t); + } + Ok(()) + })?; + Ok(json!({ "count": count, "ids": ids })) +} + +/// `runs` with each character at a byte of `changes` (in order) changed: its run split into +/// characters, the changes applied, and runs that came out alike merged again. +fn tweak(runs: Vec, changes: &[(usize, CharChange)]) -> Vec { + let mut out = Vec::with_capacity(runs.len() + changes.len() * 2); + let mut next = changes.iter().peekable(); + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if r.inline.is_some() || next.peek().is_none_or(|(at, _)| *at >= end) { + // An inline graphic is one character: its style changes whole. + if let Some((_, change)) = next.next_if(|(at, _)| (off..end).contains(at)) { + let mut r = r; + change.apply(&mut r.style); + out.push(r); + } else { + out.push(r); + } + off = end; + continue; + } + for (i, c) in r.text.char_indices() { + let mut piece = TextRun::new(c.to_string(), r.style.clone()); + if let Some((_, change)) = next.next_if(|(at, _)| *at == off + i) { + change.apply(&mut piece.style); + } + out.push(piece); + } + off = end; + } + edit::normalize(&mut out); + out +} diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs new file mode 100644 index 0000000000..47a1b92b9d --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -0,0 +1,195 @@ +//! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo +//! step, and bad params refused without a change. + +use serde_json::json; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; + +use super::amount; +use crate::Session; + +const C: &str = "addon.type.textTweaker"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn text(s: &mut Session, words: &str) -> NodeId { + NodeId(s.execute("text.create", &json!({"x": 40, "y": 100, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn obj(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each character of `id` with its style. +fn styles(s: &Session, id: NodeId) -> Vec<(char, CharStyle)> { + obj(s, id).runs.iter().flat_map(|r| r.text.chars().map(|c| (c, r.style.clone())).collect::>()).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn near(a: &[f64], b: &[f64]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn the_shapes_run_from_the_start_value_to_the_end_value() { + let at = |shape, n| (0..n).map(|i| amount(shape, i, n, 0.5)).collect::>(); + assert!(near(&at("straight", 5), &[0.0, 0.25, 0.5, 0.75, 1.0])); + assert!(near(&at("ease", 5), &[0.0, 0.15625, 0.5, 0.84375, 1.0]), "slow at both ends"); + let bow = at("bow", 5); + assert!(near(&[bow[0], bow[2], bow[4]], &[0.0, 1.0, 0.0]) && (bow[1] - 0.5f64.sqrt()).abs() < 1e-9, "a smooth arc"); + assert!(near(&at("spike", 5), &[0.0, 0.5, 1.0, 0.5, 0.0]), "straight up and down"); + assert!(near(&at("random", 3), &[0.5; 3])); + assert!(near(&at("straight", 1), &[0.0]), "one character takes the start value"); +} + +#[test] +fn a_straight_ramp_sizes_each_letter_and_skips_spaces() { + let mut s = session(); + let id = text(&mut s, "ab cd"); + select(&mut s, &[id]); + let n = steps(&s); + let out = s.execute(C, &json!({"attribute": "size", "from": 10, "to": 40})).unwrap(); + assert_eq!(out, json!({"count": 4, "ids": [id.0]})); + assert_eq!(steps(&s), n + 1, "one undo step"); + let sizes: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect(); + assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size"); + assert_eq!(obj(&s, id).plain_text(), "ab cd", "the text stays live"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(styles(&s, id).iter().all(|(_, st)| st.size == 20.0), "undone"); +} + +#[test] +fn spaces_can_count_too() { + let mut s = session(); + let id = text(&mut s, "a b"); + select(&mut s, &[id]); + s.execute(C, &json!({"attribute": "baselineShift", "from": 0, "to": 10, "skipSpaces": false})).unwrap(); + let shifts: Vec = styles(&s, id).iter().map(|(_, st)| st.baseline_shift).collect(); + assert_eq!(shifts, [0.0, 5.0, 10.0]); +} + +#[test] +fn every_attribute_is_set_as_the_character_panel_sets_it() { + let mut s = session(); + for (attribute, get) in [ + ("size", (|st: &CharStyle| st.size) as fn(&CharStyle) -> f64), + ("baselineShift", |st| st.baseline_shift), + ("rotation", |st| st.rotation), + ("hScale", |st| st.h_scale), + ("vScale", |st| st.v_scale), + ("tracking", |st| st.tracking), + ("leading", |st| st.leading.unwrap_or(-1.0)), + ("strokeWidth", |st| st.stroke_width), + ] { + let id = text(&mut s, "xyz"); + select(&mut s, &[id]); + s.execute(C, &json!({"attribute": attribute, "from": 2, "to": 6})).unwrap(); + let got: Vec = styles(&s, id).iter().map(|(_, st)| get(st)).collect(); + assert!(near(&got, &[2.0, 4.0, 6.0]), "{attribute}: {got:?}"); + } +} + +#[test] +fn each_object_gets_its_own_ramp() { + let mut s = session(); + let (a, b) = (text(&mut s, "abc"), text(&mut s, "de")); + select(&mut s, &[a, b]); + let out = s.execute(C, &json!({"attribute": "rotation", "from": 0, "to": 30})).unwrap(); + assert_eq!(out["count"], json!(5)); + let turns = |id| styles(&s, id).iter().map(|(_, st)| st.rotation).collect::>(); + assert_eq!((turns(a), turns(b)), (vec![0.0, 15.0, 30.0], vec![0.0, 30.0])); +} + +#[test] +fn a_range_changes_only_its_characters() { + let mut s = session(); + let id = text(&mut s, "abcde"); + s.execute(C, &json!({"id": id.0, "start": 1, "end": 4, "attribute": "tracking", "from": 100, "to": 300})).unwrap(); + let tracking: Vec = styles(&s, id).iter().map(|(_, st)| st.tracking).collect(); + assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]); +} + +#[test] +fn random_values_stay_in_range_and_repeat_with_the_seed() { + let mut s = session(); + let id = text(&mut s, "randomness"); + select(&mut s, &[id]); + let run = |s: &mut Session, seed| { + s.execute(C, &json!({"attribute": "vScale", "from": 50, "to": 150, "shape": "random", "seed": seed})).unwrap(); + styles(s, id).iter().map(|(_, st)| st.v_scale).collect::>() + }; + let first = run(&mut s, 7); + assert!(first.iter().all(|v| (50.0..=150.0).contains(v)), "{first:?}"); + assert!(first.windows(2).any(|w| w[0] != w[1]), "values vary"); + assert_eq!(run(&mut s, 7), first, "same seed, same values"); + assert_ne!(run(&mut s, 8), first, "another seed, other values"); +} + +#[test] +fn values_follow_the_text_transform_as_the_character_panel_does() { + let mut s = session(); + let id = text(&mut s, "ab"); + select(&mut s, &[id]); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + s.execute(C, &json!({"attribute": "size", "from": 20, "to": 40})).unwrap(); + let sizes: Vec = styles(&s, id).iter().map(|(_, st)| st.size).collect(); + // Shown sizes are the asked ones: stored sizes are half, the text being scaled twice. + let scale = obj(&s, id).style_scale().unwrap().points; + assert!(near(&sizes.iter().map(|v| v * scale).collect::>(), &[20.0, 40.0]), "{sizes:?} at {scale}"); +} + +#[test] +fn empty_text_and_only_spaces_change_nothing() { + let mut s = session(); + let id = text(&mut s, " "); + select(&mut s, &[id]); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"count": 0, "ids": []})); + assert_eq!(steps(&s), n, "no step"); +} + +#[test] +fn bad_params_are_refused_without_a_change() { + let mut s = session(); + let id = text(&mut s, "abc"); + select(&mut s, &[id]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + for p in [ + json!({"attribute": "colour"}), + json!({"attribute": 3}), + json!({"shape": "zigzag"}), + json!({"attribute": "size", "from": 0}), + json!({"attribute": "size", "to": 5000}), + json!({"attribute": "hScale", "from": -1}), + json!({"from": "big"}), + json!({"to": f64::MAX}), + json!({"seed": -1}), + json!({"skipSpaces": "yes"}), + json!({"ids": [999_999]}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().doc, before, "{p}"); + assert_eq!(steps(&s), n, "{p}"); + } +} + +#[test] +fn it_needs_a_selection() { + let mut s = session(); + text(&mut s, "abc"); + select(&mut s, &[]); + assert!(s.execute(C, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 133a3d788f..ace8e84e0a 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -154,14 +154,14 @@ pub fn specs() -> Vec { ] } -fn text_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Option<&mut TextObject> { +pub(crate) fn text_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Option<&mut TextObject> { match d.node_mut(id).map(|n| &mut n.kind) { Some(NodeKind::Text(t)) => Some(t), _ => None, } } -fn text_ref(s: &Session, id: NodeId) -> Result { +pub(crate) fn text_ref(s: &Session, id: NodeId) -> Result { match s.doc()?.doc.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => Ok((**t).clone()), Some(_) => Err(EngineError::Other(format!("node {} is not text", id.0))), @@ -708,7 +708,7 @@ impl CharChange { && self.font_height_reference.is_none() } - fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> { + pub(crate) fn localize(&mut self, t: &TextObject, cmd: &str) -> Result<()> { use super::typecmd::local_type_value; self.size = self.size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, cmd)).transpose()?; self.leading = self.leading.map(|v| v.map(|v| local_type_value(t, v, (0.1, 5000.0), false, cmd)).transpose()).transpose()?; @@ -1255,7 +1255,7 @@ pub(crate) fn editing_range(s: &mut Session) -> Result Vec { Item::Sub("Document Tools", document::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), Item::Sub("Smart Pen", pen::menu()), + Item::Sub("Type Tools", typetools::menu()), Item::Sep, ] } diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs new file mode 100644 index 0000000000..f9bfa3ca36 --- /dev/null +++ b/crates/ui-egui/src/addons/typetools.rs @@ -0,0 +1,96 @@ +//! Type Tools in the interface: its submenu (Object › Plug-ins › Type Tools) and Text Tweaker's +//! dialog, which picks an attribute, its start and end values and a shape, previews on the canvas +//! and runs `addon.type.textTweaker` on OK. + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::widgets; + +/// The command the dialog runs, and its kind. +pub const COMMAND: &str = "addon.type.textTweaker"; +pub const KIND: &str = "textTweaker"; +/// An attribute: (param, label, unit, decimals, values taken, default start and end), as the +/// command takes it. +type Attribute = (&'static str, &'static str, &'static str, usize, (f64, f64), (f64, f64)); + +const ATTRIBUTES: [Attribute; 8] = [ + ("size", "Font Size", "pt", 1, (0.1, 1296.0), (12.0, 36.0)), + ("baselineShift", "Baseline Shift", "pt", 1, (-1296.0, 1296.0), (0.0, 12.0)), + ("rotation", "Character Rotation", "°", 1, (-360.0, 360.0), (0.0, 30.0)), + ("hScale", "Horizontal Scale", "%", 0, (1.0, 10000.0), (100.0, 150.0)), + ("vScale", "Vertical Scale", "%", 0, (1.0, 10000.0), (100.0, 150.0)), + ("tracking", "Tracking", "", 0, (-1000.0, 10000.0), (0.0, 200.0)), + ("leading", "Leading", "pt", 1, (0.1, 5000.0), (12.0, 36.0)), + ("strokeWidth", "Stroke Weight", "pt", 2, (0.0, 1000.0), (0.0, 2.0)), +]; +const SHAPES: [(&str, &str); 5] = [("straight", "Straight"), ("ease", "Ease In Out"), ("bow", "Bow"), ("spike", "Spike"), ("random", "Random")]; +/// The seeds the dialog offers. +const SEEDS: u64 = 1_000_000; +const LABEL_W: f32 = 90.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Type Tools. +pub fn menu() -> Vec { + vec![Item::Cmd("Text Tweaker…", COMMAND, Value::Null)] +} + +/// The attribute row of param `key` (the first, Font Size, for an unknown one). +fn attribute(key: &str) -> &'static Attribute { + ATTRIBUTES.iter().find(|a| a.0 == key).unwrap_or(&ATTRIBUTES[0]) +} + +/// The dialog's fields to start with: Font Size from 12 to 36 pt in a straight ramp, and a new +/// seed each time the document has changed, so running it again varies a random result. +pub(crate) fn fields(app: &VectorcraftApp) -> Value { + let seed = app.session.active().map_or(0, |st| st.revision % SEEDS); + json!({ + "attribute": "size", "__shown": "size", "from": 12, "to": 36, "shape": "straight", "seed": seed, "skipSpaces": true, + }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Text Tweaker").to_string(), body, confirm, preview: true, min_width: 320.0, ..DialogSpec::FORM }; + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let widths = (LABEL_W, 170.0); + let options: Vec<(&str, &str)> = ATTRIBUTES.iter().map(|a| (a.0, a.1)).collect(); + form::choice(ui, d, "attribute", tl!("Attribute:"), widths, &options); + let &(key, _, unit, decimals, (lo, hi), (from, to)) = attribute(&d.str("attribute")); + // Another attribute starts from its own values. + if d.str("__shown") != key { + d.fields.insert("__shown".into(), json!(key)); + d.fields.insert("from".into(), json!(from)); + d.fields.insert("to".into(), json!(to)); + } + for (field, label) in [("from", tl!("From:")), ("to", tl!("To:"))] { + widgets::label_row(ui, label, LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("text-tweaker", field), d.f64(field, lo), lo..=hi, unit, decimals, FIELD_W) { + d.fields.insert(field.into(), json!(v)); + } + }); + } + form::choice(ui, d, "shape", tl!("Shape:"), widths, &SHAPES); + ui.add_enabled_ui(d.str("shape") == "random", |ui| { + widgets::label_row(ui, tl!("Seed:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("text-tweaker", "seed"), d.f64("seed", 0.0), 0.0..=(SEEDS - 1) as f64, "", 0, FIELD_W) { + d.fields.insert("seed".into(), json!(v as u64)); + } + }); + }); + form::check(ui, d, "skipSpaces", tl!("Skip Spaces")); + form::preview(app, ui, d, "Text Tweaker", COMMAND, form::params(d)); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/typetools/tests.rs b/crates/ui-egui/src/addons/typetools/tests.rs new file mode 100644 index 0000000000..36e3ef2f31 --- /dev/null +++ b/crates/ui-egui/src/addons/typetools/tests.rs @@ -0,0 +1,62 @@ +use serde_json::json; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; + +use super::KIND; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with one type object, selected. +fn app() -> (VectorcraftApp, NodeId) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(app.run("text.create", json!({"x": 40, "y": 100, "text": "abc", "size": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + (app, id) +} + +fn sizes(app: &VectorcraftApp, id: NodeId) -> Vec { + match &app.session.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().flat_map(|r| r.text.chars().map(|_| r.style.size).collect::>()).collect(), + _ => panic!("not text"), + } +} + +fn open(app: &mut VectorcraftApp) { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Type Tools"] && e.label == "Text Tweaker…").unwrap(); + let (id, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &id, p); +} + +#[test] +fn text_tweaker_opens_its_dialog_previews_and_runs_on_ok() { + let (mut app, id) = app(); + open(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Text Tweaker", "Attribute:", "Font Size", "From:", "To:", "Shape:", "Straight", "Seed:", "Skip Spaces", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(sizes(&app, id), [12.0, 24.0, 36.0], "previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(sizes(&app, id), [20.0; 3], "rolled back"); + open(&mut app); + let n = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1, "one undo step"); + assert_eq!(sizes(&app, id), [12.0, 24.0, 36.0]); +} + +#[test] +fn another_attribute_starts_from_its_own_values() { + let (mut app, _) = app(); + open(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("attribute".into(), json!("rotation")); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["from"].clone(), d.fields["to"].clone()), (json!(0.0), json!(30.0))); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6221e6d90b..805388dd48 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -408,6 +408,7 @@ registry! { DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, + TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d64cd51179..691f33f88c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6112,3 +6112,13 @@ breakText Glyphs Глифи Create Swatch Legend Създаване на легенда на образците Create Swatch Legend… Създаване на легенда на образците… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Инструменти за текст + Text Tweaker… Настройка на текста… + Text Tweaker Настройка на текста + Attribute: Атрибут: + From: От: + To: До: + Bow Дъга + Spike Връх + Skip Spaces Пропускане на интервалите diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 7e29b19084..25dde07c6c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6146,3 +6146,13 @@ shape Open Otvoren Create Swatch Legend Kreiraj legendu uzoraka boja Create Swatch Legend… Kreiraj legendu uzoraka boja… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Alati za tekst + Text Tweaker… Podešavanje teksta… + Text Tweaker Podešavanje teksta + Attribute: Atribut: + From: Od: + To: Do: + Bow Luk + Spike Šiljak + Skip Spaces Preskoči razmake diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2c9ea12679..d44d0594a9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6246,3 +6246,13 @@ breakText Glyphs Glifs Create Swatch Legend Crea una llegenda de mostres Create Swatch Legend… Crea una llegenda de mostres… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Eines de text + Text Tweaker… Ajustador de text… + Text Tweaker Ajustador de text + Attribute: Atribut: + From: De: + To: A: + Bow Arc + Spike Pic + Skip Spaces Omet els espais diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index dede785a75..3051468cd3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6260,3 +6260,13 @@ breakText Glyphs Glyfy Create Swatch Legend Vytvořit legendu vzorníku Create Swatch Legend… Vytvořit legendu vzorníku… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Nástroje textu + Text Tweaker… Ladění textu… + Text Tweaker Ladění textu + Attribute: Atribut: + From: Od: + To: Do: + Bow Oblouk + Spike Špička + Skip Spaces Přeskočit mezery diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 6d307f60f1..aecb2a8c8a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6128,3 +6128,13 @@ breakText Glyphs Glyffer Create Swatch Legend Opret farveprøveforklaring Create Swatch Legend… Opret farveprøveforklaring… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Tekstværktøjer + Text Tweaker… Tekstjustering… + Text Tweaker Tekstjustering + Attribute: Attribut: + From: Fra: + To: Til: + Bow Bue + Spike Spids + Skip Spaces Spring mellemrum over diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f1aece5390..6fe42bdfac 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5846,3 +5846,13 @@ breakText Glyphs Glyphen Create Swatch Legend Farbfeldlegende erstellen Create Swatch Legend… Farbfeldlegende erstellen… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Textwerkzeuge + Text Tweaker… Text-Tweaker… + Text Tweaker Text-Tweaker + Attribute: Attribut: + From: Von: + To: Bis: + Bow Bogen + Spike Spitze + Skip Spaces Leerzeichen überspringen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 56e14d395d..a0ca7ab17a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6212,3 +6212,13 @@ breakText Glyphs Γλύφοι Create Swatch Legend Δημιουργία υπομνήματος δειγμάτων χρωμάτων Create Swatch Legend… Δημιουργία υπομνήματος δειγμάτων χρωμάτων… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Εργαλεία κειμένου + Text Tweaker… Ρύθμιση κειμένου… + Text Tweaker Ρύθμιση κειμένου + Attribute: Ιδιότητα: + From: Από: + To: Έως: + Bow Τόξο + Spike Αιχμή + Skip Spaces Παράλειψη κενών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 84b860be9f..9907c409d4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6202,3 +6202,13 @@ breakText Glyphs Glifos Create Swatch Legend Crear leyenda de muestras Create Swatch Legend… Crear leyenda de muestras… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Herramientas de texto + Text Tweaker… Ajustador de texto… + Text Tweaker Ajustador de texto + Attribute: Atributo: + From: Desde: + To: Hasta: + Bow Arco + Spike Pico + Skip Spaces Omitir espacios diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 14d0957e02..176498542a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6290,3 +6290,13 @@ breakText Glyphs Merkit Create Swatch Legend Luo värimallien selite Create Swatch Legend… Luo värimallien selite… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Tekstityökalut + Text Tweaker… Tekstin säätö… + Text Tweaker Tekstin säätö + Attribute: Määrite: + From: Alku: + To: Loppu: + Bow Kaari + Spike Piikki + Skip Spaces Ohita välilyönnit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0e8434dc4e..3d4eb8583f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6255,3 +6255,13 @@ breakText Glyphs Glyphes Create Swatch Legend Créer une légende des nuances Create Swatch Legend… Créer une légende des nuances… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Outils de texte + Text Tweaker… Ajusteur de texte… + Text Tweaker Ajusteur de texte + Attribute: Attribut : + From: De : + To: À : + Bow Arc + Spike Pointe + Skip Spaces Ignorer les espaces diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e3fee02cb5..7dfdf687c3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6244,3 +6244,13 @@ breakText Glyphs Glifák Create Swatch Legend Színmintajelmagyarázat létrehozása Create Swatch Legend… Színmintajelmagyarázat létrehozása… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Szövegeszközök + Text Tweaker… Szöveghangoló… + Text Tweaker Szöveghangoló + Attribute: Jellemző: + From: Ettől: + To: Eddig: + Bow Ív + Spike Csúcs + Skip Spaces Szóközök kihagyása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 06cf4da3aa..b2aa569202 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6128,3 +6128,13 @@ breakText Glyphs Glif Create Swatch Legend Buat Legenda Swatch Create Swatch Legend… Buat Legenda Swatch… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Alat Teks + Text Tweaker… Penyetel Teks… + Text Tweaker Penyetel Teks + Attribute: Atribut: + From: Dari: + To: Ke: + Bow Busur + Spike Puncak + Skip Spaces Lewati Spasi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 742624e12d..50bf09162f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5880,3 +5880,13 @@ breakText Glyphs Glifi Create Swatch Legend Crea legenda campioni Create Swatch Legend… Crea legenda campioni… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Strumenti testo + Text Tweaker… Regolatore testo… + Text Tweaker Regolatore testo + Attribute: Attributo: + From: Da: + To: A: + Bow Arco + Spike Picco + Skip Spaces Salta gli spazi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1584618d11..7b0a1e6391 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5945,3 +5945,13 @@ breakText Glyphs 字形 Create Swatch Legend スウォッチの凡例を作成 Create Swatch Legend… スウォッチの凡例を作成… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools テキストツール + Text Tweaker… テキストの調整… + Text Tweaker テキストの調整 + Attribute: 属性: + From: 開始: + To: 終了: + Bow 弓形 + Spike 山形 + Skip Spaces スペースをスキップ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index fabc4a3694..52bdf75991 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6248,3 +6248,13 @@ breakText Glyphs გლიფები Create Swatch Legend ფერის ნიმუშების ლეგენდის შექმნა Create Swatch Legend… ფერის ნიმუშების ლეგენდის შექმნა… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools ტექსტის ხელსაწყოები + Text Tweaker… ტექსტის მორგება… + Text Tweaker ტექსტის მორგება + Attribute: ატრიბუტი: + From: საწყისი: + To: საბოლოო: + Bow რკალი + Spike პიკი + Skip Spaces ჰარების გამოტოვება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7376f14d85..a36341694f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5841,3 +5841,13 @@ breakText Glyphs 글리프 Create Swatch Legend 견본 범례 만들기 Create Swatch Legend… 견본 범례 만들기… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools 텍스트 도구 + Text Tweaker… 텍스트 조정… + Text Tweaker 텍스트 조정 + Attribute: 속성: + From: 시작: + To: 끝: + Bow 활 모양 + Spike 뾰족한 모양 + Skip Spaces 공백 건너뛰기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c2670658d3..cc9970da95 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6172,3 +6172,13 @@ breakText Glyphs Glyphs Create Swatch Legend Stalenlegenda maken Create Swatch Legend… Stalenlegenda maken… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Teksthulpmiddelen + Text Tweaker… Tekst bijstellen… + Text Tweaker Tekst bijstellen + Attribute: Kenmerk: + From: Van: + To: Tot: + Bow Boog + Spike Piek + Skip Spaces Spaties overslaan diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 10ebc96bd0..14765e9e76 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6115,3 +6115,13 @@ breakText Glyphs Glify Create Swatch Legend Utwórz legendę próbek Create Swatch Legend… Utwórz legendę próbek… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Narzędzia tekstu + Text Tweaker… Strojenie tekstu… + Text Tweaker Strojenie tekstu + Attribute: Atrybut: + From: Od: + To: Do: + Bow Łuk + Spike Szpic + Skip Spaces Pomiń spacje diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f43b74b971..798b3db35e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6333,3 +6333,13 @@ swatch Yellow Green Verde-amarelado Create Swatch Legend Criar Legenda de Amostras Create Swatch Legend… Criar Legenda de Amostras… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Ferramentas de texto + Text Tweaker… Ajustador de texto… + Text Tweaker Ajustador de texto + Attribute: Atributo: + From: De: + To: Até: + Bow Arco + Spike Pico + Skip Spaces Ignorar espaços diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 0a42894b63..52fc8da784 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6349,3 +6349,13 @@ breakText Glyphs Глифы digits Hindi Хинди font-script Japanese Японский shape Open Открытый +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Инструменты текста + Text Tweaker… Настройка текста… + Text Tweaker Настройка текста + Attribute: Атрибут: + From: От: + To: До: + Bow Дуга + Spike Пик + Skip Spaces Пропускать пробелы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 214b19aed4..725bad0185 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6316,3 +6316,13 @@ breakText Glyphs Glyfer # The strings the report listed as missing for sv. Font Size: Teckenstorlek: digits Hindi Hindi +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Textverktyg + Text Tweaker… Textjustering… + Text Tweaker Textjustering + Attribute: Attribut: + From: Från: + To: Till: + Bow Båge + Spike Spets + Skip Spaces Hoppa över mellanslag diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cdf14d3f5a..9f7c47f746 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6217,3 +6217,13 @@ breakText Glyphs Glifler Create Swatch Legend Renk Örneği Açıklaması Oluştur Create Swatch Legend… Renk Örneği Açıklaması Oluştur… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Metin Araçları + Text Tweaker… Metin Ayarlayıcı… + Text Tweaker Metin Ayarlayıcı + Attribute: Öznitelik: + From: Başlangıç: + To: Bitiş: + Bow Yay + Spike Sivri Uç + Skip Spaces Boşlukları Atla diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 112ed58400..43c5208dd6 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5860,3 +5860,13 @@ breakText Glyphs Гліфи Create Swatch Legend Створити легенду зразків Create Swatch Legend… Створити легенду зразків… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Інструменти тексту + Text Tweaker… Налаштування тексту… + Text Tweaker Налаштування тексту + Attribute: Атрибут: + From: Від: + To: До: + Bow Дуга + Spike Пік + Skip Spaces Пропускати пробіли diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 05b1dda5c7..49b89fb6fa 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5861,3 +5861,13 @@ breakText Glyphs Glyph Create Swatch Legend Tạo chú giải mẫu màu Create Swatch Legend… Tạo chú giải mẫu màu… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools Công cụ văn bản + Text Tweaker… Tinh chỉnh văn bản… + Text Tweaker Tinh chỉnh văn bản + Attribute: Thuộc tính: + From: Từ: + To: Đến: + Bow Cung + Spike Đỉnh nhọn + Skip Spaces Bỏ qua khoảng trắng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 336057c436..372a0681d9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6101,3 +6101,13 @@ breakText Glyphs 字形 Create Swatch Legend 创建色板图例 Create Swatch Legend… 创建色板图例… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools 文字工具 + Text Tweaker… 文字微调… + Text Tweaker 文字微调 + Attribute: 属性: + From: 起始: + To: 结束: + Bow 弓形 + Spike 尖峰 + Skip Spaces 跳过空格 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4ddbf0f694..ac16292013 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5898,3 +5898,13 @@ breakText Glyphs 字符 Create Swatch Legend 建立色票圖例 Create Swatch Legend… 建立色票圖例… HEX HEX +# Type Tools add-on (Object › Plug-ins › Type Tools). + Type Tools 文字工具 + Text Tweaker… 文字微調… + Text Tweaker 文字微調 + Attribute: 屬性: + From: 起始: + To: 結束: + Bow 弓形 + Spike 尖峰 + Skip Spaces 略過空格 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7a3213f78a..0b30e0dc63 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -71,6 +71,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), crate::addons::color::legend::COMMAND => (crate::addons::color::legend::KIND, crate::addons::color::legend::fields()), + crate::addons::typetools::COMMAND => (crate::addons::typetools::KIND, crate::addons::typetools::fields(app)), "artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::open_fields(app)), _ => return None, }) diff --git a/docs/mcp.md b/docs/mcp.md index bbd4451f5b..a7fb8f10f1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6777,3 +6777,30 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ```json {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` + +## Type Tools add-on + +Type Tools is a built-in add-on for type: its command is `addon.type.textTweaker`, and in the desktop app it lives in +Object › Plug-ins › Type Tools (#4924). Text Tweaker gives one character attribute to the characters letter by letter, +from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set +as `text.setRangeStyle` sets it (the Character panel), in its units and ranges, so on scaled type it is the size shown. +It changes the range of `id` (`start`/`end` bytes), else all the text of the type objects in `ids`, else the text the +Type tool has selected (at a caret: all of that object's text), else all the text of every selected type object; each +object gets its own ramp, and at most 100000 characters change in one run. A run that changes nothing makes no step. + +| Parameter | Values (default) | +|---|---| +| `attribute` | `size` (pt 0.1…1296), `baselineShift` (pt −1296…1296), `rotation` (° −360…360), `hScale`, `vScale` (% 1…10000), `tracking` (1/1000 em −1000…10000), `leading` (pt 0.1…5000), `strokeWidth` (pt 0…1000; shows only on characters with a stroke) (`size`) | +| `from`, `to` | the first and last character's values, in the attribute's units and range (size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2) | +| `shape` | `straight` (an even ramp), `ease` (slow at both ends), `bow` (`from` at both ends, rising smoothly to `to` in the middle), `spike` (the same, in straight lines), `random` (each character anywhere from `from` to `to`) (`straight`) | +| `seed` | whole number (0): `random` with the same seed and text gives the same values | +| `skipSpaces` | true: spaces and line breaks keep their values and don't count | + +→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog kind +`textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own +default values, and the seed starts new whenever the document has changed. + +```json +{"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"baselineShift","from":0,"to":18,"shape":"bow"}}} +{"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"rotation","from":-15,"to":15,"shape":"random","seed":4}}} +``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a76d8e44ab..9f54f0f892 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; Units › East Asian Type acts, with Q and Ha units; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type Tools add-on: Text Tweaker, #4924; font-family fields accept the mouse wheel, #5253; Units › East Asian Type acts, with Q and Ha units; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | | 2026-11-02 | minor | Legacy `.ai` saves (version 7) write type with rotated characters as outlines that keep each character's rotation, with a warning unless `outlineText` is on (#5186); scores unchanged. | | 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | | 2026-10-31 | minor | New Document: More Settings has the Save Preset button beside the name too, saving its settings (artboard layout included) as a preset (#4893); scores unchanged. | @@ -1500,6 +1501,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Sort Objects… sorts the top-level selected objects (or `ids`, at most 20000) by one attribute (width, height, area, x or y position, opacity or stacking order; small to large, large to small, or a random order from a seed) and gives them another in that order, the first the smallest value: the objects trade the values they have, or with Distribute Evenly the values step evenly from the smallest to the largest. Lining objects up left to right by size, restacking them so the largest is at the back, or giving them heights that step with their x position are each one run. Sizes and places are measured and set as `object.setBounds` measures them (Use Preview Bounds); a width, height or area changes about each object's centre (an area in proportion), and stacking order trades places only among objects of the same layer or group. One undo step; no step when nothing changes. Tests: `sort_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each attribute sorted by and applied, both directions, distribute, layers kept apart, the seeded random order, `ids`, no step when in order, bad params), `sort_objects_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Type Tools add-on: Text Tweaker (2026-11-03) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. From bc70180047df5425c74ab064722f397d4a1de0b1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 19:35:41 +0700 Subject: [PATCH 374/674] Text Tweaker: an id that isn't type is refused as ids of it is --- crates/engine/src/cmd/textedit.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index ace8e84e0a..7135f6ae5d 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1263,6 +1263,10 @@ pub(crate) fn type_ranges( ) -> Result> { // (text, its range; None: all of it). let targets: Vec<(NodeId, Option<(usize, usize)>)> = match id_param(p, "id") { + // An object that isn't type is refused as `ids` of it is. + Some(id) if s.doc()?.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Text(_))) => { + return Err(bad(c, "no text objects selected")); + } Some(id) => vec![(id, Some(range_of(p, edit::runs_len(&text_ref(s, id)?.runs), c)?))], None => { let editing = editing_range(s)?.filter(|_| p.get("ids").filter(|v| !v.is_null()).is_none()); From 0fa627c6df5932c5ef5d8c06e533c45d74324722 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:12:11 +0000 Subject: [PATCH 375/674] chore(deps): bump wat from 1.262.0 to 1.263.0 Bumps [wat](https://github.com/bytecodealliance/wasm-tools) from 1.262.0 to 1.263.0. - [Release notes](https://github.com/bytecodealliance/wasm-tools/releases) - [Commits](https://github.com/bytecodealliance/wasm-tools/compare/v1.262.0...v1.263.0) --- updated-dependencies: - dependency-name: wat dependency-version: 1.263.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- Cargo.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dc704e6d15..46998c4c3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6754,12 +6754,12 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" dependencies = [ "leb128fmt", - "wasmparser 0.262.0", + "wasmparser 0.263.0", ] [[package]] @@ -6814,9 +6814,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" dependencies = [ "bitflags 2.13.2", "indexmap", @@ -6825,9 +6825,9 @@ dependencies = [ [[package]] name = "wast" -version = "262.0.0" +version = "263.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23" +checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7" dependencies = [ "bumpalo", "leb128fmt", @@ -6838,9 +6838,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.262.0" +version = "1.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1" +checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7" dependencies = [ "wast", ] From 4db6e7b448d8d5dbfd5d0ab83bddc6968c43c068 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 04:59:59 -0800 Subject: [PATCH 376/674] Paint: use the document color model for new gradient defaults --- ROADMAP.md | 4 ++- crates/engine/src/cmd/gradient.rs | 47 +++++++++++++++++++++-------- crates/engine/src/cmd/paint.rs | 2 +- crates/engine/src/tests/gradient.rs | 41 +++++++++++++++++++++++++ docs/gaps.md | 5 ++- docs/roadmap.md | 5 ++- docs/target-app-parity.md | 5 ++- docs/ui-parity.md | 5 ++- 8 files changed, 95 insertions(+), 19 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 7aa720205e..6cf80d3628 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,7 @@ # VectorCraft Roadmap +- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. + - PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. - PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. @@ -9,7 +11,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Progress log row for the Type Tools add-on's Text Tweaker, #4924; headline numbers unchanged; previously: font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index b506c18f83..52daa9b747 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -312,10 +312,31 @@ pub(crate) fn apply_gradient_edit_in( bounds: Option, inside: &dyn Fn(Point) -> bool, ) -> std::result::Result { - let mut gp = match paint { + apply_gradient_edit_in_model(paint, p, bounds, inside, None) +} + +/// New implicit stops use the document's model; existing gradients retain their own colors. +fn gradient_for_edit(paint: &Paint, model: Option) -> GradientPaint { + match paint { Paint::Gradient(g) => (**g).clone(), - _ => GradientPaint::new(Gradient::default()), - }; + _ => { + let mut gradient = Gradient::default(); + for stop in &mut gradient.stops { + stop.color = super::paint::stored_color(model, stop.color); + } + GradientPaint::new(gradient) + } + } +} + +fn apply_gradient_edit_in_model( + paint: &Paint, + p: &Value, + bounds: Option, + inside: &dyn Fn(Point) -> bool, + model: Option, +) -> std::result::Result { + let mut gp = gradient_for_edit(paint, model); let mut switched = false; if let Some(k) = str_param(p, "kind") { let kind = parse_kind(k)?; @@ -414,13 +435,15 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`dither` applies to gradient fills (stroke: false)")); } super::paint::check_keep_model(p, C)?; + let model = super::paint::new_color_model(s, p); // New RGB stop colors take the document's model; those of the swatches the stops name don't. let stored = stop_colors(s, p, p); // Stops naming swatches take their colours from them. let p = &link_stops(&s.doc()?.doc, p).map_err(|e| bad(C, e))?; // Validate against the defaults first so bad params fail without touching the document. let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() }; - let new_default = apply_gradient_edit(&default_paint, &with_stored_stops(p, &default_paint, &stored), None).map_err(|e| bad(C, e))?; + let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(p, &default_paint, &stored), None, &|_| true, model) + .map_err(|e| bad(C, e))?; let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform); edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| { if index.is_none() @@ -429,7 +452,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { let lb = t.local_bounds(); for r in &mut t.runs { let (cur, b) = run_paint_mut(r, stroke, lb); - *cur = apply_gradient_edit(cur, &with_stored_stops(p, cur, &stored), Some(b)).map_err(|e| bad(C, e))?; + *cur = apply_gradient_edit_in_model(cur, &with_stored_stops(p, cur, &stored), Some(b), &|_| true, model).map_err(|e| bad(C, e))?; } return Ok(()); } @@ -441,7 +464,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { None => &|_| true, }; let old = n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None); - let np = apply_gradient_edit_in(old, &with_stored_stops(p, old, &stored), b, inside).map_err(|e| bad(C, e))?; + let np = apply_gradient_edit_in_model(old, &with_stored_stops(p, old, &stored), b, inside, model).map_err(|e| bad(C, e))?; n.appearance.set_paint_at(index, !stroke, np); if let Some(m) = mode && let Some(st) = n.appearance.stroke_at_mut(index) @@ -547,12 +570,9 @@ impl GeomEdit { /// `cur` with the vector, aspect and focal point of `e` (given in the document). `to_doc` maps /// the paint's space (text space for type runs) to the document and `bounds` (in that space) fits /// an unplaced gradient, so what the document shows carries over where `e` keeps it. -fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option) -> Option { +fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option, model: Option) -> Option { let from_doc = invert(to_doc)?; - let mut gp = match cur { - Paint::Gradient(g) => (**g).clone(), - _ => GradientPaint::new(Gradient::default()), - }; + let mut gp = gradient_for_edit(cur, model); let kind = gp.gradient.kind; let map = |mut g: GradientGeom, a: Affine| { if a != Affine::IDENTITY { @@ -597,6 +617,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { if targets.is_empty() { return Err(EngineError::Other("nothing selected".into())); } + let model = super::paint::new_color_model(s, &Value::Null); edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind @@ -607,14 +628,14 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { run_stroke_weight(&mut r.style); } let (paint, b) = run_paint_mut(r, stroke, lb); - if let Some(np) = vector_paint(paint, &edit, xf, Some(b)) { + if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model) { *paint = np; } } return Ok(()); } let b = item_paint_bounds(n, index, !stroke); - if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b) { + if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b, model) { n.appearance.set_paint_at(index, !stroke, np); } Ok(()) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 33c69589b7..ec59e4e9e5 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -303,7 +303,7 @@ pub(crate) fn check_keep_model(p: &Value, cmd: &str) -> Result<()> { /// The model RGB colours given in `p` are stored in: the document's in a CMYK document (`None` in /// an RGB one, or with `keepModel`). -fn new_color_model(s: &Session, p: &Value) -> Option { +pub(super) fn new_color_model(s: &Session, p: &Value) -> Option { let mode = s.active()?.doc.color_mode; (mode != vectorcraft_doc::ColorMode::Rgb && !bool_or(p, "keepModel", false)).then(|| mode.model()) } diff --git a/crates/engine/src/tests/gradient.rs b/crates/engine/src/tests/gradient.rs index c36addcbc5..e6f9383fe3 100644 --- a/crates/engine/src/tests/gradient.rs +++ b/crates/engine/src/tests/gradient.rs @@ -30,6 +30,47 @@ fn fill_gradient(s: &Session, id: NodeId) -> GradientPaint { } } +#[test] +fn new_gradient_defaults_follow_the_cmyk_document_mode() { + for kind in ["linear", "radial", "freeform"] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); + let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + s.execute("paint.editGradient", &json!({"kind":kind})).unwrap(); + let g = fill_gradient(&s, id); + assert!(g.gradient.stops.iter().all(|stop| matches!(stop.color, Color::Cmyk { .. })), "{kind}: {:?}", g.gradient.stops); + if let Some(freeform) = g.freeform { + assert!(freeform.points.iter().all(|point| matches!(point.color, Color::Cmyk { .. })), "freeform points must use the same color model"); + } + } +} + +#[test] +fn editing_an_explicit_rgb_gradient_in_cmyk_keeps_its_color_model() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); + let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + s.execute("paint.editGradient", &json!({"kind":"linear","keepModel":true})).unwrap(); + let before = fill_gradient(&s, id).gradient.stops; + assert!(before.iter().all(|stop| matches!(stop.color, Color::Rgb { .. }))); + s.execute("paint.editGradient", &json!({"angle":45})).unwrap(); + assert_eq!(fill_gradient(&s, id).gradient.stops, before); +} + +#[test] +fn drawing_a_new_gradient_vector_uses_cmyk_default_stops() { + for stroke in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap(); + let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + s.execute("paint.setGradientGeom", &json!({"start":[10,10],"end":[110,10],"stroke":stroke})).unwrap(); + let appearance = &node(&s, id).appearance; + let paint = if stroke { appearance.stroke_paint() } else { appearance.fill_paint() }; + let Paint::Gradient(g) = paint else { panic!("not a gradient") }; + assert!(g.gradient.stops.iter().all(|stop| matches!(stop.color, Color::Cmyk { .. })), "stroke={stroke}: {:?}", g.gradient.stops); + } +} + /// A three-stop freeform gradient with a 0.3 midpoint, partial opacity and a placed vector. fn three_stops() -> GradientPaint { let stop = |offset, color, opacity, midpoint| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }; diff --git a/docs/gaps.md b/docs/gaps.md index 783dc97110..87721de914 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,9 +1,11 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (G15: a compound path's assembled path is kept between frames; estimate unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence +Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. + The closed font-family fields in Character, Properties and Control now accept the mouse wheel for selected text (#5253). Each effective notch applies one family and adds one undo step; the list follows saved font filters, ignores search text, and @@ -26,6 +28,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | diff --git a/docs/roadmap.md b/docs/roadmap.md index bf5f67279b..2ea970a6a6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,9 +1,11 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence +Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. + **Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -19,6 +21,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; scores and estimates unchanged. | | 2026-10-30 | minor | Raster effects: bounded length fields in effect dialogs clamp on commit and reject invalid inputs visibly (#4638); estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9f54f0f892..7513ebe092 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,9 +1,11 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type Tools add-on: Text Tweaker, #4924; font-family fields accept the mouse wheel, #5253; Units › East Asian Type acts, with Q and Ha units; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence +Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. + **Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -19,6 +21,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | | 2026-11-02 | minor | Legacy `.ai` saves (version 7) write type with rotated characters as outlines that keep each character's rotation, with a warning unless `outlineText` is on (#5186); scores unchanged. | | 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ae4eb5626b..a0b4225841 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,9 +1,11 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence +Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. + **Feature evidence last updated:** 2026-11-03. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -19,6 +21,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-10-26 | minor | Pencil Fidelity goes down to 0.01 pt (dialog, tool and engine; Smooth keeps 0.05) on a logarithmic slider across the Tool Options row, with hundredths in the field and key steps that fit the range (#3328); scores and estimates unchanged (estimated) | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | From 40ed074caed49dd1bf65d6655a4100d18196ca65 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 20:27:02 +0700 Subject: [PATCH 377/674] Actions: New Action asks for the action's name, set, function key and color Squashed from #5270 onto main. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/action_new.rs | 120 ++ .../ui-egui/src/dialogs/action_set_options.rs | 34 +- crates/ui-egui/src/i18n/bg.tsv | 12 + crates/ui-egui/src/i18n/bs.tsv | 12 + crates/ui-egui/src/i18n/ca.tsv | 12 + crates/ui-egui/src/i18n/cs.tsv | 12 + crates/ui-egui/src/i18n/da.tsv | 12 + crates/ui-egui/src/i18n/de.tsv | 12 + crates/ui-egui/src/i18n/el.tsv | 12 + crates/ui-egui/src/i18n/es.tsv | 12 + crates/ui-egui/src/i18n/fi.tsv | 12 + crates/ui-egui/src/i18n/fr.tsv | 12 + crates/ui-egui/src/i18n/hu.tsv | 12 + crates/ui-egui/src/i18n/id.tsv | 12 + crates/ui-egui/src/i18n/it.tsv | 12 + crates/ui-egui/src/i18n/ja.tsv | 12 + crates/ui-egui/src/i18n/ka.tsv | 12 + crates/ui-egui/src/i18n/ko.tsv | 12 + crates/ui-egui/src/i18n/nl.tsv | 12 + crates/ui-egui/src/i18n/pl.tsv | 12 + crates/ui-egui/src/i18n/pt-br.tsv | 12 + crates/ui-egui/src/i18n/ru.tsv | 12 + crates/ui-egui/src/i18n/sv.tsv | 12 + crates/ui-egui/src/i18n/tr.tsv | 12 + crates/ui-egui/src/i18n/uk.tsv | 12 + crates/ui-egui/src/i18n/vi.tsv | 12 + crates/ui-egui/src/i18n/zh-hans.tsv | 12 + crates/ui-egui/src/i18n/zh-hant.tsv | 12 + crates/ui-egui/src/menus/run.rs | 4 + crates/ui-egui/src/menus/ui_commands.rs | 26 +- crates/ui-egui/src/panels/actions.rs | 1031 ++++++++++++++++- crates/ui-egui/src/panels/actions/files.rs | 25 +- crates/ui-egui/src/panels/pathfinder.rs | 4 +- crates/ui-egui/src/shortcut_editor.rs | 29 + crates/ui-egui/src/shortcuts.rs | 11 +- crates/ui-egui/src/state.rs | 6 + docs/mcp.md | 29 +- docs/target-app-parity.md | 3 +- docs/ui-parity.md | 5 +- 41 files changed, 1558 insertions(+), 84 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/action_new.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 63bb4de7b0..7cbe32d1eb 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -350,6 +350,7 @@ impl VectorcraftApp { } crate::keymap::note_os(ctx); shortcut_editor::sync(&self.ui); + crate::panels::actions::sync_function_keys(&self.ui); prefs_dialog::apply_runtime(self, ctx); // The OS title bar (and the taskbar / Alt-Tab entry) follows the active file; with the // system title bar this is where the document name lives, as the in-app mark is hidden. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 805388dd48..d68217e52a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -8,6 +8,7 @@ mod about; pub mod action_batch; +pub mod action_new; pub mod action_set_options; pub mod artboard_options; pub mod blend_options; @@ -361,6 +362,7 @@ registry! { Package: [package::KIND] => package::SPEC, ActionBatch: [action_batch::KIND] => action_batch::SPEC, ActionSetOptions: [action_set_options::KIND] => action_set_options::SPEC, + ActionNew: [action_new::KIND] => action_new::SPEC, SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/action_new.rs b/crates/ui-egui/src/dialogs/action_new.rs new file mode 100644 index 0000000000..dab6013e1d --- /dev/null +++ b/crates/ui-egui/src/dialogs/action_new.rs @@ -0,0 +1,120 @@ +//! Actions panel › Create New Action (and ≡ › New Action…): the name, set, function key and color +//! of a new action. Record adds the action and starts recording into it (`ui.action.new`). +//! +//! Fields: `set` (the index of the set the action goes into), `name`, `key` (0 for none, 1 to 15 +//! for F1 to F15), `cmd` (Ctrl, Command on macOS), `shift`, `color` (a value of +//! [`crate::panels::actions::COLORS`], `""` for none). An invalid set or function key is an error: +//! Record then adds nothing and the dialog stays open. + +use serde_json::{Value, json}; + +use super::DialogSpec; +use crate::panels::actions::{COLORS, FUNCTION_KEYS, FunctionKey}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of New Action. +pub const KIND: &str = "actionNew"; + +/// The width of the label column. +const LABEL_W: f32 = 90.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("New Action").into(), + body, + confirm, + ok: Some("Record"), + ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()), + min_width: 340.0, + ..DialogSpec::FORM +}; + +/// Whether New Action can open: there is a set to put the action in and nothing is recording. +pub fn can_open(app: &VectorcraftApp) -> bool { + !app.ui.action_sets.is_empty() && app.ui.recording.is_none() +} + +/// Opens New Action for the current set, else the first set, named "Action N" with the first +/// number from the set's action count plus one that no action of the set uses, with no function +/// key and no color. +pub fn open(app: &mut VectorcraftApp) -> Result<(), String> { + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + let len = app.ui.action_sets.len(); + let set = app.ui.action_set.filter(|&s| s < len).unwrap_or(0); + let Some(s) = app.ui.action_sets.get(set) else { return Err("no such action set".into()) }; + let taken = |n: usize| s.actions.iter().any(|a| a.name == format!("Action {n}")); + let n = (s.actions.len() + 1..).find(|&n| !taken(n)).unwrap_or(1); + let fields = json!({"set": set, "name": format!("Action {n}"), "key": 0, "cmd": false, "shift": false, "color": ""}); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(()) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + widgets::label_row(ui, "Name:", LABEL_W, |ui| { + super::form::text(ui, d, "name", 200.0); + }); + let names: Vec<&str> = app.ui.action_sets.iter().map(|s| s.name.as_str()).collect(); + let set = d.fields.get("set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let shown = set.and_then(|s| names.get(s)).copied().unwrap_or_default(); + widgets::label_row(ui, "Action Set:", LABEL_W, |ui| { + if let Some(i) = widgets::dropdown_names(ui, "action-new-set", shown, &names, 200.0) { + d.fields.insert("set".into(), json!(i)); + } + }); + key_and_color(ui, d); + false +} + +/// The Function Key and Color rows of New Action and Action Options show errors for invalid keys. +pub(super) fn key_and_color(ui: &mut egui::Ui, d: &mut Dialog) { + let key = d.fields.get("key").and_then(Value::as_u64).unwrap_or(0); + let none = tl!("None"); + let keys: Vec = std::iter::once(none.to_string()).chain((1..=FUNCTION_KEYS).map(|n| format!("F{n}"))).collect(); + let labels: Vec<&str> = keys.iter().map(String::as_str).collect(); + let shown = usize::try_from(key).ok().and_then(|k| labels.get(k)).copied().unwrap_or(none); + let modifier = if crate::keymap::platform() == craft_keymap::Platform::Mac { "⌘" } else { "Ctrl" }; + widgets::label_row(ui, "Function Key:", LABEL_W, |ui| { + if let Some(i) = widgets::dropdown_names(ui, "action-key", shown, &labels, 70.0) { + d.fields.insert("key".into(), json!(i)); + } + super::form::check(ui, d, "cmd", modifier); + super::form::check(ui, d, "shift", "Shift"); + }); + let picked = FunctionKey::from_params(&json!({"key": key, "cmd": d.bool("cmd"), "shift": d.bool("shift")})); + if let Ok(Some(k)) = picked + && let Some(message) = crate::panels::actions::key_error(k) + { + widgets::label_row(ui, "", LABEL_W, |ui| { + ui.label(crate::i18n::msg(&message)); + }); + } + let colors: Vec<(&str, &str)> = std::iter::once(("", "None")).chain(COLORS).collect(); + super::form::choice(ui, d, "color", "Color:", (LABEL_W, 120.0), &colors); +} + +/// The function key and color params the dialog's fields give, as `ui.action.new` and +/// `ui.action.options` take them. +pub(super) fn key_and_color_params(d: &Dialog) -> Value { + json!({ + "key": d.fields.get("key").and_then(Value::as_u64).unwrap_or(0), + "cmd": d.bool("cmd"), + "shift": d.bool("shift"), + "color": d.str("color"), + }) +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let name = d.str("name").trim().to_string(); + // Record is disabled without a name; `ui.dialog.confirm` keeps the dialog open the same way. + if name.is_empty() { + return Ok(Value::Null); + } + let mut p = key_and_color_params(d); + p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null); + p["name"] = json!(name); + app.run(crate::panels::actions::NEW_ACTION, p)?; + app.ui.dialog = None; + Ok(Value::Null) +} diff --git a/crates/ui-egui/src/dialogs/action_set_options.rs b/crates/ui-egui/src/dialogs/action_set_options.rs index 568ea41c0b..f4c2ecdedf 100644 --- a/crates/ui-egui/src/dialogs/action_set_options.rs +++ b/crates/ui-egui/src/dialogs/action_set_options.rs @@ -2,10 +2,12 @@ //! the name of a new action set, of the current one, or of the selected action. //! //! Fields: `set` (the index of the set renamed, or of the action's set; none for a new set), -//! `action` (the index of the action renamed, in `set`; none for a set) and `name`. OK adds the set -//! and makes it the current one, renames the set, or renames the action (`ui.action.rename`). A -//! `set` or `action` field that is not the index of a set or action is an error, OK then changes -//! no set or action, and the dialog stays open. +//! `action` (the index of the action renamed, in `set`; none for a set) and `name`. Action Options +//! also holds the action's function key and color, as New Action does (`key`, `cmd`, `shift`, +//! `color`, see [`super::action_new`]). OK adds the set and makes it the current +//! one, renames the set, or changes the action's name, function key and color +//! (`ui.action.options`). An invalid `set`, `action` or function key is an error. OK then changes no set or +//! action, and the dialog stays open. use serde_json::{Value, json}; @@ -43,17 +45,26 @@ pub fn open(app: &mut VectorcraftApp, set: usize) { } } -/// Open Action Options for the action at `action` in set `set`, if there is one. +/// Open Action Options for the action at `action` in set `set`, if there is one, with its name, +/// function key and color. pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) { if let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)) { - app.ui.dialog = Some(Dialog::new(KIND, json!({"set": set, "action": action, "name": a.name}))); + let (key, cmd, shift) = a.key.map_or((0, false, false), |k| (k.key, k.cmd, k.shift)); + let color = a.color.clone().unwrap_or_default(); + let fields = json!({"set": set, "action": action, "name": a.name, "key": key, "cmd": cmd, "shift": shift, "color": color}); + app.ui.dialog = Some(Dialog::new(KIND, fields)); } } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - widgets::label_row(ui, "Name:", 50.0, |ui| { +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + // Action Options lines its rows up with the Function Key and Color rows. + let action = d.fields.contains_key("action") && d.fields.contains_key("key"); + widgets::label_row(ui, "Name:", if action { 90.0 } else { 50.0 }, |ui| { super::form::text(ui, d, "name", 200.0); }); + if action { + super::action_new::key_and_color(ui, d); + } false } @@ -65,7 +76,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } // The fields the dialog holds choose what OK does, as they choose its heading. if d.fields.contains_key("action") { - app.run(crate::panels::actions::RENAME_ACTION, json!({"set": d.fields.get("set"), "action": d.fields.get("action"), "name": name}))?; + // A dialog without the key fields (made by `ui.dialog.set`) keeps the key and color. + let mut p = if d.fields.contains_key("key") { super::action_new::key_and_color_params(d) } else { json!({}) }; + p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null); + p["action"] = d.fields.get("action").cloned().unwrap_or(Value::Null); + p["name"] = json!(name); + app.run(crate::panels::actions::ACTION_OPTIONS, p)?; } else if let Some(set) = d.fields.get("set") { let s = set.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| app.ui.action_sets.get_mut(i)).ok_or("no such action set")?; s.name = name; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 691f33f88c..39cc049f39 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5476,6 +5476,11 @@ theme Appearance Външен вид Export Type: Тип на експортиране: Movie Clip Филмов клип @msg name is empty името е празно +@msg an action is already recording вече се записва действие +@msg no such function key няма такъв функционален клавиш +@msg no such color няма такъв цвят +@msg {_1} cannot be used on Windows {_1} не може да се използва в Windows +@msg more than one action is named “{_1}” повече от едно действие се казва „{_1}“ @msg no symbol named `{n}` няма символ с име `{n}` Smudge Stick… Размазваща пръчка… Smudge Stick Размазваща пръчка @@ -5622,6 +5627,13 @@ axis Y Axis Y ос Action Options… Опции на действието… Action Options Опции на действието Rename Action Преименуване на действие + New Action… Ново действие… + New Action Ново действие + Create New Action Създаване на ново действие + Play Action Изпълнение на действие + Action Set: Набор от действия: + Function Key: Функционален клавиш: + Record Запис Create New Set Създаване на нов набор Stop Global Edit Край на глобалното редактиране Global Edit Options Опции за глобално редактиране diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 25dde07c6c..61fcd183ff 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5480,6 +5480,11 @@ mark-style Japanese Japanski Export Type: Vrsta izvoza: Movie Clip Filmski klip @msg name is empty naziv je prazan +@msg an action is already recording akcija se već snima +@msg no such function key nema takve funkcijske tipke +@msg no such color nema takve boje +@msg {_1} cannot be used on Windows {_1} se ne može koristiti na Windowsu +@msg more than one action is named “{_1}” više od jedne akcije ima naziv „{_1}” @msg no symbol named `{n}` nema simbola pod nazivom `{n}` Smudge Stick… Štapić za razmazivanje… Smudge Stick Štapić za razmazivanje @@ -5645,6 +5650,13 @@ axis Y Axis Y osa Action Options… Opcije akcije… Action Options Opcije akcije Rename Action Preimenuj akciju + New Action… Nova akcija… + New Action Nova akcija + Create New Action Napravi novu akciju + Play Action Reprodukuj akciju + Action Set: Skup akcija: + Function Key: Funkcijska tipka: + Record Snimi Create New Set Napravi novi skup Stop Global Edit Zaustavi globalno uređivanje Global Edit Options Opcije globalnog uređivanja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d44d0594a9..18b9e6b3cc 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3774,6 +3774,13 @@ digits Malayalam Malaiàlam Action Options… Opcions de l’acció… Action Options Opcions de l’acció Rename Action Canvia el nom de l’acció + New Action… Acció nova… + New Action Acció nova + Create New Action Crea una acció nova + Play Action Reprodueix l’acció + Action Set: Conjunt d’accions: + Function Key: Tecla de funció: + Record Enregistra Set Options… Defineix les opcions… Set Preference Defineix la preferència Set Slice Rectangle Defineix el rectangle del tall @@ -5160,6 +5167,11 @@ digits Malayalam Malaiàlam @msg move requires an existing destination panel per moure cal un panell de destinació existent @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Els fitxers PSD multicanal no es poden llegir: deseu-los en mode RGB, CMYK o escala de grisos @msg name is empty el nom és buit +@msg an action is already recording ja s’està enregistrant una acció +@msg no such function key no existeix aquesta tecla de funció +@msg no such color no existeix aquest color +@msg {_1} cannot be used on Windows {_1} no es pot fer servir al Windows +@msg more than one action is named “{_1}” més d’una acció es diu “{_1}” @msg name the file poseu un nom al fitxer @msg New Window isn't available yet: a document opens in one window Finestra nova encara no està disponible: un document s’obre en una sola finestra @msg no active document no hi ha cap document actiu diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3051468cd3..d05064235b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5567,6 +5567,11 @@ mark-style Japanese Japonské Export Type: Typ exportu: Movie Clip Filmový klip @msg name is empty název je prázdný +@msg an action is already recording akce se už zaznamenává +@msg no such function key taková funkční klávesa neexistuje +@msg no such color taková barva neexistuje +@msg {_1} cannot be used on Windows Zkratku {_1} nelze ve Windows použít +@msg more than one action is named “{_1}” název „{_1}“ má více než jedna akce @msg no symbol named `{n}` žádný symbol s názvem `{n}` Smudge Stick… Rozmazávací tyčinka… Smudge Stick Rozmazávací tyčinka @@ -5737,6 +5742,13 @@ axis Y Axis osa Y Action Options… Možnosti akce… Action Options Možnosti akce Rename Action Přejmenovat akci + New Action… Nová akce… + New Action Nová akce + Create New Action Vytvořit novou akci + Play Action Přehrát akci + Action Set: Sada akcí: + Function Key: Funkční klávesa: + Record Zaznamenat Create New Set Vytvořit novou sadu Stop Global Edit Ukončit globální úpravy Global Edit Options Možnosti globálních úprav diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index aecb2a8c8a..bb2b7b4713 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5360,6 +5360,11 @@ swatch Bright Violet Kraftig violet Export Type: Eksporttype: Movie Clip Filmklip @msg name is empty navnet er tomt +@msg an action is already recording en handling optages allerede +@msg no such function key ingen sådan funktionstast +@msg no such color ingen sådan farve +@msg {_1} cannot be used on Windows {_1} kan ikke bruges i Windows +@msg more than one action is named “{_1}” mere end én handling hedder »{_1}« @msg no symbol named `{n}` intet symbol med navnet `{n}` Remove Color Profile… Fjern farveprofil… Color wheel Farvehjul @@ -5639,6 +5644,13 @@ axis Y Axis Y-akse Action Options… Indstillinger for handling… Action Options Indstillinger for handling Rename Action Omdøb handling + New Action… Ny handling… + New Action Ny handling + Create New Action Opret ny handling + Play Action Afspil handling + Action Set: Handlingssæt: + Function Key: Funktionstast: + Record Optag Create New Set Opret nyt sæt Stop Global Edit Stop global redigering Global Edit Options Indstillinger for global redigering diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6fe42bdfac..5c57b58954 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5145,6 +5145,11 @@ effect Soft Weich Export Type: Exporttyp: Movie Clip Movieclip @msg name is empty Name ist leer +@msg an action is already recording eine Aktion wird bereits aufgezeichnet +@msg no such function key keine solche Funktionstaste +@msg no such color keine solche Farbe +@msg {_1} cannot be used on Windows {_1} kann unter Windows nicht verwendet werden +@msg more than one action is named “{_1}” mehr als eine Aktion heißt „{_1}“ @msg no symbol named `{n}` kein Symbol namens `{n}` Smudge Stick… Wischstift… Smudge Stick Wischstift @@ -5319,6 +5324,13 @@ axis Y Axis Y-Achse Action Options… Aktionsoptionen… Action Options Aktionsoptionen Rename Action Aktion umbenennen + New Action… Neue Aktion… + New Action Neue Aktion + Create New Action Neue Aktion erstellen + Play Action Aktion abspielen + Action Set: Aktionssatz: + Function Key: Funktionstaste: + Record Aufzeichnen Create New Set Neuen Satz erstellen Stop Global Edit Globale Bearbeitung beenden Global Edit Options Optionen für globale Bearbeitung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a0ca7ab17a..2a17c0baba 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5518,6 +5518,11 @@ effect Points Σημεία Export Type: Τύπος εξαγωγής: Movie Clip Κλιπ ταινίας @msg name is empty το όνομα είναι κενό +@msg an action is already recording μια ενέργεια καταγράφεται ήδη +@msg no such function key δεν υπάρχει τέτοιο πλήκτρο λειτουργίας +@msg no such color δεν υπάρχει τέτοιο χρώμα +@msg {_1} cannot be used on Windows Το {_1} δεν μπορεί να χρησιμοποιηθεί στα Windows +@msg more than one action is named “{_1}” περισσότερες από μία ενέργειες ονομάζονται «{_1}» @msg no symbol named `{n}` κανένα σύμβολο με όνομα `{n}` Smudge Stick… Μουτζούρα… Smudge Stick Μουτζούρα @@ -5688,6 +5693,13 @@ axis Y Axis Άξονας Y Action Options… Επιλογές ενέργειας… Action Options Επιλογές ενέργειας Rename Action Μετονομασία ενέργειας + New Action… Νέα ενέργεια… + New Action Νέα ενέργεια + Create New Action Δημιουργία νέας ενέργειας + Play Action Αναπαραγωγή ενέργειας + Action Set: Σύνολο ενεργειών: + Function Key: Πλήκτρο λειτουργίας: + Record Καταγραφή Create New Set Δημιουργία νέου συνόλου Stop Global Edit Τερματισμός καθολικής επεξεργασίας Global Edit Options Επιλογές καθολικής επεξεργασίας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9907c409d4..3ca5ebf1f7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5508,6 +5508,11 @@ mark-style Japanese Japonesas Export Type: Tipo de exportación: Movie Clip Clip de película @msg name is empty el nombre está vacío +@msg an action is already recording ya se está grabando una acción +@msg no such function key no existe esa tecla de función +@msg no such color no existe ese color +@msg {_1} cannot be used on Windows {_1} no se puede usar en Windows +@msg more than one action is named “{_1}” más de una acción se llama “{_1}” @msg no symbol named `{n}` no hay ningún símbolo llamado `{n}` Smudge Stick… Difuminar con barra… Smudge Stick Difuminar con barra @@ -5678,6 +5683,13 @@ axis Y Axis Eje Y Action Options… Opciones de acción… Action Options Opciones de acción Rename Action Cambiar nombre de acción + New Action… Nueva acción… + New Action Nueva acción + Create New Action Crear nueva acción + Play Action Reproducir acción + Action Set: Conjunto de acciones: + Function Key: Tecla de función: + Record Grabar Create New Set Crear nuevo conjunto Stop Global Edit Detener edición global Global Edit Options Opciones de edición global diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 176498542a..78d810c7a2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5530,6 +5530,11 @@ mark-style Japanese Japanilainen Export Type: Vientityyppi: Movie Clip Elokuvaleike @msg name is empty nimi on tyhjä +@msg an action is already recording toimintoa nauhoitetaan jo +@msg no such function key toimintonäppäintä ei ole +@msg no such color väriä ei ole +@msg {_1} cannot be used on Windows {_1} ei ole käytettävissä Windowsissa +@msg more than one action is named “{_1}” useamman kuin yhden toiminnon nimi on ”{_1}” @msg no symbol named `{n}` symbolia nimeltä `{n}` ei ole Smudge Stick… Sumennuskynä… Smudge Stick Sumennuskynä @@ -5767,6 +5772,13 @@ axis Y Axis Y-akseli Action Options… Toiminnon asetukset… Action Options Toiminnon asetukset Rename Action Nimeä toiminto uudelleen + New Action… Uusi toiminto… + New Action Uusi toiminto + Create New Action Luo uusi toiminto + Play Action Toista toiminto + Action Set: Toimintosarja: + Function Key: Toimintonäppäin: + Record Nauhoita Create New Set Luo uusi sarja Stop Global Edit Lopeta yleismuokkaus Global Edit Options Yleismuokkauksen asetukset diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3d4eb8583f..d5972a384d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5562,6 +5562,11 @@ theme Appearance Apparence Export Type: Type d'exportation : Movie Clip Clip @msg name is empty le nom est vide +@msg an action is already recording un script est déjà en cours d’enregistrement +@msg no such function key touche de fonction inexistante +@msg no such color couleur inexistante +@msg {_1} cannot be used on Windows {_1} ne peut pas être utilisé sous Windows +@msg more than one action is named “{_1}” plusieurs scripts s’appellent « {_1} » @msg no symbol named `{n}` aucun symbole nommé `{n}` Smudge Stick… Estompe… Smudge Stick Estompe @@ -5732,6 +5737,13 @@ axis Y Axis Axe Y Action Options… Options de script… Action Options Options de script Rename Action Renommer le script + New Action… Nouveau script… + New Action Nouveau script + Create New Action Créer un script + Play Action Exécuter le script + Action Set: Jeu de scripts : + Function Key: Touche de fonction : + Record Enregistrer Create New Set Créer un jeu Stop Global Edit Arrêter la modification globale Global Edit Options Options de modification globale diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 7dfdf687c3..c9a798077a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5550,6 +5550,11 @@ imageTrace Outline Körvonal Export Type: Exportálás típusa: Movie Clip Mozgóklip @msg name is empty a név üres +@msg an action is already recording már folyik egy művelet felvétele +@msg no such function key nincs ilyen funkcióbillentyű +@msg no such color nincs ilyen szín +@msg {_1} cannot be used on Windows A(z) {_1} nem használható Windows rendszeren +@msg more than one action is named “{_1}” több művelet neve is „{_1}” @msg no symbol named `{n}` nincs `{n}` nevű szimbólum Smudge Stick… Elmosó rúd… Smudge Stick Elmosó rúd @@ -5720,6 +5725,13 @@ axis Y Axis Y tengely Action Options… Művelet beállításai… Action Options Művelet beállításai Rename Action Művelet átnevezése + New Action… Új művelet… + New Action Új művelet + Create New Action Új művelet létrehozása + Play Action Művelet lejátszása + Action Set: Műveletkészlet: + Function Key: Funkcióbillentyű: + Record Felvétel 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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b2aa569202..1b315d849e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5360,6 +5360,11 @@ swatch Bright Violet Violet cerah Export Type: Jenis ekspor: Movie Clip Klip film @msg name is empty nama kosong +@msg an action is already recording sebuah tindakan sedang direkam +@msg no such function key tidak ada tombol fungsi seperti itu +@msg no such color tidak ada warna seperti itu +@msg {_1} cannot be used on Windows {_1} tidak dapat digunakan di Windows +@msg more than one action is named “{_1}” lebih dari satu tindakan bernama “{_1}” @msg no symbol named `{n}` tidak ada simbol bernama `{n}` Remove Color Profile… Hapus profil warna… Color wheel Roda warna @@ -5639,6 +5644,13 @@ axis Y Axis Sumbu Y Action Options… Opsi tindakan… Action Options Opsi tindakan Rename Action Ganti nama tindakan + New Action… Tindakan baru… + New Action Tindakan baru + Create New Action Buat tindakan baru + Play Action Putar tindakan + Action Set: Set tindakan: + Function Key: Tombol fungsi: + Record Rekam Create New Set Buat set baru Stop Global Edit Hentikan edit global Global Edit Options Opsi edit global diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 50bf09162f..0b07d67690 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5180,6 +5180,11 @@ lighting Light Luce Export Type: Tipo di esportazione: Movie Clip Clip filmato @msg name is empty il nome è vuoto +@msg an action is already recording è già in corso la registrazione di un’azione +@msg no such function key tasto funzione inesistente +@msg no such color colore inesistente +@msg {_1} cannot be used on Windows {_1} non può essere usato su Windows +@msg more than one action is named “{_1}” più di un’azione si chiama “{_1}” @msg no symbol named `{n}` nessun simbolo denominato `{n}` Smudge Stick… Sfumino… Smudge Stick Sfumino @@ -5353,6 +5358,13 @@ axis Y Axis Asse Y Action Options… Opzioni azione… Action Options Opzioni azione Rename Action Rinomina azione + New Action… Nuova azione… + New Action Nuova azione + Create New Action Crea nuova azione + Play Action Esegui azione + Action Set: Set di azioni: + Function Key: Tasto funzione: + Record Registra Create New Set Crea nuovo set Stop Global Edit Interrompi modifica globale Global Edit Options Opzioni modifica globale diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 7b0a1e6391..de9c692c69 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5223,6 +5223,11 @@ lighting Light ライト Export Type: 書き出しタイプ: Movie Clip ムービークリップ @msg name is empty 名前が空です +@msg an action is already recording すでにアクションを記録中です +@msg no such function key 指定されたファンクションキーが見つかりません +@msg no such color 指定されたカラーが見つかりません +@msg {_1} cannot be used on Windows {_1} は Windows では使用できません +@msg more than one action is named “{_1}” 「{_1}」という名前のアクションが複数あります @msg no symbol named `{n}` `{n}` という名前のシンボルはありません Smudge Stick… スマッジスティック… Smudge Stick スマッジスティック @@ -5418,6 +5423,13 @@ axis Y Axis Y 軸 Action Options… アクションオプション… Action Options アクションオプション Rename Action アクション名を変更 + New Action… 新規アクション… + New Action 新規アクション + Create New Action 新規アクションを作成 + Play Action アクションを再生 + Action Set: アクションセット: + Function Key: ファンクションキー: + Record 記録 Create New Set 新規セットを作成 Stop Global Edit グローバル編集を終了 Global Edit Options グローバル編集オプション diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 52bdf75991..0eb9cd390a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5267,6 +5267,11 @@ imageTrace Outline კონტური Export Type: ექსპორტის ტიპი: Movie Clip ანიმაციური კლიპი @msg name is empty სახელი ცარიელია +@msg an action is already recording მოქმედება უკვე იწერება +@msg no such function key ასეთი ფუნქციური კლავიში არ არის +@msg no such color ასეთი ფერი არ არის +@msg {_1} cannot be used on Windows {_1} ვერ გამოიყენება Windows-ში +@msg more than one action is named “{_1}” „{_1}“ ერთზე მეტი მოქმედების სახელია @msg no symbol named `{n}` სიმბოლო სახელით `{n}` არ არის @msg no saved selection recalled შენახული მონიშვნა გამოძახებული არ არის @msg The last start of VectorCraft ended on {name} before its window appeared, so it started on {summary}. To try that graphics processor again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set VectorCraft-ის ბოლო გაშვება ფანჯრის გამოჩენამდე შეწყდა (გრაფიკული პროცესორი: {name}), ამიტომ VectorCraft გაეშვა: {summary}. ამ გრაფიკული პროცესორის ხელახლა საცდელად შეცვალეთ პარამეტრები › წარმადობა › გრაფიკული პროცესორი ან გაუშვით WGPU_BACKEND ცვლადის მითითებით @@ -5651,6 +5656,13 @@ axis Y Axis Y ღერძი Action Options… მოქმედების პარამეტრები… Action Options მოქმედების პარამეტრები Rename Action მოქმედების სახელის შეცვლა + New Action… ახალი მოქმედება… + New Action ახალი მოქმედება + Create New Action ახალი მოქმედების შექმნა + Play Action მოქმედების შესრულება + Action Set: მოქმედებების ნაკრები: + Function Key: ფუნქციური კლავიში: + Record ჩაწერა Create New Set ახალი ნაკრების შექმნა Stop Global Edit გლობალური რედაქტირების დასრულება Global Edit Options გლობალური რედაქტირების პარამეტრები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a36341694f..e4c58c1d58 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5141,6 +5141,11 @@ lighting Light 광원 Export Type: 내보내기 유형: Movie Clip 무비 클립 @msg name is empty 이름이 비어 있습니다 +@msg an action is already recording 이미 액션을 기록하고 있습니다 +@msg no such function key 해당 기능 키가 없습니다 +@msg no such color 해당 색상이 없습니다 +@msg {_1} cannot be used on Windows {_1}은(는) Windows에서 사용할 수 없습니다 +@msg more than one action is named “{_1}” “{_1}”(이)라는 이름의 액션이 둘 이상 있습니다 @msg no symbol named `{n}` 이름이 `{n}`인 심볼이 없습니다 Smudge Stick… 문지르기 막대… Smudge Stick 문지르기 막대 @@ -5314,6 +5319,13 @@ axis Y Axis Y축 Action Options… 액션 옵션… Action Options 액션 옵션 Rename Action 액션 이름 바꾸기 + New Action… 새 액션… + New Action 새 액션 + Create New Action 새 액션 만들기 + Play Action 액션 재생 + Action Set: 액션 세트: + Function Key: 기능 키: + Record 기록 Create New Set 새 세트 만들기 Stop Global Edit 전체 편집 중지 Global Edit Options 전체 편집 옵션 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index cc9970da95..af1269a7f5 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5368,6 +5368,11 @@ swatch Bright Violet Felviolet Export Type: Exporttype: Movie Clip Filmclip @msg name is empty naam is leeg +@msg an action is already recording er wordt al een actie opgenomen +@msg no such function key functietoets bestaat niet +@msg no such color kleur bestaat niet +@msg {_1} cannot be used on Windows {_1} kan niet worden gebruikt in Windows +@msg more than one action is named “{_1}” meer dan één actie heet „{_1}” @msg no symbol named `{n}` geen symbool met de naam `{n}` Remove Color Profile… Kleurprofiel verwijderen… Color wheel Kleurenwiel @@ -5683,6 +5688,13 @@ axis Y Axis Y-as Action Options… Actieopties… Action Options Actieopties Rename Action Actie hernoemen + New Action… Nieuwe actie… + New Action Nieuwe actie + Create New Action Nieuwe actie maken + Play Action Actie afspelen + Action Set: Actieset: + Function Key: Functietoets: + Record Opnemen Create New Set Nieuwe set maken Stop Global Edit Globale bewerking stoppen Global Edit Options Opties voor globale bewerking diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14765e9e76..08f91930ef 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5420,6 +5420,11 @@ mark-style Japanese Japońskie Export Type: Typ eksportu: Movie Clip Klip filmowy @msg name is empty nazwa jest pusta +@msg an action is already recording operacja jest już nagrywana +@msg no such function key brak takiego klawisza funkcyjnego +@msg no such color brak takiego koloru +@msg {_1} cannot be used on Windows Skrótu {_1} nie można używać w systemie Windows +@msg more than one action is named “{_1}” więcej niż jedna operacja nazywa się „{_1}” @msg no symbol named `{n}` brak symbolu o nazwie `{n}` Smudge Stick… Rozmazywacz… Smudge Stick Rozmazywacz @@ -5590,6 +5595,13 @@ axis Y Axis Oś Y Action Options… Opcje operacji… Action Options Opcje operacji Rename Action Zmień nazwę operacji + New Action… Nowa operacja… + New Action Nowa operacja + Create New Action Utwórz nową operację + Play Action Odtwórz operację + Action Set: Zestaw operacji: + Function Key: Klawisz funkcyjny: + Record Nagraj Create New Set Utwórz nowy zestaw Stop Global Edit Zakończ edycję globalną Global Edit Options Opcje edycji globalnej diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 798b3db35e..40a2538466 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5482,6 +5482,11 @@ mark-style Japanese Japonesas # Symbol Options › Export Type @msg name is empty o nome está vazio +@msg an action is already recording uma ação já está sendo gravada +@msg no such function key tecla de função inexistente +@msg no such color cor inexistente +@msg {_1} cannot be used on Windows {_1} não pode ser usado no Windows +@msg more than one action is named “{_1}” mais de uma ação se chama “{_1}” @msg no symbol named `{n}` nenhum símbolo chamado `{n}` Smudge Stick… Esfuminho… Smudge Stick Esfuminho @@ -5652,6 +5657,13 @@ axis Y Axis Eixo Y Action Options… Opções da Ação… Action Options Opções da Ação Rename Action Renomear Ação + New Action… Nova Ação… + New Action Nova Ação + Create New Action Criar Nova Ação + Play Action Reproduzir Ação + Action Set: Conjunto de Ações: + Function Key: Tecla de Função: + Record Gravar Create New Set Criar Novo Conjunto Stop Global Edit Parar Edição Global Global Edit Options Opções de Edição Global diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 52fc8da784..199d7a06d4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5175,6 +5175,11 @@ lighting Light Свет Export Type: Тип экспорта: Movie Clip Видеоклип @msg name is empty имя пустое +@msg an action is already recording действие уже записывается +@msg no such function key такой функциональной клавиши нет +@msg no such color такого цвета нет +@msg {_1} cannot be used on Windows Сочетание {_1} нельзя использовать в Windows +@msg more than one action is named “{_1}” несколько действий называются «{_1}» @msg no symbol named `{n}` нет символа с именем `{n}` Smudge Stick… Растушёвка… Smudge Stick Растушёвка @@ -5348,6 +5353,13 @@ axis Y Axis Ось Y Action Options… Параметры действия… Action Options Параметры действия Rename Action Переименовать действие + New Action… Новое действие… + New Action Новое действие + Create New Action Создать новое действие + Play Action Воспроизвести действие + Action Set: Набор действий: + Function Key: Функциональная клавиша: + Record Записать Create New Set Создать новый набор Stop Global Edit Завершить глобальное редактирование Global Edit Options Параметры глобального редактирования diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 725bad0185..8fb160ceac 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5522,6 +5522,11 @@ theme Appearance Utseende Export Type: Exporttyp: Movie Clip Filmklipp @msg name is empty namnet är tomt +@msg an action is already recording en åtgärd spelas redan in +@msg no such function key funktionstangenten finns inte +@msg no such color färgen finns inte +@msg {_1} cannot be used on Windows {_1} kan inte användas i Windows +@msg more than one action is named “{_1}” fler än en åtgärd heter ”{_1}” @msg no symbol named `{n}` ingen symbol med namnet `{n}` Angular Vinkelmått Away from the Line Bort från linjen @@ -5760,6 +5765,13 @@ axis Y Axis Y-axel Action Options… Alternativ för åtgärd… Action Options Alternativ för åtgärd Rename Action Byt namn på åtgärd + New Action… Ny åtgärd… + New Action Ny åtgärd + Create New Action Skapa ny åtgärd + Play Action Spela upp åtgärd + Action Set: Åtgärdsuppsättning: + Function Key: Funktionstangent: + Record Spela in Create New Set Skapa ny uppsättning Stop Global Edit Avsluta global redigering Global Edit Options Alternativ för global redigering diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9f7c47f746..fe8244ad8f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5232,6 +5232,11 @@ theme Appearance Görünüm Export Type: İhracat Türü: Movie Clip Film Klibi @msg name is empty isim boş +@msg an action is already recording zaten bir eylem kaydediliyor +@msg no such function key öyle bir işlev tuşu yok +@msg no such color öyle bir renk yok +@msg {_1} cannot be used on Windows {_1} Windows'ta kullanılamaz +@msg more than one action is named “{_1}” birden fazla eylemin adı “{_1}” @msg no symbol named `{n}` `{n}` adında bir sembol yok Artboard Options: edit with the Artboard tool Çalışma Yüzeyi Seçenekleri: Çalışma Yüzeyi aracıyla düzenleme @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG bu henüz açılamayan bir PostScript dosyasıdır (eski bir formatta kaydedilmiş veya PDF uyumluluğu olmayan bir .ai veya bir EPS dosyası): PDF, PDF uyumlu .ai veya SVG olarak kaydedin @@ -5694,6 +5699,13 @@ axis Y Axis Y ekseni Action Options… Eylem Seçenekleri… Action Options Eylem Seçenekleri Rename Action Eylemi Yeniden Adlandır + New Action… Yeni Eylem… + New Action Yeni Eylem + Create New Action Yeni Eylem Oluştur + Play Action Eylemi Oynat + Action Set: Eylem Seti: + Function Key: İşlev Tuşu: + Record Kayıt Create New Set Yeni Set Oluştur Stop Global Edit Genel Düzenlemeyi Durdur Global Edit Options Genel Düzenleme Seçenekleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 43c5208dd6..b676cbf4da 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5160,6 +5160,11 @@ lighting Light Світло Export Type: Тип експорту: Movie Clip Кліп @msg name is empty ім’я порожнє +@msg an action is already recording дія вже записується +@msg no such function key такої функціональної клавіші немає +@msg no such color такого кольору немає +@msg {_1} cannot be used on Windows Сполучення {_1} не можна використовувати у Windows +@msg more than one action is named “{_1}” кілька дій мають назву «{_1}» @msg no symbol named `{n}` немає символу з назвою `{n}` Smudge Stick… Розтушовування… Smudge Stick Розтушовування @@ -5333,6 +5338,13 @@ axis Y Axis Вісь Y Action Options… Параметри дії… Action Options Параметри дії Rename Action Перейменувати дію + New Action… Нова дія… + New Action Нова дія + Create New Action Створити нову дію + Play Action Відтворити дію + Action Set: Набір дій: + Function Key: Функціональна клавіша: + Record Записати Create New Set Створити новий набір Stop Global Edit Завершити глобальне редагування Global Edit Options Параметри глобального редагування diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 49b89fb6fa..1575decd9b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5161,6 +5161,11 @@ theme Appearance Giao diện Export Type: Kiểu xuất: Movie Clip Clip phim @msg name is empty tên trống +@msg an action is already recording đang ghi một hành động +@msg no such function key không có phím chức năng như vậy +@msg no such color không có màu như vậy +@msg {_1} cannot be used on Windows không thể dùng {_1} trên Windows +@msg more than one action is named “{_1}” có nhiều hành động tên là “{_1}” @msg no symbol named `{n}` không có biểu tượng nào tên `{n}` Smudge Stick… Bút chì xóa mờ… Smudge Stick Bút chì xóa mờ @@ -5334,6 +5339,13 @@ axis Y Axis Trục Y Action Options… Tùy chọn hành động… Action Options Tùy chọn hành động Rename Action Đổi tên hành động + New Action… Hành động mới… + New Action Hành động mới + Create New Action Tạo hành động mới + Play Action Phát hành động + Action Set: Bộ hành động: + Function Key: Phím chức năng: + Record Ghi 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 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 372a0681d9..204aee9b7b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5400,6 +5400,11 @@ lighting Light 光源 Export Type: 导出类型: Movie Clip 影片剪辑 @msg name is empty 名称为空 +@msg an action is already recording 已在记录动作 +@msg no such function key 没有此功能键 +@msg no such color 没有此颜色 +@msg {_1} cannot be used on Windows {_1} 在 Windows 上不能使用 +@msg more than one action is named “{_1}” 有多个动作名为“{_1}” @msg no symbol named `{n}` 没有名为 `{n}` 的符号 Smudge Stick… 涂抹棒… Smudge Stick 涂抹棒 @@ -5575,6 +5580,13 @@ axis Y Axis Y 轴 Action Options… 动作选项… Action Options 动作选项 Rename Action 重命名动作 + New Action… 新建动作… + New Action 新建动作 + Create New Action 创建新动作 + Play Action 播放动作 + Action Set: 动作组: + Function Key: 功能键: + Record 记录 Create New Set 创建新组 Stop Global Edit 停止全局编辑 Global Edit Options 全局编辑选项 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ac16292013..23b253f0e7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5217,6 +5217,11 @@ lighting Light 光源 Export Type: 轉存類型: Movie Clip 影片片段 @msg name is empty 名稱為空 +@msg an action is already recording 已在錄製動作 +@msg no such function key 沒有這個功能鍵 +@msg no such color 沒有這個顏色 +@msg {_1} cannot be used on Windows {_1} 無法在 Windows 上使用 +@msg more than one action is named “{_1}” 有多個動作名為「{_1}」 @msg no symbol named `{n}` 沒有名為 `{n}` 的符號 Smudge Stick… 塗抹棒… Smudge Stick 塗抹棒 @@ -5371,6 +5376,13 @@ axis Y Axis Y 軸 Action Options… 動作選項… Action Options 動作選項 Rename Action 重新命名動作 + New Action… 新增動作… + New Action 新增動作 + Create New Action 建立新動作 + Play Action 播放動作 + Action Set: 動作組: + Function Key: 功能鍵: + Record 錄製 Create New Set 建立新組 Stop Global Edit 停止整體編輯 Global Edit Options 整體編輯選項 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b788cd58bb..d97d092221 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -815,6 +815,10 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::package::open(app), crate::panels::actions::RENAME_ACTION => crate::panels::actions::rename_action(app, p), + crate::panels::actions::NEW_ACTION => crate::panels::actions::new_action(app, p), + crate::panels::actions::ACTION_OPTIONS => crate::panels::actions::action_options(app, p), + crate::panels::actions::PLAY_ACTION => crate::panels::actions::play_action(app, p), + crate::panels::actions::STOP_RECORDING => crate::panels::actions::stop(app, p), "ui.batchDialog" => { let set = p.get("set").and_then(Value::as_u64).unwrap_or(0) as usize; let action = p.get("action").and_then(Value::as_u64).unwrap_or(0) as usize; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 97b7926e83..9e887870a1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1180,7 +1180,31 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::RENAME_ACTION, "Rename Action", "", - "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps stay. The panel menu's Action Options… (dialog `actionSetOptions` with set, action and name) runs this for the selected action. An index past the last set or action, or an empty name, is an error and renames nothing → {name}", + "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps, function key and color stay. An index past the last set or action, or an empty name, is an error and renames nothing → {name}", + ), + ( + crate::panels::actions::NEW_ACTION, + "New Action", + "", + "{set: index, name, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} add an action named name (spaces trimmed from both ends) after the last action of the Actions panel's set at set (0 is the top set) and start recording into it; Stop Playing/Recording (ui.action.stop) ends the recording. key 1 to 15 is the function key F1 to F15 that plays the action (0 or null: none), with cmd (Ctrl, Command on macOS) and shift; color is its Button Mode color (null or \"\": none), which the panel does not show. Action function keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 cannot be used. The set becomes current and the new action is selected. The panel's Create New Action button and menu's New Action… (dialog `actionNew` with set, name, key, cmd, shift and color) run this on Record. While an action is recording, and for an index past the last set, an empty name, or a key or color that is not one of these, it is an error and nothing is added → {set, action}", + ), + ( + crate::panels::actions::ACTION_OPTIONS, + "Action Options", + "", + "{set: index, action: index, name?, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} change the Actions panel's action at action in set (0 is the top set); its steps stay. name renames it (spaces trimmed from both ends), key 1 to 15 with cmd (Ctrl, Command on macOS) and shift sets the function key F1 to F15 that plays it (0 or null: none), and color sets its Button Mode color (null or \"\": none); a param left out keeps what the action has, and cmd or shift alone changes that modifier of its key. Action function keys take priority over command shortcuts and preserve the command's binding. The panel menu's Action Options… (dialog `actionSetOptions` with set, action, name, key, cmd, shift and color) runs this for the selected action. An index past the last set or action, an empty name, or a key or color that is not one of these is an error and changes nothing → {name, key, color}", + ), + ( + crate::panels::actions::PLAY_ACTION, + "Play Action", + "", + "{action: name, set?: name} play the Actions panel's action named action as one undoable batch; set names the set to look in (default: every set). A name no action has, or one that more than one action in the sets looked in has, is an error and nothing plays → what command.batch returns", + ), + ( + crate::panels::actions::STOP_RECORDING, + "Stop Playing/Recording", + "", + "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. With nothing recording it changes nothing → {stopped}", ), ( "ui.batchDialog", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 30a95705ce..174fab9bc3 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -16,8 +16,116 @@ pub use files::{ACTIONS_EXT, LOAD_SET, SAVE_SET, load_set, save_set}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Action { + /// Tells the action apart from every other action in this run, also one with the same name: + /// the recording New Action starts fills the action with this id wherever it is. It is not + /// saved: each action gets a new id when it is made, copied or loaded. + #[serde(skip, default = "next_action_id")] + pub id: u64, pub name: String, pub steps: Vec<(String, Value)>, + /// The function key that plays the action when shortcuts are read, if one is assigned. A + /// saved value that is not a function key loads as none. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_key")] + pub key: Option, + /// The action's Button Mode color, one of [`COLORS`], if one is assigned. The panel does not + /// show it. A saved value that is not one of them loads as none. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "deserialize_color")] + pub color: Option, +} + +impl Action { + /// An action with a new [`Action::id`], no function key and no color. + pub fn new(name: impl Into, steps: Vec<(String, Value)>) -> Self { + Self { id: next_action_id(), name: name.into(), steps, key: None, color: None } + } + + /// A copy of the action with a new [`Action::id`] and no function key, so the key still plays + /// only the original. + pub fn copy(&self) -> Self { + Self { id: next_action_id(), key: None, ..self.clone() } + } +} + +/// An action id no other action in this run has. +fn next_action_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +/// The highest function key an action can play with: F1 to F15. +pub const FUNCTION_KEYS: u8 = 15; + +/// A function key that plays an action: F1 to F15, alone or with Ctrl (Command on macOS), Shift, +/// or both. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionKey { + /// 1 to [`FUNCTION_KEYS`]: F1 to F15. + pub key: u8, + /// Held with Ctrl, Command on macOS. + #[serde(default)] + pub cmd: bool, + #[serde(default)] + pub shift: bool, +} + +impl FunctionKey { + /// The key as shortcut text (`Cmd+Shift+F5`). + fn shortcut(self) -> String { + format!("{}{}F{}", if self.cmd { "Cmd+" } else { "" }, if self.shift { "Shift+" } else { "" }, self.key) + } + + /// The chord the key is pressed as; none when `key` is not 1 to [`FUNCTION_KEYS`]. + pub fn chord(self) -> Option { + (1..=FUNCTION_KEYS).contains(&self.key).then(|| crate::keymap::vc_chord(&self.shortcut())).flatten() + } + + /// The key as the menus show shortcuts on this platform (`Ctrl+Shift+F5`, `⇧⌘F5`). + pub fn text(self) -> String { + crate::menus::pretty_shortcut(&self.shortcut()) + } + + /// The function key that params `p` give: `key` (1 to 15, F1 to F15; 0 or null for none), `cmd` + /// and `shift`. `Ok(None)` for no key; an error for a `key` that is not one of them. + pub fn from_params(p: &Value) -> Result, String> { + match p.get("key") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_u64() { + Some(0) => Ok(None), + Some(n) if n <= u64::from(FUNCTION_KEYS) => { + let flag = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false); + Ok(Some(Self { key: n as u8, cmd: flag("cmd"), shift: flag("shift") })) + } + _ => Err("no such function key".into()), + }, + } + } +} + +/// The Button Mode colors an action can have, as (value, label). +pub const COLORS: [(&str, &str); 5] = [("red", "Red"), ("yellow", "Yellow"), ("green", "Green"), ("blue", "Blue"), ("violet", "Violet")]; + +/// Serde reader for [`Action::key`]: a value that is not a function key is none. +fn deserialize_key<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let v = ::deserialize(d)?; + Ok(serde_json::from_value::(v).ok().filter(|k| k.chord().is_some())) +} + +/// Serde reader for [`Action::color`]: a value that is not one of [`COLORS`] is none. +fn deserialize_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let v = ::deserialize(d)?; + Ok(v.as_str().filter(|c| COLORS.iter().any(|(id, _)| id == c)).map(str::to_string)) +} + +/// The color that params `p` give: `color`, one of [`COLORS`], or null or `""` for none. +fn color_param(p: &Value) -> Result, String> { + match p.get("color") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_str() { + Some("") => Ok(None), + Some(c) if COLORS.iter().any(|(id, _)| *id == c) => Ok(Some(c.to_string())), + _ => Err("no such color".into()), + }, + } } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -57,18 +165,15 @@ pub fn default_sets() -> Vec { vec![ActionSet::new( "Default Actions", vec![ - Action { name: "Duplicate and Offset 10 pt".into(), steps: vec![step("object.move", json!({"dx": 10, "dy": 10, "copy": true}))] }, - Action { - name: "Unite and Simplify".into(), - steps: vec![step("object.pathfinder.unite", json!({})), step("object.path.simplify", json!({"tolerance": 0.5}))], - }, - Action { - name: "Center on Artboard".into(), - steps: vec![step("object.align", json!({"horizontal": "center", "vertical": "center", "to": "artboard"}))], - }, - Action { name: "Outline Text".into(), steps: vec![step("type.createOutlines", json!({}))] }, - Action { name: "Rotate 90° CW".into(), steps: vec![step("object.rotate", json!({"angle": -90}))] }, - Action { name: "Reflect Horizontal".into(), steps: vec![step("object.reflect", json!({"axis": "vertical"}))] }, + Action::new("Duplicate and Offset 10 pt", vec![step("object.move", json!({"dx": 10, "dy": 10, "copy": true}))]), + Action::new( + "Unite and Simplify", + vec![step("object.pathfinder.unite", json!({})), step("object.path.simplify", json!({"tolerance": 0.5}))], + ), + Action::new("Center on Artboard", vec![step("object.align", json!({"horizontal": "center", "vertical": "center", "to": "artboard"}))]), + Action::new("Outline Text", vec![step("type.createOutlines", json!({}))]), + Action::new("Rotate 90° CW", vec![step("object.rotate", json!({"angle": -90}))]), + Action::new("Reflect Horizontal", vec![step("object.reflect", json!({"axis": "vertical"}))]), ], )] } @@ -84,9 +189,9 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result Result { let index = |k: &str| p.get(k).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); let name = p.get("name").and_then(Value::as_str).map(str::trim).unwrap_or_default(); @@ -98,6 +203,255 @@ pub fn rename_action(app: &mut VectorcraftApp, p: &Value) -> Result Result { + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + let len = app.ui.action_sets.len(); + let set = p.get("set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|&s| s < len).ok_or("no such action set")?; + let name = p.get("name").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_string(); + if name.is_empty() { + return Err("name is empty".into()); + } + let key = FunctionKey::from_params(p)?; + let color = color_param(p)?; + if let Some(message) = key.and_then(key_error) { + return Err(message); + } + let action = Action { key, color, ..Action::new(name.clone(), vec![]) }; + let id = action.id; + let Some(s) = app.ui.action_sets.get_mut(set) else { return Err("no such action set".into()) }; + s.actions.push(action); + let index = s.actions.len() - 1; + start_recording(app, set, name, Some(id)); + app.ui.action_set = Some(set); + app.ui.action_sets_selected = vec![set]; + if let Some(ctx) = app.ui_ctx.clone() { + set_pstate::>(&ctx, "actions-selected", Some((set, index))); + } + Ok(json!({ "set": set, "action": index })) +} + +/// The command that changes an action's name, function key and color ([`action_options`]). +pub const ACTION_OPTIONS: &str = "ui.action.options"; + +/// `ui.action.options {set, action, name?, key?, cmd?, shift?, color?}`: changes the +/// action at index `action` of set `set` (0 is the top set) and keeps its steps. `name` renames it +/// (spaces trimmed from both ends), `key` (1 to 15, F1 to F15; 0 or null for none) with `cmd` +/// (Ctrl, Command on macOS) and `shift` sets the function key that plays it, and `color` (one of +/// [`COLORS`]; null or `""` for none) its Button Mode color; a param left out keeps what the action +/// has, and `cmd` or `shift` alone changes that modifier of the action's key. The action's function +/// key takes priority over command shortcuts. An index past the last set or action, an empty name, +/// or a key or color that is not one of them is an error, and then nothing changes. The panel +/// menu's Action Options… runs this for the selected action. → {name, key, color} +pub fn action_options(app: &mut VectorcraftApp, p: &Value) -> Result { + let index = |k: &str| p.get(k).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let (set, at) = index("set").zip(index("action")).ok_or("no such action")?; + let had = app.ui.action_sets.get(set).and_then(|s| s.actions.get(at)).map(|a| a.key).ok_or("no such action")?; + let name = match p.get("name") { + None | Some(Value::Null) => None, + Some(v) => match v.as_str().map(str::trim).unwrap_or_default() { + "" => return Err("name is empty".into()), + n => Some(n.to_string()), + }, + }; + // `cmd` and `shift` left out keep the modifiers of the action's key. + let flag = |k: &str, kept: bool| p.get(k).and_then(Value::as_bool).unwrap_or(kept); + let with_mods = + |k: FunctionKey| FunctionKey { cmd: flag("cmd", had.is_some_and(|h| h.cmd)), shift: flag("shift", had.is_some_and(|h| h.shift)), ..k }; + let key = if p.get("key").is_some() { + Some(FunctionKey::from_params(p)?.map(with_mods)) + } else if p.get("cmd").is_some() || p.get("shift").is_some() { + had.map(|h| Some(with_mods(h))) + } else { + None + }; + let color = if p.get("color").is_some() { Some(color_param(p)?) } else { None }; + if let Some(Some(k)) = key + && had != Some(k) + && let Some(message) = key_error(k) + { + return Err(message); + } + let Some(action) = app.ui.action_sets.get_mut(set).and_then(|s| s.actions.get_mut(at)) else { return Err("no such action".into()) }; + if let Some(name) = name { + action.name = name; + } + if let Some(key) = key { + action.key = key; + } + if let Some(color) = color { + action.color = color; + } + Ok(json!({ "name": action.name, "key": action.key, "color": action.color })) +} + +/// The command that plays an action by its name ([`play_action`]). +pub const PLAY_ACTION: &str = "ui.action.play"; + +/// `ui.action.play {action, set?}`: plays the action named `action` as one undoable batch, as +/// Play Current Selection does. `set` names the set to look in (default: every set); a `set` that +/// is not a string is an error. A name that no action has is an error, and so is a name that more +/// than one action in the sets looked in has: then nothing plays. → what `command.batch` returns +pub fn play_action(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("action").and_then(Value::as_str).ok_or("no such action")?; + let in_set = match p.get("set") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_str().ok_or("no such action set")?), + }; + let found: Vec<(usize, usize)> = app + .ui + .action_sets + .iter() + .enumerate() + .filter(|(_, s)| in_set.is_none_or(|n| s.name == n)) + .flat_map(|(si, s)| s.actions.iter().enumerate().filter(|(_, a)| a.name == name).map(move |(ai, _)| (si, ai))) + .collect(); + match found[..] { + [] => Err("no such action".into()), + [(s, a)] => play(app, s, a), + _ => Err(format!("more than one action is named “{}”", name)), + } +} + +/// The command that ends a recording ([`stop`]). +pub const STOP_RECORDING: &str = "ui.action.stop"; + +/// `ui.action.stop {}`: ends the recording in progress and keeps its steps, in the action New +/// Action made for it, else in a new action after the last action of its set, as the bottom bar's +/// Stop Playing/Recording does. With nothing recording it changes nothing. → {stopped} +pub fn stop(app: &mut VectorcraftApp, _: &Value) -> Result { + let stopped = app.ui.recording.is_some(); + stop_recording(app); + Ok(json!({ "stopped": stopped })) +} + +/// The command that `chord` runs under `km`, pressed once or pressed twice. +#[cfg(test)] +fn command_on(km: &craft_keymap::Keymap, chord: &craft_keymap::Chord) -> Option { + crate::keymap::lookup(km, chord).or_else(|| match km.lookup(chord, true, &craft_keymap::Active::NONE) { + craft_keymap::Lookup::Run(c) => Some(c), + craft_keymap::Lookup::Cycle(v) => v.into_iter().next(), + _ => None, + }) +} + +/// The function returns an error message if the function key is invalid or reserved on this platform. +pub fn key_error(key: FunctionKey) -> Option { + let Some(chord) = key.chord() else { return Some("no such function key".into()) }; + if crate::keymap::platform() == craft_keymap::Platform::Windows && (key.key == 1 || key.cmd && !key.shift && matches!(key.key, 4 | 6)) { + return Some(format!("{} cannot be used on Windows", key.text())); + } + if crate::keymap::template().is_reserved(&chord) { + return Some(format!("{} is reserved by the system", key.text())); + } + None +} + +fn playable_chord(key: FunctionKey) -> Option { + key_error(key).is_none().then(|| key.chord()).flatten() +} + +/// Starts recording into set `set`: Stop Playing/Recording adds an action named `name` with the +/// steps, or, with `into`, gives them to the action with that id. +fn start_recording(app: &mut VectorcraftApp, set: usize, name: String, into: Option) { + let start = app.session.journal.len(); + // Keep every step from here on until recording stops, however long it runs. + app.session.journal.hold(Some(start)); + app.ui.recording = Some((set, name, start)); + app.ui.recording_into = into; +} + +/// Stop Playing/Recording: ends the recording and keeps its steps (see [`start_recording`]). An +/// action New Action made that was deleted while it recorded keeps nothing. +fn stop_recording(app: &mut VectorcraftApp) { + let Some((set, name, start)) = app.ui.recording.take() else { return }; + // A canceled undo group numbers the steps down when it drops entries made before them. + let start = app.session.journal.held().unwrap_or(start); + let steps = app.session.journal_for_action(start); + app.session.journal.hold(None); + match app.ui.recording_into.take() { + Some(id) => { + if let Some(a) = app.ui.action_sets.iter_mut().flat_map(|s| s.actions.iter_mut()).find(|a| a.id == id) { + a.steps.extend(steps); + } + } + None => { + if let Some(s) = app.ui.action_sets.get_mut(set) { + s.actions.push(Action::new(name, steps)); + } + } + } +} + +crate::shortcut_editor::ui_mirror!(fn function_key_chords() -> Vec); + +/// Mirrors the actions' function keys for code without app access (cheap when unchanged). +pub fn sync_function_keys(ui: &crate::UiState) { + let chords: Vec = ui.action_sets.iter().flat_map(|s| s.actions.iter().filter_map(|a| playable_chord(a.key?))).collect(); + if function_key_chords().read().is_ok_and(|v| *v != chords) + && let Ok(mut v) = function_key_chords().write() + { + *v = chords; + } +} + +/// Whether `chord` plays an action, by the function keys [`sync_function_keys`] last mirrored. +pub(crate) fn plays_an_action(chord: &craft_keymap::Chord) -> bool { + let platform = crate::keymap::platform(); + let chord = chord.effective(platform); + function_key_chords().read().is_ok_and(|v| v.iter().any(|c| c.effective(platform) == chord)) +} + +/// Plays each action whose function key was pressed this frame, in the order of the presses and +/// before any command with the same shortcut, and takes those key presses. The frame's other +/// events stay for the command, panel and tool shortcuts. +pub fn play_function_key(app: &mut VectorcraftApp, ctx: &egui::Context) { + let keys: Vec<(craft_keymap::Chord, (usize, usize))> = app + .ui + .action_sets + .iter() + .enumerate() + .flat_map(|(si, s)| s.actions.iter().enumerate().filter_map(move |(ai, a)| Some((playable_chord(a.key?)?, (si, ai))))) + .collect(); + if keys.is_empty() { + return; + } + let platform = crate::keymap::platform(); + let hits: Vec<(usize, usize)> = ctx.input_mut(|i| { + let mut hits = Vec::new(); + i.events.retain(|e| { + let hit = match e { + egui::Event::Key { key, pressed: true, modifiers, .. } => craft_keymap::Key::from_egui(*key) + .map(|k| craft_keymap::Chord::new(craft_keymap::Mods::from_egui(modifiers, platform), k)) + .and_then(|c| keys.iter().find(|(k, _)| *k == c).map(|(_, at)| *at)), + _ => None, + }; + if !matches!(e, egui::Event::Key { repeat: true, .. }) { + hits.extend(hit); + } + hit.is_none() + }); + hits + }); + for (set, action) in hits { + if let Err(e) = play(app, set, action) { + app.status(e); + } + } +} + /// The command that deletes action sets ([`delete_sets`]). pub const DELETE_SETS: &str = "ui.actionSet.delete"; @@ -143,8 +497,8 @@ fn delete_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { /// ([`ActionSet::id`]), which Delete Selection's question passes: the sets with these ids are /// deleted wherever they are now, `sets` is not read, and when one of them no longer exists /// nothing is deleted. A recording into a deleted set stops, and its steps are dropped; a -/// recording into another set goes on. An open Set Options or Batch dialog for a deleted set -/// closes. When the current set is deleted, no set is current afterwards. +/// recording into another set goes on. An open Set Options, New Action or Batch dialog for a +/// deleted set closes. When the current set is deleted, no set is current afterwards. pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result { let len = app.ui.action_sets.len(); let mut sets: Vec = match (p.get("ids"), p.get("sets")) { @@ -169,13 +523,14 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result if let Some((rec, ..)) = app.ui.recording.as_mut() { if sets.contains(rec) { app.ui.recording = None; + app.ui.recording_into = None; app.session.journal.hold(None); } else { *rec -= sets.iter().filter(|&&s| s < *rec).count(); } } - // An open Set Options or Batch dialog holds a set index: it closes when its set is deleted, - // and otherwise follows its set down. + // An open Set Options, New Action or Batch dialog holds a set index: it closes when its set is + // deleted, and otherwise follows its set down. if let Some(d) = app.ui.dialog.as_mut().filter(|d| holds_set(d)) && let Some(set) = d.fields.get("set").and_then(Value::as_u64).and_then(|s| usize::try_from(s).ok()) { @@ -203,9 +558,12 @@ pub fn delete_sets(app: &mut VectorcraftApp, p: &Value) -> Result Ok(json!({ "deleted": sets.len() })) } -/// Whether dialog `d` is a Set Options or Batch dialog that holds a set index in its `set` field. +/// Whether dialog `d` is a Set Options, New Action or Batch dialog that holds a set index in its +/// `set` field. fn holds_set(d: &crate::state::Dialog) -> bool { - d.kind == crate::dialogs::action_batch::KIND || (d.kind == crate::dialogs::action_set_options::KIND && d.fields.contains_key("set")) + d.kind == crate::dialogs::action_batch::KIND + || d.kind == crate::dialogs::action_new::KIND + || (d.kind == crate::dialogs::action_set_options::KIND && d.fields.contains_key("set")) } /// The command that duplicates an action or an action set ([`duplicate`]). @@ -234,8 +592,9 @@ fn duplicate_selection(app: &mut VectorcraftApp, ctx: &egui::Context) { /// of set `set` into the same set, right after the original; without `action`, copies set `set` /// with all its actions to right after the original set (default: the current set). The copy is /// named after the original with " copy" added, and a copied set gets an id of its own -/// ([`ActionSet::id`]). The copy is selected and its set is the current one. A recording and an -/// open Set Options or Batch dialog keep to their own set and action. → {set, action?} +/// ([`ActionSet::id`]). Copied actions have no function key, so a key plays only the original. +/// The copy is selected and its set is the current one. A recording and an open Set Options or +/// Batch dialog keep to their own set and action. → {set, action?} pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { const SELECTED: &str = "actions-selected"; let len = app.ui.action_sets.len(); @@ -250,7 +609,7 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(index(v).filter(|&a| a < src.actions.len()).ok_or("no such action")?), }; let (copy, result) = if let Some(a) = action { - let Some(mut copy) = src.actions.get(a).cloned() else { return Err("no such action".into()) }; + let Some(mut copy) = src.actions.get(a).map(Action::copy) else { return Err("no such action".into()) }; copy.name = format!("{} copy", copy.name); src.actions.insert(a + 1, copy); // A Batch dialog open on a later action of the set follows it down. @@ -262,7 +621,7 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { } (Some((set, a + 1)), json!({ "set": set, "action": a + 1 })) } else { - let copy = ActionSet::new(format!("{} copy", src.name), src.actions.clone()); + let copy = ActionSet::new(format!("{} copy", src.name), src.actions.iter().map(Action::copy).collect()); app.ui.action_sets.insert(set + 1, copy); if let Some((rec, ..)) = app.ui.recording.as_mut() && *rec > set @@ -291,6 +650,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // deleted since leaves the stored pair pointing at another set's action. let selected = pstate::>(ui.ctx(), "actions-selected").filter(|&(s, _)| app.ui.action_set == Some(s)); let has = selected.and_then(|(s, a)| app.ui.action_sets.get(s).and_then(|set| set.actions.get(a))).is_some(); + if widgets::menu_item(ui, tl!("New Action…"), crate::dialogs::action_new::can_open(app), false) + && let Err(e) = crate::dialogs::action_new::open(app) + { + app.status(e); + } if widgets::menu_item(ui, tl!("New Set…"), true, false) { crate::dialogs::action_set_options::open_new(app); } @@ -412,19 +776,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.ui.action_set = current; app.ui.action_sets_selected = sets_selected; widgets::divider(ui); - // Bottom bar: stop, record, play, new set, delete. + // Bottom bar: stop, record, play, new set, new action, delete. ui.horizontal(|ui| { let recording = app.ui.recording.is_some(); if widgets::icon_button(ui, "square", tl!("Stop Playing/Recording"), false, 24.0).clicked() - && let Some((set, name, start)) = app.ui.recording.take() + && let Err(e) = app.run(STOP_RECORDING, json!({})) { - // A canceled undo group numbers the steps down when it drops entries made before them. - let start = app.session.journal.held().unwrap_or(start); - let steps = app.session.journal_for_action(start); - app.session.journal.hold(None); - if let Some(s) = app.ui.action_sets.get_mut(set) { - s.actions.push(Action { name, steps }); - } + app.status(e); } let (r, resp) = ui.allocate_exact_size(egui::vec2(24.0, 24.0), egui::Sense::click()); ui.painter().circle_filled(r.center(), 6.0, if recording { egui::Color32::from_rgb(0xe0, 0x30, 0x30) } else { t.icon }); @@ -440,10 +798,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.ui.action_sets_selected = vec![set]; } let n = app.ui.action_sets.get(set).map_or(0, |s| s.actions.len()) + 1; - let start = app.session.journal.len(); - // Keep every step from here on until recording stops, however long it runs. - app.session.journal.hold(Some(start)); - app.ui.recording = Some((set, format!("Action {n}"), start)); + start_recording(app, set, format!("Action {n}"), None); } if widgets::icon_button(ui, "dc-actions", tl!("Play Current Selection"), false, 24.0).clicked() && let Some(s) = selected @@ -453,6 +808,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { if widgets::icon_button(ui, "dc-folder", tl!("Create New Set"), false, 24.0).clicked() { crate::dialogs::action_set_options::open_new(app); } + if widgets::icon_button(ui, "dc-new-item", tl!("Create New Action"), false, 24.0).clicked() + && let Err(e) = crate::dialogs::action_new::open(app) + { + app.status(e); + } if widgets::icon_button(ui, "trash-2", tl!("Delete Selection"), false, 24.0).clicked() { delete_selection(app, ui.ctx()); } @@ -501,10 +861,11 @@ mod tests { click(&ctx, &mut app, text_rect(&texts, "Reflect Horizontal").center(), show); frame_events(&ctx, &mut app, vec![], show); assert_eq!(pstate::>(&ctx, "actions-selected"), Some((0, 5)), "selected on the frames after the click"); - // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, delete. + // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, new action, + // delete. let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [_, _, play, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [_, _, play, _, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, text_rect(&texts, "Duplicate and Offset 10 pt").center(), show); click(&ctx, &mut app, play.center(), show); assert_eq!(app.session.active().unwrap().selection.len(), 1); @@ -526,13 +887,13 @@ mod tests { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let ctx = egui::Context::default(); - // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, delete. A new - // set or action moves the bar down. + // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, new action, + // delete. A new set or action moves the bar down. let bar = |ctx: &egui::Context, app: &mut VectorcraftApp| { frame_events(ctx, app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, new_set, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, new_set, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; (stop, record, new_set) }; let (_, _, new_set) = bar(&ctx, &mut app); @@ -667,7 +1028,7 @@ mod tests { fn action_options_is_off_after_a_set_above_the_selection_is_deleted() { use super::super::tests_appearance::{click, frame_events}; let mut app = app_with_sets(); - let action = |name: &str| Action { name: name.into(), steps: vec![] }; + let action = |name: &str| Action::new(name, vec![]); app.ui.action_sets[2].actions.push(action("Spin")); app.ui.action_sets.push(ActionSet::new("Last", vec![action("Wrong")])); let ctx = egui::Context::default(); @@ -698,13 +1059,13 @@ mod tests { app.ui.action_sets.push(ActionSet::new("Last", vec![])); app.ui.action_set = Some(2); set_pstate::>(&ctx, "actions-selected", Some((2, 0))); - app.ui.action_sets[2].actions.push(Action { name: "Spin".into(), steps: vec![] }); + app.ui.action_sets[2].actions.push(Action::new("Spin", vec![])); app.run(DELETE_SETS, json!({"sets": [2]})).unwrap(); assert_eq!(selected(&ctx), None, "the deleted set's action is no longer selected"); crate::dialogs::action_set_options::open_new(&mut app); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.ui.action_set, Some(2), "the new set is current, at the deleted set's index"); - app.ui.action_sets[2].actions.push(Action { name: "Recorded".into(), steps: vec![] }); + app.ui.action_sets[2].actions.push(Action::new("Recorded", vec![])); let texts = frame_events(&ctx, &mut app, vec![], menu); let item = texts.iter().find(|(s, _)| s.trim() == "Action Options…").map(|(_, r)| *r).expect("Action Options… in the menu"); click(&ctx, &mut app, item.center(), menu); @@ -714,7 +1075,7 @@ mod tests { /// An app with the default set and the sets Mine (two actions) and Other. fn app_with_sets() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let action = |name: &str| Action { name: name.into(), steps: vec![("object.move".into(), json!({"dx": 1, "dy": 0}))] }; + let action = |name: &str| Action::new(name, vec![("object.move".into(), json!({"dx": 1, "dy": 0}))]); app.ui.action_sets.push(ActionSet::new("Mine", vec![action("Nudge"), action("Nudge Again")])); app.ui.action_sets.push(ActionSet::new("Other", vec![])); app @@ -724,12 +1085,12 @@ mod tests { app.ui.action_sets.iter().map(|s| s.name.clone()).collect() } - /// The bottom bar's Delete Selection button (stop, record, play, new set, delete). + /// The bottom bar's Delete Selection button (stop, record, play, new set, new action, delete). fn trash(ctx: &egui::Context, app: &mut VectorcraftApp) -> egui::Pos2 { super::super::tests_appearance::frame_events(ctx, app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [_, _, _, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [_, _, _, _, _, delete] = bar[..] else { panic!("the bottom bar: {bar:?}") }; delete.center() } @@ -871,7 +1232,7 @@ mod tests { fn ok_deletes_only_the_asked_one_of_two_sets_with_the_same_name() { use super::super::tests_appearance::click; let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let x = |n: &str| ActionSet::new("X", vec![Action { name: n.into(), steps: vec![] }]); + let x = |n: &str| ActionSet::new("X", vec![Action::new(n, vec![])]); app.ui.action_sets = vec![x("first"), x("second")]; let ctx = egui::Context::default(); click_set(&ctx, &mut app, "X", egui::Modifiers::NONE); @@ -943,7 +1304,7 @@ mod tests { frame_events(&ctx, &mut app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, record.center(), show); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); click(&ctx, &mut app, stop.center(), show); @@ -970,7 +1331,7 @@ mod tests { frame_events(&ctx, &mut app, vec![], show); let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, record.center(), show); assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0]), "the set recorded into is current"); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); @@ -1171,10 +1532,11 @@ mod tests { } let ctx = egui::Context::default(); frame_events(&ctx, &mut app, vec![], show); - // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, delete. + // The bottom bar's 24-point buttons, left to right: stop, record, play, new set, new action, + // delete. let mut bar = crate::toolbar::tests::widget_rects(&ctx, egui::vec2(24.0, 24.0)); bar.sort_by(|a, b| a.left().total_cmp(&b.left())); - let [stop, record, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + let [stop, record, _, _, _, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; click(&ctx, &mut app, record.center(), show); for (id, p) in [("document.activate", json!({"index": 1})), ("shape.rectangle", rect(50)), ("edit.undoGroup.end", json!({"cancel": true}))] { app.run(id, p).unwrap(); @@ -1200,7 +1562,7 @@ mod tests { let start = app.session.journal.len(); app.run(id, params).unwrap(); let steps = app.session.journal_for_action(start); - app.ui.action_sets[0].actions.push(Action { name: name.into(), steps }); + app.ui.action_sets[0].actions.push(Action::new(name, steps)); app.ui.action_sets[0].actions.len() - 1 }; app.run("edit.copy", json!({})).unwrap(); @@ -1249,7 +1611,7 @@ mod tests { let start = app.session.journal.len(); app.run(id, params).unwrap(); let steps = app.session.journal_for_action(start); - app.ui.action_sets[0].actions.push(Action { name: name.into(), steps }); + app.ui.action_sets[0].actions.push(Action::new(name, steps)); app.ui.action_sets[0].actions.len() - 1 }; let (x0, x1) = (boards[0].x0, boards[0].x1); @@ -1374,7 +1736,7 @@ mod tests { fn save_actions_does_not_write_a_set_load_actions_refuses() { let mut app = app_with_sets(); let files = with_files(&mut app, "/sets/none.vcactions"); - app.ui.action_sets[2].actions = vec![Action { name: "A".into(), steps: vec![] }; 1001]; + app.ui.action_sets[2].actions = vec![Action::new("A", vec![]); 1001]; let r = app.run(SAVE_SET, json!({"set": 2, "path": "/sets/big.vcactions"})); assert_eq!(r.unwrap_err(), "the action set file holds more than 1,000 actions"); assert!(files.borrow().is_empty(), "nothing written"); @@ -1396,4 +1758,559 @@ mod tests { assert_eq!(v["name"], json!("Other"), "the set chosen, not the current one"); assert_eq!(app.run(SAVE_SET, json!({"id": 0, "set": 0, "path": "/sets/y.vcactions"})).unwrap_err(), "no such action set"); } + + /// The bottom bar's stop and Create New Action buttons (stop, record, play, new set, new + /// action, delete). + fn stop_and_new_action(ctx: &egui::Context, app: &mut VectorcraftApp) -> (egui::Pos2, egui::Pos2) { + super::super::tests_appearance::frame_events(ctx, app, vec![], show); + let mut bar = crate::toolbar::tests::widget_rects(ctx, egui::vec2(24.0, 24.0)); + bar.sort_by(|a, b| a.left().total_cmp(&b.left())); + let [stop, _, _, _, new_action, _] = bar[..] else { panic!("the bottom bar: {bar:?}") }; + (stop.center(), new_action.center()) + } + + /// The texts the dialog layer draws once the open dialog has settled. + fn dialog_texts(app: &mut VectorcraftApp) -> Vec { + let ctx = egui::Context::default(); + let mut texts = vec![]; + for _ in 0..3 { + texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + texts.into_iter().map(|(t, _)| t).collect() + } + + /// The Create New Action button and the panel menu's New Action… both open New Action with a + /// suggested name in the current set, no function key and no color; Cancel adds nothing and + /// starts no recording. Record with another set chosen adds the action there, selects it and + /// records into it, and Stop keeps exactly the steps recorded in that action; Record and Stop + /// with nothing done in between keep an empty action. + #[test] + fn new_action_asks_for_a_name_and_set_and_records_into_the_new_action() { + use super::super::tests_appearance::{click, frame_events}; + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + click_set(&ctx, &mut app, "Mine", egui::Modifiers::NONE); + let (_, new_action) = stop_and_new_action(&ctx, &mut app); + click(&ctx, &mut app, new_action, show); + let d = app.ui.dialog.as_ref().expect("Create New Action opens New Action"); + assert_eq!(d.kind, crate::dialogs::action_new::KIND); + let fields = (d.fields["set"].clone(), d.str("name"), d.fields["key"].clone(), d.str("color")); + assert_eq!(fields, (json!(1), "Action 3".to_string(), json!(0), String::new()), "the current set, a free name, no key or color"); + crate::dialogs::cancel(&mut app); + let counts = |app: &VectorcraftApp| app.ui.action_sets.iter().map(|s| s.actions.len()).collect::>(); + assert_eq!(counts(&app), [6, 2, 0], "Cancel adds nothing"); + assert!(app.ui.recording.is_none(), "and records nothing"); + let texts = frame_events(&ctx, &mut app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "New Action…").map(|(_, r)| *r).expect("New Action… in the menu"); + click(&ctx, &mut app, item.center(), menu); + let d = app.ui.dialog.as_mut().expect("New Action… opens New Action"); + assert_eq!(d.kind, crate::dialogs::action_new::KIND); + d.fields.insert("set".into(), json!(2)); + d.fields.insert("name".into(), json!(" Box ")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(action_names(&app, 2), ["Box"], "added to the set chosen, with the name trimmed"); + let selected = pstate::>(&ctx, "actions-selected"); + assert_eq!((app.ui.action_set, selected), (Some(2), Some((2, 0))), "its set is current and it is selected"); + assert!(app.ui.recording.is_some(), "Record starts recording"); + assert!(frame_events(&ctx, &mut app, vec![], show).iter().any(|(t, _)| t == "● Recording"), "the panel shows the recording"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + click(&ctx, &mut app, stop, show); + assert!(app.ui.recording.is_none()); + let steps: Vec = app.ui.action_sets[2].actions[0].steps.iter().map(|(c, _)| c.clone()).collect(); + assert_eq!(steps, ["shape.rectangle"], "the recorded steps, in the new action"); + assert_eq!(counts(&app), [6, 2, 1], "Stop adds no other action"); + app.run(NEW_ACTION, json!({"set": 2, "name": "Empty"})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + click(&ctx, &mut app, stop, show); + assert_eq!(action_names(&app, 2), ["Box", "Empty"]); + assert!(app.ui.action_sets[2].actions[1].steps.is_empty(), "nothing recorded: an empty action"); + } + + /// New Action shows Name, Action Set, Function Key with Ctrl (Command on macOS) and Shift, Color and Record. + #[test] + fn new_action_shows_its_fields() { + let mut app = app_with_sets(); + crate::dialogs::action_new::open(&mut app).unwrap(); + let texts = dialog_texts(&mut app); + for label in ["New Action", "Name:", "Action Set:", "Default Actions", "Function Key:", "Shift", "Color:", "None", "Record", "Cancel"] { + assert!(texts.iter().any(|t| t == label), "{label}: {texts:?}"); + } + assert!(!texts.iter().any(|t| t == "Replace")); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("key".into(), json!(14)); + d.fields.insert("shift".into(), json!(true)); + let texts = dialog_texts(&mut app); + assert!(!texts.iter().any(|s| s == "Replace" || s.contains("already used")), "{texts:?}"); + } + + /// `ui.action.new` refuses an index past the last set, an empty name, a key or color that is + /// not one, and a second recording, and then adds nothing. New Action does not open without a + /// set or while recording, follows its set when an earlier set is deleted, and closes when its + /// set is deleted. On Windows F1, Ctrl+F4 and Ctrl+F6 are refused. + #[test] + fn new_action_refuses_bad_params_and_adds_nothing() { + let mut app = app_with_sets(); + let counts = |app: &VectorcraftApp| app.ui.action_sets.iter().map(|s| s.actions.len()).collect::>(); + for (p, want) in [ + (json!({"set": 3, "name": "A"}), "no such action set"), + (json!({"name": "A"}), "no such action set"), + (json!({"set": 1, "name": " "}), "name is empty"), + (json!({"set": 1}), "name is empty"), + (json!({"set": 1, "name": "A", "key": 16}), "no such function key"), + (json!({"set": 1, "name": "A", "key": "F5"}), "no such function key"), + (json!({"set": 1, "name": "A", "color": "pink"}), "no such color"), + ] { + assert_eq!(app.run(NEW_ACTION, p.clone()).unwrap_err(), want, "{p}"); + } + if crate::keymap::platform() == craft_keymap::Platform::Windows { + for (key, cmd) in [(1, false), (1, true), (4, true), (6, true)] { + let want = format!("{} cannot be used on Windows", FunctionKey { key, cmd, shift: false }.text()); + assert_eq!(app.run(NEW_ACTION, json!({"set": 1, "name": "A", "key": key, "cmd": cmd})).unwrap_err(), want); + } + } + assert_eq!(counts(&app), [6, 2, 0], "nothing added"); + assert!(app.ui.recording.is_none(), "nothing recording"); + // The dialog follows its set down, and closes with it. + crate::dialogs::action_new::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("set".into(), json!(2)); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["set"].clone()), Some(json!(1)), "New Action follows Other"); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + assert!(app.ui.dialog.is_none(), "New Action closes with its set"); + crate::dialogs::action_new::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("set".into(), json!(9)); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some(), "a set that is gone: the dialog stays open"); + app.ui.dialog = None; + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(NEW_ACTION, json!({"set": 0, "name": "A"})).unwrap(); + assert_eq!(app.run(NEW_ACTION, json!({"set": 0, "name": "B"})).unwrap_err(), "an action is already recording"); + assert_eq!(crate::dialogs::action_new::open(&mut app).unwrap_err(), "an action is already recording"); + assert!(!crate::dialogs::action_new::can_open(&app)); + assert_eq!(counts(&app), [7], "one action added"); + app.ui.action_sets.clear(); + app.ui.recording = None; + assert_eq!(crate::dialogs::action_new::open(&mut app).unwrap_err(), "no such action set"); + assert!(app.ui.dialog.is_none()); + } + + /// A recording that New Action started goes into its action wherever the action is when Stop + /// is pressed, and is dropped when the action was deleted meanwhile. + #[test] + fn a_new_actions_recording_follows_its_action() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let ctx = egui::Context::default(); + app.run(NEW_ACTION, json!({"set": 2, "name": "Box"})).unwrap(); + app.run(DELETE_SETS, json!({"sets": [1]})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + super::super::tests_appearance::click(&ctx, &mut app, stop, show); + assert_eq!((action_names(&app, 1), app.ui.action_sets[1].actions[0].steps.len()), (vec!["Box".to_string()], 1)); + app.run(NEW_ACTION, json!({"set": 1, "name": "Gone"})).unwrap(); + app.ui.action_sets[1].actions.pop(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let (stop, _) = stop_and_new_action(&ctx, &mut app); + super::super::tests_appearance::click(&ctx, &mut app, stop, show); + assert_eq!(action_names(&app, 1), ["Box"], "the deleted action is not made again"); + assert!(app.ui.recording.is_none() && app.ui.recording_into.is_none()); + // `ui.action.stop` ends a recording as the button does. + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": false}), "nothing recording"); + app.run(NEW_ACTION, json!({"set": 1, "name": "Remote"})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": true})); + assert_eq!((action_names(&app, 1), app.ui.action_sets[1].actions[1].steps.len()), (vec!["Box".to_string(), "Remote".into()], 1)); + assert!(app.ui.recording.is_none()); + } + + #[test] + fn shortcut_precedence_assignment_preserves_command_bindings() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + let before = app.ui.shortcut_overrides.clone(); + let set = app.ui.shortcut_set.clone(); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 14, "shift": true})).unwrap(); + assert_eq!(app.ui.shortcut_overrides, before); + assert_eq!(app.ui.shortcut_set, set); + let ctx = egui::Context::default(); + let event = egui::Event::Key { key: egui::Key::F14, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::SHIFT }; + let mut output = ctx.run_ui(egui::RawInput { events: vec![event], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.undo.last().unwrap().label, "Nudge"); + assert_eq!(app.ui.shortcut_overrides, before); + let undo = app.session.active().unwrap().history.undo.len(); + let repeated = egui::Event::Key { key: egui::Key::F14, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::SHIFT }; + let mut output = + ctx.run_ui(egui::RawInput { events: vec![repeated], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + app.run(NEW_ACTION, json!({"set": 2, "name": "Another", "key": 14, "shift": true})).unwrap(); + assert_eq!(app.ui.shortcut_overrides, before); + assert_eq!(app.ui.shortcut_set, set); + } + + #[test] + fn shortcut_precedence_action_options_does_not_offer_replacement() { + let mut app = app_with_sets(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + crate::dialogs::action_set_options::open_action(&mut app, 1, 0); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("key".into(), json!(14)); + d.fields.insert("shift".into(), json!(true)); + let texts = dialog_texts(&mut app); + assert!(!texts.iter().any(|s| s == "Replace" || s.contains("already used")), "{texts:?}"); + } + + #[test] + fn shortcut_precedence_duplicate_keys_play_the_first_action_once() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let key = Some(FunctionKey { key: 15, cmd: false, shift: false }); + app.ui.action_sets[1].actions[0].key = key; + app.ui.action_sets[1].actions[1].key = key; + let before = app.session.active().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + let event = egui::Event::Key { key: egui::Key::F15, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let mut output = ctx.run_ui(egui::RawInput { events: vec![event], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + let history = &app.session.active().unwrap().history.undo; + assert_eq!(history.len(), before + 1); + assert_eq!(history.last().unwrap().label, "Nudge"); + } + + #[test] + fn shortcut_precedence_preferences_and_files_retain_action_keys() { + let mut app = app_with_sets(); + let key = FunctionKey { key: 14, cmd: false, shift: true }; + app.ui.action_sets[1].actions[0].key = Some(key); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + let saved = serde_json::to_value(&app.ui).unwrap(); + let restored = serde_json::from_value::(saved).unwrap().sanitized(); + assert_eq!(restored.action_sets[1].actions[0].key, Some(key)); + let _files = with_files(&mut app, "/sets/Mine.vcactions"); + app.run(SAVE_SET, json!({"set": 1, "path": "/sets/Mine.vcactions"})).unwrap(); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + assert_eq!(app.ui.action_sets.last().unwrap().actions[0].key, Some(key)); + } + + #[test] + fn shortcut_precedence_applies_while_the_type_tool_edits() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("text.create", json!({"x": 20, "y": 50, "text": "Hi"})).unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + assert!(app.session.tool_wants_text()); + let key = FunctionKey { key: 15, cmd: true, shift: false }; + app.ui.action_sets[1].actions[0].key = Some(key); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Cmd+F15"); + let before = app.session.active().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + let event = egui::Event::Key { key: egui::Key::F15, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + let mut output = ctx.run_ui(egui::RawInput { events: vec![event], ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + output.textures_delta.clear(); + let history = &app.session.active().unwrap().history.undo; + assert_eq!(history.len(), before + 1); + assert_eq!(history.last().unwrap().label, "Nudge"); + } + + #[test] + fn shortcut_precedence_command_edits_retain_action_keys() { + let mut app = app_with_sets(); + let key = FunctionKey { key: 15, cmd: false, shift: false }; + app.ui.action_sets[1].actions[0].key = Some(key); + app.run("shortcuts.set", json!({"id": "edit.duplicate", "shortcut": "F15"})).unwrap(); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(key)); + crate::shortcut_editor::open(&mut app); + let mut overrides = app.ui.shortcut_overrides.clone(); + crate::keymap::set_override(&mut overrides, "edit.duplicate", "Shift+F14"); + app.ui.dialog.as_mut().unwrap().fields.insert("overrides".into(), crate::keymap::stored::to_value(&overrides)); + crate::shortcut_editor::confirm(&mut app).unwrap(); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(key)); + } + + /// Action function keys take priority over command shortcuts and keep both assignments. + #[test] + fn function_keys_play_their_action_and_preserve_other_assignments() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let p = |set: usize, action: usize, k: FunctionKey| json!({"set": set, "action": action, "key": k.key, "cmd": k.cmd, "shift": k.shift}); + let keys = |app: &VectorcraftApp| app.ui.action_sets[1].actions.iter().map(|a| a.key).collect::>(); + let f15 = FunctionKey { key: 15, cmd: false, shift: false }; + app.run(ACTION_OPTIONS, p(1, 0, f15)).unwrap(); + assert_eq!(keys(&app), [Some(f15), None]); + app.run(ACTION_OPTIONS, p(1, 1, f15)).unwrap(); + app.run(NEW_ACTION, json!({"set": 2, "name": "New", "key": 15})).unwrap(); + stop_recording(&mut app); + assert_eq!(keys(&app), [Some(f15), Some(f15)]); + assert_eq!(app.ui.action_sets[2].actions[0].key, Some(f15)); + let shift_f14 = FunctionKey { key: 14, cmd: false, shift: true }; + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Shift+F14"); + app.run(ACTION_OPTIONS, p(1, 0, shift_f14)).unwrap(); + let km = |app: &VectorcraftApp| crate::keymap::keymap_with(&app.ui.shortcut_overrides); + assert!(crate::keymap::lookup(&km(&app), &shift_f14.chord().unwrap()).is_some(), "the command keeps its shortcut"); + assert_eq!(keys(&app), [Some(shift_f14), Some(f15)]); + // The keys play their actions. + app.ui.action_sets[1].actions[1].steps = vec![("shape.rectangle".into(), json!({"x": 10, "y": 10, "width": 20, "height": 20}))]; + let ctx = egui::Context::default(); + let press = |app: &mut VectorcraftApp, key, modifiers| { + let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx())); + out.textures_delta.clear(); + }; + let last = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.last().map(|s| s.label.clone()); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = undo(&app); + press(&mut app, egui::Key::F15, egui::Modifiers::NONE); + assert_eq!((last(&app), undo(&app)), (Some("Nudge Again".to_string()), before + 1), "F15 plays Nudge Again"); + let id = app.session.active().unwrap().selection.objects.clone(); + let x = |app: &VectorcraftApp| app.session.active().unwrap().doc.bounds_of(&id, false).unwrap().x0; + let before = x(&app); + press(&mut app, egui::Key::F14, egui::Modifiers::SHIFT); + assert_eq!((last(&app), x(&app)), (Some("Nudge".to_string()), before + 1.0), "Shift+F14 plays Nudge"); + let before = undo(&app); + press(&mut app, egui::Key::F14, egui::Modifiers::NONE); + assert_eq!(undo(&app), before, "F14 without Shift plays nothing"); + app.run("shortcuts.set", json!({"id": "edit.duplicate", "shortcut": "F15"})).unwrap(); + assert_eq!(keys(&app), [Some(shift_f14), Some(f15)]); + crate::shortcut_editor::open(&mut app); + let mut ov = app.ui.shortcut_overrides.clone(); + crate::keymap::set_override(&mut ov, "edit.duplicate", "Shift+F14"); + app.ui.dialog.as_mut().unwrap().fields.insert("overrides".into(), crate::keymap::stored::to_value(&ov)); + crate::shortcut_editor::confirm(&mut app).unwrap(); + assert_eq!(keys(&app), [Some(shift_f14), Some(f15)]); + } + + /// Off macOS, an action's Cmd function key and a command's Ctrl shortcut share the chord. + #[test] + fn an_action_keeps_a_commands_ctrl_shortcut_for_a_cmd_function_key() { + if crate::keymap::platform().is_mac() { + return; + } + let mut app = app_with_sets(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Ctrl+F13"); + let cmd_f13 = FunctionKey { key: 13, cmd: true, shift: false }; + let km = |app: &VectorcraftApp| crate::keymap::keymap_with(&app.ui.shortcut_overrides); + assert!(crate::keymap::lookup(&km(&app), &cmd_f13.chord().unwrap()).is_some(), "Ctrl+F13 runs Duplicate"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 13, "cmd": true, "shift": false})).unwrap(); + assert!(crate::keymap::lookup(&km(&app), &cmd_f13.chord().unwrap()).is_some(), "the command keeps its shortcut"); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(cmd_f13)); + } + + /// An action's function key leaves a command's double-press shortcut assigned. + #[test] + fn a_double_press_shortcut_keeps_the_function_key() { + let mut app = app_with_sets(); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "F15 F15"); + let f15 = FunctionKey { key: 15, cmd: false, shift: false }; + let km = |app: &VectorcraftApp| crate::keymap::keymap_with(&app.ui.shortcut_overrides); + assert!(command_on(&km(&app), &f15.chord().unwrap()).is_some(), "F15 pressed twice runs Duplicate"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 15})).unwrap(); + assert!(command_on(&km(&app), &f15.chord().unwrap()).is_some(), "the command keeps its shortcut"); + assert_eq!(app.ui.action_sets[1].actions[0].key, Some(f15)); + } + + /// The web build keeps an action's Ctrl or Cmd function key from the browser. + #[test] + fn an_action_key_runs_a_shortcut_for_the_web_build() { + let mut app = app_with_sets(); + let press = || crate::shortcuts::runs_a_shortcut("F13", "F13", egui::Modifiers::COMMAND); + sync_function_keys(&app.ui); + assert!(!press(), "Ctrl+F13 runs nothing"); + app.ui.action_sets[1].actions[0].key = Some(FunctionKey { key: 13, cmd: true, shift: false }); + sync_function_keys(&app.ui); + assert!(press(), "Ctrl+F13 plays Nudge"); + } + + /// Every action key pressed in one frame plays its action, and a command shortcut pressed in + /// the same frame still runs. + #[test] + fn action_keys_and_a_command_shortcut_in_one_frame_all_run() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.ui.action_sets[1].actions[0].key = Some(FunctionKey { key: 15, cmd: false, shift: false }); + app.ui.action_sets[1].actions[1].key = Some(FunctionKey { key: 14, cmd: false, shift: false }); + app.run("shortcuts.set", json!({"id": "edit.duplicate", "shortcut": "F13"})).unwrap(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.iter().map(|s| s.label.clone()).collect::>(); + let before = undo(&app).len(); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let events = vec![key(egui::Key::F15), key(egui::Key::F14), key(egui::Key::F13)]; + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!(undo(&app)[before..], ["Nudge", "Nudge Again", "Duplicate"], "both actions played, then Duplicate ran"); + } + + /// `ui.action.play` plays an action by its name, in the set named when one is, and refuses a + /// name that more than one action has, or that none has. + #[test] + fn play_action_by_name_refuses_a_name_more_than_one_action_has() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.ui.action_sets[2].actions.push(Action::new("Nudge", vec![("object.move".into(), json!({"dx": 5, "dy": 0}))])); + let id = app.session.active().unwrap().selection.objects.clone(); + let x = |app: &VectorcraftApp| app.session.active().unwrap().doc.bounds_of(&id, false).unwrap().x0; + let before = x(&app); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nudge"})).unwrap_err(), "more than one action is named “Nudge”"); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nope"})).unwrap_err(), "no such action"); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nudge", "set": "Missing"})).unwrap_err(), "no such action"); + assert_eq!(app.run(PLAY_ACTION, json!({})).unwrap_err(), "no such action"); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Nudge Again", "set": 0})).unwrap_err(), "no such action set"); + assert_eq!(x(&app), before, "nothing played"); + app.run(PLAY_ACTION, json!({"action": "Nudge", "set": "Other"})).unwrap(); + assert_eq!(x(&app), before + 5.0, "Other's Nudge played"); + app.run(PLAY_ACTION, json!({"action": "Nudge Again"})).unwrap(); + assert_eq!(x(&app), before + 6.0, "a name one action has plays without a set"); + } + + /// Action Options shows the action's function key and color; OK sets them and keeps the name's + /// steps, Cancel keeps them as they were. A rename keeps them, and a copy has no key. + #[test] + fn action_options_sets_the_function_key_and_color_and_keeps_the_steps() { + use crate::dialogs::action_set_options::open_action; + let mut app = app_with_sets(); + open_action(&mut app, 1, 1); + let texts = dialog_texts(&mut app); + for label in ["Action Options", "Name:", "Function Key:", "Shift", "Color:"] { + assert!(texts.iter().any(|t| t == label), "{label}: {texts:?}"); + } + let set = |app: &mut VectorcraftApp| { + let d = app.ui.dialog.as_mut().expect("Action Options is open"); + assert_eq!((d.fields["key"].clone(), d.bool("shift"), d.str("color")), (json!(0), false, String::new())); + d.fields.insert("key".into(), json!(15)); + d.fields.insert("shift".into(), json!(true)); + d.fields.insert("color".into(), json!("green")); + }; + set(&mut app); + crate::dialogs::cancel(&mut app); + let a = |app: &VectorcraftApp, i: usize| app.ui.action_sets[1].actions[i].clone(); + assert_eq!((a(&app, 1).key, a(&app, 1).color), (None, None), "Cancel keeps them"); + open_action(&mut app, 1, 1); + set(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + let shift_f15 = FunctionKey { key: 15, cmd: false, shift: true }; + assert_eq!((a(&app, 1).name, a(&app, 1).key, a(&app, 1).color), ("Nudge Again".to_string(), Some(shift_f15), Some("green".to_string()))); + assert_eq!(a(&app, 1).steps, [("object.move".to_string(), json!({"dx": 1, "dy": 0}))], "the steps stay"); + open_action(&mut app, 1, 1); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["key"].clone(), d.bool("shift"), d.str("color")), (json!(15), true, "green".to_string()), "shown when it opens again"); + assert!(dialog_texts(&mut app).iter().any(|t| t == "Green")); + app.ui.dialog = None; + app.run(RENAME_ACTION, json!({"set": 1, "action": 1, "name": "Push"})).unwrap(); + assert_eq!((a(&app, 1).key, a(&app, 1).color.as_deref()), (Some(shift_f15), Some("green")), "a rename keeps them"); + app.run(DUPLICATE, json!({"set": 1, "action": 1})).unwrap(); + assert_eq!( + (a(&app, 2).name.as_str(), a(&app, 2).key, a(&app, 2).color.as_deref()), + ("Push copy", None, Some("green")), + "the copy has no key" + ); + assert_ne!(a(&app, 2).id, a(&app, 1).id); + assert_eq!(a(&app, 1).key, Some(shift_f15), "the original keeps it"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "key": 0, "color": null})).unwrap(); + assert_eq!((a(&app, 1).name.as_str(), a(&app, 1).key, a(&app, 1).color.clone()), ("Push", None, None), "cleared; the name stays"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "key": 15, "cmd": true, "shift": true})).unwrap(); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "key": 14})).unwrap(); + assert_eq!(a(&app, 1).key, Some(FunctionKey { key: 14, cmd: true, shift: true }), "a new key keeps the modifiers left out"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 1, "shift": false})).unwrap(); + assert_eq!(a(&app, 1).key, Some(FunctionKey { key: 14, cmd: true, shift: false }), "shift alone changes Shift"); + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 2, "shift": true})).unwrap(); + assert_eq!(a(&app, 2).key, None, "a modifier alone gives no key"); + for (p, want) in [ + (json!({"set": 1, "action": 9}), "no such action"), + (json!({"set": 1, "action": 1, "name": " "}), "name is empty"), + (json!({"set": 1, "action": 1, "color": "pink"}), "no such color"), + (json!({"set": 1, "action": 1, "key": 99}), "no such function key"), + ] { + assert_eq!(app.run(ACTION_OPTIONS, p.clone()).unwrap_err(), want, "{p}"); + } + } + + /// Function keys and colors are saved with the UI preferences and in action set files; older + /// preferences and files without them, or with values that are not one, load none. + #[test] + fn function_keys_and_colors_are_kept_with_the_preferences_and_in_set_files() { + let mut app = app_with_sets(); + let k = FunctionKey { key: 13, cmd: true, shift: true }; + app.run(ACTION_OPTIONS, json!({"set": 1, "action": 0, "key": 13, "cmd": true, "shift": true, "color": "violet"})).unwrap(); + let saved = serde_json::to_value(&app.ui).unwrap(); + let first = &saved["action_sets"][1]["actions"][0]; + assert_eq!((first["key"].clone(), first["color"].clone()), (json!({"key": 13, "cmd": true, "shift": true}), json!("violet"))); + assert!(saved["action_sets"][1]["actions"][1].get("key").is_none(), "no key: nothing written"); + let restored = serde_json::from_value::(saved.clone()).unwrap(); + let a = &restored.action_sets[1].actions[0]; + assert_eq!((a.key, a.color.as_deref()), (Some(k), Some("violet"))); + let mut odd = saved.clone(); + odd["action_sets"][1]["actions"][0]["key"] = json!("F13"); + odd["action_sets"][1]["actions"][0]["color"] = json!("pink"); + let restored = serde_json::from_value::(odd).unwrap(); + let a = &restored.action_sets[1].actions[0]; + assert_eq!((a.name.as_str(), a.key, a.color.clone()), ("Nudge", None, None), "values that are not one load as none"); + let files = with_files(&mut app, "/sets/Mine.vcactions"); + app.run(SAVE_SET, json!({"set": 1, "path": "/sets/Mine.vcactions"})).unwrap(); + let v: Value = serde_json::from_slice(&files.borrow()["/sets/Mine.vcactions"]).unwrap(); + assert_eq!( + (v["version"].clone(), v["actions"][0]["key"].clone(), v["actions"][0]["color"].clone()), + (json!(1), first["key"].clone(), json!("violet")) + ); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + let loaded = &app.ui.action_sets[3].actions[0]; + assert_eq!((loaded.key, loaded.color.as_deref()), (Some(k), Some("violet"))); + app.run(DELETE_SETS, json!({"sets": [1, 3]})).unwrap(); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + assert_eq!(app.ui.action_sets[2].actions[0].key, Some(k), "a free key loads with its action"); + let plain = json!({"format": "vcactions", "version": 1, "name": "P", "actions": [{"name": "A", "steps": []}]}); + app.run(LOAD_SET, json!({"data": plain.to_string()})).unwrap(); + let a = &app.ui.action_sets[3].actions[0]; + assert_eq!((a.key, a.color.clone()), (None, None), "a file without them loads none"); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "edit.duplicate", "Cmd+Shift+F13"); + app.run(DELETE_SETS, json!({"sets": [2]})).unwrap(); + app.run(LOAD_SET, json!({"path": "/sets/Mine.vcactions"})).unwrap(); + let a = &app.ui.action_sets.last().unwrap().actions[0]; + assert_eq!((a.key, a.color.as_deref()), (Some(k), Some("violet"))); + } + + /// Saved function keys survive loading; reserved keys cannot play actions on this platform. + #[test] + fn loaded_preferences_keep_function_keys_and_skip_reserved_keys_at_playback() { + let app = app_with_sets(); + let mut saved = serde_json::to_value(&app.ui).unwrap(); + let key = |k: u8, cmd: bool, shift: bool| json!({"key": k, "cmd": cmd, "shift": shift}); + for (set, action, k) in [ + (1, 0, key(13, false, false)), + (1, 1, key(13, false, false)), + (0, 0, key(1, false, false)), + (0, 1, key(12, false, true)), + (0, 2, key(4, true, false)), + ] { + saved["action_sets"][set]["actions"][action]["key"] = k; + } + let mut overrides = app.ui.shortcut_overrides.clone(); + crate::keymap::set_override(&mut overrides, "edit.duplicate", "Shift+F12"); + saved["shortcut_overrides"] = crate::keymap::stored::to_value(&overrides); + let ui = serde_json::from_value::(saved).unwrap().sanitized(); + let keys = |set: usize| ui.action_sets[set].actions.iter().map(|a| a.key).collect::>(); + let f13 = FunctionKey { key: 13, cmd: false, shift: false }; + assert_eq!(keys(1), [Some(f13), Some(f13)]); + let windows = crate::keymap::platform() == craft_keymap::Platform::Windows; + let f1 = FunctionKey { key: 1, cmd: false, shift: false }; + let ctrl_f4 = FunctionKey { key: 4, cmd: true, shift: false }; + let shift_f12 = FunctionKey { key: 12, cmd: false, shift: true }; + assert_eq!(keys(0)[..3], [Some(f1), Some(shift_f12), Some(ctrl_f4)]); + assert_eq!(playable_chord(f1).is_some(), !windows); + assert_eq!(playable_chord(ctrl_f4).is_some(), !windows); + assert!( + crate::keymap::lookup(&crate::keymap::keymap_with(&ui.shortcut_overrides), &shift_f12.chord().unwrap()).is_some(), + "the command keeps its shortcut" + ); + } } diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index df5ffe8523..cd1e1e0181 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,8 +1,10 @@ //! Action set files: the Actions panel menu's Save Actions… and Load Actions…. //! //! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1, "name", -//! "actions": [{"name", "steps": [{"command", "params"}]}]}`. Each step is a command id and its -//! params, as `command.batch` takes them. +//! "actions": [{"name", "steps": [{"command", "params"}], "key"?, "color"?}]}`. Each step is a +//! command id and its params, as `command.batch` takes them. `key` is the action's function key +//! (`{"key": 1 to 15, "cmd", "shift"}`) and `color` its Button Mode color; an action without them, +//! or with a value that is not one, has none. use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -42,6 +44,10 @@ struct SetFile { struct FileAction { name: String, steps: Vec, + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "super::deserialize_key")] + key: Option, + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "super::deserialize_color")] + color: Option, } /// A step of an action in an action set file: a command id and its params, as `command.batch` @@ -61,6 +67,8 @@ pub fn write_set(set: &ActionSet) -> String { .map(|a| FileAction { name: a.name.clone(), steps: a.steps.iter().map(|(command, params)| FileStep { command: command.clone(), params: params.clone() }).collect(), + key: a.key, + color: a.color.clone(), }) .collect(); let file = SetFile { format: ACTIONS_EXT.into(), version: 1, name: set.name.clone(), actions }; @@ -85,8 +93,11 @@ pub fn read_set(text: &str, name: &str) -> Result { if f.actions.iter().any(|a| a.steps.len() > MAX_ACTION_STEPS) { return Err("an action in the action set file has more than 10,000 steps".into()); } - let actions = - f.actions.into_iter().map(|a| Action { name: a.name, steps: a.steps.into_iter().map(|s| (s.command, s.params)).collect() }).collect(); + let actions = f + .actions + .into_iter() + .map(|a| Action { key: a.key, color: a.color, ..Action::new(a.name, a.steps.into_iter().map(|s| (s.command, s.params)).collect()) }) + .collect(); let set_name = if f.name.trim().is_empty() { name.to_string() } else { f.name }; Ok(ActionSet::new(set_name, actions)) } @@ -151,8 +162,10 @@ pub(crate) fn can_load(app: &VectorcraftApp) -> bool { /// `ui.actionSet.load {path? | data?}`: reads the action set file at `path` (else a picked one), or /// the file's text `data`, and adds its set after the others, with its actions. A set with the -/// same name as one in the panel gets the next free number (`Print 2`). The current set and the -/// other sets stay as they are → `{set: index, name, actions: n}`. +/// same name as one in the panel gets the next free number (`Print 2`). A loaded action whose +/// function key an action in the panel or a command, tool or panel already has, or that cannot be +/// used on this platform, gets no key. The current set and the other sets stay as they are → +/// `{set: index, name, actions: n}`. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { let (text, stem) = match p.get("data") { Some(Value::String(data)) => { diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 34f2b58f3a..4d08938c53 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -522,9 +522,7 @@ mod tests { fn actions_panel_play_records_pathfinder_step() { let mut app = two_squares(); click_button(&mut app, "Intersect"); - app.ui.action_sets[0] - .actions - .push(crate::panels::actions::Action { name: "Unite".into(), steps: vec![("object.pathfinder.unite".into(), json!({}))] }); + app.ui.action_sets[0].actions.push(crate::panels::actions::Action::new("Unite", vec![("object.pathfinder.unite".into(), json!({}))])); let idx = app.ui.action_sets[0].actions.len() - 1; select_two_squares(&mut app, 110.0); crate::panels::actions::play(&mut app, 0, idx).unwrap(); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 0d531a2ae2..3b46710240 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1445,6 +1445,35 @@ mod tests { assert!(import_json(&json!({})).is_err()); } + /// The dialog's Import… leaves an action its function key when the imported set gives the key + /// to a command, through both Cancel and OK. + #[test] + fn importing_into_the_dialog_preserves_action_keys_on_ok() { + use crate::panels::actions::{Action, ActionSet, FunctionKey}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let f15 = FunctionKey { key: 15, cmd: false, shift: false }; + let mut nudge = Action::new("Nudge", vec![]); + nudge.key = Some(f15); + app.ui.action_sets.push(ActionSet::new("Mine", vec![nudge])); + let mut ov = Overrides::new(); + crate::keymap::set_override(&mut ov, "edit.duplicate", "F15"); + let bytes = serde_json::to_vec(&export_json("Imported", &ov)).unwrap(); + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| Some("/sets/Imported.json".to_string()))); + app.services.read = Some(Box::new(move |_: &str| Ok(bytes.clone()))); + let key = |app: &VectorcraftApp| app.ui.action_sets.last().and_then(|s| s.actions.first()).and_then(|a| a.key); + open(&mut app); + import_into_dialog(&mut app); + assert_eq!(key(&app), Some(f15), "the import alone keeps the action's key"); + assert!(app.ui.shortcut_overrides.is_empty(), "the import is only in the dialog"); + app.ui.dialog = None; + assert_eq!(key(&app), Some(f15), "Cancel keeps the action's key"); + open(&mut app); + import_into_dialog(&mut app); + assert_eq!(key(&app), Some(f15)); + confirm(&mut app).unwrap(); + assert_eq!(key(&app), Some(f15), "OK keeps the action's function key"); + } + #[test] fn presets_are_the_defaults() { for p in PRESETS { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index f93bde770b..9c62eb1885 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -154,14 +154,18 @@ fn runs_a_command(i: &egui::InputState, key: Key, cmd_only: bool) -> bool { /// `key` and `code` are the browser's names for the character typed and the key's position, which /// egui reads with [`Key::from_name`]; `modifiers` as egui reports them. The press is matched as /// the dispatcher matches it ([`dispatch`]) on a layout about which nothing is known: what typing -/// has shown of the layout is left out, and so are double presses. +/// has shown of the layout is left out, and so are double presses. An action's function key runs +/// a shortcut too. pub fn runs_a_shortcut(key: &str, code: &str, modifiers: Modifiers) -> bool { let physical_key = Key::from_name(code); let Some(key) = Key::from_name(key).or(physical_key) else { return false }; let press = egui::Event::Key { key, physical_key, pressed: true, repeat: false, modifiers }; let Some(input) = craft_keymap::KeyInput::from_egui(&press, crate::keymap::platform()) else { return false }; let mirror = crate::shortcut_editor::current(); - craft_keymap::Layout::default().candidates(&input).iter().any(|c| mirror.keymap.lookup(c, false, &Active::NONE) != craft_keymap::Lookup::None) + craft_keymap::Layout::default() + .candidates(&input) + .iter() + .any(|c| mirror.keymap.lookup(c, false, &Active::NONE) != craft_keymap::Lookup::None || crate::panels::actions::plays_an_action(c)) } /// Process one frame's events against the keymap at most once per context, viewport and frame, so @@ -338,6 +342,8 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { if claimed_tool_keys(app, ctx, view, rows_keys) { return; } + // An action's function key plays the action, also when a command has the same shortcut. + crate::panels::actions::play_function_key(app, ctx); // Command, panel and tool shortcuts. A bound shifted punctuation chord uses its key press; // other text keys use the typed character below. let row_key = |chord: &craft_keymap::Chord| { @@ -487,6 +493,7 @@ fn type_tool_input(app: &mut VectorcraftApp, ctx: &egui::Context, composing: boo }) }); } + crate::panels::actions::play_function_key(app, ctx); // Editing keys with modifiers and the clipboard (Cmd+A is Select All's, below: the text). crate::panels::character::route_type_input(app, ctx); // Enter was already delivered above as ToolKey::Enter (newline). Only chords with the diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 4dd6d9012d..4fc10697f6 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -491,6 +491,11 @@ pub struct UiState { /// Recording in progress: (set index, action name, journal length when recording started). #[serde(skip)] pub recording: Option<(usize, String, usize)>, + /// The id of the action New Action made for the recording in progress + /// ([`crate::panels::actions::Action::id`]): Stop gives it the recorded steps. None when Stop + /// adds a new action, as after Begin Recording. + #[serde(skip)] + pub recording_into: Option, /// Keyboard shortcut overrides: command id, `tool:` or `panel:` → chord ("" = none), /// stored in the form every earlier version reads. #[serde(default, with = "crate::keymap::stored")] @@ -961,6 +966,7 @@ impl Default for UiState { action_set: None, action_sets_selected: vec![], recording: None, + recording_into: None, shortcut_overrides: Default::default(), shortcut_set: default_shortcut_set(), workspace: default_workspace(), diff --git a/docs/mcp.md b/docs/mcp.md index a7fb8f10f1..501ce8c738 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1757,9 +1757,32 @@ already walks Image Trace. Short agent entry points: refused, and no set is added. The Actions panel menu's Save Actions… and Load Actions… run these; Load Actions… is disabled where there is no open dialog (the web). - Actions: `ui.action.rename {set, action, name}` renames the Actions panel's action at `action` in set `set` (0 is - the top set) to `name` with spaces trimmed from both ends, keeps its steps, and returns `{name}`. An index past the - last set or action, or an empty name, is an error, and then nothing is renamed. The panel menu's Action Options… - runs this for the selected action. + the top set) to `name` with spaces trimmed from both ends, keeps its steps, function key and color, and returns + `{name}`. An index past the last set or action, or an empty name, is an error, and then nothing is renamed. +- Actions: `ui.action.new {set, name, key?, cmd?, shift?, color?}` adds an action named `name` (spaces + trimmed) after the last action of set `set` (0 is the top set), starts recording into it and returns + `{set, action}`; Stop Playing/Recording (`ui.action.stop`) ends the recording. `key` 1 to 15 is the function key F1 to F15 that plays the + action (0 or null for none), with `cmd` (Ctrl, Command on macOS) and `shift`. `color` is its Button Mode color + (`red`, `yellow`, `green`, `blue` or `violet`; null or `""` for none), which the panel does not show. Action function + keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 + cannot be used. While an action is recording, and for an index past the last set, + an empty name, or a key or color that is not one of these, it is an error and nothing is added. The panel's Create + New Action button and menu's New Action… open the `actionNew` dialog, whose Record runs this. +- Actions: `ui.action.options {set, action, name?, key?, cmd?, shift?, color?}` changes the action at + `action` in set `set` and keeps its steps: `name` renames it, `key` with `cmd` and `shift` sets its function key, + and `color` its Button Mode color, as `ui.action.new` takes them; a param left out keeps what the action has, and + `cmd` or `shift` alone changes that modifier of its key. It + returns `{name, key, color}`. The panel menu's Action Options… runs this for the selected action. A function key + plays its action from the keyboard; like command shortcuts, it does nothing while a dialog, the command palette or + a text field has the keyboard, or while a tool is busy. Editing command shortcuts (`shortcuts.set`, Keyboard Shortcuts), loading preferences and + `ui.actionSet.load` preserve action function keys. When several actions have the same key, the first in panel order + plays. A stored key reserved on the current platform does not play an action. +- Actions: `ui.action.play {action, set?}` plays the action named `action` as one undoable batch; `set` names the set + to look in (default: every set), and a `set` that is not a string is an error. A name that no action has, or that + more than one action in the sets looked in has, is an error, and then nothing plays. +- Actions: `ui.action.stop {}` ends the recording in progress and keeps its steps, in the action `ui.action.new` made + for it, else in a new action after the last action of its set, and returns `{stopped}`. With nothing recording it + changes nothing. The panel's Stop Playing/Recording button runs this. - Action sets: `ui.actionSet.delete {sets?: [index], ids?: [id]}` deletes the Actions panel's sets at these indexes (0 is the top set) with their actions, by default the current set, and returns `{deleted}`. An index past the last set is an error, and then no set is deleted. `ids` holds the panel's own set ids, which its question passes: the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7513ebe092..48f2194f43 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -562,7 +562,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Lock Variables (`variable.lock`, in the Variables panel's bottom bar and menu) stops variables from being defined, deleted or renamed until they are unlocked, while objects can still be bound and unbound and data sets still change and apply; the lock is saved with the document. - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel menu: Save Actions… writes the current action set with all its actions to a file, and Load Actions… adds the set from such a file to the panel ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html): "Select Save Actions from the Actions panel menu", "You can save only the entire contents of a set", "Select Load Actions from the Actions panel menu"; `ui.actionSet.save`, `ui.actionSet.load`). The file is VectorCraft's own action set file (`.vcactions`); a loaded set named like one in the panel gets the next free number. - - Actions panel: the panel menu's Action Options… renames the selected action and keeps its steps ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Opens a dialog to rename or assign function keys/colors to the action"; `ui.action.rename`). The dialog has the name only; the function key and color are not there yet. + - Actions panel: the panel menu's Action Options… renames the selected action and keeps its steps ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): the menu item opens a dialog that renames the action or gives it a function key and color; `ui.action.options`). It also sets the action's function key and color. + - Actions panel: Create New Action (bottom bar) and the panel menu's New Action… ask for the new action's name, set, function key and color, and Record adds the action and starts recording into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html): the New Action dialog takes the action's name and the set it goes in; `ui.action.new`, `ui.action.play`). The function key (F1 to F15, with Ctrl or Command and Shift) plays the action. VectorCraft's own rules, which the page does not cover: a key another action or a command has is refused until Replace is ticked, which takes it from them; a shortcut given to a command later takes the key from the action; a copied action, and a loaded action whose key is taken, have no key; New Action does not open while an action is recording. The color is kept with the action for Button Mode, which VectorCraft does not have yet. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. - Actions panel: Delete Selection deletes the selected action 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"; `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a0b4225841..75bb06032c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -303,9 +303,10 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | | Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; the reference app's `.aia` files and Reset, Clear and Replace Actions remain | -| Actions panel: ≡ › Action Options… renames the selected action ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Opens a dialog to rename or assign function keys/colors to the action") | partial | `ui.action.rename`; `panels/actions.rs` tests (part of #1629). The dialog has the name only: the function key and color remain | +| Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Opens a dialog to rename or assign function keys/colors to the action") | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). The color shows nowhere until Button Mode exists | | Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | -| 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)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; the New Action dialog (name, set menu, shortcut, colour) and dragging actions between sets remain | +| 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)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; dragging actions between sets remains | +| Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action; a taken key needs Replace, and a shortcut given to a command later takes the key from the action. Button Mode, which shows the color, remains | | 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 | | Actions panel: ≡ › Duplicate copies the selected action or set ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Makes a copy of the selected action or set.") | partial | `ui.actionSet.duplicate`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected, and a copied set holds copies of all its actions. Undo does not remove the copy, and recorded commands cannot be duplicated | | 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 | From 14b0667e95f315b02c2d3aa8e4ae3bd688711f8d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 20:27:30 +0700 Subject: [PATCH 378/674] Actions: docs describe function keys as they now work (no Replace, keys kept) --- crates/ui-egui/src/panels/actions/files.rs | 5 ++--- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index cd1e1e0181..252d4c8e7d 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -162,9 +162,8 @@ pub(crate) fn can_load(app: &VectorcraftApp) -> bool { /// `ui.actionSet.load {path? | data?}`: reads the action set file at `path` (else a picked one), or /// the file's text `data`, and adds its set after the others, with its actions. A set with the -/// same name as one in the panel gets the next free number (`Print 2`). A loaded action whose -/// function key an action in the panel or a command, tool or panel already has, or that cannot be -/// used on this platform, gets no key. The current set and the other sets stay as they are → +/// same name as one in the panel gets the next free number (`Print 2`). Loaded actions keep their +/// function keys. The current set and the other sets stay as they are → /// `{set: index, name, actions: n}`. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { let (text, stem) = match p.get("data") { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 48f2194f43..c4f0921aa9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -563,7 +563,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel menu: Save Actions… writes the current action set with all its actions to a file, and Load Actions… adds the set from such a file to the panel ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html): "Select Save Actions from the Actions panel menu", "You can save only the entire contents of a set", "Select Load Actions from the Actions panel menu"; `ui.actionSet.save`, `ui.actionSet.load`). The file is VectorCraft's own action set file (`.vcactions`); a loaded set named like one in the panel gets the next free number. - Actions panel: the panel menu's Action Options… renames the selected action and keeps its steps ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): the menu item opens a dialog that renames the action or gives it a function key and color; `ui.action.options`). It also sets the action's function key and color. - - Actions panel: Create New Action (bottom bar) and the panel menu's New Action… ask for the new action's name, set, function key and color, and Record adds the action and starts recording into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html): the New Action dialog takes the action's name and the set it goes in; `ui.action.new`, `ui.action.play`). The function key (F1 to F15, with Ctrl or Command and Shift) plays the action. VectorCraft's own rules, which the page does not cover: a key another action or a command has is refused until Replace is ticked, which takes it from them; a shortcut given to a command later takes the key from the action; a copied action, and a loaded action whose key is taken, have no key; New Action does not open while an action is recording. The color is kept with the action for Button Mode, which VectorCraft does not have yet. + - Actions panel: Create New Action (bottom bar) and the panel menu's New Action… ask for the new action's name, set, function key and color, and Record adds the action and starts recording into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html): the New Action dialog takes the action's name and the set it goes in; `ui.action.new`, `ui.action.play`). The function key (F1 to F15, with Ctrl or Command and Shift) plays the action. An action's function key plays the action even when a command has the same shortcut, and the command keeps it. VectorCraft's own rules, which the page does not cover: when several actions have the same key the first in panel order plays; a copied action has no key; New Action does not open while an action is recording. The color is kept with the action for Button Mode, which VectorCraft does not have yet. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. - Actions panel: Delete Selection deletes the selected action 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"; `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 75bb06032c..59a5cccad7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -306,7 +306,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Opens a dialog to rename or assign function keys/colors to the action") | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). The color shows nowhere until Button Mode exists | | Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | | 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)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; dragging actions between sets remains | -| Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action; a taken key needs Replace, and a shortcut given to a command later takes the key from the action. Button Mode, which shows the color, remains | +| Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action, even when a command has the same shortcut, and the command keeps it. Button Mode, which shows the color, remains | | 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 | | Actions panel: ≡ › Duplicate copies the selected action or set ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html): "Makes a copy of the selected action or set.") | partial | `ui.actionSet.duplicate`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected, and a copied set holds copies of all its actions. Undo does not remove the copy, and recorded commands cannot be duplicated | | 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 | From e9a3ca2c81240345adec21f63b5e153df930da7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 05:34:23 -0800 Subject: [PATCH 379/674] Character style evidence links to help without copied instructions --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c4f0921aa9..d18b503962 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -508,8 +508,8 @@ since 2026-10-01. - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). -- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (above 0% and at most 4,000,000%), Baseline Shift (-4,000,000 pt to 4,000,000 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) ("Adjust the Horizontal and Vertical Scale, Baseline Shift, Character Rotation, and Language options"). -- **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) ("Change the Character Color, Tint, Weight, and Overprint Fill or Stroke options"; "Set the Figure, Position, Ligatures, Alternates, Ordinals, or Fractions options") and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) ("In the Character Styles or Paragraph Styles panel, select OpenType Features"). +- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (above 0% and at most 4,000,000%), Baseline Shift (-4,000,000 pt to 4,000,000 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). - **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy ` copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Auto Leading outside the layout:** a paragraph's Justification… › Auto Leading () also sets the Leading the Character panel shows for Auto type (blank where the selected paragraphs differ), the leading the Alt+↑/↓ nudge (`type.step`) steps from, each paragraph's own, and the lines Fill with Placeholder Text counts in area type. Evidence: `ParaStyle::effective_leading` (`crates/doc/src/text.rs` test `paragraph_effective_leading_follows_auto_leading`), `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading`. From 0a9d65175ad36c7be5d98327db9be749d1a20318 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 05:08:15 -0800 Subject: [PATCH 380/674] Docs: record Find Font replacement sources --- docs/roadmap.md | 8 +++++--- docs/target-app-parity.md | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 2ea970a6a6..6693278439 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -24,6 +24,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; scores and estimates unchanged. | +| 2026-11-03 | minor | M7: Find Font replacement sources Document, Recent and System are shipped (#5217); estimates unchanged. | | 2026-10-30 | minor | Raster effects: bounded length fields in effect dialogs clamp on commit and reject invalid inputs visibly (#4638); estimates unchanged. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | @@ -95,9 +96,9 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); 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 | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | @@ -149,6 +150,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| | 2026-11-02 | minor | Font-family fields in Character, Properties and Control step selected text with the wheel (#5253), with one undo step per notch; scores and estimates unchanged. | +| 2026-11-03 | minor | M7 records Find Font's shipped replacement-source chooser (#5217); estimates unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-10-30 | patch | M5: opaque solid-fill knockout paths avoid redundant erase/add layers in hard-edge frames and supersampled raster export; exact-pixel regression coverage retains analytical-AA rounding and translucent knockout behavior; scores and estimates unchanged | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d18b503962..646198a8f3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -24,6 +24,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | | 2026-11-02 | minor | Legacy `.ai` saves (version 7) write type with rotated characters as outlines that keep each character's rotation, with a warning unless `outlineText` is on (#5186); scores unchanged. | +| 2026-11-03 | minor | Record shipped Find Font replacement sources: Document, Recent and System (#5217); scores and estimates unchanged. | | 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | | 2026-10-31 | minor | New Document: More Settings has the Save Preset button beside the name too, saving its settings (artboard layout included) as a preset (#4893); scores unchanged. | | 2026-10-31 | minor | Object › Rasterize in a CMYK document with its CMYK colour model makes a CMYK image of the art's ink amounts (as CMYK exports draw them), so the Properties panel says CMYK and CMYK exports keep its inks; a transparent background becomes the image's opacity mask (#4882); scores unchanged. | @@ -891,7 +892,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) ("Kerning is the process of adding or subtracting space between specific pairs of characters."). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). -- **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, is the font menu of every installed family. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`. +- **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, lists the installed families available in the font menu. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the menu's saved font filters but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. - **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). @@ -1557,6 +1558,7 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente | Date | Change | Summary | |---|---|---| | 2026-11-02 | minor | Wheel input over closed font-family fields changes selected text (#5253); public documentation and application choices distinguished; scores and estimates unchanged. | +| 2026-11-03 | minor | Find Font's replacement-source chooser offers Document, Recent and System (#5217); scores and estimates unchanged. | | 2026-11-03 | minor | SVG imports preserve exported ellipses as four-anchor paths (#5243). Inline graphics use manual kerning (#5245). Symbol editing shows draggable 9-slice guides (#5280). Recolor Artwork offers smooth and segmented wheels and color bars (#5249). Scores and hours remain unchanged. | | 2026-11-01 | minor | Repeat: a double-click isolates it to edit its source art, text included (#5054); evidence added; scores unchanged. | | 2026-11-01 | minor | Live Corners: Up/Down while dragging a corner widget step the corner kind (#2898); evidence added; scores unchanged. | From 0f5e4c261a608645423d47347b667e8e7171b1ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 05:32:37 -0800 Subject: [PATCH 381/674] Transform previews typed values in its effect dialog --- crates/ui-egui/src/dialogs/effect.rs | 8 +- crates/ui-egui/src/dialogs/transform_each.rs | 26 +- crates/ui-egui/src/panels/tests_appearance.rs | 310 ++++++++++++++++++ crates/ui-egui/src/widgets.rs | 6 +- crates/ui-egui/src/widgets/numeric.rs | 81 ++++- docs/mcp.md | 4 + docs/target-app-parity.md | 3 +- docs/ui-parity.md | 4 +- 8 files changed, 416 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 1e1ad72fcf..85282add14 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -106,10 +106,10 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// The effects of the first selected object that `item` (an index or null) addresses. +/// The function reads effects at `item` (an index or null) from the targeted node or first selected object. fn target_effects(app: &VectorcraftApp, item: &Value) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - let node = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let node = st.selection.subjects().first().and_then(|id| st.doc.node(*id)); node.and_then(|n| n.appearance.effects_at(item.as_u64().map(|i| i as usize))).cloned().unwrap_or_default() } @@ -550,7 +550,7 @@ fn scribble_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Uni /// last previewed. fn transform_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit) -> bool { ui.horizontal_top(|ui| { - ui.vertical(|ui| transform_each::sections(ui, d, unit)); + ui.vertical(|ui| transform_each::sections(ui, d, unit, true)); ui.add_space(16.0); ui.vertical(|ui| { widgets::subheader(ui, tl!("Options")); @@ -560,7 +560,7 @@ fn transform_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Un form::check(ui, d, "strokes", tl!("Scale Strokes & Effects")); ui.horizontal(|ui| { widgets::dim_label(ui, tl!("Copies:")); - if let Some(n) = widgets::range_field(ui, "fx-copies", d.f64("copies", 0.0), 0.0..=1000.0, "", 0, 50.0) { + if let Some(n) = widgets::range_field_live(ui, "fx-copies", d.f64("copies", 0.0), 0.0..=1000.0, "", 0, 50.0) { d.fields.insert("copies".into(), json!(n)); } }); diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index f18cd7ece8..71f5145a22 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -78,7 +78,7 @@ const MAX_SCALE: f64 = 100_000.0; /// `scaleH` and `scaleV` (rails 0–200 %) and for `moveH` and `moveV` (rails ±1000 pt, fields in /// `units`), and an angle dial for `rotate` (counter-clockwise). The fields take values past the /// rails. -pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit) { +pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit, live: bool) { let rail = Tokens::get(ui.ctx()).input_border; let track = move |_| rail; let axes = |h, v| [(h, tl!("Horizontal:")), (v, tl!("Vertical:"))]; @@ -87,7 +87,12 @@ pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc widgets::label_row(ui, label, LABEL_W, |ui| { let shown = widgets::SliderValue::field(d.f64(key, 100.0).clamp(-MAX_SCALE, MAX_SCALE), 0.0..=200.0, "%", 2); form::slider_rail_valued(ui, d, key, label, 0.0..=200.0, Some(shown), &track); - if let Some(n) = widgets::range_field(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) { + let value = if live { + widgets::range_field_live(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) + } else { + widgets::range_field(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) + }; + if let Some(n) = value { d.fields.insert(key.into(), json!(n)); } }); @@ -97,14 +102,25 @@ pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc widgets::label_row(ui, label, LABEL_W, |ui| { let shown = form::length_value(d, key, units, -1000.0..=1000.0); form::slider_rail_valued(ui, d, key, label, -1000.0..=1000.0, shown, &track); - form::length(ui, d, key, units, FIELD_W); + if live { + if let Some(n) = widgets::num_field_live(ui, ("dlg-len", key), Some(d.f64(key, 0.0)), units, FIELD_W) { + d.fields.insert(key.into(), json!(n)); + } + } else { + form::length(ui, d, key, units, FIELD_W); + } }); } widgets::subheader(ui, tl!("Rotate")); widgets::label_row(ui, tl!("Angle:"), LABEL_W, |ui| { let angle = d.f64("rotate", 0.0); let dialed = widgets::angle_dial(ui, "te-dial", angle, 28.0); - if let Some(a) = widgets::plain_field(ui, ("te", "rotate"), angle, "°", 2, FIELD_W).or(dialed) { + let typed = if live { + widgets::plain_field_live(ui, ("te", "rotate"), angle, "°", 2, FIELD_W) + } else { + widgets::plain_field(ui, ("te", "rotate"), angle, "°", 2, FIELD_W) + }; + if let Some(a) = typed.or(dialed) { d.fields.insert("rotate".into(), json!(a)); } }); @@ -128,7 +144,7 @@ pub(super) fn reflect_options(ui: &mut egui::Ui, d: &mut Dialog) { fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let units = app.session.general_unit(); ui.horizontal_top(|ui| { - ui.vertical(|ui| sections(ui, d, units)); + ui.vertical(|ui| sections(ui, d, units, false)); ui.add_space(16.0); ui.vertical(|ui| { widgets::subheader(ui, tl!("Options")); diff --git a/crates/ui-egui/src/panels/tests_appearance.rs b/crates/ui-egui/src/panels/tests_appearance.rs index 1fee26cc68..dc56d99e8a 100644 --- a/crates/ui-egui/src/panels/tests_appearance.rs +++ b/crates/ui-egui/src/panels/tests_appearance.rs @@ -835,6 +835,316 @@ fn an_effects_name_edits_it_and_its_empty_space_highlights_it() { assert!(app.ui.dialog.is_some(), "a double-click on the empty space opens the dialog"); } +#[test] +fn transform_effect_name_edits_the_displayed_appearance_target() { + for target_kind in ["object", "group", "layer"] { + let mut app = app_with_rect(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + if target_kind == "group" { + let group = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("layer.target", json!({"id": group})).unwrap(); + } else if target_kind == "layer" { + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.target", json!({"id": layer.0})).unwrap(); + } + let target = app.session.doc().unwrap().selection.subjects()[0]; + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": {"moveH": 12}})).unwrap(); + let ctx = drop_ctx(); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + let dialog = app.ui.dialog.as_mut().unwrap_or_else(|| panic!("Transform did not open for {target_kind}")); + assert_eq!(dialog.f64("moveH", 0.0), 12.0); + dialog.fields.insert("moveH".into(), json!(35)); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(text.lines().any(|s| s == "Transform"), "{text}"); + assert!(app.session.in_interaction()); + let rendered = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + assert_eq!(rendered.over_white(30, 50), [255, 255, 255], "{target_kind}: original position"); + assert_eq!(rendered.over_white(130, 50), [255, 0, 0], "{target_kind}: transformed position"); + crate::dialogs::confirm(&mut app).unwrap(); + let node = app.session.doc().unwrap().doc.node(target).unwrap(); + assert_eq!(node.appearance.effects.len(), 1); + assert_eq!(node.appearance.effects[0].params["moveH"].as_f64(), Some(35.0)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.node(target).unwrap().appearance.effects[0].params["moveH"].as_f64(), Some(12.0)); + } +} + +#[test] +fn transform_effect_typed_scale_changes_the_painted_object() { + for layer_target in [false, true] { + let mut app = app_with_rect(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + if layer_target { + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": {"objects": false}})).unwrap(); + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.target", json!({"id": layer.0})).unwrap(); + } + app.run("effect.apply", json!({"effect": "distort.transform", "item": null})).unwrap(); + let target = app.session.doc().unwrap().selection.subjects()[0]; + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + frame_events(&ctx, &mut app, vec![egui::Event::Text("50".into())], |app, ui| crate::dialogs::show(app, ui.ctx())); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame_events(&ctx, &mut app, vec![enter], |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(app.ui.dialog.is_none()); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.node(target).unwrap().appearance.effects[0].params["scaleH"].as_f64(), Some(50.0)); + let rendered = vectorcraft_testkit::raster::render_artboard(doc); + assert_eq!(rendered.over_white(20, 50), [255, 255, 255], "layer target: {layer_target}"); + assert_eq!(rendered.over_white(50, 50), [255, 0, 0], "layer target: {layer_target}"); + } +} + +#[test] +fn transform_effect_preview_commit_cancel_and_undo_cover_artwork_targets() { + use vectorcraft_testkit::raster::{Image, render_artboard}; + let rightmost = + |image: &Image| (0..image.width).rev().find(|&x| (0..image.height).any(|y| image.over_white(x, y).iter().any(|&c| c < 245))).unwrap(); + for kind in ["object", "fill", "stroke", "group", "layer", "text", "image"] { + for preview in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + match kind { + "text" => { + app.run("text.create", json!({"x": 20, "y": 80, "size": 20, "text": "HI"})).unwrap(); + } + "image" => { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + app.run( + "file.place", + json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false, "at": [30, 70]}), + ) + .unwrap(); + } + _ => { + app.run("shape.rectangle", json!({"x": 20, "y": 60, "width": 20, "height": 20})).unwrap(); + } + } + if kind != "image" { + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + } + if kind == "stroke" { + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.run("stroke.set", json!({"weight": 4})).unwrap(); + } + if kind == "group" { + app.run("object.group", json!({})).unwrap(); + } else if kind == "layer" { + let layer = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.target", json!({"id": layer.0})).unwrap(); + } + let item = match kind { + "fill" => Some(0), + "stroke" => Some(1), + _ => None, + }; + app.run("effect.apply", json!({"effect": "distort.transform", "item": item})).unwrap(); + let baseline = render_artboard(&app.session.doc().unwrap().doc); + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + let mut texts = frame_events(&ctx, &mut app, vec![], appearance::show); + if let Some(i) = item { + let label = text_rect(&texts, if i == 0 { "Fill:" } else { "Stroke:" }); + click_mod(&ctx, &mut app, egui::pos2(label.left() - 12.0, label.center().y), egui::Modifiers::NONE); + texts = frame_events(&ctx, &mut app, vec![], appearance::show); + } + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + let d = app.ui.dialog.as_mut().unwrap_or_else(|| panic!("{kind}: dialog did not open")); + d.fields.insert("moveH".into(), json!(40)); + d.fields.insert("copies".into(), json!(2)); + d.fields.insert("preview".into(), json!(preview)); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let painted = render_artboard(&app.session.doc().unwrap().doc); + if preview { + assert!(rightmost(&painted) >= rightmost(&baseline) + 75, "{kind}: preview must draw both copies"); + } else { + assert_eq!(painted.rgba, baseline.rgba, "{kind}: Preview off"); + } + crate::dialogs::confirm(&mut app).unwrap(); + let committed = render_artboard(&app.session.doc().unwrap().doc); + assert!(rightmost(&committed) >= rightmost(&baseline) + 75, "{kind}: OK must draw both copies"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{kind}: undo"); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": item, "index": 0})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("moveH".into(), json!(40)); + d.fields.insert("copies".into(), json!(2)); + crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::cancel(&mut app); + assert_eq!(render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{kind}: Cancel"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "{kind}: Cancel must preserve undo history"); + } + } +} + +#[test] +fn transform_effect_copies_preview_while_the_field_is_still_focused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.units_general = "cm".into(); + app.run("file.new", json!({"width": 400, "height": 1200})).unwrap(); + assert_eq!(app.session.general_unit(), Unit::named("cm").unwrap()); + app.run("shape.rectangle", json!({"x": 20, "y": 60, "width": 20, "height": 20})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("paint.setFill", json!({"item": 0, "color": "#000000"})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("paint.setFill", json!({"item": 1, "color": "#ffffff"})).unwrap(); + app.run("effect.apply", json!({"effect": "path.offsetPath", "item": 0, "params": {"offset": 10}})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": 0, "params": {"scaleH": 99.5, "moveV": 72.0 / 2.54}})).unwrap(); + let target = app.session.doc().unwrap().selection.subjects()[0]; + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + let fill = texts.iter().filter(|(s, _)| s == "Fill:").max_by(|(_, a), (_, b)| a.top().total_cmp(&b.top())).unwrap().1; + click_mod(&ctx, &mut app, egui::pos2(fill.left() - 12.0, fill.center().y), egui::Modifiers::NONE); + let texts = frame_events(&ctx, &mut app, vec![], appearance::show); + click_mod(&ctx, &mut app, text_rect(&texts, "Transform").center(), egui::Modifiers::NONE); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let texts = frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + let copies = text_rect(&texts, "0").center(); + click(&ctx, &mut app, copies, |app, ui| crate::dialogs::show(app, ui.ctx())); + frame_events(&ctx, &mut app, vec![egui::Event::Text("30".into())], |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(app.ui.dialog.is_some()); + assert!(ctx.memory(|m| m.focused().is_some())); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("copies", 0.0), 30.0); + let effect = &app.session.doc().unwrap().doc.node(target).unwrap().appearance.items[0].effects()[1]; + assert_eq!(effect.params["copies"].as_f64(), Some(30.0)); + let rendered = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + assert!(rendered.over_white(30, 600).iter().any(|&c| c < 245), "the focused field must update the visible copy stack"); + crate::dialogs::cancel(&mut app); + let restored = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + assert_eq!(restored.over_white(30, 600), [255, 255, 255]); +} + +#[test] +fn transform_effect_live_fields_keep_partial_text_and_honor_preview() { + let cm = 72.0 / 2.54; + let cases: [(&str, &str, usize, &[&str], f64); 6] = [ + ("scaleH", "100%", 0, &["5", "0", ".", "1", "2", "5", "6"], 50.13), + ("scaleV", "100%", 1, &["7", "5"], 75.0), + ("moveH", "0cm", 0, &["1", ".", "5"], 1.5 * cm), + ("moveV", "0cm", 1, &["-", "1", ",", "5"], -1.5 * cm), + ("rotate", "0°", 0, &["4", "5", ".", "1", "2", "3"], 45.123), + ("copies", "0", 0, &["2", ".", "5", "6"], 3.0), + ]; + for (key, shown, index, chunks, expected) in cases { + for preview in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.units_general = "cm".into(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let params = if key == "copies" { json!({"moveH": 20}) } else { json!({}) }; + app.run("effect.apply", json!({"effect": "distort.transform", "item": null, "params": params})).unwrap(); + let target = app.session.doc().unwrap().selection.subjects()[0]; + let baseline = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": null, "index": 0})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(preview)); + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let texts = frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + let at = texts + .iter() + .filter(|(s, _)| s.replace(' ', "") == shown) + .nth(index) + .unwrap_or_else(|| panic!("{key}: missing field {shown}: {texts:?}")) + .1 + .center(); + click(&ctx, &mut app, at, |app, ui| crate::dialogs::show(app, ui.ctx())); + let select_all = + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + frame_events(&ctx, &mut app, vec![select_all], |app, ui| crate::dialogs::show(app, ui.ctx())); + for chunk in chunks { + frame_events(&ctx, &mut app, vec![egui::Event::Text((*chunk).into())], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let held = app.ui.dialog.as_ref().unwrap().f64(key, f64::NAN); + assert!((held - expected).abs() < 1e-8, "{key}, Preview {preview}: {held} != {expected}"); + let rendered = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + if preview { + let applied = app.session.doc().unwrap().doc.node(target).unwrap().appearance.effects[0].params[key].as_f64().unwrap(); + assert!((applied - expected).abs() < 1e-8, "{key}: preview parameters"); + assert_ne!(rendered.rgba, baseline.rgba, "{key}: visible preview"); + } else { + assert_eq!(rendered.rgba, baseline.rgba, "{key}: Preview off"); + } + let texts = frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + click(&ctx, &mut app, text_rect(&texts, "OK").center(), |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(app.ui.dialog.is_none()); + let applied = app.session.doc().unwrap().doc.node(target).unwrap().appearance.effects[0].params[key].as_f64().unwrap(); + assert!((applied - expected).abs() < 1e-8, "{key}: confirmed parameters"); + if preview { + assert_eq!( + vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, + rendered.rgba, + "{key}: OK matches preview" + ); + } + assert_ne!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: OK"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: undo"); + } + } +} + +#[test] +fn transform_effect_sliders_update_the_painted_preview_and_cancel() { + for (key, label, index, fraction, expected, tolerance) in [ + ("scaleH", "Horizontal:", 0, 0.25, 50.0, 4.0), + ("scaleV", "Vertical:", 0, 0.25, 50.0, 4.0), + ("moveH", "Horizontal:", 1, 0.55, 100.0, 20.0), + ("moveV", "Vertical:", 1, 0.55, 100.0, 20.0), + ] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("effect.apply", json!({"effect": "distort.transform", "item": null})).unwrap(); + let baseline = vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc); + app.run("effect.dialog", json!({"effect": "distort.transform", "item": null, "index": 0})).unwrap(); + let ctx = drop_ctx(); + crate::theme::install_fonts(&ctx); + for _ in 0..2 { + frame_events(&ctx, &mut app, vec![], |app, ui| crate::dialogs::show(app, ui.ctx())); + } + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + output.textures_delta.clear(); + let mut rails: Vec<_> = output + .platform_output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Slider && n.label() == Some(label)) + .filter_map(|(_, n)| n.bounds()) + .collect(); + rails.sort_by(|a, b| a.y0.total_cmp(&b.y0)); + let bounds = rails.get(index).unwrap_or_else(|| panic!("{key}: slider not found")); + let at = egui::pos2((bounds.x0 + (bounds.x1 - bounds.x0) * fraction) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + click(&ctx, &mut app, at, |app, ui| crate::dialogs::show(app, ui.ctx())); + let value = app.ui.dialog.as_ref().unwrap().f64(key, f64::NAN); + assert!((value - expected).abs() <= tolerance, "{key}: {value}"); + assert_ne!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: slider preview"); + crate::dialogs::cancel(&mut app); + assert_eq!(vectorcraft_testkit::raster::render_artboard(&app.session.doc().unwrap().doc).rgba, baseline.rgba, "{key}: Cancel"); + } +} + /// A fill or stroke row's label ("Fill:", "Stroke:") is a link: a click opens the Color or Stroke /// panel with or without modifiers, with the tooltip "Click to edit". Its empty space only takes the /// click rules: no tooltip, and neither a Ctrl-click nor a double-click there opens a panel. diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b6b4130b88..2e139d0131 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -52,9 +52,9 @@ pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_labe pub(crate) use labels::{label_field, take_previous_label}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ - SpinPick, mixed_field, mixed_field_named, num_field, num_field_named, num_field_within, opt_field, opt_field_named, range_field, - range_field_named, range_field_stepped, size_field, size_field_named, slider, spin_field, spin_field_auto, spin_field_auto_named, - spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, + SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_within, opt_field, opt_field_named, + plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped, size_field, size_field_named, slider, spin_field, + spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, }; #[cfg(test)] use numeric::{decimal_point, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 9244c32bf6..91cd18eebc 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -59,14 +59,20 @@ pub fn num_field_within( bounds: RangeInclusive, ) -> Option { let label = take_previous_label(ui); - unit_field(ui, id, label, None, value, unit, width, false, bounds, &[]) + unit_field(ui, id, label, None, value, unit, width, false, bounds, &[], false) } /// [`num_field`] for a row whose visible label is not an adjacent label widget (a grid cell with /// its label painted separately): screen readers name the field `name` (already translated). pub fn num_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str>, value: Option, unit: Unit, width: f32) -> Option { let label = take_previous_label(ui); - unit_field(ui, id, label, name, value, unit, width, false, ANY, &[]) + unit_field(ui, id, label, name, value, unit, width, false, ANY, &[], false) +} + +/// The field returns valid typed distances immediately and preserves the text being edited. +pub fn num_field_live(ui: &mut Ui, id: impl std::hash::Hash, value: Option, unit: Unit, width: f32) -> Option { + let label = take_previous_label(ui); + unit_field(ui, id, label, None, value, unit, width, false, ANY, &[], true) } /// Any number: the bounds of a field that has none. @@ -93,6 +99,7 @@ fn unit_field( share_of_value: bool, bounds: RangeInclusive, stops: &[f64], + live: bool, ) -> Option { let id = id_with(ui.scope_id(), id); let shown = value.map(|v| unit.format(v)).unwrap_or_default(); @@ -129,7 +136,18 @@ fn unit_field( } } else { ui.data_mut(|d| d.insert_temp(id, buf.clone())); - stepped.or(scrubbed).map(|v| unit.to_pt(v)) + if let Some(v) = stepped.or(scrubbed) { + return Some(unit.to_pt(v)); + } + if live + && resp.changed() + && let Some(v) = read(&buf).filter(|v| v.is_finite()).map(|v| within(v, &bounds)).filter(|v| Some(*v) != value) + { + ui.data_mut(|d| d.insert_temp(id.with("shown"), unit.format(v))); + ui.ctx().request_repaint(); + return Some(v); + } + None } } @@ -312,7 +330,7 @@ pub fn size_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str } }); } - unit_field(ui, id, label, name, value, unit, width, true, ANY, &[]) + unit_field(ui, id, label, name, value, unit, width, true, ANY, &[], false) } /// [`plain_field`] for a number kept within `range` (the values of dialogs, preferences and panels @@ -346,7 +364,34 @@ pub fn range_field_named( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None, false).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None, false, false).map(|v| within(round_to(v, places), &range)) +} + +/// The field returns valid typed values immediately within `range` and preserves incomplete input. +pub fn range_field_live( + ui: &mut Ui, + id: impl std::hash::Hash, + value: impl Into>, + range: RangeInclusive, + suffix: &str, + decimals: usize, + width: f32, +) -> Option { + let value = value.into().map(|v| within(v, &range)); + let label = take_previous_label(ui); + let field = id_with(ui.scope_id(), &id); + let result = bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, None, false, true) + .map(|v| within(round_to(v, decimals.min(6) as i32), &range)); + if let Some(value) = result { + ui.data_mut(|d| d.insert_temp(field.with("shown"), field_text(value, suffix, decimals))); + } + result +} + +/// The field returns valid typed numbers immediately and preserves the text being edited. +pub fn plain_field_live(ui: &mut Ui, id: impl std::hash::Hash, value: f64, suffix: &str, decimals: usize, width: f32) -> Option { + let label = take_previous_label(ui); + bounded_field(ui, id, label, None, Some(value), suffix, decimals, width, &ANY, None, false, true) } /// [`range_field`] whose ↑/↓ and wheel take `step`'s steps instead of whole numbers (see @@ -366,7 +411,7 @@ pub fn range_field_stepped( let places = decimals.min(6) as i32; let value = value.into().map(|v| within(v, &range)); let label = take_previous_label(ui); - bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step), false).map(|v| within(round_to(v, places), &range)) + bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step), false, false).map(|v| within(round_to(v, places), &range)) } /// [`plain_field`] for a value the selected objects may not share: `None` shows a blank field. @@ -385,7 +430,7 @@ pub fn mixed_field_named( width: f32, ) -> Option { let label = take_previous_label(ui); - bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false) + bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false, false) } /// [`mixed_field`] whose ↑/↓, wheel and scrub stop at `bounds`; ↑/↓ and the wheel take `step`'s steps @@ -404,6 +449,7 @@ fn bounded_field( bounds: &RangeInclusive, step: Option f64>, parentheses: bool, + live: bool, ) -> Option { let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); @@ -431,7 +477,18 @@ fn bounded_field( let decimals = decimals.min(6) as i32; let stepped = step_value(ui, &resp, &mut buf, bounds, (read, show), step, &[]).map(|v| round_to(v, decimals)); let scrubbed = scrub::field(ui, id, rect, &buf, value, decimals, bounds); - if commit && buf != shown { read(&buf) } else { stepped.or(scrubbed).filter(|&v| Some(v) != value) } + if commit && buf != shown { + read(&buf) + } else if let Some(v) = stepped.or(scrubbed).filter(|&v| Some(v) != value) { + Some(v) + } else if live && resp.changed() { + read(&buf).filter(|v| v.is_finite()).map(|v| within(v, bounds)).filter(|v| Some(*v) != value).inspect(|&v| { + ui.data_mut(|d| d.insert_temp(id.with("shown"), show(v))); + ui.ctx().request_repaint(); + }) + } else { + None + } } /// The text [`plain_field`] shows for `value`: at most `decimals` places, without trailing zeros, @@ -510,7 +567,7 @@ pub fn spin_field_stops_named( ) -> Option { let label = take_previous_label(ui); spin_generic(ui, label, value, None, None, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { - unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets) + unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets, false) }) .and_then(SpinPick::value) } @@ -567,7 +624,7 @@ pub fn spin_field_auto_named( ) -> Option { let label = take_previous_label(ui); spin_generic(ui, label, value, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { - unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[]) + unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[], false) }) } @@ -606,7 +663,7 @@ pub fn spin_plain_named( let value = value.into(); let fmt = |v: f64| format!("{v}{suffix}"); spin_generic(ui, label, value, None, None, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| { - bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false) + bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false, false) }) .and_then(SpinPick::value) } @@ -638,7 +695,7 @@ pub fn spin_kerning( presets, &[], &|v| format!("{v}"), - &mut |ui, fw, label| bounded_field(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses), + &mut |ui, fw, label| bounded_field(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses, false), ) } diff --git a/docs/mcp.md b/docs/mcp.md index 501ce8c738..11a4a09415 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1939,6 +1939,10 @@ act on several fills/strokes at once, and `appearance.showAllHidden` makes every visible again. In remote mode, `effect.dialog {effect, index, item}` opens an applied effect's dialog prefilled (`ui.dialog.confirm` runs `effect.setParams`); see the control protocol for the "already applied" question. +Effect dialogs use the targeted object, group, or layer shown in Appearance. The Transform dialog previews valid +numbers as they are typed, including Copies, distances with units, and rotation. With Preview off, changes apply +on OK. Cancel restores the original artwork. + ## Overprint Each fill and stroke (and each character's fill and stroke) can overprint: its inks print over the inks below instead diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 646198a8f3..043e460178 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard |---|---|---| | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | +| 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | | 2026-11-02 | minor | Legacy `.ai` saves (version 7) write type with rotated characters as outlines that keep each character's rotation, with a warning unless `outlineText` is on (#5186); scores unchanged. | | 2026-11-03 | minor | Record shipped Find Font replacement sources: Document, Recent and System (#5217); scores and estimates unchanged. | | 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | @@ -131,7 +132,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 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, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (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 | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | -| Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | +| Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 59a5cccad7..7a62b78eea 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; Transform previews typed values and reads the Appearance target; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -21,6 +21,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-10-26 | minor | Pencil Fidelity goes down to 0.01 pt (dialog, tool and engine; Smooth keeps 0.05) on a logarithmic slider across the Tool Options row, with hundredths in the field and key steps that fit the range (#3328); scores and estimates unchanged (estimated) | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | @@ -185,6 +186,7 @@ tools, never checked side by side) isn't captured row by row. | Transform tools: click sets the reference point (snaps to anchors/centres), Alt-click opens the dialog, Alt-release copies | done | with anchors selected with Direct Selection, the tools, the dialogs and Move transform those anchors alone, about the centre of their box by default (#1408; the default point and whole-object copies are our choices) | | Move, Rotate, Scale, Reflect and Shear dialogs: live Preview; Up/Down step angles and percentages by 1, Shift by 10 | done | #1412; Preview starts off (our choice: the public documentation gives no default), Move's as it was last confirmed; OK is one undo step and Transform Again repeats it | | Transform Again, Transform Each, Scale Strokes & Effects, Scale Corners | done | | +| The Transform effect dialog previews valid typed scale, move, rotation, and Copies values while fields remain focused. Preview off defers the artwork change until OK; Cancel restores the original artwork. | done | `crates/ui-egui/src/panels/tests_appearance.rs` covers numeric input, sliders, artwork targets, preview, and undo. | | Move opens on the offset of the last move (a drag of the selection or Move) and with the Copy, Transform Objects and Preview it was last confirmed with, so Enter, Enter repeats a move or a copy | done | the public source: [an Adobe Community thread](https://community.adobe.com/questions-652/move-tool-771221) (the dialog shows the last move, drags included); that the checkboxes are kept, Preview among them, and that a nudge with the arrow keys is not a move here are our choices; Transform Patterns is General › Transform Pattern Tiles, which Move's OK sets; the offset is the session's (not kept between launches) | | Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with, and has a Copy button left of Cancel that transforms a copy of each object (no Copy checkbox) | done | #1732; the Copy button: [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html); the remembered values: a maintainer's call on [#1732](https://github.com/storytold/vectorcraft/issues/1732#issuecomment-6157505075), not the help page; Copy itself is never kept; Preview still starts off on first use (the owner's call) | | Transform Objects beside Transform Patterns in the Move, Rotate, Scale, Reflect and Shear dialogs and Transform Each; Reflect across an angle | done | #1448, #1460; off, only the pattern tiles transform; the checkboxes are always enabled (our choice); the link that keeps Transform Each's two scales equal is missing (not documented) | From b751dce8e32d57268ae4482ed1c879eea5388978 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 05:45:53 -0800 Subject: [PATCH 382/674] SVG import preserves selector matches while retaining metadata --- Cargo.lock | 1 + crates/svg/Cargo.toml | 1 + crates/svg/src/import.rs | 5 +- crates/svg/src/import/prepass.rs | 33 +++++- crates/svg/src/import/prepass/id_styles.rs | 113 +++++++++++++++++++++ crates/svg/src/import/text.rs | 33 ++++-- crates/svg/tests/it/import_live.rs | 52 ++++++++++ crates/svg/tests/it/import_text.rs | 40 ++++++++ 8 files changed, 262 insertions(+), 16 deletions(-) create mode 100644 crates/svg/src/import/prepass/id_styles.rs diff --git a/Cargo.lock b/Cargo.lock index 46998c4c3c..137e9a2be7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6458,6 +6458,7 @@ dependencies = [ "resvg", "serde", "serde_json", + "simplecss", "skrifa 0.47.0", "svgtypes 0.16.1", "thiserror 2.0.21", diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 6ef3b64ddf..44b8c696e4 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -28,6 +28,7 @@ flate2 = { workspace = true } image = { workspace = true } # Colour / transform / length parsing for the fallback (MIT OR Apache-2.0; already used by usvg). svgtypes = "0.16" +simplecss = "0.2.2" [dev-dependencies] # Reading embedded font subsets back. diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 0201c591e5..78c12043f2 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -113,7 +113,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; - let (svg, found) = prepass(svg, &scan.markers, &xml, opts); + let (svg, found) = prepass(svg, &scan.markers, &xml, opts)?; // The prepass's edits are in the text: the XML is read again only when it made any. let xml = match &svg { Cow::Borrowed(_) => xml, @@ -126,7 +126,8 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul let units = RootUnits::of(xml.root_element()); let root_name = root_layer_name(xml.root_element()); let mut warnings = found.warnings; - let (src, slots) = text::prepare(svg, &xml, units.dpi, &mut warnings); + let text_xml = found.text_source.as_deref().map(parse).transpose()?; + let (src, slots) = text::prepare(svg, &xml, text_xml.as_ref(), units.dpi, &mut warnings); let files = found.files; let tree = { let opt = usvg::Options { diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index 5a393e79aa..f02f436cdb 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -5,6 +5,8 @@ use super::{ symbol_units, vector_effect, }; +mod id_styles; + /// What usvg would lose, found in the XML before it runs ([`prepass`]). #[derive(Default)] pub(super) struct Found { @@ -31,6 +33,8 @@ pub(super) struct Found { /// Ids of the `` and `` elements, which come back as the ellipse VectorCraft /// draws ([`drawn_ellipse`](super::convert::drawn_ellipse)). pub(super) ellipses: HashSet, + /// The text importer reads styles from this SVG before tracking IDs are added. + pub(super) text_source: Option, pub(super) warnings: Vec, } @@ -38,6 +42,8 @@ pub(super) struct Found { #[derive(Default)] pub(crate) struct Edits { list: Vec<(std::ops::Range, String)>, + /// These edits assign tracking IDs. + id_edits: Vec<(std::ops::Range, String)>, /// The ids made up so far, by element. ids: HashMap, /// The numbers `n` of the `{MADE_UP_ID}n` the file names (as an element's id, in a style @@ -70,7 +76,13 @@ impl Edits { } let id = format!("{MADE_UP_ID}{}", self.next); self.next += 1; - self.set(svg, n, "id", &id); + match n.attributes().find(|a| a.name() == "id" && a.namespace().is_none()) { + Some(a) => self.id_edits.push((a.range_value(), id.clone())), + None => { + let at = tag_name_end(svg, n); + self.id_edits.push((at..at, format!(" id=\"{id}\""))); + } + } self.ids.insert(n.id(), id.clone()); id } @@ -98,6 +110,7 @@ impl Edits { /// `svg` with the edits made; overlapping ones and ranges off character boundaries are /// skipped. fn apply(mut self, svg: &str) -> Cow<'_, str> { + self.list.append(&mut self.id_edits); for (at, has_style, decls) in std::mem::take(&mut self.styles).into_values() { self.insert(at, if has_style { decls } else { format!(" style=\"{}\"", decls.strip_prefix(';').unwrap_or(&decls)) }); } @@ -157,7 +170,12 @@ fn named_made_up_ids(xml: &roxmltree::Document) -> HashSet { /// Whether each is there at all is read from `markers`: `svg` with its data URLs left out /// ([`depth::prescan`]), so an embedded picture isn't searched a dozen times. The edits are made /// in `svg` itself. -pub(super) fn prepass<'s>(svg: &'s str, markers: &str, xml: &roxmltree::Document, opts: &ImportOptions) -> (Cow<'s, str>, Found) { +pub(super) fn prepass<'s>( + svg: &'s str, + markers: &str, + xml: &roxmltree::Document, + opts: &ImportOptions, +) -> Result<(Cow<'s, str>, Found), crate::SvgError> { let mut found = Found::default(); // (`:` for prefixed elements such as ``.) let css_transform = has_css_transform(markers); @@ -176,7 +194,7 @@ pub(super) fn prepass<'s>(svg: &'s str, markers: &str, xml: &roxmltree::Document .iter() .any(|t| markers.contains(t)) { - return (svg.into(), found); + return Ok((svg.into(), found)); } let mut edits = Edits::default(); let elements = || xml.descendants().filter(|n| n.is_element()); @@ -245,7 +263,14 @@ pub(super) fn prepass<'s>(svg: &'s str, markers: &str, xml: &roxmltree::Document if css_transform { edits.list.extend(css_transform::rewrites(svg, xml)); } - (edits.apply(svg), found) + if attribute_selectors && !edits.ids.is_empty() { + if elements().any(|n| matches!(n.tag_name().name(), "text" | "flowRoot")) { + let text_edits = Edits { list: edits.list.clone(), styles: edits.styles.clone(), ..Default::default() }; + found.text_source = Some(text_edits.apply(svg).into_owned()); + } + id_styles::preserve_matches(svg, xml, &mut edits)?; + } + Ok((edits.apply(svg), found)) } /// Is there a `transform` CSS declaration in `markers` (`transform` followed by `:`)? diff --git a/crates/svg/src/import/prepass/id_styles.rs b/crates/svg/src/import/prepass/id_styles.rs new file mode 100644 index 0000000000..7804dfa4da --- /dev/null +++ b/crates/svg/src/import/prepass/id_styles.rs @@ -0,0 +1,113 @@ +use super::{Edits, XNode, css_transform, roxmltree}; +use crate::SvgError; + +struct Element<'a, 'input>(XNode<'a, 'input>); + +impl simplecss::Element for Element<'_, '_> { + fn parent_element(&self) -> Option { + self.0.parent_element().map(Self) + } + + fn prev_sibling_element(&self) -> Option { + self.0.prev_sibling_element().map(Self) + } + + fn has_local_name(&self, name: &str) -> bool { + self.0.tag_name().name() == name + } + + fn attribute_matches(&self, name: &str, operator: simplecss::AttributeOperator<'_>) -> bool { + self.0.attribute(name).is_some_and(|value| operator.matches(value)) + } + + fn pseudo_class_matches(&self, class: simplecss::PseudoClass<'_>) -> bool { + matches!(class, simplecss::PseudoClass::FirstChild) && self.0.prev_sibling_element().is_none() + } +} + +fn append(out: &mut String, declaration: &simplecss::Declaration<'_>, remaining: &mut usize) -> Result<(), SvgError> { + let transform = if declaration.name == "transform" { css_transform::to_svg(declaration.value) } else { None }; + let value = transform.as_deref().unwrap_or(declaration.value); + let important = if declaration.important { "!important" } else { "" }; + let text = crate::xml_escape(&format!("{}:{value}{important};", declaration.name)); + *remaining = remaining.checked_sub(text.len()).ok_or_else(|| SvgError::TooBig("expanded SVG styles exceed the import size limit".into()))?; + out.push_str(&text); + Ok(()) +} + +pub(super) fn preserve_matches(svg: &str, xml: &roxmltree::Document, edits: &mut Edits) -> Result<(), SvgError> { + preserve_with_limit(svg, xml, edits, usize::try_from(crate::MAX_SVGZ).unwrap_or(usize::MAX)) +} + +fn preserve_with_limit(svg: &str, xml: &roxmltree::Document, edits: &mut Edits, mut remaining: usize) -> Result<(), SvgError> { + let styles: Vec<_> = xml.descendants().filter(|n| n.has_tag_name("style") && n.attribute("type").is_none_or(|t| t == "text/css")).collect(); + let texts: Vec = styles.iter().map(|n| n.children().filter(XNode::is_text).filter_map(|n| n.text()).collect()).collect(); + let mut sheet = simplecss::StyleSheet::new(); + for text in &texts { + sheet.parse_more(text); + } + let element_count = xml.descendants().filter(XNode::is_element).count(); + if element_count.checked_mul(sheet.rules.len()).is_none_or(|work| work > 1_000_000) { + return Err(SvgError::TooBig("SVG stylesheet matching exceeds the import work limit".into())); + } + for node in xml.descendants().filter(XNode::is_element) { + let mut declarations = String::new(); + for rule in sheet.rules.iter().filter(|r| r.selector.matches(&Element(node))) { + for declaration in &rule.declarations { + append(&mut declarations, declaration, &mut remaining)?; + } + } + if declarations.is_empty() { + continue; + } + for declaration in simplecss::DeclarationTokenizer::from(node.attribute("style").unwrap_or_default()) { + append(&mut declarations, &declaration, &mut remaining)?; + } + if let Some((_, _, previous)) = edits.styles.remove(&node.id()) { + declarations.push_str(&previous); + } + if let Some(attribute) = node.attributes().find(|a| a.name() == "style" && a.namespace().is_none()) { + edits.list.push((attribute.range_value(), declarations)); + } else { + edits.style(svg, node, &declarations); + } + } + for style in styles { + edits.list.extend(style.children().map(|child| (child.range(), String::new()))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expanded_styles_are_bounded() { + let svg = r#""#; + let xml = roxmltree::Document::parse(svg).unwrap(); + assert!(matches!(preserve_with_limit(svg, &xml, &mut Edits::default(), 1), Err(SvgError::TooBig(_)))); + assert!(preserve_with_limit(svg, &xml, &mut Edits::default(), 64).is_ok()); + } + + #[test] + fn selector_matching_is_bounded_even_without_matches() { + let rules = "circle[missing]{fill:red}".repeat(1001); + let elements = "".repeat(1000); + let svg = format!(r#"{elements}"#); + let xml = roxmltree::Document::parse(&svg).unwrap(); + assert!(matches!(preserve_matches(&svg, &xml, &mut Edits::default()), Err(SvgError::TooBig(_)))); + } + + #[test] + fn stylesheet_text_after_comments_is_preserved() { + let svg = r#"x"#; + let xml = roxmltree::Document::parse(svg).unwrap(); + let mut edits = Edits::default(); + preserve_matches(svg, &xml, &mut edits).unwrap(); + let output = edits.apply(svg); + let xml = roxmltree::Document::parse(&output).unwrap(); + let text = xml.descendants().find(|n| n.has_tag_name("text")).unwrap(); + assert_eq!(text.attribute("style"), Some("font-size:30px;")); + } +} diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 0e26fc5249..57a156b82e 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -188,17 +188,30 @@ impl TextSlots { } /// Replace every `` usvg would draw by a placeholder group (see the module docs). -pub(super) fn prepare<'s>(svg: &'s str, xml: &roxmltree::Document, dpi: f64, warnings: &mut Vec) -> (Cow<'s, str>, TextSlots) { +/// `original_xml` supplies text styles; `xml` supplies placeholder positions and tracking IDs. +pub(super) fn prepare<'s>( + svg: &'s str, + xml: &roxmltree::Document, + original_xml: Option<&roxmltree::Document>, + dpi: f64, + warnings: &mut Vec, +) -> (Cow<'s, str>, TextSlots) { let mut prefix = String::from("vectorcraft-text-"); while xml.descendants().any(|n| n.attribute("id").is_some_and(|id| id.starts_with(&prefix))) { prefix.insert(0, '_'); } let mut slots = TextSlots { prefix, texts: vec![] }; - let cx = Ctx::new(xml, dpi); + let style_xml = original_xml.unwrap_or(xml); + let cx = Ctx::new(style_xml, dpi); let mut out = String::new(); let mut copied = 0; - let is_text = |n: &XNode| n.is_element() && matches!(n.tag_name().name(), "text" | "flowRoot") && n.tag_name().namespace() == Some(SVG_NS); - for t in xml.descendants().filter(is_text) { + let is_text = |n: &XNode| { + n.is_element() + && matches!(n.tag_name().name(), "text" | "flowRoot") + && n.tag_name().namespace() == Some(SVG_NS) + && !n.ancestors().any(|a| a.has_tag_name("style")) + }; + for (t, style_t) in xml.descendants().filter(is_text).zip(style_xml.descendants().filter(is_text)) { let label = t.attribute("id").map_or_else(|| "a text".to_string(), |id| format!("text '{id}'")); if t.ancestors().skip(1).any(|a| a.is_element() && a.tag_name().name() == "clipPath") { warnings.push(format!("{label} in a clip path ignored")); @@ -216,13 +229,13 @@ pub(super) fn prepare<'s>(svg: &'s str, xml: &roxmltree::Document, dpi: f64, war }; let flowed = t.tag_name().name() == "flowRoot"; let Some(q) = qname.strip_suffix(t.tag_name().name()).filter(|q| q.is_empty() || q.ends_with(':')) else { continue }; - if cx.css.own(t, "display").as_deref() == Some("none") || r.start < copied { + if cx.css.own(style_t, "display").as_deref() == Some("none") || r.start < copied { continue; } - let built = if flowed { cx.build_flow(t, &label, warnings) } else { cx.build(xml, t, &label, warnings) }; + let built = if flowed { cx.build_flow(style_t, &label, warnings) } else { cx.build(style_xml, style_t, &label, warnings) }; let Some((text, paints)) = built else { continue }; out.push_str(&svg[copied..r.start]); - placeholder(&mut out, q, &cx.css, t, &slots.prefix, slots.texts.len(), text.marker, &paints); + placeholder(&mut out, q, &cx.css, t, style_t, &slots.prefix, slots.texts.len(), text.marker, &paints); copied = r.end; slots.texts.push(text); } @@ -235,7 +248,7 @@ pub(super) fn prepare<'s>(svg: &'s str, xml: &roxmltree::Document, dpi: f64, war /// Write the placeholder group for text `t` (namespace prefix `q`), slot `index`. #[allow(clippy::too_many_arguments)] -fn placeholder(out: &mut String, q: &str, css: &Styles, t: XNode, prefix: &str, index: usize, b: Rect, paints: &[String]) { +fn placeholder(out: &mut String, q: &str, css: &Styles, t: XNode, style_t: XNode, prefix: &str, index: usize, b: Rect, paints: &[String]) { let _ = write!(out, "<{q}g"); for a in ["id", "transform", "systemLanguage", "requiredFeatures", "requiredExtensions"] { if let Some(v) = t.attribute(a) { @@ -247,9 +260,9 @@ fn placeholder(out: &mut String, q: &str, css: &Styles, t: XNode, prefix: &str, for (p, initial) in [("opacity", "1"), ("clip-path", "none"), ("mask", "none"), ("filter", "none"), ("mix-blend-mode", "normal"), ("isolation", "auto")] { - let _ = write!(style, "{p}:{};", css.own(t, p).as_deref().unwrap_or(initial)); + let _ = write!(style, "{p}:{};", css.own(style_t, p).as_deref().unwrap_or(initial)); } - if let Some(v) = css.own(t, "visibility") { + if let Some(v) = css.own(style_t, "visibility") { let _ = write!(style, "visibility:{v};"); } let _ = write!(out, " style=\"{}display:inline\">", xml_escape(&style)); diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index dbac48947e..b4dd58256d 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -37,6 +37,58 @@ fn decoded_id_selectors_do_not_recolor_bare_ellipses() { } } +#[test] +fn metadata_ids_preserve_attribute_selector_colors_and_metadata() { + for attrs in [r#"data-foo="kept""#, r#"xmlns:meta="https://example.org/metadata" meta:key="kept""#, r#"onclick="kept""#] { + let source = svg(&format!( + r#""# + )); + let doc = import(&source).unwrap(); + let actual = render_artboard(&doc); + let expected = resvg_render(&source, 200, 120); + for (x, y) in [(40, 50), (100, 50)] { + let at = 4 * (y * actual.width + x) as usize; + assert_eq!(&actual.rgba[at..at + 4], &expected.rgba[at..at + 4], "{attrs}: ({x}, {y})"); + } + let has_metadata = |doc: &Document| { + art(doc) + .into_iter() + .filter(|n| { + n.extras().attrs.as_deref().is_some_and(|a| { + a.data.iter().any(|(k, v)| k == "foo" && v == "kept") + || a.foreign.iter().any(|a| a.ns == "https://example.org/metadata" && a.name == "key" && a.value == "kept") + || a.events.iter().any(|(k, v)| k == "onclick" && v == "kept") + }) + }) + .count() + }; + assert_eq!(has_metadata(&doc), 2, "{attrs}"); + let back = import(&export(&doc, &ExportOptions::default())).unwrap(); + assert_eq!(has_metadata(&back), 2, "round trip: {attrs}"); + } +} + +#[test] +fn metadata_id_styles_keep_the_original_cascade_and_structure() { + for body in [ + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + ] { + let source = svg(body); + let actual = render_artboard(&import(&source).unwrap()); + let expected = resvg_render(&source, 200, 120); + for (x, y) in [(40, 50), (100, 50)] { + let at = 4 * (y * actual.width + x) as usize; + assert_eq!(&actual.rgba[at..at + 4], &expected.rgba[at..at + 4], "{body}: ({x}, {y})"); + } + } +} + /// All non-layer nodes in paint order. fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index f688e60e32..5fa2b5d7f2 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -51,6 +51,46 @@ fn close(a: f64, b: f64, tol: f64) -> bool { (a - b).abs() < tol } +#[test] +fn metadata_ids_preserve_the_original_text_cascade() { + for (rules, text, color) in [ + ("text:not(.x){fill:red!important} text{fill:blue!important}", r#"Hi"#, (255, 0, 0)), + ("#t{fill:blue} [id]{fill:red}", r#"Hi"#, (0, 0, 255)), + ("#holder{fill:blue} g[id]{fill:red}", r#"Hi"#, (0, 0, 255)), + ] { + for metadata in [false, true] { + let attribute = if metadata { r#" data-note="kept""# } else { "" }; + let doc = open(&format!(r#"{text}"#)); + let expected = Paint::solid(vectorcraft_color::Color::rgb8(color.0, color.1, color.2)); + assert_eq!(only_text(&doc).runs[0].style.fill, expected, "{rules}, metadata {metadata}"); + } + } +} + +#[test] +fn metadata_ids_preserve_text_preprocessing_and_relative_styles() { + for body in [ + r#"AB"#, + r#"Hidden"#, + r#"Moved"#, + r##"Path"##, + ] { + let load = |attribute: &str| { + let doc = open(&format!(r#"{body}"#)); + art(&doc) + .into_iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((n.visible, serde_json::to_value(t).unwrap())), + _ => None, + }) + .collect::>() + }; + let expected = load(""); + assert!(!expected.is_empty(), "{body}"); + assert_eq!(load(r#" data-note="kept""#), expected, "{body}"); + } +} + #[test] fn text_keeps_its_z_order_between_shapes() { let d = open(r#"Hi"#); From 96330fb54e9e45d0cb2c1d6651652b7b0a98c1c0 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 21:11:13 +0700 Subject: [PATCH 383/674] SVG import: a style sheet too large to match opens with a warning; fuzz reaches the pass --- crates/engine/tests/import_fuzz.rs | 4 +++- crates/svg/src/import/prepass.rs | 2 +- crates/svg/src/import/prepass/id_styles.rs | 27 +++++++++++++++------- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 5b858b5f78..095d0ec146 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -648,6 +648,8 @@ proptest! { survive(&svg, || vectorcraft_svg::import(&svg).ok())?; } + /// The linked `` gets an id from the importer, so attribute selectors in `sheet` reach the + /// pass that copies style sheet matches into the elements' styles. #[test] fn svg_hostile_css_never_panics( sheet in r#"[a-z#.>*\[\]=:;{}@ !"'/,-]{0,160}"#, @@ -655,7 +657,7 @@ proptest! { body in prop::collection::vec(arb_svg_element(1), 0..3), ) { let svg = format!( - "abc{}", + "abc{}", body.concat() ); survive(&svg, || vectorcraft_svg::import(&svg).ok())?; diff --git a/crates/svg/src/import/prepass.rs b/crates/svg/src/import/prepass.rs index f02f436cdb..3f52c4e35f 100644 --- a/crates/svg/src/import/prepass.rs +++ b/crates/svg/src/import/prepass.rs @@ -268,7 +268,7 @@ pub(super) fn prepass<'s>( let text_edits = Edits { list: edits.list.clone(), styles: edits.styles.clone(), ..Default::default() }; found.text_source = Some(text_edits.apply(svg).into_owned()); } - id_styles::preserve_matches(svg, xml, &mut edits)?; + id_styles::preserve_matches(svg, xml, &mut edits, &mut found.warnings)?; } Ok((edits.apply(svg), found)) } diff --git a/crates/svg/src/import/prepass/id_styles.rs b/crates/svg/src/import/prepass/id_styles.rs index 7804dfa4da..217c56ab9d 100644 --- a/crates/svg/src/import/prepass/id_styles.rs +++ b/crates/svg/src/import/prepass/id_styles.rs @@ -35,11 +35,17 @@ fn append(out: &mut String, declaration: &simplecss::Declaration<'_>, remaining: Ok(()) } -pub(super) fn preserve_matches(svg: &str, xml: &roxmltree::Document, edits: &mut Edits) -> Result<(), SvgError> { - preserve_with_limit(svg, xml, edits, usize::try_from(crate::MAX_SVGZ).unwrap_or(usize::MAX)) +pub(super) fn preserve_matches(svg: &str, xml: &roxmltree::Document, edits: &mut Edits, warnings: &mut Vec) -> Result<(), SvgError> { + preserve_with_limit(svg, xml, edits, warnings, usize::try_from(crate::MAX_SVGZ).unwrap_or(usize::MAX)) } -fn preserve_with_limit(svg: &str, xml: &roxmltree::Document, edits: &mut Edits, mut remaining: usize) -> Result<(), SvgError> { +fn preserve_with_limit( + svg: &str, + xml: &roxmltree::Document, + edits: &mut Edits, + warnings: &mut Vec, + mut remaining: usize, +) -> Result<(), SvgError> { let styles: Vec<_> = xml.descendants().filter(|n| n.has_tag_name("style") && n.attribute("type").is_none_or(|t| t == "text/css")).collect(); let texts: Vec = styles.iter().map(|n| n.children().filter(XNode::is_text).filter_map(|n| n.text()).collect()).collect(); let mut sheet = simplecss::StyleSheet::new(); @@ -47,8 +53,10 @@ fn preserve_with_limit(svg: &str, xml: &roxmltree::Document, edits: &mut Edits, sheet.parse_more(text); } let element_count = xml.descendants().filter(XNode::is_element).count(); + // Too much matching: the file opens without this pass (nothing is edited yet), as it did before it. if element_count.checked_mul(sheet.rules.len()).is_none_or(|work| work > 1_000_000) { - return Err(SvgError::TooBig("SVG stylesheet matching exceeds the import work limit".into())); + warnings.push("the style sheet is too large to match against every element: attribute selectors may not apply to linked objects".into()); + return Ok(()); } for node in xml.descendants().filter(XNode::is_element) { let mut declarations = String::new(); @@ -86,8 +94,8 @@ mod tests { fn expanded_styles_are_bounded() { let svg = r#""#; let xml = roxmltree::Document::parse(svg).unwrap(); - assert!(matches!(preserve_with_limit(svg, &xml, &mut Edits::default(), 1), Err(SvgError::TooBig(_)))); - assert!(preserve_with_limit(svg, &xml, &mut Edits::default(), 64).is_ok()); + assert!(matches!(preserve_with_limit(svg, &xml, &mut Edits::default(), &mut vec![], 1), Err(SvgError::TooBig(_)))); + assert!(preserve_with_limit(svg, &xml, &mut Edits::default(), &mut vec![], 64).is_ok()); } #[test] @@ -96,7 +104,10 @@ mod tests { let elements = "".repeat(1000); let svg = format!(r#"{elements}"#); let xml = roxmltree::Document::parse(&svg).unwrap(); - assert!(matches!(preserve_matches(&svg, &xml, &mut Edits::default()), Err(SvgError::TooBig(_)))); + let (mut edits, mut warnings) = (Edits::default(), vec![]); + assert!(preserve_matches(&svg, &xml, &mut edits, &mut warnings).is_ok(), "the file still opens"); + assert!(edits.list.is_empty() && edits.styles.is_empty(), "nothing is edited"); + assert_eq!(warnings.len(), 1, "{warnings:?}"); } #[test] @@ -104,7 +115,7 @@ mod tests { let svg = r#"x"#; let xml = roxmltree::Document::parse(svg).unwrap(); let mut edits = Edits::default(); - preserve_matches(svg, &xml, &mut edits).unwrap(); + preserve_matches(svg, &xml, &mut edits, &mut vec![]).unwrap(); let output = edits.apply(svg); let xml = roxmltree::Document::parse(&output).unwrap(); let text = xml.descendants().find(|n| n.has_tag_name("text")).unwrap(); From 2b63bf1b67c648823b9ca9d3d515ab9e331f4226 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 06:13:40 -0800 Subject: [PATCH 384/674] Type: keep composition spacing along the line when characters rotate --- crates/text/src/layout.rs | 10 ++--- crates/text/src/layout/wrapping_tests.rs | 50 ++++++++++++++++++++++++ crates/text/src/lib.rs | 2 +- crates/text/src/tests/typo.rs | 22 +++++++++++ docs/roadmap.md | 2 + docs/target-app-parity.md | 3 ++ 6 files changed, 83 insertions(+), 6 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index cbdd41725c..6697776876 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -285,21 +285,21 @@ impl Ctx<'_> { Some(ib) => Affine::translate((g.kern_shift - lead, -g.bshift)) * ib.xf, // Baseline shift moves the glyph across its line, and Character Rotation then turns it // about its shifted pen position, so the shift is across the line at any rotation. - // Right-to-left manual kerning moves that pen position along the line. + // Manual kerning and composition trim move that pen position along the line. None => { - Affine::translate((g.kern_shift, -g.bshift)) + Affine::translate((g.kern_shift - lead, -g.bshift)) * Affine::rotate(-g.rotation.to_radians()) - * Affine::translate((g.dx - lead, g.dy)) + * Affine::translate((g.dx, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy) } }; // The turning point in font units, which later moves of the glyph's transform keep. let pivot = match local.determinant() { - det if det != 0.0 && det.is_finite() => local.inverse() * Point::new(g.kern_shift, -g.bshift), + det if det != 0.0 && det.is_finite() => local.inverse() * Point::new(g.kern_shift - lead, -g.bshift), _ => Point::ZERO, }; let unturned = if g.inline.is_none() && g.rotation != 0.0 && g.sx != 0.0 && g.sy != 0.0 { - let placed = Affine::translate((g.dx - lead, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy); + let placed = Affine::translate((g.dx, g.dy)) * Affine::scale_non_uniform(g.sx, g.sy); placed.inverse() * Affine::rotate(g.rotation.to_radians()) * placed } else { Affine::IDENTITY diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 2e036c3cf9..9f1a048b38 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -49,6 +49,56 @@ fn source_range(glyphs: &[SGlyph], start: usize, end: usize) -> Range { first.byte..last.byte + last.len } +#[test] +fn composition_trim_stays_along_the_line_when_a_character_rotates() { + let db = FontDb::with_font_dirs(vec![]); + let style = CharStyle::default(); + let opts = LayoutOptions::default(); + for angle in [0.0_f64, std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_2] { + let origin = Point::new(100.0, 80.0); + let pre = Affine::translate(origin.to_vec2()) * Affine::rotate(angle); + let draw = |rotation: f64, lead: f64| { + let mut glyph = synthetic_glyphs(&[(0, 1, 30.0, 'A')]).remove(0); + glyph.sx = 0.02; + glyph.sy = 0.02; + glyph.dx = 2.0; + glyph.dy = -1.0; + glyph.bshift = 4.0; + glyph.kern_shift = 3.0; + glyph.rotation = rotation; + glyph.lead = lead; + let mut cx = Ctx { + on_path: angle != 0.0, + db: &db, + text: "A", + runs: vec![(0..1, &style)], + inlines: vec![None], + default: style.clone(), + opts: &opts, + vertical: false, + system_layout: false, + fractional_widths: true, + upright_cluster: None, + out: TextLayout::default(), + }; + cx.emit(&glyph, pre, origin, angle, 30.0 - lead, 0); + cx.out.glyphs.remove(0) + }; + let expected = Vec2::new(-angle.cos(), -angle.sin()) * 5.0; + for rotation in [0.0, 45.0, 90.0, -90.0] { + let (plain, trimmed) = (draw(rotation, 0.0), draw(rotation, 5.0)); + assert!(!trimmed.outline.elements().is_empty(), "fixture has drawn geometry"); + let shift = trimmed.xf * Point::ZERO - plain.xf * Point::ZERO; + assert!((shift - expected).hypot() < 1e-9, "line {angle}, character {rotation}: {shift:?} versus {expected:?}"); + let pivot_shift = trimmed.xf * trimmed.pivot - plain.xf * plain.pivot; + assert!((pivot_shift - expected).hypot() < 1e-9, "composition moves the turning point along the line: {pivot_shift:?}"); + let unrotated = draw(0.0, 5.0); + let actual = (trimmed.xf * trimmed.unturned).as_coeffs(); + assert!(actual.iter().zip(unrotated.xf.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "removing rotation keeps composition placement"); + } + } +} + #[test] fn greedy_wrap_keeps_an_oversized_first_cluster_and_its_source_range() { let text = "بَت"; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index bafaf70af0..1d32036076 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -147,7 +147,7 @@ pub struct PositionedGlyph { /// its Character Rotation. The identity for a glyph without one. pub unturned: Affine, /// Font units: `xf * pivot` is the point its Character Rotation turns it about, its pen - /// position on the baseline moved by its baseline shift. + /// position after composition spacing adjustments, moved by its baseline shift. pub pivot: Point, /// A ligature (one glyph that alone stands for several characters, grapheme clusters, of the /// text): the caret stop between each two of them, in logical order, as the byte offset of the diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 2627b81eef..092ed4c09f 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1729,6 +1729,28 @@ fn proportional_metrics_set_full_width_glyphs_on_their_proportional_widths() { assert!((moved - 10.0).abs() < 0.01, "〙's empty half goes past the line's end: あ moved {moved}"); } +#[test] +fn mojikumi_trim_keeps_a_rotated_opening_bracket_on_its_line() { + use vectorcraft_doc::Mojikumi; + if db().face("Shippori Mincho", "Regular").is_none_or(|f| f.family != "Shippori Mincho") { + eprintln!("skipped: Shippori Mincho is not in CRAFT_FONTS_DIR"); + return; + } + let lay = |rotation, mojikumi| { + let st = CharStyle { font_family: "Shippori Mincho".into(), size: 20.0, rotation, ..Default::default() }; + let mut t = area("「あ", st, Rect::new(0.0, 0.0, 200.0, 200.0), Justify::Left); + t.para.mojikumi = mojikumi; + layout(db(), &t) + }; + for rotation in [0.0, 45.0, 90.0, -90.0] { + let (plain, trimmed) = (lay(rotation, Mojikumi::None), lay(rotation, Mojikumi::LineEndHalf)); + let (a, b) = (&plain.glyphs[0], &trimmed.glyphs[0]); + assert!((a.advance - 20.0).abs() < 0.01 && (b.advance - 10.0).abs() < 0.01, "full-width bracket fixture"); + let shift = b.xf * Point::ZERO - a.xf * Point::ZERO; + assert!((shift.x + 10.0).abs() < 0.01 && shift.y.abs() < 0.01, "{rotation} degrees: {shift:?}"); + } +} + /// The arrows pass a Thai consonant with its vowel and tone marks whole (น้ำ: no, mai tho, sara am), /// as an accented letter written with a combining mark; plain text moves a character at a time. #[test] diff --git a/docs/roadmap.md b/docs/roadmap.md index 6693278439..a0d6c74734 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -26,6 +26,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-10-30 | minor | M4: File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; scores and estimates unchanged. | | 2026-11-03 | minor | M7: Find Font replacement sources Document, Recent and System are shipped (#5217); estimates unchanged. | | 2026-10-30 | minor | Raster effects: bounded length fields in effect dialogs clamp on commit and reject invalid inputs visibly (#4638); estimates unchanged. | +| 2026-11-03 | minor | M7: composition spacing remains along the line when characters rotate; estimates unchanged. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile subsequent upstream progress updates without changing the runtime or repeating completed evidence; retain every dated upstream and feature revision. | @@ -153,6 +154,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-11-03 | minor | M7 records Find Font's shipped replacement-source chooser (#5217); estimates unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-10-30 | patch | M5: opaque solid-fill knockout paths avoid redundant erase/add layers in hard-edge frames and supersampled raster export; exact-pixel regression coverage retains analytical-AA rounding and translucent knockout behavior; scores and estimates unchanged | +| 2026-11-03 | minor | M7: retain composition trimming in rotated character placement and rotation metadata; estimates unchanged. | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: File formats: `.ai`/EPS editing-data fidelity from an audit of a user's files: All Caps and Small Caps (#4708); placed files at their box's corner, kept where they draw closer to the page (#4664, #4723, #4742); pages cropped to the art, with `UserUnit` (#4658, #4727); gradient mesh corners with handle weights of 0 and the state written after a mesh (#4738, #4744, #4748); type on a path spaced as the file lays it out (#4743); synthetic regressions in `crates/eps`; scores and estimates unchanged. | | 2026-10-29 | minor | M6: Pathfinder: live compound shapes (#4522): the panel menu's Make, Release and Expand Compound Shape, Alt-clicking a Shape Mode, a selected member's Shape Mode and the Expand button act; scores unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 043e460178..537062829e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -29,6 +29,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-10-31 | minor | Object › Path › Smooth smooths a path along its length before refitting it, so Auto-Smooth takes a shaky line to one smooth curve instead of leaving its jags, and with anchor points direct-selected it smooths only that section; scores unchanged. | | 2026-10-31 | minor | New Document: More Settings has the Save Preset button beside the name too, saving its settings (artboard layout included) as a preset (#4893); scores unchanged. | | 2026-10-31 | minor | Object › Rasterize in a CMYK document with its CMYK colour model makes a CMYK image of the art's ink amounts (as CMYK exports draw them), so the Properties panel says CMYK and CMYK exports keep its inks; a transparent background becomes the image's opacity mask (#4882); scores unchanged. | +| 2026-11-03 | minor | Composition spacing stays along the line under Character Rotation, including the turning point and unrotated placement; scores and estimates unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as Illustrator's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Export for Screens is laid out as the reference app's: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix under them, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File or Multiple Files (`pdfs`), iOS and Android rows, the format presets in a ☰ menu, and a Selected / files-to-export count; the naming pattern, Layers and Selection pages and folders list stay in `document.exportForScreens` for scripts and MCP; scores unchanged. | | 2026-10-31 | minor | Artwork Cleanup add-on: Join Point Text (`addon.cleanup.joinText`) joins stacked one-line point type into one object, a paragraph per line keeping its baseline (#4826); scores unchanged. | @@ -774,6 +775,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Inside a ligature (one glyph for several characters, such as fi), the Type tool's caret, clicks, arrow keys and selection stop between its characters, at the font's ligature carets ([OpenType GDEF ligature caret list](https://learn.microsoft.com/en-us/typography/opentype/spec/gdef)) or, when the font does not list one valid caret for each stop, at the glyph's width divided equally. Duplicate Artboards, the Artboard tool's Alt-drag and Paste give the new artboard an id that no other artboard has, also when an artboard's id is the largest possible value (#1718). Deleting the copy or the original then leaves the other's guides. - **Touch Type:** a click with the Touch Type tool (Shift+T) selects one character and shows a box around it. Dragging the box or its lower-left handle moves the character. The upper-left handle scales it vertically, the lower-right handle scales it horizontally, the upper-right handle scales it proportionally, and the upper-middle handle rotates it. Each drag is one undo step that sets the character's kerning, baseline shift, scales or rotation, and the type stays editable (`text.touchType`; behavior reference: [Touch Type tool](https://web.archive.org/web/20261007185617/https://helpx.adobe.com/illustrator/using/tool-techniques/touch-type-tool.html), [Add text with the Type, Area Type, and Touch Type tools](https://web.archive.org/web/20260926095922/https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-text-illustrator-text-tools.html)). + Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. @@ -1563,6 +1565,7 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente | 2026-11-03 | minor | SVG imports preserve exported ellipses as four-anchor paths (#5243). Inline graphics use manual kerning (#5245). Symbol editing shows draggable 9-slice guides (#5280). Recolor Artwork offers smooth and segmented wheels and color bars (#5249). Scores and hours remain unchanged. | | 2026-11-01 | minor | Repeat: a double-click isolates it to edit its source art, text included (#5054); evidence added; scores unchanged. | | 2026-11-01 | minor | Live Corners: Up/Down while dragging a corner widget step the corner kind (#2898); evidence added; scores unchanged. | +| 2026-11-03 | minor | Rotated characters retain line-axis composition trimming; scores and estimates unchanged. | | 2026-11-01 | minor | Shortcuts for Effect menu items (#3296); evidence added; scores unchanged. | | 2026-11-01 | minor | Color Effects add-on (a VectorCraft addition): Find Nearest Swatch (#4923); evidence added; scores unchanged. | | 2026-11-01 | minor | Create Swatch Legend add-on under Object › Plug-ins › Color Effects (`addon.color.swatchLegend`, #4919); evidence added; scores unchanged. | From 2264edd0c9853b6e308ce8432e3a16e800a2c474 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:35:42 +0100 Subject: [PATCH 385/674] Lasso picks gradient mesh points instead of dropping the mesh Fixes #5351 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/paint.rs | 4 +- crates/engine/src/tests/xform.rs | 21 ++++++++++ crates/tools/src/meshedit.rs | 21 ++++++++++ crates/tools/src/xform/wand.rs | 71 +++++++++++++++++++++++++++++--- docs/mcp.md | 3 +- 5 files changed, 112 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index ec59e4e9e5..e53b9b8f3a 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -697,8 +697,8 @@ fn black_or_white(c: &Color) -> bool { } } -/// The points the active tool has picked (its `meshPoints` option: the Mesh tool's or Direct -/// Selection's) on the gradient meshes among `ids`, in range, each mesh with its points. +/// The points the active tool has picked (its `meshPoints` option: the Mesh tool's, Direct +/// Selection's or the Lasso's) on the gradient meshes among `ids`, in range, each mesh with its points. fn picked_mesh_points(s: &Session, ids: &[NodeId]) -> Vec<(NodeId, Vec)> { let o = s.tool_options(); let (Some(picked), Ok(st)) = (o.get("meshPoints").and_then(Value::as_array), s.doc()) else { return vec![] }; diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index eb503cce98..5dfd7ca09b 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -976,6 +976,27 @@ fn lasso_selects_anchor_subset() { assert_eq!(st.selection.partial(a).map(|p| p.len()), Some(2)); } +/// #5351: a Lasso loop round a gradient mesh's points keeps the mesh selected and picks the +/// points inside it, so a solid fill colour recolours just those points. +#[test] +fn lasso_picks_gradient_mesh_points() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + // Round the top row of points (100,100), (150,100) and (200,100). + gesture(&mut s, "lasso", &[(90.0, 90.0), (210.0, 90.0), (210.0, 110.0), (90.0, 110.0), (90.0, 110.0)], Mods::default()); + let st = s.doc().unwrap(); + let Some(NodeKind::Mesh(m)) = st.doc.node(a).map(|n| &n.kind) else { panic!("still a gradient mesh") }; + assert_eq!(m.points.len(), 9); + assert_eq!(st.selection.objects, vec![a], "the mesh stays selected"); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(a).map(|n| &n.kind) else { panic!("still a gradient mesh") }; + let red: Vec = (0..m.points.len()).filter(|i| m.points[*i].color.to_hex() == "#ff0000").collect(); + let top: Vec = (0..3).map(|c| m.idx(0, c)).collect(); + assert_eq!(red, top, "only the points inside the loop are recoloured"); +} + /// Shift-drag a marquee with the Selection tool (#483): the selected objects it reaches are /// deselected and the others selected, the rest of the selection staying as it was. #[test] diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index e0ef779fb5..c0c1d96231 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -257,6 +257,27 @@ impl MeshEdit { meshes.into_iter().map(|id| (id, self.picked.range((id, 0)..=(id, usize::MAX)).next().is_some())).collect() } + /// A Lasso's picks: the points `inside` it are picked alone, or added to the picked points + /// (`add`), or taken away from them (`sub`). Returns each mesh with points inside and whether + /// any of its points are picked now. + pub fn lasso(&mut self, inside: &[(NodeId, usize)], add: bool, sub: bool) -> Vec<(NodeId, bool)> { + if !add && !sub { + return self.marquee(inside, false); + } + for k in inside { + if sub { + self.picked.remove(k); + } else { + self.picked.insert(*k); + } + } + self.click = None; + self.focus = self.focus.filter(|f| self.picked.contains(f)); + let mut meshes: Vec = inside.iter().map(|(id, _)| *id).collect(); + meshes.dedup(); + meshes.into_iter().map(|id| (id, self.picked.range((id, 0)..=(id, usize::MAX)).next().is_some())).collect() + } + /// An arrow key's nudge of the picked points of the meshes `shown` accepts /// (`object.mesh.movePoints`); `None` during a drag, for other keys or without picked points. pub fn nudge(&self, cx: &ToolContext, key: ToolKey, mods: Mods, shown: &dyn Fn(NodeId) -> bool) -> Option> { diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index 530c9302d5..41f42718a7 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -3,7 +3,8 @@ //! Magic Wand: click an object to select every object with similar attributes. The matching and //! its settings (Magic Wand panel) live in the engine's `select.magicWand` command; Shift adds, //! Alt subtracts. Lasso: freehand loop selecting anchor points inside it (direct-selection -//! style); Shift adds, Alt subtracts. +//! style), and picking the gradient mesh points inside it with their meshes selected (the +//! tool's `meshPoints` option, which a solid fill colour recolours); Shift adds, Alt subtracts. use std::collections::BTreeSet; @@ -13,6 +14,7 @@ use vectorcraft_doc::{AnchorRef, NodeId, NodeKind}; use vectorcraft_geom::Point; use super::paint_owner; +use crate::meshedit::{MeshEdit, grid_of}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Default)] @@ -67,6 +69,8 @@ pub fn point_in_polygon(poly: &[Point], p: Point) -> bool { pub struct LassoTool { points: Vec, active: bool, + /// The picked gradient mesh points. + mesh: MeshEdit, } fn anchors_json(v: &BTreeSet) -> Value { @@ -105,7 +109,11 @@ impl Tool for LassoTool { } // Anchors inside the loop for every editable path the Lasso may pick. let mut hits: Vec<(NodeId, BTreeSet)> = vec![]; + let mut inside: Vec<(NodeId, usize)> = vec![]; crate::draw2::walk_pickable(cx, |n| { + if let Some(grid) = grid_of(n) { + inside.extend(grid.points.iter().enumerate().filter(|(_, q)| point_in_polygon(&poly, q.p)).map(|(i, _)| (n.id, i))); + } if let NodeKind::Path { path, .. } = &n.kind { let v: BTreeSet = path.anchors().filter(|(_, _, a)| point_in_polygon(&poly, a.p)).map(|(s, i, _)| (s, i)).collect(); @@ -116,6 +124,14 @@ impl Tool for LassoTool { }); let editable = cx.doc.editable(); hits.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); + // The mesh points inside the loop are picked, and their meshes selected whole; + // Alt deselects a mesh only when it loses its last picked point. + inside.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); + for (id, any) in self.mesh.lasso(&inside, add, sub) { + if any != sub { + hits.push((id, BTreeSet::new())); + } + } let items: Vec = hits.iter().map(|(id, v)| json!({ "id": id.0, "anchors": anchors_json(v) })).collect(); let mode = if sub { "subtract" @@ -138,11 +154,16 @@ impl Tool for LassoTool { vec![] } - fn overlays(&self, _cx: &ToolContext) -> Vec { - if !self.active || self.points.len() < 2 { - return vec![]; + fn options(&self) -> Value { + self.mesh.options() + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); + if self.active && self.points.len() >= 2 { + out.push(Overlay::Path { path: super::polygon(&self.points, false), color: [0x40, 0x40, 0x40], width: 1.0, dashed: true }); } - vec![Overlay::Path { path: super::polygon(&self.points, false), color: [0x40, 0x40, 0x40], width: 1.0, dashed: true }] + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { @@ -222,4 +243,44 @@ mod tests { assert_eq!(v["mode"], "set"); assert!(point_in_polygon(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0)], Point::new(2.0, 2.0))); } + + /// A Lasso loop round a corner of a path warped by a mesh envelope still selects the path's + /// anchor there, besides picking the envelope's grid point (#5351). + #[test] + fn lasso_keeps_picking_the_anchors_of_an_envelopes_path() { + use std::sync::Arc; + use vectorcraft_doc::Node; + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, grid_points}; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, a) = doc_with_rect(); + let rect = d.node(a).cloned().unwrap(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points: grid_points(Rect::new(100.0, 100.0, 200.0, 200.0), 1, 1), handles: vec![] }; + let env = NodeKind::Envelope { + content: vec![Arc::new(rect)], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: EnvelopeOptions::NEW, + frame: Box::new(Affine::IDENTITY), + }; + d.remove(a).unwrap(); + let e = d.alloc_id(); + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::new(e, env)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = LassoTool::default(); + // A triangle around the top-left corner (100,100) only. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 80.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 80.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 80.0, 140.0)); + let r = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 80.0, 140.0)); + let Some(Action::Exec(c, v)) = r.first() else { panic!("a selection command: {r:?}") }; + assert_eq!(c, "select.anchorsMany"); + let items = v["items"].as_array().unwrap(); + let path = items.iter().find(|it| it["id"] == a.0).expect("the warped path's anchor is selected"); + assert_eq!(path["anchors"].as_array().unwrap().len(), 1); + assert!(items.iter().any(|it| it["id"] == e.0), "the envelope is selected with its grid point"); + assert_eq!(t.options()["meshPoints"].as_array().unwrap().len(), 1); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 11a4a09415..0ca4e32353 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6177,7 +6177,8 @@ Envelope Options. The Mesh tool and Direct Selection pick mesh points on gradient meshes and mesh envelopes. A click picks one point (its handles show); Shift-click adds a point or takes a picked one away. Direct Selection's marquee picks the points -inside it (Shift toggles them) and selects their meshes; its click on a gradient mesh's line picks the line's two +inside it (Shift toggles them) and selects their meshes, as does a Lasso loop round them (Shift adds, Alt takes +away); its click on a gradient mesh's line picks the line's two ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone, and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options From 4aea3cc95c205664d9b84ea2860929e81ef18558 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:06 +0000 Subject: [PATCH 386/674] fix(effects): a dash pattern whose period overflows draws solid --- crates/effects/src/stroke/dash.rs | 4 ++++ crates/effects/src/stroke/tests.rs | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/crates/effects/src/stroke/dash.rs b/crates/effects/src/stroke/dash.rs index 5c47c07439..689c88dae1 100644 --- a/crates/effects/src/stroke/dash.rs +++ b/crates/effects/src/stroke/dash.rs @@ -57,6 +57,10 @@ pub fn dash(bp: &BezPath, d: &Dash) -> Option { pat.extend_from_within(..); } let period: f64 = pat.iter().sum(); + // Finite entries can still sum to infinity, which would never leave the phase loop below. + if !period.is_finite() { + return None; + } let plans: Vec = subpaths(bp) .into_iter() .map(|(r, closed)| { diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 067064950a..1da14b334e 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -21,6 +21,11 @@ fn stroke(width: f64, f: impl FnOnce(&mut StrokeLayer)) -> StrokeLayer { st } +#[test] +fn dash_period_overflowing_to_infinity_is_solid() { + assert!(dash(&line(0.0, 60.0), &dashed(&[f64::MAX, f64::MAX], -1.0)).is_none()); +} + fn dashed(pattern: &[f64], offset: f64) -> Dash { Dash { pattern: pattern.to_vec(), offset, align_corners: false } } From e3ef19142ffbda82d83bedd4eba087e66a2dc66a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:06 +0000 Subject: [PATCH 387/674] fix(eps): refuse Illustrator arrays nested past the depth limit --- crates/eps/src/import/ai/read/ops.rs | 8 ++++++++ crates/eps/src/import/ai/tests.rs | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index de12631eba..2fda3dec19 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -82,6 +82,14 @@ impl<'a> Reader<'a> { // highlight `-- -- angle length Bh`): a NaN keeps the other operands where they are. "--" => return self.push(V::Num(f64::NAN)), "[" => { + // Drop marks that operators have taken off, so `marks` is the open nesting. + while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) { + self.marks.pop(); + } + // Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack. + if self.marks.len() >= MAX_DEPTH { + return Err("it has arrays nested too deeply".into()); + } self.marks.push(self.stack.len()); return self.push(V::Mark); } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 6b1e8622d0..52248aa1b7 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -54,6 +54,14 @@ fn ruler_units_from_the_header_set_the_documents_units() { assert_eq!(read(with_px.as_bytes()).unwrap().doc.units, Unit::Pixels); } +#[test] +fn arrays_nested_past_the_depth_limit_are_refused() { + let deep = |n: usize| layer(&format!("{}{} pop", "[".repeat(n), "]".repeat(n))); + let nested = |n: usize| read(stream(&deep(n)).as_bytes()).err().is_some_and(|e| e.contains("nested too deeply")); + assert!(!nested(200)); + assert!(nested(100_000)); +} + /// The children of the first layer. fn art(doc: &Document) -> Vec> { doc.layers.first().and_then(|l| l.children()).cloned().unwrap_or_default() From 9d3c45a7b56317746e7076cb764390dfbf65db7d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 22:17:45 +0700 Subject: [PATCH 388/674] .ai import: the nested-arrays refusal uses the translated nesting message --- crates/eps/src/import/ai/read/ops.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 2fda3dec19..e8ff52f6c7 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -88,7 +88,7 @@ impl<'a> Reader<'a> { } // Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack. if self.marks.len() >= MAX_DEPTH { - return Err("it has arrays nested too deeply".into()); + return Err("its objects are nested too deeply".into()); } self.marks.push(self.stack.len()); return self.push(V::Mark); From 40b9fa4717d8135badaf01671e403d7274190bef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:07 +0000 Subject: [PATCH 389/674] fix(engine): recovery reads only plain files in its own areas --- crates/engine/src/cmd/recovery.rs | 8 ++++++++ crates/engine/src/tests/recovery.rs | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 753fad69c2..e36bb56ffb 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -308,6 +308,14 @@ impl RecoveryStore for FolderStore { } fn read(&self, name: &str) -> std::result::Result, String> { let f = self.file(name)?; + // Entry names come from the copy's metadata: refuse a link (or a folder another account + // owns) that would read a file from outside the store. + if let Some(dir) = f.parent() { + Self::own_area(dir)?; + } + if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() { + return Err(format!("{}: not a plain file", f.display())); + } std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display())) } fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> { diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index cfd72aedf4..38fbd86748 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -417,6 +417,21 @@ fn the_folder_store_makes_owner_only_folders() { let _ = std::fs::remove_dir_all(&base); } +/// An entry that is a link (the copy's metadata names it) is not followed out of the store. +#[cfg(unix)] +#[test] +fn the_folder_store_reads_no_linked_entries() { + let base = std::env::temp_dir().join(format!("vc-recovery-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let store = FolderStore::new(&base); + store.write("1-1/Untitled-1-1.vectorcraft", b"copy").unwrap(); + std::fs::write(base.join("outside"), b"private").unwrap(); + std::os::unix::fs::symlink(base.join("outside"), base.join("1-1").join("img")).unwrap(); + assert_eq!(store.read("1-1/Untitled-1-1.vectorcraft").unwrap(), b"copy"); + assert!(store.read("1-1/img").is_err()); + let _ = std::fs::remove_dir_all(&base); +} + #[test] fn saving_reverting_or_closing_removes_the_copy() { let dir = std::env::temp_dir().join(format!("vc-recovery-save-{}", std::process::id())); From 4d0ecb264cc9eab413d1ffeef2dc0052b7dffd09 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:07 +0000 Subject: [PATCH 390/674] fix(engine): link watch and Link Info read within the asking caller's roots --- crates/engine/src/cmd/links.rs | 6 ++++-- crates/engine/src/link_watch.rs | 12 ++++++++++-- crates/engine/src/tests/linkspanel.rs | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 2e8d974d65..441249b05b 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1338,8 +1338,10 @@ fn placement_json(o: PlacementOptions) -> Value { /// Link Info's fields of the linked file `l` (of object `id` of `st`) into `out`. fn file_fields(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { - // Within what the caller that opened the document may read, whoever asks. - crate::file_access::confine(st.opened_by.as_ref(), || file_fields_here(st, id, l, out)); + // A confined caller reads within its own roots; anyone else within what the caller that + // opened the document may read (never wider than the caller asking now). + let roots = crate::file_access::current().or_else(|| st.opened_by.clone()); + crate::file_access::confine(roots.as_ref(), || file_fields_here(st, id, l, out)); } fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Value) { diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 94fc568f44..51ffbd0986 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -69,6 +69,9 @@ impl Session { } let Some(st) = self.active() else { return }; let (uid, files, doc_path) = (st.uid, crate::cmd::links::linked_groups(&st.doc), st.path.clone()); + // A confined caller's roots, else what the caller that opened the document may read (the + // desktop frame is unconfined). + let opened_by = st.opened_by.clone(); if files.is_empty() { return; } @@ -76,7 +79,11 @@ impl Session { let out = slot.clone(); let scope = crate::file_access::ScopeHandle::capture(); let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || { - let stamps = scope.run(|| files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect()); + let stamps = scope.run(|| { + crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || { + files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect() + }) + }); *out.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps)); }); if spawned.is_ok() { @@ -141,7 +148,8 @@ impl Session { let mode = if update { "automatically" } else { self.prefs.update_links.as_str() }; match mode { "automatically" => { - let r = self.execute("links.update", &json!({"ids": ids}))?; + let roots = crate::file_access::current().or_else(|| self.active().and_then(|d| d.opened_by.clone())); + let r = crate::file_access::confine(roots.as_ref(), || self.execute("links.update", &json!({"ids": ids})))?; // Not readable yet (still being written): the next look tries again. let unread: BTreeSet = r["missing"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); for (path, ids) in &changed { diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index b08d9acab6..56784b69d9 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -278,6 +278,24 @@ fn link_info_has_the_file_and_placement_details() { assert_eq!((i["status"].as_str(), i["linked"].as_bool(), i["fileName"].as_str()), (Some("embedded"), Some(false), None)); } +/// Link Info reads within the opener's roots for an unconfined caller, and never past a confined +/// caller's own roots. +#[test] +fn link_info_stays_within_the_asking_callers_roots() { + let dir = Folder::new("info-roots"); + let other = Folder::new("info-other"); + let pic = dir.file("photo.png"); + write(&pic, &png(60, 30, RED)); + let mut s = session(); + let id = place(&mut s, &pic); + let roots = |p: &std::path::Path| crate::file_access::AutomationRoots::new(&[p], &[]).unwrap().unwrap(); + s.active_mut().unwrap().opened_by = Some(roots(&dir.0)); + assert_eq!(run(&mut s, "links.info", json!({"id": id.0}))["status"], "ok"); + let narrow = roots(&other.0); + let i = crate::file_access::confine(Some(&narrow), || run(&mut s, "links.info", json!({"id": id.0}))); + assert_ne!(i["status"], "ok", "{i}"); +} + /// A 600×300 pt image at the centre of the artboard, its placement options set to `options`, /// relinked to a 300×100 px file → the image's id and session. fn relinked(name: &str, options: Value) -> (Session, NodeId, Folder) { From 1c4162b2c9ac642fe0bf78d27f86410b6c0d7fbe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:08 +0000 Subject: [PATCH 391/674] fix(doc): a refused placed-document read shows the preview, not a cached full read --- crates/doc/src/placed_document.rs | 3 +++ crates/engine/src/tests/placed_document.rs | 24 ++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 310d7b784f..33eccb178a 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -559,6 +559,9 @@ impl Document { reads += usize::from(read_full && depth > 0); let full = if read_full { full_bytes(&p, &blob) } else { None }; if full.and_then(|b| read(&p, &b)).is_none() { + // A full read cached for another caller (one allowed to read the file) must not + // stand in for the one refused or not tried here: the preview shows instead. + cache().entries.remove(&(p.key.clone(), false)); let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() }; if let Some(bytes) = preview { read_preview(&p, &bytes); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 0ea8fd33b5..08071df059 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -349,6 +349,30 @@ fn native_included_links_keep_missing_placed_documents_editable() { } } +/// Output prepared by a caller that may not read the placed file shows its preview, not the full +/// art an earlier caller that could read it left cached. +#[test] +fn a_confined_export_does_not_reuse_full_art_read_for_another_caller() { + let dir = Folder::new("placed-confined"); + let other = Folder::new("placed-confined-other"); + let src = dir.file("src.vectorcraft"); + source(&src, 100.0, 50.0, BLUE, 0); + let mut s = session(); + place(&mut s, &src); + // As a document saved with previews opens: each placed file's blob holds only its preview. + for b in std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.values_mut() { + if let Some(p) = b.proxy.clone() { + b.bytes = p; + } + } + let d = s.doc().unwrap().doc.clone(); + let preview = |d: &Document| d.images.keys().any(|k| k.starts_with(vectorcraft_doc::placed_document::RESOURCE_PREFIX) && k.ends_with("/preview")); + assert!(!preview(&d.with_placed_art()), "the file is read in full"); + let roots = crate::file_access::AutomationRoots::new(&[&other.0], &[]).unwrap().unwrap(); + let confined = crate::file_access::confine(Some(&roots), || d.with_placed_art().into_owned()); + assert!(preview(&confined), "only the preview shows"); +} + #[test] fn a_document_saved_with_previews_outputs_its_files_art() { let dir = Folder::new("placed-preview-output"); From 8e595afdf0243d62855a2d18b48fed035787dde6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:08 +0000 Subject: [PATCH 392/674] fix(app): open and paste read only regular files --- apps/vectorcraft/src/clipboard.rs | 4 ++++ apps/vectorcraft/src/host_services.rs | 18 +++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index cec7fca1fb..59b30b7649 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -157,6 +157,10 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { None if vectorcraft_engine::file_access::current().is_none() => {} None => return None, } + // A device or pipe may never end: only a regular file is read whole. + if !std::fs::metadata(&path).ok()?.is_file() { + return None; + } let mut head = Vec::with_capacity(FILE_HEAD); std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?; let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?; diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 81a20e601c..16fe1d469c 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -151,6 +151,22 @@ fn reveal_command(path: &str) -> std::process::Command { c } +/// Read a whole file. A device or pipe may never end: only a regular file is read. +fn read_file(path: &str) -> Result, String> { + if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() { + return Err(format!("{path}: not a file")); + } + std::fs::read(path).map_err(|e| e.to_string()) +} + +#[cfg(test)] +#[test] +fn read_file_refuses_what_is_not_a_regular_file() { + assert!(read_file(&std::env::temp_dir().to_string_lossy()).is_err()); + #[cfg(unix)] + assert!(read_file("/dev/zero").is_err()); +} + /// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]). fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) @@ -277,7 +293,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Windows reads it from the pen's pointer messages (`windows_stylus`). #[cfg(windows)] stylus: Some(windows_stylus::start()), - read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + read: Some(Box::new(read_file)), write: Some(Box::new(write_file)), exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())), // Background Save and Export write from a worker thread. From c879ff369b43d47a793532d967118a9a0349e38b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:09 +0000 Subject: [PATCH 393/674] fix(app): keep preference copies, dialog passwords and migrated folders private --- apps/vectorcraft/src/prefs.rs | 22 +++++++++++++++++++++- apps/vectorcraft/src/profile.rs | 31 ++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index cf4e59b28d..a6daacb83a 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -62,7 +62,12 @@ pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str) use std::io::Write as _; for n in 1..100u32 { let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") }; - match std::fs::OpenOptions::new().write(true).create_new(true).open(path.with_file_name(name)) { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + // The preferences hold recent document paths: the copy is owner-only, whatever the umask. + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + match options.open(path.with_file_name(name)) { Ok(mut file) => { if file.write_all(bytes).is_ok() { return; @@ -312,6 +317,8 @@ pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result> { /// [`prefs_bytes`] as JSON. fn prefs_value(app: &VectorcraftApp) -> serde_json::Result { let mut ui = app.ui.clone(); + // An open dialog is never restored, and its fields can hold passwords (PDF import and save). + ui.dialog = None; ui.engine_prefs = app.session.prefs.to_json(); serde_json::to_value(&ui) } @@ -324,6 +331,19 @@ mod tests { /// Two windows open at once (#4625): the one that saves last keeps the other's changes and /// adds its own, instead of putting back the preferences it started from. + #[cfg(unix)] + #[test] + fn a_kept_preferences_copy_is_owner_only() { + use std::os::unix::fs::PermissionsExt as _; + let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable"); + let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_window_saves_only_what_it_changed_over_another_windows_save() { let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}}); diff --git a/apps/vectorcraft/src/profile.rs b/apps/vectorcraft/src/profile.rs index 4030d0aeae..8ef0355831 100644 --- a/apps/vectorcraft/src/profile.rs +++ b/apps/vectorcraft/src/profile.rs @@ -149,6 +149,15 @@ fn copy_dir(from: &Path, to: &Path) -> Result<(), String> { } } +/// Make folder `dir`, owner-only on Unix. +fn private_dir(dir: &Path) -> std::io::Result<()> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder.create(dir) +} + fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) { let entries = match std::fs::read_dir(from) { Ok(entries) => entries, @@ -165,7 +174,12 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) { let (src, dst) = (entry.path(), to.join(entry.file_name())); // A symbolic link is copied as what it points to, or skipped when that is a folder. let copied = match entry.file_type() { - Ok(kind) if kind.is_dir() => std::fs::create_dir_all(&dst).map(|()| copy_dir_into(&src, &dst, skip)), + // The copy keeps the folder's permissions (a private recovery folder stays private): + // owner-only while it fills, then the source's. + Ok(kind) if kind.is_dir() => private_dir(&dst).and_then(|()| { + copy_dir_into(&src, &dst, skip); + std::fs::set_permissions(&dst, std::fs::metadata(&src)?.permissions()) + }), Ok(_) => std::fs::copy(&src, &dst).map(|_| ()), Err(e) => Err(e), }; @@ -387,4 +401,19 @@ mod tests { let _ = std::fs::remove_dir_all(&from); let _ = std::fs::remove_dir_all(&to); } + + #[cfg(unix)] + #[test] + fn a_copied_folder_keeps_its_permissions() { + use std::os::unix::fs::PermissionsExt as _; + let from = temp("copy-mode-from"); + let to = temp("copy-mode-to"); + std::fs::create_dir_all(from.join("recovery")).unwrap(); + std::fs::write(from.join("recovery/copy.vectorcraft"), b"unsaved").unwrap(); + std::fs::set_permissions(from.join("recovery"), std::fs::Permissions::from_mode(0o700)).unwrap(); + copy_dir(&from, &to).unwrap(); + assert_eq!(std::fs::metadata(to.join("recovery")).unwrap().permissions().mode() & 0o777, 0o700); + let _ = std::fs::remove_dir_all(&from); + let _ = std::fs::remove_dir_all(&to); + } } From 9b10a40709f5c4fa4e649efe99a8a780d337edb2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:10 +0000 Subject: [PATCH 394/674] fix: Templates folder needs write access; portal saves keep exact file names --- apps/vectorcraft/src/portal_save.rs | 19 ++++++++++++++----- crates/engine/src/cmd/fileio/save.rs | 12 ++++++++++-- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/apps/vectorcraft/src/portal_save.rs b/apps/vectorcraft/src/portal_save.rs index b6dd3cc8e9..0357829aec 100644 --- a/apps/vectorcraft/src/portal_save.rs +++ b/apps/vectorcraft/src/portal_save.rs @@ -96,6 +96,12 @@ fn answer(code: u32, results: &HashMap) -> Result) = v.try_clone().ok()?.try_into().ok()?; Some(label) @@ -103,9 +109,9 @@ fn answer(code: u32, results: &HashMap) -> Result Option { +/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere +/// (`file://host/`) or another scheme. +fn file_uri_path(uri: &str) -> Option> { let rest = uri.strip_prefix("file://")?; let rest = rest.strip_prefix("localhost").unwrap_or(rest); if !rest.starts_with('/') { @@ -126,8 +132,7 @@ fn file_uri_path(uri: &str) -> Option { } } } - // `show_dialog` makes rfd's path a string with `to_string_lossy` too. - Some(String::from_utf8_lossy(&out).into_owned()) + Some(out) } /// `saved` as the answer of the save dialog for `request`: the path, then the first extension of @@ -406,6 +411,7 @@ mod tests { #[test] fn file_uris_become_local_paths() { + let file_uri_path = |uri: &str| super::file_uri_path(uri).map(|b| String::from_utf8(b).unwrap()); assert_eq!(file_uri_path("file:///home/me/Untitled-1.vectorcraft").as_deref(), Some("/home/me/Untitled-1.vectorcraft")); assert_eq!(file_uri_path("file:///home/me/A%20b%C3%A9.svg").as_deref(), Some("/home/me/A bé.svg")); assert_eq!(file_uri_path("file://localhost/tmp/x.pdf").as_deref(), Some("/tmp/x.pdf")); @@ -413,6 +419,9 @@ mod tests { assert_eq!(file_uri_path("file:///tmp/100%+1%2").as_deref(), Some("/tmp/100%+1%2")); assert_eq!(file_uri_path("file://host/x.svg"), None); assert_eq!(file_uri_path("sftp://host/x.svg"), None); + // Not UTF-8: the bytes as they are, which `answer` refuses rather than changing them. + assert_eq!(super::file_uri_path("file:///tmp/a%FF.svg"), Some(b"/tmp/a\xff.svg".to_vec())); + assert!(matches!(answer(0, &results("file:///tmp/a%FF.svg", None)), Ok(None))); } #[test] diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 3ce489f03a..de67968dad 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -134,8 +134,9 @@ pub fn templates_folder(prefs: &Prefs) -> Option { pub fn templates_dialog_folder(prefs: &Prefs) -> Option { let folder = std::path::PathBuf::from(templates_folder(prefs)?); if !folder.is_dir() { - // Best effort: a folder that can't be made leaves the nearest one that exists. - let _ = std::fs::create_dir_all(&folder); + // Best effort: a folder that can't be made (or automation may not write) leaves the + // nearest one that exists. + let _ = super::create_dir(&folder.to_string_lossy()); } folder.ancestors().find(|a| a.is_dir()).map(|a| a.to_string_lossy().into_owned()).or_else(home_folder) } @@ -1074,6 +1075,13 @@ mod tests_folders { std::fs::write(base.join("blocked"), b"x").unwrap(); prefs.templates_folder = base.join("blocked").join("Templates").to_string_lossy().into_owned(); assert_eq!(super::templates_dialog_folder(&prefs).map(PathBuf::from), Some(base.clone())); + // Automation that may not write there makes no folder. + let outside = base.join("Outside").join("Templates"); + prefs.templates_folder = outside.to_string_lossy().into_owned(); + std::fs::create_dir_all(base.join("Allowed")).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&base], &[&base.join("Allowed")]).unwrap().unwrap(); + crate::file_access::confine(Some(&roots), || super::templates_dialog_folder(&prefs)); + assert!(!outside.exists(), "not made"); let _ = std::fs::remove_dir_all(&base); } } From d68652a8f2ee5dc6e1c6d7f7552aeab2db07ebb1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:11 +0000 Subject: [PATCH 395/674] fix(format): a replacement takes no inherited ACL the old file lacked --- crates/format/src/atomic.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index f79b0bd370..c208f1b524 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -288,7 +288,13 @@ fn keep_acl(target: &Path, tmp: &Path) -> bool { let mut buf = vec![0u8; 64 << 10]; match rustix::fs::getxattr(target, ACL, &mut buf[..]) { Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::setxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()), - Err(e) => e == Errno::NODATA || e == Errno::NOTSUP, + // None to keep: drop the one `tmp` may have inherited from the folder's default ACL, which + // the old file's group bits (its mask) would otherwise open to the people it names. + Err(e) if e == Errno::NODATA => match rustix::fs::removexattr(tmp, ACL) { + Ok(()) => true, + Err(e) => e == Errno::NODATA || e == Errno::NOTSUP, + }, + Err(e) => e == Errno::NOTSUP, } } @@ -313,6 +319,24 @@ mod tests { d } + /// A replaced file that had no access ACL gets none from the folder's default ACL, whose named + /// users the old file's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) + #[cfg(target_os = "linux")] + #[test] + fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() { + let d = dir("acl"); + let f = d.join("doc.vectorcraft"); + std::fs::write(&f, b"old").unwrap(); + let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(&d).status(); + if !set.is_ok_and(|s| s.success()) { + return; + } + write_atomic(&f, b"new").unwrap(); + let mut buf = vec![0u8; 4096]; + assert_eq!(rustix::fs::getxattr(&f, "system.posix_acl_access", &mut buf[..]), Err(rustix::io::Errno::NODATA)); + let _ = std::fs::remove_dir_all(&d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() From 4bca3c15f17abaff6934e1e263eac215c7830c69 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:12 +0000 Subject: [PATCH 396/674] fix(color): recolor clustering seeds each colour once --- crates/color/src/recolor.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index e7cf22c41f..5117f16a36 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -433,10 +433,11 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec> { .collect(); let w = |i: usize| weights.get(i).copied().unwrap_or(1.0).max(1e-6); let d2 = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2); - let n = n.max(1); if pts.is_empty() { return vec![]; } + // No more rows than colours: each colour seeds one at most. + let n = n.clamp(1, pts.len()); // Seeds: the heaviest colour, then each time the one farthest from every seed so far. let first = (0..pts.len()).fold(0, |best, i| if w(i) > w(best) { i } else { best }); let mut centres = vec![pts[first]]; @@ -447,6 +448,8 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec> { break; } centres.push(pts[i]); + // Picked: a colour whose distances aren't finite (an infinite coordinate) stays farthest. + near[i] = 0.0; for (j, p) in pts.iter().enumerate() { near[j] = near[j].min(d2(p, &pts[i])); } @@ -670,6 +673,12 @@ mod tests { assert!(matches!(shaded(lab[0], 0.5), Color::Lab { .. })); } + #[test] + fn clustering_seeds_each_colour_once_even_unbounded() { + let colors = [Color::lab(f32::INFINITY, 0.0, 0.0), Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]; + assert!(cluster(&colors, &[], usize::MAX).len() <= colors.len()); + } + #[test] fn clustering_reduces_to_n_rows_of_similar_colours() { let colors = From 706c8f850eb674806ee4041c8b23a96de5bb6522 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:12 +0000 Subject: [PATCH 397/674] fix(engine): refuse network paths outside the roots before resolving them --- crates/engine/src/file_access.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index d110149dac..722b854d69 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -99,9 +99,14 @@ impl AutomationRoots { Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), }; } - let resolved = resolve(path)?; - if roots.iter().any(|r| inside(&resolved, &r.resolved)) { - return Ok(()); + // Resolving a path on another computer connects to it: unless a root is on a network + // share, such a path is refused by its name before anything is looked up. + let remote = cfg!(windows) && network_path(path) && !roots.iter().any(|r| network_path(&r.resolved.to_string_lossy())); + if !remote { + let resolved = resolve(path)?; + if roots.iter().any(|r| inside(&resolved, &r.resolved)) { + return Ok(()); + } } let shown: Vec = roots.iter().map(|r| r.shown.display().to_string()).collect(); match (shown.as_slice(), access) { @@ -282,6 +287,14 @@ pub(crate) fn is_device_name(component: &str) -> bool { matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") } +/// Is `path` a Windows name of a file on another computer (`\\server\share\…`, `\\?\UNC\…`)? +/// (Judged by name alone, so it can be tested on any platform; `check` applies it on Windows only.) +fn network_path(path: &str) -> bool { + let p = path.replace('/', "\\"); + let upper = p.to_ascii_uppercase(); + upper.starts_with(r"\\?\UNC\") || upper.starts_with(r"\\.\UNC\") || (p.starts_with(r"\\") && !p.starts_with(r"\\?\") && !p.starts_with(r"\\.\")) +} + /// Why Windows would not take `path` as an ordinary file name, for the first of its components /// that is a device name, or holds a `:` (a drive letter's own colon belongs to the prefix, not to /// a name, so only a stream such as `x.svg:evil` has one). (Judged by name alone, so it can be @@ -315,6 +328,16 @@ mod tests { p.to_string_lossy().into_owned() } + #[test] + fn network_paths_are_told_by_name() { + for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { + assert!(network_path(p), "{p}"); + } + for p in [r"C:\art\x.svg", r"\\?\C:\art\x.svg", r"\\.\C:\x", "/home/me/x.svg", "x.svg"] { + assert!(!network_path(p), "{p}"); + } + } + #[test] fn paths_inside_the_roots_pass_and_others_dont() { let (base, roots) = folders("inside"); From 891e90bfee560fc73bdcf591e16de060a1200e41 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:43:12 +0000 Subject: [PATCH 398/674] fix(engine): preset imports number duplicate names in linear time --- crates/engine/src/cmd.rs | 20 ++++++++++++++++++++ crates/engine/src/cmd/pdfcmds.rs | 8 ++++++-- crates/engine/src/cmd/printpresets.rs | 8 ++++++-- crates/engine/src/tests/cmdsplit.rs | 22 ++++++++++++++++++++++ 4 files changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 285604af5c..1af3693ca5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -611,6 +611,26 @@ pub(crate) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String { (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) } +/// [`unique_name`] for names given one after another (an import): `next` keeps, per base (in +/// any case), the number after the last one tried, so a run of one name doesn't count up from 2 +/// again for each copy. Names only become taken meanwhile, so the result is the same. +pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap, taken: impl Fn(&str) -> bool) -> String { + if !taken(base) { + return base.to_string(); + } + let i = next.entry(base.to_lowercase()).or_insert(2); + loop { + let n = format!("{base} {i}"); + *i += 1; + if !taken(&n) { + return n; + } + } +} + +/// The most presets one presets file imports: each is looked up among the saved ones. +pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; + pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/pdfcmds.rs b/crates/engine/src/cmd/pdfcmds.rs index c9c94d808b..b5a8778fe6 100644 --- a/crates/engine/src/cmd/pdfcmds.rs +++ b/crates/engine/src/cmd/pdfcmds.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_pdf::{PdfPreset, builtin_preset, builtin_presets}; use super::fileio::pdf::{find_preset, resolve}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param, unique_name}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param}; /// The `format` of a PDF presets file, also its extension. pub const PRESET_FORMAT: &str = "vcpdfpresets"; @@ -196,8 +196,12 @@ fn import(s: &mut Session, p: &Value) -> Result { for q in &file.presets { q.settings.check_values().map_err(|e| bad(C, format!("`{}`: {e}", q.name)))?; } + if file.presets.len() > super::MAX_IMPORTED_PRESETS { + return Err(bad(C, format!("a PDF presets file with over {} presets", super::MAX_IMPORTED_PRESETS))); + } let replace = bool_or(p, "replace", false); let mut imported = vec![]; + let mut next = std::collections::HashMap::new(); for mut preset in file.presets { preset.settings.clear_passwords(); let base = Some(preset.name.trim()).filter(|n| !n.is_empty()).unwrap_or("PDF Preset").to_string(); @@ -211,7 +215,7 @@ fn import(s: &mut Session, p: &Value) -> Result { } } None => { - preset.name = unique_name(&base, |n| s.pdf_preset_taken(n, None)); + preset.name = super::unique_name_from(&base, &mut next, |n| s.pdf_preset_taken(n, None)); imported.push(preset.name.clone()); s.store_pdf_preset(None, &preset); s.prefs.pdf_presets.push(preset); diff --git a/crates/engine/src/cmd/printpresets.rs b/crates/engine/src/cmd/printpresets.rs index 8f0dd298d1..2cc44586eb 100644 --- a/crates/engine/src/cmd/printpresets.rs +++ b/crates/engine/src/cmd/printpresets.rs @@ -8,7 +8,7 @@ use vectorcraft_pdf::PrintSettings; use super::fileio::pdf::changed; use super::print::settings_over; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param, unique_name}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, str_param}; /// The built-in preset's name. pub const DEFAULT_PRESET: &str = "[Default]"; @@ -221,8 +221,12 @@ fn import(s: &mut Session, p: &Value) -> Result { for q in &file.presets { q.settings.check().map_err(|e| bad(C, format!("`{}`: {e}", q.name)))?; } + if file.presets.len() > super::MAX_IMPORTED_PRESETS { + return Err(bad(C, format!("a print presets file with over {} presets", super::MAX_IMPORTED_PRESETS))); + } let replace = bool_or(p, "replace", false); let mut imported = vec![]; + let mut next = std::collections::HashMap::new(); for mut preset in file.presets { // [Default] comes in as a saved copy ("Default 2"…): the built-in one stays. let name = preset.name.trim().trim_start_matches('[').trim_end_matches(']').trim(); @@ -236,7 +240,7 @@ fn import(s: &mut Session, p: &Value) -> Result { } } None => { - preset.name = unique_name(&base, |n| s.print_preset_taken(n, None)); + preset.name = super::unique_name_from(&base, &mut next, |n| s.print_preset_taken(n, None)); imported.push(preset.name.clone()); s.prefs.print_presets.push(preset); } diff --git a/crates/engine/src/tests/cmdsplit.rs b/crates/engine/src/tests/cmdsplit.rs index af94ea3f39..2511e6f3de 100644 --- a/crates/engine/src/tests/cmdsplit.rs +++ b/crates/engine/src/tests/cmdsplit.rs @@ -66,6 +66,28 @@ fn unique_name_appends_the_first_free_number() { assert_eq!(unique_name("A 2", |n| taken.contains(&n)), "A 2 2"); } +#[test] +fn unique_name_from_counts_on_for_a_run_of_one_name() { + let mut taken = vec!["A".to_string(), "a 3".to_string()]; + let mut next = std::collections::HashMap::new(); + for want in ["A 2", "A 4", "A 5"] { + let is_taken = |n: &str| taken.iter().any(|t| t.eq_ignore_ascii_case(n)); + let n = crate::cmd::unique_name_from("A", &mut next, is_taken); + assert_eq!(n, want); + taken.push(n); + } + assert_eq!(crate::cmd::unique_name_from("B", &mut next, |_| false), "B"); +} + +#[test] +fn a_presets_file_with_too_many_presets_is_refused() { + let mut s = Session::new(); + let presets: Vec<_> = (0..=crate::cmd::MAX_IMPORTED_PRESETS).map(|_| serde_json::json!({"name": "P"})).collect(); + let file = serde_json::json!({"format": crate::cmd::printpresets::PRESET_FORMAT, "presets": presets}).to_string(); + let e = s.execute("print.presets.import", &serde_json::json!({"data": file})).unwrap_err().to_string(); + assert!(e.contains("over"), "{e}"); +} + #[test] fn leaf_targets_expand_groups_and_stop_at_compound_paths() { let mut s = session(); From ffe1ee62acb12b64ade63a1644b7511735e6b06c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:45:43 +0000 Subject: [PATCH 399/674] fix: gradients drawn pixel by pixel find their stops by binary search --- crates/affinity/src/overlay.rs | 46 +++++++++++++++++++----------- crates/color/src/gradient.rs | 6 ++++ crates/color/src/gradient/tests.rs | 15 ++++++++++ crates/metafile/src/scene.rs | 3 +- 4 files changed, 52 insertions(+), 18 deletions(-) diff --git a/crates/affinity/src/overlay.rs b/crates/affinity/src/overlay.rs index 170c50ec38..80f54f68e9 100644 --- a/crates/affinity/src/overlay.rs +++ b/crates/affinity/src/overlay.rs @@ -332,7 +332,7 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool { }; let to_unit = match o.source { Source::Gradient(g) => match invert(g.transform) { - Some(m) => Some((img.transform.then(m), g)), + Some(m) => Some((img.transform.then(m), g, stop_reach(g))), None => return false, }, Source::Solid(_) => None, @@ -343,9 +343,9 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool { } let (s, sa) = match (solid, &to_unit) { (Some(s), _) => s, - (None, Some((m, g))) => { + (None, Some((m, g, reach))) => { let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 }); - let c = sample(g, q); + let c = sample(g, reach, q); (rgb(c), c.alpha()) } (None, None) => continue, @@ -376,8 +376,22 @@ fn decode(bytes: &[u8], width: u32, height: u32) -> Option> { Some(reader.decode().ok()?.into_rgba8().into_raw()) } -/// The gradient's colour at unit-space point `q`. -fn sample(g: &Gradient, q: Point) -> Color { +/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset of stops `1..=k + 1`: +/// the first pair whose end offset a `t` doesn't pass is the first whose reach it doesn't pass, and +/// reaches never decrease, so [`sample`] finds it by binary search, sorted stops or not. +fn stop_reach(g: &Gradient) -> Vec { + g.stops + .iter() + .skip(1) + .scan(f64::NEG_INFINITY, |m, s| { + *m = m.max(s.offset); + Some(*m) + }) + .collect() +} + +/// The gradient's colour at unit-space point `q` (`reach`: [`stop_reach`] of `g`). +fn sample(g: &Gradient, reach: &[f64], q: Point) -> Color { let t = match g.kind { GradientKind::Linear => q.x, GradientKind::Radial => q.x.hypot(q.y), @@ -388,18 +402,16 @@ fn sample(g: &Gradient, q: Point) -> Color { if t <= first.offset { return first.color; } - for w in g.stops.windows(2) { - let [a, b] = [&w[0], &w[1]]; - if t <= b.offset { - let span = b.offset - a.offset; - let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 }; - // Affinity's midpoint bias (see `Stop::half_point`). - let k = 1.0 + 8.0 * (a.bias - 0.5).abs(); - let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) }; - let (x, y) = (rgb(a.color), rgb(b.color)); - let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u); - return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u }; - } + let k = reach.partition_point(|r| *r < t); + if let (Some(a), Some(b)) = (g.stops.get(k), g.stops.get(k + 1)) { + let span = b.offset - a.offset; + let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 }; + // Affinity's midpoint bias (see `Stop::half_point`). + let k = 1.0 + 8.0 * (a.bias - 0.5).abs(); + let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) }; + let (x, y) = (rgb(a.color), rgb(b.color)); + let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u); + return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u }; } last.color } diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 8441ebcc52..652db3340b 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -245,6 +245,12 @@ impl Gradient { pub fn sample(&self, t: f32) -> (Color, f32) { self.sample_with(t, |a, b, v| self.method.mix(a, b, v)) } + /// [`Self::sample`] for many points in no order (a gradient drawn pixel by pixel): the stops + /// are prepared once, so each sample costs a binary search rather than a scan of the stops. + pub fn sampler(&self) -> impl Fn(f32) -> (Color, f32) + '_ { + let reach = StopReach::new(&self.stops); + move |t| reach.sample_with(&self.stops, t, &|a, b, v| self.method.mix(a, b, v)) + } /// [`Self::sample`], a Classic gradient's neighbouring stop colours of one model mixed in it /// (CMYK stays CMYK; [`Color::lerp_keep_model`]) rather than in display RGB, a Perceptual /// gradient's as [`Self::sample`] mixes them. diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index da9a3f2cce..1e75feb335 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -23,6 +23,21 @@ fn increasing_samples_match_single_samples() { assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one); } +/// The prepared sampler gives what sampling each position alone does, out-of-order stops included. +#[test] +fn the_sampler_matches_single_samples() { + let stop = |offset: f32, hex: &str| GradientStop::new(offset, Color::from_hex(hex).unwrap()); + let g = Gradient::new( + GradientKind::Linear, + vec![stop(0.1, "#ff0000"), stop(0.4, "#00ff00"), stop(0.4, "#0000ff"), stop(0.2, "#ffff00"), stop(0.9, "#000000")], + ); + let sample = g.sampler(); + for k in (0..=40).rev() { + let t = k as f32 / 40.0; + assert_eq!(sample(t), g.sample(t), "{t}"); + } +} + /// Looking stops up by their reach finds what scanning them does, for any order of offsets, /// repeated, out-of-order and NaN ones included, and for positions outside and between them. #[test] diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 7dea2afba4..36aa663d87 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -412,6 +412,7 @@ impl<'a> Scene<'a> { field.grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect() } else { let geom = g.resolve(bounds); + let sample = g.gradient.sampler(); let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows)); (0..usize::from(rows) * usize::from(cols)) .flat_map(|i| { @@ -419,7 +420,7 @@ impl<'a> Scene<'a> { let p = Point::new(area.x0 + (x as f64 + 0.5) * cw, area.y0 + (y as f64 + 0.5) * ch); let t = geom.param_at(g.gradient.kind, p); let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - let (c, a) = g.gradient.sample(t as f32); + let (c, a) = sample(t as f32); c.to_rgba8(a) }) .collect() From 824310e6117e3b728ba9db67d6127e85a1ab5f25 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:47:15 +0000 Subject: [PATCH 400/674] fix: brush and library names number repeats without rescanning --- crates/brush/src/lib.rs | 7 +++---- crates/engine/src/cmd/library.rs | 9 ++++++++- crates/engine/src/tests/library.rs | 12 ++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index bc75f09cf1..40225c0541 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -781,10 +781,9 @@ pub fn unique_name(lib: &[Brush], base: &str) -> String { return base.to_string(); } // At most `lib.len()` names are taken, so one of the first `lib.len() + 1` candidates is free. - (2..=lib.len() + 2) - .map(|i| format!("{base} {i}")) - .find(|n| !lib.iter().any(|b| &b.name == n)) - .unwrap_or_else(|| format!("{base} {}", lib.len() + 2)) + // Each is looked up in a set: scanning the library per candidate is quadratic in its size. + let taken: std::collections::HashSet<&str> = lib.iter().map(|b| b.name.as_str()).collect(); + (2..=lib.len() + 2).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n.as_str())).unwrap_or_else(|| format!("{base} {}", lib.len() + 2)) } // ---------- geometry ---------- diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 70aa9561fe..49865914e9 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -448,6 +448,8 @@ fn clip(name: &mut String) { fn uniquify<'a>(names: impl Iterator, fallback: &str, sep: &str, fold: bool) { let key = |n: &str| if fold { n.to_lowercase() } else { n.to_string() }; let mut seen = HashSet::new(); + // Per repeated name, the number to try next: a run of one name counts on instead of from 2. + let mut next: std::collections::HashMap = std::collections::HashMap::new(); for name in names { clip(name); if name.trim().is_empty() { @@ -455,7 +457,12 @@ fn uniquify<'a>(names: impl Iterator, fallback: &str, sep } if seen.contains(&key(name)) { let base = name.clone(); - *name = (2..).map(|n| format!("{base}{sep}{n}")).find(|n| !seen.contains(&key(n))).unwrap_or_default(); + let n = next.entry(key(&base)).or_insert(2); + while seen.contains(&key(&format!("{base}{sep}{n}"))) { + *n += 1; + } + *name = format!("{base}{sep}{n}"); + *n += 1; } seen.insert(key(name)); } diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index 92c780e29d..a9bafc540b 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -821,6 +821,18 @@ fn imported_libraries_are_made_consistent() { ); } +/// A library of one name repeated as often as it may hold numbers the copies in one pass. +#[test] +fn a_library_of_one_repeated_name_imports_numbered() { + let mut s = session(); + let red = json!({"name": "Red", "color": {"model": "rgb", "r": 1, "g": 0, "b": 0}}); + let lib = json!({"name": "Many", "colors": vec![red; 10_000]}); + run(&mut s, "library.import", json!({"data": lib.to_string()})); + let got = run(&mut s, "library.get", json!({})); + let colors = got["colors"].as_array().unwrap(); + assert_eq!((colors.len(), colors[1]["name"].as_str(), colors[9_999]["name"].as_str()), (10_000, Some("Red 2"), Some("Red 10000"))); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_library_is_exported_to_a_file_and_imported_from_it() { From f854b7a2cfce75a203e55b99d4d7240d86ae8dcf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:48:20 +0000 Subject: [PATCH 401/674] fix(metafile): a full WMF object table is not rescanned for every creation --- crates/metafile/src/import.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index ed31d496e7..0a3d791ee2 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -429,6 +429,9 @@ impl Player { let start = self.free_hint.min(self.objects.len()); let i = self.objects.iter().skip(start).position(Option::is_none).map_or(self.objects.len(), |p| p + start); if i > u16::MAX as usize { + // The table is full past the hint: the next creation looks from the end, not again + // through every slot. + self.free_hint = i; return; } if i == self.objects.len() { @@ -897,3 +900,25 @@ pub(crate) fn import(bytes: &[u8]) -> Result { None => Err("not an EMF or WMF file".into()), } } + +#[cfg(test)] +mod table_tests { + use super::*; + + /// Once the WMF table is full, a rejected creation leaves the hint at its end, so the next + /// ones don't scan every slot again; a freed slot is still found. + #[test] + fn a_full_object_table_is_not_rescanned() { + let mut p = Player::new(Kind::Wmf, Affine::IDENTITY, 1.0, Rect::new(0.0, 0.0, 10.0, 10.0)); + for _ in 0..=u16::MAX as usize + 1 { + p.create(Obj::Other); + } + p.delete(5); + p.create(Obj::Other); + p.create(Obj::Other); + assert!(p.free_hint > u16::MAX as usize); + p.delete(7); + p.create(Obj::Other); + assert!(p.objects[7].is_some()); + } +} From dabb9ae3801182cbf634d6d2dc255e2259dd3e0a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:49:28 +0000 Subject: [PATCH 402/674] fix(engine): Delete Design handles each listed name once --- crates/engine/src/cmd/graph/designs.rs | 2 ++ crates/engine/src/cmd/graph/tests.rs | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 1009bcceb7..6ab79bac77 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -145,6 +145,8 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "id": id.0 })); } if let Some(names) = names_param(p, "delete", C)? { + // Each name once: a repeated one would regenerate the graphs using it again. + let names: std::collections::BTreeSet = names.into_iter().collect(); if let Some(n) = names.iter().find(|n| !taken(s, n)) { return Err(bad(C, format!("no design named `{n}`"))); } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 66f04f0ef9..5876de1d6e 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -1304,6 +1304,10 @@ fn graph_designs_are_saved_pasted_and_deleted() { s.execute("edit.undo", &json!({})).unwrap(); assert!(series_parts(&s, id, 0).iter().skip(1).all(|n| matches!(n.kind, NodeKind::Group { .. }))); assert!(s.execute("graph.design", &json!({"delete": "Nope"})).is_err()); + // A name listed many times deletes once (its graphs regenerate once). + s.execute("graph.design", &json!({"delete": vec!["Pill"; 1000]})).unwrap(); + assert!(s.doc().unwrap().doc.graph_designs.is_empty()); + assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); } #[test] From 43e391918fe2ab22c375bc0d9ea3625042c065c2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:51:00 +0000 Subject: [PATCH 403/674] fix(engine): Create from Guides stops at one past the slice limit --- crates/engine/src/cmd/slices.rs | 9 +++++++-- crates/engine/src/tests/slices.rs | 13 +++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index cad1335c13..1adc147c56 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -348,8 +348,13 @@ fn from_guides(s: &mut Session, _: &Value) -> Result { v }; let (xs, ys) = (cuts(true, region.x0, region.x1), cuts(false, region.y0, region.y1)); - let rects: Vec = - ys.windows(2).flat_map(|y| xs.windows(2).map(move |x| Rect::new(x[0], y[0], x[1], y[1]))).filter(|r| valid_rect(*r)).collect(); + // One past the limit tells too many, without making every piece of a huge grid first. + let rects: Vec = ys + .windows(2) + .flat_map(|y| xs.windows(2).map(move |x| Rect::new(x[0], y[0], x[1], y[1]))) + .filter(|r| valid_rect(*r)) + .take(MAX_PIECES + 1) + .collect(); if rects.len() > MAX_PIECES { return Err(EngineError::Other(format!("Create from Guides: the guides make more than {MAX_PIECES} slices"))); } diff --git a/crates/engine/src/tests/slices.rs b/crates/engine/src/tests/slices.rs index f14e878d31..eee1a47694 100644 --- a/crates/engine/src/tests/slices.rs +++ b/crates/engine/src/tests/slices.rs @@ -86,6 +86,19 @@ fn releasing_a_user_slice_leaves_an_unpainted_rectangle() { assert_eq!(s.doc().unwrap().selection.objects, vec![NodeId(rid)]); } +/// Guides cutting more pieces than a document takes are refused before the grid is made. +#[test] +fn too_many_guide_pieces_are_refused() { + let mut s = session(); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + for i in 1..3000 { + for vertical in [true, false] { + doc.guides.push(vectorcraft_doc::Guide::new(vertical, f64::from(i) * 0.1)); + } + } + assert!(s.execute("object.slice.fromGuides", &json!({})).unwrap_err().to_string().contains("more than")); +} + #[test] fn guides_give_nine_slices() { let mut s = session(); From 24e63b8b4fe0a1111909c446c6f311e009a917fe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:51:51 +0000 Subject: [PATCH 404/674] fix(eps): Illustrator import looks swatch names up in a set --- crates/eps/src/import/ai/read/document.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index ee82175a6f..f38ec76239 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -661,11 +661,15 @@ impl<'a> Reader<'a> { // of a default swatch of that name when the file has no palette of its own (a reserved name // in brackets, such as `[None]`, keeps its swatch). let mut defined = std::collections::HashSet::new(); + // The swatch names there are, looked up rather than scanned for each name a file defines + // (`Document::swatch` also knows the registration colour). + let mut have: std::collections::HashSet = doc.swatches_iter().map(|s| s.name.clone()).collect(); + have.insert(vectorcraft_color::swatch::REGISTRATION.to_string()); let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true))); for (n, spot) in colors { let first = defined.insert(n.name.clone()); let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot }; - if doc.swatch(&n.name).is_none() { + if have.insert(n.name.clone()) { doc.swatches.push(swatch); } else if first && !own_palette @@ -679,7 +683,7 @@ impl<'a> Reader<'a> { doc.metadata.author = author; } for name in doc.patterns.iter().map(|p| p.name.clone()).collect::>() { - if doc.swatch(&name).is_none() { + if have.insert(name.clone()) { doc.swatches.push(Swatch { paint: Paint::Pattern { pattern: name.clone(), xf: Affine::IDENTITY }, name, global: false, spot: false }); } } From 61d9a1c3e4ebfa93788a33436f1f67e27e019077 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:53:51 +0000 Subject: [PATCH 405/674] fix(engine): recovery writes and reads an image entry shared by several keys once --- crates/engine/src/cmd/recovery.rs | 18 ++++++++++++------ crates/engine/src/tests/recovery.rs | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index e36bb56ffb..1ad456b94e 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -701,11 +701,12 @@ impl RecoveryJob { let meta_bytes = serde_json::to_vec_pretty(&meta).map_err(|e| e.to_string())?; let area = self.file.split_once('/').map_or("", |(a, _)| a); let _turn = WRITES.lock().unwrap_or_else(|e| e.into_inner()); - let have: BTreeSet = if images.is_empty() { BTreeSet::new() } else { store.list()?.into_iter().collect() }; + let mut have: BTreeSet = if images.is_empty() { BTreeSet::new() } else { store.list()?.into_iter().collect() }; let mut image_bytes = 0; for (blob, data) in images { let name = format!("{area}/{blob}"); - if !have.contains(&name) { + // Images of several keys can share one entry: it is written once. + if have.insert(name.clone()) { store.write(&name, data)?; image_bytes += data.len(); } @@ -1009,16 +1010,21 @@ fn restore_one(s: &mut Session, store: &Arc, file: &str) -> R super::threads::mark_continued(&mut doc); // The images, from the entries of the copy's area. let from = file.split_once('/').map_or("", |(a, _)| a); - let mut blobs = vec![]; + let mut blobs: BTreeMap>> = BTreeMap::new(); for (key, r) in &meta.images { - match store.read(&format!("{from}/{}", r.blob)) { + // Keys sharing an entry share its bytes: each entry is read (and written again) once. + let read = match blobs.get(&r.blob) { + Some(data) => Ok(data.clone()), + None => store.read(&format!("{from}/{}", r.blob)).map(Arc::new), + }; + match read { Ok(data) => { - let mut blob = ImageBlob::new(r.mime.clone(), data); + let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None }; // Until the linked file is read, the preview stands in for it. if r.proxy { blob.proxy = Some(blob.bytes.clone()); } - blobs.push((r.blob.clone(), blob.bytes.clone())); + blobs.insert(r.blob.clone(), blob.bytes.clone()); doc.images.insert(key.clone(), blob); } Err(e) => warnings.push(format!("the image “{key}” of the recovered document couldn't be read: {e}")), diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index 38fbd86748..56c8d899da 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -643,6 +643,31 @@ fn images_are_kept_apart_and_written_again_only_when_they_change() { assert!(store.images().is_empty(), "{:?}", store.list()); } +/// Image keys sharing their bytes share one entry: it is written once when saved, and read and +/// written once when restored. +#[test] +fn images_sharing_an_entry_are_written_once() { + let store = Arc::new(Counting::default()); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + place_png(&mut s, "red.png", crate::tests_links::RED); + let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let blob = doc.images.values().next().unwrap().clone(); + for i in 0..50 { + doc.images.insert(format!("copy-{i}"), blob.clone()); + } + s.execute("file.recovery.save", &json!({})).unwrap(); + assert_eq!(store.images_written().len(), 1); + let images = images_of(&s); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(store.clone()); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1); + assert_eq!(images_of(&s), images); + assert_eq!(store.images_written().len(), 1, "restored into this session's area once"); +} + #[test] fn copies_from_before_images_were_kept_apart_still_restore() { let store = Arc::new(MemoryStore::default()); From 1806da580cf62f1ede3ec2ef81cde0239831b48e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:54:48 +0000 Subject: [PATCH 406/674] fix(mcp): busy replies don't repeat a long request id --- crates/mcp/src/intake.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/intake.rs b/crates/mcp/src/intake.rs index 272c2a6ecc..35a7bb17ad 100644 --- a/crates/mcp/src/intake.rs +++ b/crates/mcp/src/intake.rs @@ -146,10 +146,15 @@ impl Shared { fn long_running(&self, st: &State) -> Option { let r = st.running.as_ref()?; let secs = r.since.elapsed(); - (secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": r.key, "seconds": secs.as_secs()})) + // A long id isn't repeated: every busy reply would carry it twice. + let key = r.key.as_deref().filter(|k| k.len() <= MAX_ECHOED_ID); + (secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": key, "seconds": secs.as_secs()})) } } +/// The longest running request id a busy reply repeats (as JSON, quotes included). +const MAX_ECHOED_ID: usize = 256; + /// The id of a request message: `Some` when `msg` is a JSON-RPC 2.0 request with a usable id. fn request_id(msg: &Value) -> Option<&Value> { let o = msg.as_object()?; From 1574dfe7293c3acf0f5d66b47a628e6483a96260 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:55:50 +0000 Subject: [PATCH 407/674] fix: anchor positions and Simplify measure curves through the guarded arc length --- crates/geom/src/path.rs | 11 +++++++++-- crates/pathops/src/edit.rs | 8 +++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 4455c4ed9a..d836d2e021 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -278,7 +278,7 @@ impl SubPath { } let mut pos = vec![0.0]; for i in 0..self.segment_count() { - let len = kurbo::ParamCurveArclen::arclen(&self.segment(i), 1e-3); + let len = measured_arclen(&PathSeg::Cubic(self.segment(i)), 1e-3); pos.push(pos.last().copied().unwrap_or(0.0) + len); } pos @@ -621,7 +621,7 @@ const MEASURE_LIMIT: f64 = 1e9; /// The length of `seg` to `accuracy`; 0 for a segment whose control points are not finite or past /// [`MEASURE_LIMIT`]. -pub(crate) fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { +pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 { let ok = |p: Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MEASURE_LIMIT && p.y.abs() <= MEASURE_LIMIT; let fits = match seg { PathSeg::Line(l) => ok(l.p0) && ok(l.p1), @@ -838,6 +838,13 @@ mod tests { assert_eq!(c.kind, AnchorKind::Corner); } + /// Handles too large to measure give the curve no length instead of subdividing it without end. + #[test] + fn anchor_positions_of_an_unmeasurable_curve_are_finite() { + let p = curve(Point::new(100.0, 1e300), Point::new(300.0, -1e300)); + assert_eq!(p.subpaths[0].anchor_arc_positions(), [0.0, 0.0]); + } + #[test] fn length_of_square() { assert!((square().length() - 40.0).abs() < 1e-6); diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 32b47b7b97..2a39cccfa6 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -3,7 +3,8 @@ use std::collections::{BTreeMap, BTreeSet}; -use kurbo::{CubicBez, ParamCurveArclen, Point, Rect, Vec2}; +use kurbo::{CubicBez, PathSeg, Point, Rect, Vec2}; +use vectorcraft_geom::path::measured_arclen; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; use crate::boolean::{Seg, segs_to_subpath}; @@ -115,7 +116,8 @@ fn simplify_run(run: &[Seg], opts: &SimplifyOptions) -> Vec { } let mut pts = Vec::new(); for (k, s) in piece.iter().enumerate() { - let len = s.c.arclen(1e-6); + // Guarded: kurbo subdivides without end on huge finite coordinates. + let len = measured_arclen(&PathSeg::Cubic(s.c), 1e-6); let m = ((len / (tol * 0.5)).ceil() as usize).clamp(4, 256); sample(&s.c, m, &mut pts, k == 0); } @@ -454,7 +456,7 @@ fn seam_error(original: &SubPath, before: &SubPath, fit: &SubPath, tol: f64) -> let mut pts = Vec::new(); for j in (0..sp.segment_count()).filter(|&j| !seam_only || is_seam(j)) { let c = sp.segment(j); - let m = ((c.arclen(1e-6) / (tol.max(1e-6) * 0.5)).ceil() as usize).clamp(4, 256); + let m = ((measured_arclen(&PathSeg::Cubic(c), 1e-6) / (tol.max(1e-6) * 0.5)).ceil() as usize).clamp(4, 256); sample(&c, m, &mut pts, true); } pts From bc50fa782e21944d19a7727e5b290c96784960fb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:27:38 +0000 Subject: [PATCH 408/674] Place: a placement read again when it completes stays within the roots it was read in Follow-up to #5306. A DXF placed off the UI thread against an artboard that changed meanwhile is read again in finish(), on the UI thread, outside the automation roots captured when the read started. Pending now keeps that scope and poll runs finish inside it. --- crates/ui-egui/src/placing.rs | 8 ++++-- crates/ui-egui/src/placing/tests.rs | 39 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 294f227708..7bdc1f9d69 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -137,6 +137,9 @@ pub struct Pending { /// The number of the paste's chain ([`Placing::chains`]). chain: Option, done: Receiver>, + /// The automation roots in force when the read started, kept in force when it is placed: a + /// DXF placed against an artboard that changed meanwhile is read again then. + scope: ScopeHandle, } /// A read waiting for the thread that reads the files. @@ -318,6 +321,7 @@ fn spawn_labeled( let (tx, done) = channel(); // The automation roots in force here are in force there. let scope = ScopeHandle::capture(); + let completion = scope.clone(); #[cfg(test)] let reading = app.placing.reading.clone(); let job: Job = Box::new(move || { @@ -352,7 +356,7 @@ fn spawn_labeled( let _ = reader.send(job); app.placing.reader = Some(reader); } - app.placing.pending.push(Pending { name, label: label.clone(), doc, dropped, paste: chain.is_some(), chain, done }); + app.placing.pending.push(Pending { name, label: label.clone(), doc, dropped, paste: chain.is_some(), chain, done, scope: completion }); let status = format!("{label}…"); app.status(status.clone()); Ok(Some(json!({ "background": true, "status": status }))) @@ -384,7 +388,7 @@ pub fn poll(app: &mut VectorcraftApp) { if app.ui.status == format!("{}…", p.label) { app.ui.status.clear(); } - finish(app, &p, r); + p.scope.clone().run(|| finish(app, &p, r)); if let Some(chain) = p.chain && !app.placing.swatch_paste.as_ref().is_some_and(|waiting| waiting.chain == chain) { diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 90d1a551a2..fcd2090161 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -1284,3 +1284,42 @@ fn a_file_read_between_a_tools_clicks_is_placed() { assert_eq!(app.session.tool_busy(), !other_document, "other document: {other_document}"); } } + +/// A DXF placed within automation roots is read again within them when it is placed against an +/// artboard that changed meanwhile: a path redirected outside the roots after the read is refused. +#[cfg(unix)] +#[test] +fn a_file_read_again_when_placed_stays_within_the_roots_it_was_read_in() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap(); + let v = src.execute("document.serialize", &json!({"format": "dxf"})).unwrap(); + let dxf = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + let base = std::env::temp_dir().join(format!("vc-placing-reread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in", "out"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + std::fs::write(base.join(d).join("real.dxf"), &dxf).unwrap(); + } + let link = base.join("in").join("plan.dxf"); + std::os::unix::fs::symlink(base.join("in").join("real.dxf"), &link).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&base.join("in")], &[]).unwrap().unwrap(); + let mut app = app(true); + let p = json!({"path": link.to_string_lossy(), "dxf": {"fit": true}, "at": [100, 150]}); + vectorcraft_engine::file_access::confine(Some(&roots), || start(&mut app, &p, false)).unwrap(); + let t0 = std::time::Instant::now(); + while !(app.placing.reading[1].load(std::sync::atomic::Ordering::SeqCst) == 1 + && app.placing.reading[0].load(std::sync::atomic::Ordering::SeqCst) == 0) + { + assert!(t0.elapsed().as_secs() < 60, "read within 60 s"); + std::thread::yield_now(); + } + // Read; now the path leads outside the roots and the artboard under `at` changes. + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(base.join("out").join("real.dxf"), &link).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "width": 200})).unwrap(); + placed(&mut app); + assert_eq!(app.session.doc().unwrap().doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).count(), 0, "nothing placed"); + assert!(app.ui.status.contains("outside the read root"), "{}", app.ui.status); + let _ = std::fs::remove_dir_all(base); +} From f0f3320d398fa7be2cd9108a6712218e982e6d9c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:27:40 +0000 Subject: [PATCH 409/674] Brushes: a brush name the library lacks doesn't make art draw a brushed stroke Follow-up to #5293. draws_brushed rejected masks, symbol instances and pattern paints whose art names a brush the library doesn't have, though such a stroke draws plain. It now counts only brush names that resolve. --- crates/brush/src/lib.rs | 8 +++++++- crates/brush/src/tests.rs | 11 ++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 40225c0541..093ce531a9 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -848,9 +848,15 @@ fn draws_brushed(doc: &Document, def: Named<'_>, known: &mut Known) -> bool { }; // Without recursion, each one looked at once: they may use one another without end. let (mut seen, mut stack) = (std::collections::HashSet::from([key.clone()]), art(def)); + // A brush name the library lacks draws a plain stroke ([`node_pieces`]), which runs no brush. + let mut names: Option> = None; + let mut resolves = |n: &Node| { + let names = names.get_or_insert_with(|| library(doc).into_iter().map(|b| b.name).collect()); + n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.as_ref().is_some_and(|b| names.contains(b)))) + }; let mut answer = false; while let Some(n) = stack.pop() { - if has_brush(n) { + if has_brush(n) && resolves(n) { answer = true; break; } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index eb7bd8865e..7871b61af6 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1301,6 +1301,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { }; let art = Node::group(NodeId(0), [instance("plain"), instance("brushed"), painted("plain"), painted("brushed")].map(std::sync::Arc::new).into()); let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }; + store(&mut doc, std::slice::from_ref(&b)); let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0)); assert!(!out.is_empty()); for piece in &out { @@ -1325,7 +1326,10 @@ fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() { let mut doc = Document::new(100.0, 100.0); let mut brushed = rect_art(10.0, 4.0); brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) })); - for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] { + // A brush the library lacks draws a plain stroke: its mask stays. + let mut unresolved = rect_art(10.0, 4.0); + unresolved.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("missing".into()), ..stroke(1.0) })); + for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed), ("unresolved", unresolved)] { doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) }); } let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); @@ -1334,8 +1338,9 @@ fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() { n.extras_mut().mask = Some(Box::new(OpacityMask::new(instance(symbol), true))); n }; - let art = Node::group(NodeId(0), [masked("plain"), masked("brushed")].map(std::sync::Arc::new).into()); + let art = Node::group(NodeId(0), [masked("plain"), masked("brushed"), masked("unresolved")].map(std::sync::Arc::new).into()); let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }; + store(&mut doc, std::slice::from_ref(&b)); let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0)); assert!(!out.is_empty()); for piece in &out { @@ -1348,7 +1353,7 @@ fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() { _ => None, }) .collect(); - assert_eq!(roots, [Some("plain"), None], "the plain mask stays and the brushed one goes"); + assert_eq!(roots, [Some("plain"), None, Some("unresolved")], "the plain and unresolved masks stay and the brushed one goes"); } } From 30ce0e3a420f00aff0d6d9ab519bbc33319d10b1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:27:38 +0000 Subject: [PATCH 410/674] Threads: a frame left alone by a dropped repeat is flowed again Follow-up to #5303. When deduplication shortens a thread ([[a, b], [b, c]] -> [[a, b], [c]]) and no frame changed, the fast path dropped [c] without clearing its threaded continuation. A thread that lost a listing now counts as changed and is flowed again. --- crates/engine/src/cmd/threads.rs | 26 ++++++++++++++++++-------- crates/engine/src/cmd/threads/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index db7082f054..537252dad0 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -97,15 +97,25 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { // copy its text into the story each time, and write the grown story back for the next thread // to copy again. Only its first place counts. let mut seen = std::collections::HashSet::new(); - let threads: Vec> = - std::mem::take(&mut doc.text_threads).into_iter().map(|t| t.into_iter().filter(|id| seen.insert(*id)).collect()).collect(); + // A thread that lost a frame that way is flowed again: its frames' layout was made for the + // thread as listed (a frame left alone must lose its threaded continuation). + let threads: Vec<(Vec, bool)> = std::mem::take(&mut doc.text_threads) + .into_iter() + .map(|t| { + let listed = t.len(); + let t: Vec = t.into_iter().filter(|id| seen.insert(*id)).collect(); + let lost = t.len() != listed; + (t, lost) + }) + .collect(); let mut kept = vec![]; - for thread in threads { - let changed = thread.iter().any(|id| match (before.node(*id), doc.node(*id)) { - (Some(a), Some(b)) => !std::ptr::eq(a, b), - (None, None) => false, - _ => true, - }); + for (thread, lost) in threads { + let changed = lost + || thread.iter().any(|id| match (before.node(*id), doc.node(*id)) { + (Some(a), Some(b)) => !std::ptr::eq(a, b), + (None, None) => false, + _ => true, + }); // When no frame changed, the thread keeps its area-type frames and their text is not copied. if !changed { let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 2dfb119fec..9d56ca0c90 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -58,6 +58,29 @@ fn frames_listed_twice_flow_the_story_once() { assert_eq!(format!("{}{}", plain(fa), plain(fb)), TEXT.repeat(4)); } +/// A frame left alone when a repeated listing is dropped (`[[a, b], [b, c]]` → `[[a, b], [c]]`) +/// is flowed again as a story of its own, even when no frame changed: it no longer continues a +/// paragraph from the frame before it. +#[test] +fn a_frame_left_alone_by_a_dropped_repeat_stops_continuing() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + let c = + s.execute("text.create", &json!({"x": 400, "y": 10, "text": "Tail", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let mut d = (*s.doc().unwrap().doc).clone(); + let (fa, fb, fc) = (NodeId(a), NodeId(b), NodeId(c)); + d.text_threads = vec![vec![fa, fb], vec![fb, fc]]; + if let Some(NodeKind::Text(t)) = d.node_mut(fc).map(|n| &mut n.kind) { + t.first_para_continues = true; + } + let before = d.clone(); + reflow(&before, &mut d); + assert_eq!(d.text_threads, vec![vec![fa, fb]]); + let NodeKind::Text(t) = &d.node(fc).unwrap().kind else { panic!("not text") }; + assert!(!t.first_para_continues, "an unthreaded frame continues nothing"); + assert_eq!(t.plain_text(), "Tail"); +} + #[test] fn edits_copy_only_the_stories_of_threads_whose_frames_changed() { let (mut s, a, b) = setup(); From ac391b0f8541c05fa4d7dcf094dc97e61230fb8e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:27:39 +0000 Subject: [PATCH 411/674] DXF import: charge every dash copy and symbol name, name the block-work limit Follow-up to #5288. A dashed compound path keeps its dash pattern on the compound node and on each loop, so the dash budget is charged for every copy. A symbol's name is charged against the text budget before the symbol is kept. Running out of block work now says so instead of reporting more than 2,000,000 objects. --- crates/cad/src/import/build.rs | 19 ++++++--- crates/cad/src/import/tests.rs | 76 +++++++++++++++++++++++++++++++++- 2 files changed, 87 insertions(+), 8 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index ee14e81f5c..eb24859f12 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -43,6 +43,7 @@ const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are const XREFS: &str = "blocks referencing other drawings (external references) are left out"; const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out"; const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out"; +const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out"; const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; @@ -499,6 +500,9 @@ impl<'d, 'a> Build<'d, 'a> { super::curve::bounds(&bp)?; let paint = Paint::solid(rgb_color(self.rgb(p, inh))); let scale = map.determinant().abs().sqrt(); + let path = PathData::from_bezpath(&bp); + // A compound path's loops each keep a copy of its appearance, beside its own. + let copies = if path.subpaths.len() > 1 { path.subpaths.len() + 1 } else { 1 }; let appearance = if fill { Appearance::basic(paint, Paint::None, 0.0) } else { @@ -514,7 +518,7 @@ impl<'d, 'a> Build<'d, 'a> { if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() && let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale) { - match self.dash_values.checked_add(dash.pattern.len()).filter(|n| *n <= MAX_DASH_VALUES) { + match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) { Some(n) => { self.dash_values = n; s.dash = Some(dash); @@ -528,7 +532,6 @@ impl<'d, 'a> Build<'d, 'a> { ap }; let rule = if fill { FillRule::EvenOdd } else { FillRule::NonZero }; - let path = PathData::from_bezpath(&bp); let kind = |path: PathData| NodeKind::Path { path, rule, live: None, clipping: false, guide: false }; let mut n = if path.subpaths.len() > 1 { // Several loops (a hatch with islands) paint as one compound path. Each loop is an @@ -630,7 +633,7 @@ impl<'d, 'a> Build<'d, 'a> { /// The art of block `name` drawn by `map`, as one object. fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option { if self.visits >= MAX_VISITS { - self.warn(TOO_MANY); + self.warn(TOO_MUCH_BLOCK_WORK); return None; } let items = self.block(name); @@ -638,7 +641,7 @@ impl<'d, 'a> Build<'d, 'a> { // makes nothing, so the node budget doesn't bound it). self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len())); if self.visits > MAX_VISITS { - self.warn(TOO_MANY); + self.warn(TOO_MUCH_BLOCK_WORK); return None; } let items = items?; @@ -671,12 +674,16 @@ impl<'d, 'a> Build<'d, 'a> { let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base); let map = self.symbol_map * Affine::translate(-base.to_vec2()); let art = self.art(name, map, &key.1, depth); - let made = art.map(|art| { + let made = art.and_then(|art| { let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); + // The symbol keeps its name: text, as its instances' copies of it are. + if !self.charge_text(label.len()) { + return None; + } let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); self.symbol_names.insert(symbol.clone()); self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) }); - symbol + Some(symbol) }); self.symbols.insert(key, made.clone()); made diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 978505ddf3..d28a48553d 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -814,7 +814,7 @@ fn nested_array_inserts_of_nothing_stop_at_the_work_budget() { blocks.extend(block("*C", None)); let top = [(0, "INSERT"), (2, "*A"), (10, "0"), (20, "0"), (70, "300"), (44, "1")]; let r = open(&drawing(&[], &[], &blocks, &top), &points()); - assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); } #[test] @@ -1273,5 +1273,77 @@ fn arrays_of_blocks_of_hidden_art_stop_at_the_work_budget() { blocks.push((0, "ENDBLK")); let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "50"), (71, "50"), (44, "1"), (45, "1")]; let r = open(&drawing(&[], &tables, &blocks, &insert), &points()); - assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn dashed_compound_paths_charge_every_copy_of_their_pattern() { + // 100 pattern hatches of 9 loops in a two-length linetype: each keeps its dashes on the + // compound path and on each loop, 2,000 dash lengths, past the 1,000 tests import with. + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + let corners = ["0", "10", "20", "30", "40", "50", "60", "70", "80", "90"]; + let mut hatch = vec![(0, "HATCH"), (6, "DASHED"), (10, "0"), (20, "0"), (30, "0"), (2, "ANSI31"), (70, "0"), (71, "0"), (91, "9")]; + for i in 0..9 { + let (a, b) = (corners[i], corners[i + 1]); + hatch.extend([ + (92, "2"), + (72, "0"), + (73, "1"), + (93, "4"), + (10, a), + (20, "0"), + (10, b), + (20, "0"), + (10, b), + (20, "5"), + (10, a), + (20, "5"), + (97, "0"), + ]); + } + hatch.extend([(75, "0"), (76, "1"), (98, "0")]); + let e: Vec<(i32, &str)> = (0..100).flat_map(|_| hatch.iter().copied()).collect(); + let r = open(&drawing(&[], &tables, &[], &e), &points()); + let (mut compounds, mut kept) = (0, 0); + r.document.walk(|n| { + compounds += usize::from(matches!(n.kind, NodeKind::Compound { .. })); + kept += n.appearance.stroke().and_then(|s| s.dash.as_ref()).map_or(0, |d| d.pattern.len()); + }); + assert_eq!(compounds, 100, "{:?}", r.warnings); + assert!(kept > 0 && kept <= 1_000, "{kept} dash lengths kept"); + assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings); +} + +#[test] +fn symbols_of_a_long_block_name_stop_at_the_text_budget() { + // A 1,000-byte block name inserted in 100 colours its art takes: a symbol per colour, each + // keeping its own copy of the name, past the 64 KB tests import with. + let name = "N".repeat(1000); + let blocks = [ + (0, "BLOCK"), + (2, name.as_str()), + (10, "0"), + (20, "0"), + (0, "LINE"), + (8, "0"), + (62, "0"), + (10, "0"), + (20, "0"), + (11, "1"), + (21, "0"), + (0, "ENDBLK"), + ]; + let colours: Vec = (1..=100).map(|c| c.to_string()).collect(); + let inserts: Vec<(i32, &str)> = + colours.iter().flat_map(|c| [(0, "INSERT"), (2, name.as_str()), (62, c.as_str()), (10, "0"), (20, "0")]).collect(); + let r = open(&drawing(&[], &[], &blocks, &inserts), &points()); + let mut bytes: usize = r.document.symbols.iter().map(|s| s.name.len()).sum(); + r.document.walk(|n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + bytes += symbol.len(); + } + }); + assert!(!r.document.symbols.is_empty()); + assert!(bytes <= 64 << 10, "{bytes} bytes of symbol names"); + assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings); } From 1ce015de86374e1e5c1594c1841901c3c8a60ec0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:27:41 +0000 Subject: [PATCH 412/674] Export for Screens: settings saved without their PDF passwords don't export unprotected Follow-up to #5305. Stripping passwords from remembered settings made the next export of a password-protected PDF row write an unencrypted file without a word. The stripped settings now keep a non-secret passwordRequired flag, and an export refuses them until a password is given again (or security without the flag is given). --- crates/engine/src/cmd/fileio/screens.rs | 34 +++++++++++++++++++++++-- crates/engine/src/tests/assets.rs | 18 +++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index dcc8833a87..26737e158c 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -927,6 +927,7 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map Result { + check_passwords(p)?; let o = ScreenParams::of(p)?; let rows = rows_of(s, p, o.preset.as_deref())?; o.one_source()?; @@ -1280,18 +1281,46 @@ fn remember(s: &mut Session, p: &Value) { /// The PDF passwords an export may be given (`security` of a PDF row or of `settings.pdf`). const PASSWORD_KEYS: [&str; 2] = ["openPassword", "permissionsPassword"]; +/// Left where [`remove_passwords`] took a password out: an export of these settings is refused +/// until a password is given again ([`check_passwords`]), rather than written unprotected. +const PASSWORD_REQUIRED: &str = "passwordRequired"; + /// `settings` without the PDF passwords anywhere in them: settings kept in the document (which /// native saves write) or in the preferences hold the export's choices, never its secrets, as -/// the PDF settings themselves are saved without them. +/// the PDF settings themselves are saved without them. Where one was given, [`PASSWORD_REQUIRED`] +/// says so. fn remove_passwords(settings: &mut Map) { + let mut removed = false; for key in PASSWORD_KEYS { - settings.remove(key); + removed |= settings.remove(key).is_some_and(|v| v.as_str().is_none_or(|p| !p.is_empty())); + } + if removed { + settings.insert(PASSWORD_REQUIRED.into(), Value::Bool(true)); } for v in settings.values_mut() { remove_passwords_in(v); } } +/// Refuse export params `v` that hold settings whose PDF passwords were left out +/// ([`PASSWORD_REQUIRED`]) without a password given again. +fn check_passwords(v: &Value) -> Result<()> { + match v { + Value::Object(m) => { + let given = PASSWORD_KEYS.iter().any(|k| m.get(*k).and_then(Value::as_str).is_some_and(|p| !p.is_empty())); + if m.get(PASSWORD_REQUIRED) == Some(&Value::Bool(true)) && !given { + return Err(bad( + C, + "the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected", + )); + } + m.values().try_for_each(check_passwords) + } + Value::Array(items) => items.iter().try_for_each(check_passwords), + _ => Ok(()), + } +} + fn remove_passwords_in(v: &mut Value) { match v { Value::Object(m) => remove_passwords(m), @@ -1376,5 +1405,6 @@ mod tests { assert!(!kept.to_string().contains("Password"), "{kept}"); assert_eq!(kept["formats"][0]["security"]["printing"], "low"); assert_eq!(kept["settings"]["pdf"]["security"]["copy"], false); + assert_eq!(kept["formats"][0]["security"]["passwordRequired"], true); } } diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 3eca3ca434..8719873a94 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -454,3 +454,21 @@ fn collecting_explicit_assets_rejects_invalid_ids_without_adding_anything() { assert_eq!(run(&mut s, "assets.add", json!({"ids": [b, a]}))["added"], 2); assert_eq!(assets(&mut s).len(), 2); } + +/// Settings saved without the PDF passwords they were given export only once a password is given +/// again, never as an unprotected PDF; security given without `passwordRequired` exports as given. +#[test] +fn settings_saved_without_their_pdf_passwords_refuse_to_export_until_given_again() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + run(&mut s, "assets.add", json!({"ids": [a]})); + let row = |security: Value| json!({"formats": [{"format": "pdf", "security": security}]}); + run(&mut s, "assets.settings.set", row(json!({"openPassword": "open sesame"}))); + let err = s.execute("assets.export", &json!({})).unwrap_err().to_string(); + assert!(err.contains("without their passwords"), "{err}"); + let encrypted = |r: &Value| files(r)[0].1.windows(8).any(|w| w == b"/Encrypt"); + let r = run(&mut s, "assets.export", row(json!({"openPassword": "open sesame", "passwordRequired": true}))); + assert!(encrypted(&r), "given again: protected"); + let r = run(&mut s, "assets.export", row(json!({}))); + assert!(!encrypted(&r), "left out on purpose: unprotected"); +} From ce5d99c363e8d68cae9aef5e6bf6faa11e9d0f55 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:27:40 +0000 Subject: [PATCH 413/674] Copy: a PNG too large to make is not offered, and the status bar says why Follow-up to #5301. flavour_types (and clipboard.flavours) still listed PNG for art too large to render at the smallest scale, and the omission was only logged. PNG eligibility is now shared, and flavours_with_warnings returns a warning the status bar shows. --- crates/engine/src/cmd/clipboard/flavours.rs | 34 +++++++++++++-------- crates/engine/src/tests/clipflavours.rs | 6 ++-- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 8e4c57d065..b2e1114e1a 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -127,6 +127,8 @@ pub struct Flavour { const COPY_PNG_SIDE: f64 = 4096.0; /// The smallest scale (pixels a point) the PNG encoder renders at. const MIN_COPY_PNG_SCALE: f64 = 0.01; +/// What Copy says when the art is too large for its PNG. +const TOO_LARGE_FOR_PNG: &str = "The art is too large to copy as a picture: other apps get no PNG of it"; /// Most bytes of text `clipboard.importText` takes. const MAX_TEXT: usize = 1 << 20; /// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the @@ -290,7 +292,18 @@ impl Clipboard { let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only); // Art without an area (a lone guide-like line) has no page or picture. let area = self.bounds().is_some_and(|b| b.width() > 0.0 && b.height() > 0.0); - [(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area)].into_iter().filter_map(|(m, on)| on.then_some(m)).collect() + [(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area && self.png_scale().is_some())] + .into_iter() + .filter_map(|(m, on)| on.then_some(m)) + .collect() + } + + /// The scale (pixels a point) of the PNG Copy offers: at most [`COPY_PNG_SIDE`] pixels a side, + /// and `None` when even [`MIN_COPY_PNG_SCALE`], the encoder's smallest, can't bring it that small + /// (rather than a PNG of up to a gigabyte of pixels). + fn png_scale(&self) -> Option { + let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); + Some((COPY_PNG_SIDE / side).min(1.0)).filter(|s| *s >= MIN_COPY_PNG_SCALE) } /// What Copy offers other apps, best first, with Include SVG Code (`svg`) and On Copy: PDF @@ -308,6 +321,9 @@ impl Clipboard { let svg = types.contains(&SVG).then(|| self.svg()).flatten(); let mut out = vec![]; let mut warnings: Vec = vec![]; + if !self.is_empty() && self.png_scale().is_none() { + warnings.push(TOO_LARGE_FOR_PNG.to_string()); + } let mut keep = |(bytes, notes): (Vec, Vec)| { for w in notes { if !warnings.contains(&w) { @@ -321,18 +337,10 @@ impl Clipboard { TEXT => self.text().or_else(|| svg.clone()).map(String::into_bytes), SVG => svg.clone().map(String::into_bytes), PDF => self.pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten().map(&mut keep), - _ => { - let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); - let scale = (COPY_PNG_SIDE / side).min(1.0); - // The encoder renders at no fewer than MIN_COPY_PNG_SCALE pixels a point: art - // too large to fit COPY_PNG_SIDE at that scale gets no PNG, rather than one - // of up to a gigabyte of pixels. - if scale < MIN_COPY_PNG_SCALE { - log::warn!("clipboard PNG: art {side} pt across is too large to copy as a picture"); - continue; - } - self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, _, _, notes)| keep((png, notes))) - } + _ => self + .png_scale() + .and_then(|scale| self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten()) + .map(|(png, _, _, notes)| keep((png, notes))), }; out.extend(data.map(|data| Flavour { mime, data })); } diff --git a/crates/engine/src/tests/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index c490c2684f..313935c21f 100644 --- a/crates/engine/src/tests/clipflavours.rs +++ b/crates/engine/src/tests/clipflavours.rs @@ -358,8 +358,10 @@ fn copy_leaves_out_the_png_of_art_too_large_to_scale_down() { let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 1_000_000, "height": 1_000_000}))["id"].clone(); run(&mut s, "select.set", json!({"ids": [id]})); run(&mut s, "edit.copy", json!({})); - assert!(s.clipboard.flavour_types(false, false).contains(&PNG)); - assert!(s.clipboard.flavours(false, false).iter().all(|f| f.mime != PNG)); + assert!(!s.clipboard.flavour_types(false, false).contains(&PNG), "not offered either"); + let (flavours, notes) = s.clipboard.flavours_with_warnings(false, false); + assert!(flavours.iter().all(|f| f.mime != PNG)); + assert!(notes.iter().any(|n| n.contains("too large to copy as a picture")), "{notes:?}"); // Art that fits at that scale still gets its PNG, at most 4096 pixels a side. let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 200_000, "height": 100}))["id"].clone(); run(&mut s, "select.set", json!({"ids": [id]})); From f53ebdf7c0325fc8ac370c3bfc504228209d1fcf Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:22:26 +0530 Subject: [PATCH 414/674] Fix #5360: Type on a Path Options has a Preview checkbox With Preview on, the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open. Cancel puts it back with no history step; OK keeps the previewed values as one undo step. Preview starts off. The public pages list no Preview for this dialog, so this is a VectorCraft choice, recorded as such in the parity docs. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/command.rs | 13 ++-- crates/ui-egui/src/tests/pathtype.rs | 97 ++++++++++++++++++++++++++- docs/type-parity.md | 5 +- docs/ui-parity.md | 4 +- 4 files changed, 110 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 089ba61ea0..77eaede785 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -59,11 +59,16 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ..DialogSpec::FORM }; -/// Does this dialog show a Preview checkbox? Only Grid Repeat Options does: the public page for -/// the grid options lists one, and the radial and mirror pages do not. (Cancel rolls a preview -/// back whichever dialog started it.) +/// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the +/// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does +/// too (#5360), our choice: its public pages list none. (Cancel rolls a preview back whichever +/// dialog started it.) fn previews(d: &Dialog) -> bool { - d.str("__command") == "object.repeat.options" && d.fields.contains_key("gridType") + match d.str("__command").as_str() { + "object.repeat.options" => d.fields.contains_key("gridType"), + "type.pathOptions" => true, + _ => false, + } } /// The command the dialog runs and its parameters: the fields shown and the fixed ones. diff --git a/crates/ui-egui/src/tests/pathtype.rs b/crates/ui-egui/src/tests/pathtype.rs index aa8397a045..46f5eff677 100644 --- a/crates/ui-egui/src/tests/pathtype.rs +++ b/crates/ui-egui/src/tests/pathtype.rs @@ -1,6 +1,7 @@ //! Type → Type on a Path → Type on a Path Options… (#429): the dialog shows the selected type's -//! options (Effect, Flip, Align to Path, Spacing) and OK leaves its brackets where they are. The -//! Selection tool draws no brackets on a huge selection. +//! options (Effect, Flip, Align to Path, Spacing) and OK leaves its brackets where they are; its +//! Preview shows them on the canvas while it is open (#5360). The Selection tool draws no brackets +//! on a huge selection. use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind, TextKind}; @@ -80,6 +81,98 @@ fn type_on_a_path_options_keep_the_type_where_it_is() { assert_eq!((d.fields.get("alignToPath"), d.fields.get("flip")), (Some(&json!("center")), Some(&json!(false)))); } +/// The effect, alignment and spacing of type on a path `id`. +fn options(app: &VectorcraftApp, id: NodeId) -> (&'static str, &'static str, f64) { + match app.session.doc().unwrap().doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => (t.path_effect.id(), t.path_align.id(), t.path_spacing), + k => panic!("not text: {k:?}"), + } +} + +/// One headless frame of the open dialog. +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// #5360: Type on a Path Options has a Preview checkbox, off when it opens. With it on, the type +/// on the canvas follows Effect, Flip, Align to Path and Spacing while the dialog is open (a +/// checked Flip turns it over once, however many frames show it); Cancel puts it back without a +/// step of history; OK keeps what was previewed as one step, and none when nothing changed. +#[test] +fn type_on_a_path_options_preview_on_the_canvas() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let path = app.run("path.create", json!({"d": "M100 200 L500 200"})).unwrap()["id"].as_u64().unwrap(); + let r = app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Along", "at": [300, 210]})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + let original = (brackets(&app, id), options(&app, id)); + let state = |app: &VectorcraftApp| (brackets(app, id), options(app, id)); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let before = steps(&app); + + open_options(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(dialogs::accepts_field(d, "preview")); + assert!(!d.bool("preview"), "Preview starts off"); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| dialogs::show(app, ui.ctx())); + assert!(text.contains("Preview"), "{text}"); + + // Off: the fields change nothing until OK. + app.ui.dialog.as_mut().unwrap().fields.insert("effect".into(), json!("skew")); + frame(&mut app); + assert_eq!(state(&app), original, "no preview without the checkbox"); + // On: the type follows the fields. + dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + frame(&mut app); + assert_eq!(options(&app, id).0, "skew"); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("alignToPath".into(), json!("center")); + d.fields.insert("spacing".into(), json!(6.0)); + frame(&mut app); + assert_eq!(options(&app, id), ("skew", "center", 6.0)); + // Flip turns the type over once, frame after frame, and back when unchecked. + app.ui.dialog.as_mut().unwrap().fields.insert("flip".into(), json!(true)); + frame(&mut app); + let flipped = brackets(&app, id); + assert_ne!(flipped, original.0, "the preview flips the type"); + frame(&mut app); + assert_eq!(brackets(&app, id), flipped, "and keeps it flipped once"); + app.ui.dialog.as_mut().unwrap().fields.insert("flip".into(), json!(false)); + frame(&mut app); + assert_eq!(brackets(&app, id), original.0, "unchecked, it turns back"); + // Cancel puts the original back and leaves no history. + dialogs::cancel(&mut app); + assert_eq!(state(&app), original, "Cancel restores the type"); + assert_eq!(steps(&app), before, "and adds no undo step"); + assert!(!app.session.in_interaction()); + + // OK with Preview on and nothing changed: no undo step. + open_options(&mut app); + dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + frame(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((state(&app), steps(&app)), (original, before)); + + // OK keeps the previewed values as one undo step. + open_options(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("effect".into(), json!("stairStep")); + d.fields.insert("flip".into(), json!(true)); + dialogs::set_field(d, "preview".into(), json!(true)); + frame(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((options(&app, id).0, brackets(&app, id)), ("stairStep", flipped)); + assert_eq!(steps(&app), before + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(state(&app), original, "one Undo takes the whole change back"); +} + /// The Selection tool's brackets on one selected type on a path add their lines to the frame's /// mesh. On 32,768 (an opened PDF can hold as many curved text lines) they add none. #[test] diff --git a/docs/type-parity.md b/docs/type-parity.md index 9ecf0f1663..0e7cf37fd7 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (font-family fields accept the mouse wheel, #5253; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -25,7 +25,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)) | | Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | -| Type on a Path effects and options; brackets | done | #429 | +| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, a VectorCraft choice: the public pages list none) | | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | @@ -76,6 +76,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Type on a Path Options has a Preview checkbox: the type follows the fields while it is on, Cancel restores it, OK is one undo step (#5360, a VectorCraft choice: the public pages list none); scores and estimates unchanged. | | 2026-11-02 | minor | The wheel over Character, Properties and Control font-family fields changes selected text, one undo step per notch (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | The Type and Vertical Type tools make area type in a clicked closed path and type on a path along a clicked open one, with their own pointers; each type tool has its own icon; scores unchanged (estimated) | | 2026-10-31 | minor | Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; scores unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7a62b78eea..594f460dc7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (font-family fields accept the mouse wheel, #5253; Transform previews typed values and reads the Appearance target; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -287,6 +287,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | | Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; Radial Repeat has no handles yet | | Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | +| Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; a VectorCraft choice: the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options but no Preview; `tests/pathtype.rs` | | Selected Mirror Repeat shows a prominent axis with move and rotation handles; bounding-box handles take priority over the axis line | done | #2877, `tools/src/mirror.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html) | | Object › Expand on radial, grid and mirror repeats makes groups of their instances | done | #1765 (#1756) | | Object › Expand… is dimmed while the selection has appearance attributes (effects, several fills or strokes, a fill or stroke with its own transparency or effects, a brush); its tooltip and the status bar say to use Object › Expand Appearance first, which leaves a stroked line with Zig Zag a stroked zig-zag line that Expand then outlines | done | #3089; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html); `dialogs/expand.rs` tests, engine `tests_objexpand`. `object.expand` (agents, scripts) still bakes effects in one step | @@ -407,6 +408,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, a VectorCraft choice); scores and estimates unchanged | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | | 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-01 | minor | A double-click on a Repeat with the Selection tool enters isolation mode on it, where its source art (type included: a double-click there edits the text) is edited and every copy follows (#5054); scores and estimates unchanged | From 9f6c7d621f6706c0855346eb2d7c852575c40b45 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 22:53:39 +0700 Subject: [PATCH 415/674] Copy: the too-large-for-PNG status message in every catalog --- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 26 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 39cc049f39..78ac89840a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6134,3 +6134,4 @@ breakText Glyphs Глифи Bow Дъга Spike Връх Skip Spaces Пропускане на интервалите +@msg The art is too large to copy as a picture: other apps get no PNG of it Графиката е твърде голяма, за да се копира като изображение: другите приложения не получават PNG от нея diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 61fcd183ff..5ab5671ff3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6168,3 +6168,4 @@ shape Open Otvoren Bow Luk Spike Šiljak Skip Spaces Preskoči razmake +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafika je prevelika da bi se kopirala kao slika: druge aplikacije ne dobijaju njen PNG diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 18b9e6b3cc..8688a6a91e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6268,3 +6268,4 @@ breakText Glyphs Glifs Bow Arc Spike Pic Skip Spaces Omet els espais +@msg The art is too large to copy as a picture: other apps get no PNG of it La il·lustració és massa gran per copiar-la com a imatge: les altres aplicacions no en reben cap PNG diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d05064235b..5346f44c9c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6282,3 +6282,4 @@ breakText Glyphs Glyfy Bow Oblouk Spike Špička Skip Spaces Přeskočit mezery +@msg The art is too large to copy as a picture: other apps get no PNG of it Kresba je příliš velká na zkopírování jako obrázek: ostatní aplikace z ní nedostanou PNG diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bb2b7b4713..00085ce518 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6150,3 +6150,4 @@ breakText Glyphs Glyffer Bow Bue Spike Spids Skip Spaces Spring mellemrum over +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafikken er for stor til at blive kopieret som et billede: andre programmer får ingen PNG af den diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5c57b58954..6fc63d81b2 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5868,3 +5868,4 @@ breakText Glyphs Glyphen Bow Bogen Spike Spitze Skip Spaces Leerzeichen überspringen +@msg The art is too large to copy as a picture: other apps get no PNG of it Das Bildmaterial ist zu groß, um es als Bild zu kopieren: Andere Apps erhalten kein PNG davon diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2a17c0baba..2b52852d4a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6234,3 +6234,4 @@ breakText Glyphs Γλύφοι Bow Τόξο Spike Αιχμή Skip Spaces Παράλειψη κενών +@msg The art is too large to copy as a picture: other apps get no PNG of it Το γραφικό είναι πολύ μεγάλο για αντιγραφή ως εικόνα: οι άλλες εφαρμογές δεν λαμβάνουν PNG του diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3ca5ebf1f7..1b2d552b8f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6224,3 +6224,4 @@ breakText Glyphs Glifos Bow Arco Spike Pico Skip Spaces Omitir espacios +@msg The art is too large to copy as a picture: other apps get no PNG of it La ilustración es demasiado grande para copiarla como imagen: las demás aplicaciones no reciben un PNG de ella diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 78d810c7a2..7333ab9888 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6312,3 +6312,4 @@ breakText Glyphs Merkit Bow Kaari Spike Piikki Skip Spaces Ohita välilyönnit +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafiikka on liian suuri kopioitavaksi kuvana: muut sovellukset eivät saa siitä PNG-kuvaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d5972a384d..a74435b318 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6277,3 +6277,4 @@ breakText Glyphs Glyphes Bow Arc Spike Pointe Skip Spaces Ignorer les espaces +@msg The art is too large to copy as a picture: other apps get no PNG of it L’illustration est trop grande pour être copiée en tant qu’image : les autres applications n’en reçoivent pas de PNG diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c9a798077a..eeb182f470 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6266,3 +6266,4 @@ breakText Glyphs Glifák Bow Ív Spike Csúcs Skip Spaces Szóközök kihagyása +@msg The art is too large to copy as a picture: other apps get no PNG of it A grafika túl nagy ahhoz, hogy képként másolható legyen: más alkalmazások nem kapnak róla PNG-t diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 1b315d849e..2c77ab5f49 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6150,3 +6150,4 @@ breakText Glyphs Glif Bow Busur Spike Puncak Skip Spaces Lewati Spasi +@msg The art is too large to copy as a picture: other apps get no PNG of it Gambar terlalu besar untuk disalin sebagai gambar: aplikasi lain tidak mendapatkan PNG darinya diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0b07d67690..c45f0baa1f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5902,3 +5902,4 @@ breakText Glyphs Glifi Bow Arco Spike Picco Skip Spaces Salta gli spazi +@msg The art is too large to copy as a picture: other apps get no PNG of it La grafica è troppo grande per essere copiata come immagine: le altre app non ne ricevono un PNG diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index de9c692c69..2d1245dacf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5967,3 +5967,4 @@ breakText Glyphs 字形 Bow 弓形 Spike 山形 Skip Spaces スペースをスキップ +@msg The art is too large to copy as a picture: other apps get no PNG of it アートワークが大きすぎるため画像としてコピーできません:他のアプリには PNG が渡されません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0eb9cd390a..430966ec7b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6270,3 +6270,4 @@ breakText Glyphs გლიფები Bow რკალი Spike პიკი Skip Spaces ჰარების გამოტოვება +@msg The art is too large to copy as a picture: other apps get no PNG of it ნახატი ზედმეტად დიდია სურათად დასაკოპირებლად: სხვა აპები მის PNG-ს ვერ მიიღებენ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e4c58c1d58..e8ee81e827 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5863,3 +5863,4 @@ breakText Glyphs 글리프 Bow 활 모양 Spike 뾰족한 모양 Skip Spaces 공백 건너뛰기 +@msg The art is too large to copy as a picture: other apps get no PNG of it 아트워크가 너무 커서 이미지로 복사할 수 없습니다: 다른 앱에는 PNG가 전달되지 않습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index af1269a7f5..0443844e50 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6194,3 +6194,4 @@ breakText Glyphs Glyphs Bow Boog Spike Piek Skip Spaces Spaties overslaan +@msg The art is too large to copy as a picture: other apps get no PNG of it Het illustratiewerk is te groot om als afbeelding te kopiëren: andere apps krijgen er geen PNG van diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 08f91930ef..e593cbfa28 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6137,3 +6137,4 @@ breakText Glyphs Glify Bow Łuk Spike Szpic Skip Spaces Pomiń spacje +@msg The art is too large to copy as a picture: other apps get no PNG of it Grafika jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 40a2538466..4444c9ae1d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6355,3 +6355,4 @@ swatch Yellow Green Verde-amarelado Bow Arco Spike Pico Skip Spaces Ignorar espaços +@msg The art is too large to copy as a picture: other apps get no PNG of it A arte é grande demais para ser copiada como imagem: outros aplicativos não recebem um PNG dela diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 199d7a06d4..0564fc9b63 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6371,3 +6371,4 @@ shape Open Открытый Bow Дуга Spike Пик Skip Spaces Пропускать пробелы +@msg The art is too large to copy as a picture: other apps get no PNG of it Графика слишком велика для копирования в виде изображения: другие приложения не получат её PNG diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8fb160ceac..47dfc5154b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6338,3 +6338,4 @@ digits Hindi Hindi Bow Båge Spike Spets Skip Spaces Hoppa över mellanslag +@msg The art is too large to copy as a picture: other apps get no PNG of it Teckningen är för stor för att kopieras som en bild: andra appar får ingen PNG av den diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fe8244ad8f..48d39c44ed 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6239,3 +6239,4 @@ breakText Glyphs Glifler Bow Yay Spike Sivri Uç Skip Spaces Boşlukları Atla +@msg The art is too large to copy as a picture: other apps get no PNG of it Çizim, resim olarak kopyalanamayacak kadar büyük: diğer uygulamalar bunun PNG'sini almaz diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b676cbf4da..2f4fc42140 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5882,3 +5882,4 @@ breakText Glyphs Гліфи Bow Дуга Spike Пік Skip Spaces Пропускати пробіли +@msg The art is too large to copy as a picture: other apps get no PNG of it Графіка завелика, щоб скопіювати її як зображення: інші програми не отримають її PNG diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1575decd9b..c9da149557 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5883,3 +5883,4 @@ breakText Glyphs Glyph Bow Cung Spike Đỉnh nhọn Skip Spaces Bỏ qua khoảng trắng +@msg The art is too large to copy as a picture: other apps get no PNG of it Hình vẽ quá lớn để sao chép dưới dạng ảnh: các ứng dụng khác không nhận được PNG của nó diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 204aee9b7b..4f01a034ac 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6123,3 +6123,4 @@ breakText Glyphs 字形 Bow 弓形 Spike 尖峰 Skip Spaces 跳过空格 +@msg The art is too large to copy as a picture: other apps get no PNG of it 图稿太大,无法作为图片复制:其他应用不会获得它的 PNG diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 23b253f0e7..5b56d39e73 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5920,3 +5920,4 @@ breakText Glyphs 字符 Bow 弓形 Spike 尖峰 Skip Spaces 略過空格 +@msg The art is too large to copy as a picture: other apps get no PNG of it 圖稿太大,無法作為圖片複製:其他應用程式不會取得它的 PNG From 28b87faeee068acb993210bfc9d0da10e57ea12d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 3 Nov 2026 22:54:12 +0700 Subject: [PATCH 416/674] Type on a Path Options: docs say where the Preview checkbox comes from --- crates/ui-egui/src/dialogs/command.rs | 2 +- docs/type-parity.md | 4 ++-- docs/ui-parity.md | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 77eaede785..2dc8efd064 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -61,7 +61,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does -/// too (#5360), our choice: its public pages list none. (Cancel rolls a preview back whichever +/// too (#5360), as public tutorials of the dialog show. (Cancel rolls a preview back whichever /// dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { diff --git a/docs/type-parity.md b/docs/type-parity.md index 0e7cf37fd7..3beeacc785 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -25,7 +25,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)) | | Threading from the ports: selected area type and type on a path show an in port and an out port, empty, with an arrow on a side where the frame is threaded, or with a red "+" in the out port when the text doesn't fit; a click on either port loads the text; a click on a closed path, area type or type on a path threads into it, a click on empty canvas makes a frame of the same kind, shape and size there, a drag draws a rectangular frame; the frame placed comes after the clicked one from its out port and before it from its in port (the story then starts there); Escape or another tool cancels; a double-click on a threaded port breaks the thread there | partial | #2572: the Selection tool, `text.thread.add {from, to?, rect?, at?, before?}`, as the reference app's help describes ports and threading ([archived help, Threading text between objects](https://web.archive.org/web/20210119051048/https://helpx.adobe.com/illustrator/using/creating-text.html), [create text threads](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html)); area type's in port sits on the left side below the top-left corner, type on a path's just before its start bracket; Show Text Threads draws its lines between the same ports; with more than 1,000 such objects selected no ports are drawn. a double-click on a port where the frame is threaded breaks the thread there, the story flowing into the frames before the break and the frames after it left empty, still threaded with each other when two or more (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)). Remaining: the ports only take clicks with the Selection tool, and the loaded cursor borrows the I-beam until it's drawn | -| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, a VectorCraft choice: the public pages list none) | +| Type on a Path effects and options; brackets | done | #429; Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show) | | Character and Paragraph panels, styles with overrides | done | Character-style Auto-leading resets, partial definitions, local leading overrides, override markers, Undo/Redo and native serialization have regression coverage; differing paragraph alignments leave the shared alignment buttons unselected (headless regressions, full integration CI and visual review pass); mixed-value display for other paragraph fields remains missing | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | @@ -76,7 +76,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | Type on a Path Options has a Preview checkbox: the type follows the fields while it is on, Cancel restores it, OK is one undo step (#5360, a VectorCraft choice: the public pages list none); scores and estimates unchanged. | +| 2026-11-03 | minor | Type on a Path Options has a Preview checkbox: the type follows the fields while it is on, Cancel restores it, OK is one undo step (#5360, as public tutorials of the dialog show); scores and estimates unchanged. | | 2026-11-02 | minor | The wheel over Character, Properties and Control font-family fields changes selected text, one undo step per notch (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | The Type and Vertical Type tools make area type in a clicked closed path and type on a path along a clicked open one, with their own pointers; each type tool has its own icon; scores unchanged (estimated) | | 2026-10-31 | minor | Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; scores unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 594f460dc7..e3beac0b72 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -287,7 +287,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | | Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; Radial Repeat has no handles yet | | Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | -| Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; a VectorCraft choice: the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options but no Preview; `tests/pathtype.rs` | +| Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options, and public tutorials of the dialog show its Preview checkbox; `tests/pathtype.rs` | | Selected Mirror Repeat shows a prominent axis with move and rotation handles; bounding-box handles take priority over the axis line | done | #2877, `tools/src/mirror.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html) | | Object › Expand on radial, grid and mirror repeats makes groups of their instances | done | #1765 (#1756) | | Object › Expand… is dimmed while the selection has appearance attributes (effects, several fills or strokes, a fill or stroke with its own transparency or effects, a brush); its tooltip and the status bar say to use Object › Expand Appearance first, which leaves a stroked line with Zig Zag a stroked zig-zag line that Expand then outlines | done | #3089; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html); `dialogs/expand.rs` tests, engine `tests_objexpand`. `object.expand` (agents, scripts) still bakes effects in one step | @@ -408,7 +408,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, a VectorCraft choice); scores and estimates unchanged | +| 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | | 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-01 | minor | A double-click on a Repeat with the Selection tool enters isolation mode on it, where its source art (type included: a double-click there edits the text) is edited and every copy follows (#5054); scores and estimates unchanged | From 6b0a434c3212e3fee78491bbe6c004bbb6f401f2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:04:00 +0000 Subject: [PATCH 417/674] perf(svg): CSS class and imported symbol names go on from the last suffix --- crates/svg/src/css.rs | 36 +++++++++++++++++++++++++------ crates/svg/src/import.rs | 8 +++++++ crates/svg/src/import/convert.rs | 21 +++++++++++------- crates/svg/src/import/importer.rs | 11 ++++++++-- 4 files changed, 59 insertions(+), 17 deletions(-) diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 747dae25bb..05ab3ce55a 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -4,7 +4,7 @@ //! here, colours are `#rrggbb` (or `rgba()` where CSS has no separate opacity), gradients take the //! stops SVG export writes, and numbers go through [`fmt_num`]. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint}; @@ -308,7 +308,7 @@ impl CssSheet { /// paragraph's alignment; shadows and glows give `box-shadow` (`text-shadow`), a Gaussian blur /// `filter: blur()`. Other art is described as its box (see [`CssOptions::rasterize`]). pub fn css_rules(doc: &Document, ids: &[NodeId], opts: &CssOptions) -> CssSheet { - let mut w = Rules { doc, opts, sheet: CssSheet::default(), seen: HashSet::new(), names: HashSet::new() }; + let mut w = Rules { doc, opts, sheet: CssSheet::default(), seen: HashSet::new(), names: HashSet::new(), next_suffix: HashMap::new() }; for n in ids.iter().filter_map(|id| doc.node(*id)) { w.object(n); } @@ -323,6 +323,8 @@ struct Rules<'a> { seen: HashSet, /// Class names given, lower case. names: HashSet, + /// The next suffix to try for each base class name, lower case. + next_suffix: HashMap, } /// The CSS of one object's art, and why it is approximate. @@ -367,14 +369,18 @@ impl Rules<'_> { /// A class name for `name` (an object's, or its kind's), unique in the sheet. fn class_name(&mut self, name: &str) -> String { let base = sanitize_id(name).replace('.', "_"); - let mut cand = base.clone(); - for i in 2.. { + if self.names.insert(base.to_lowercase()) { + return base; + } + // Each base goes on from the suffix it last gave: objects sharing a name take linear work. + let next = self.next_suffix.entry(base.to_lowercase()).or_insert(2); + loop { + let cand = format!("{base}-{next}"); + *next += 1; if self.names.insert(cand.to_lowercase()) { - break; + return cand; } - cand = format!("{base}-{i}"); } - cand } fn rule(&mut self, n: &Node) { @@ -729,4 +735,20 @@ mod tests { assert!(family("a(b").starts_with("'a(b'")); assert!(family("Arial").starts_with("Arial,")); } + + #[test] + fn class_names_sharing_a_base_take_the_next_free_suffix() { + let doc = Document::new(10.0, 10.0); + let opts = CssOptions::default(); + let mut w = + Rules { doc: &doc, opts: &opts, sheet: CssSheet::default(), seen: HashSet::new(), names: HashSet::new(), next_suffix: HashMap::new() }; + assert_eq!(w.class_name("a-3"), "a-3"); + let names: Vec = (0..4).map(|_| w.class_name("A")).collect(); + assert_eq!(names, ["A", "A-2", "A-4", "A-5"]); + // Many objects of one name: each suffix is tried once. + for _ in 0..20_000 { + w.class_name("b"); + } + assert_eq!(w.next_suffix["b"], 20_001); + } } diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 78c12043f2..11795b83fa 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -154,6 +154,9 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul hidden: found.hidden, uses: found.uses, symbols: HashMap::new(), + symbol_names: HashSet::new(), + symbol_suffixes: HashMap::new(), + pattern_suffixes: HashMap::new(), blends: fx::blends(&xml, &scan.markers), files, non_scaling: found.non_scaling, @@ -304,6 +307,11 @@ struct Importer { uses: HashMap, /// The symbols made so far, by `` id. symbols: HashMap, + /// The names of the symbols made so far. + symbol_names: HashSet, + /// Where the suffixes of each symbol and pattern name base go on from (`unique_name`). + symbol_suffixes: HashMap, + pattern_suffixes: HashMap, /// Blend modes of the shadows and glows our export wrote, by filter id ([`fx::blends`]). blends: HashMap, /// The files `` elements link to. diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 2a777b3423..92f5234ee6 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -15,15 +15,20 @@ pub(super) fn without_ids(n: &Node) -> Node { n } -/// `base`, or `base 2`, `base 3`… : the first that isn't `taken`. -pub(super) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String { - let mut name = base.to_string(); - let mut k = 2; - while taken(&name) { - name = format!("{base} {k}"); - k += 1; +/// `base`, or `base 2`, `base 3`… : the first that isn't `taken`. `next` keeps where each base's +/// suffixes go on from, so names sharing a base take linear work in all. +pub(super) fn unique_name(base: &str, next: &mut HashMap, taken: impl Fn(&str) -> bool) -> String { + if !taken(base) { + return base.to_string(); + } + let k = next.entry(base.to_string()).or_insert(2); + loop { + let name = format!("{base} {k}"); + *k += 1; + if !taken(&name) { + return name; + } } - name } /// The stops our export added for midpoints (`data-vc-midpoint`), by gradient id: for each stop, diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index eeb0a4804c..0a0372e3f4 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -183,7 +183,10 @@ impl Importer { Some(made) if whole && made.art == without_ids(&art) && made.reuse.allows(xf) => made.name.clone(), Some(_) => return None, None => { - let name = unique_name(self.name_of(&sym), |n| self.doc.symbols.iter().any(|s| s.name == n)); + let base = self.name_of(&sym).to_string(); + let names = &self.symbol_names; + let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n)); + self.symbol_names.insert(name.clone()); let reuse = Reuse::of(&self.doc, &art); let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse }; self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); @@ -541,7 +544,8 @@ impl Importer { let art = self.named("", NodeKind::Group { children, clip: true }); let Some(art) = art else { return Paint::None }; let base = if pt.id().is_empty() { "Pattern" } else { pt.id() }; - let name = unique_name(base, |n| self.doc.pattern(n).is_some()); + let doc = &self.doc; + let name = unique_name(base, &mut self.pattern_suffixes, |n| doc.pattern(n).is_some()); let mut def = PatternDef::new(&name, vec![Arc::new(art)]); def.tile = tile; self.doc.patterns.push(def); @@ -714,6 +718,9 @@ mod tests { hidden: HashSet::new(), uses: HashMap::new(), symbols: HashMap::new(), + symbol_names: HashSet::new(), + symbol_suffixes: HashMap::new(), + pattern_suffixes: HashMap::new(), blends: HashMap::new(), files: Files::default(), non_scaling: HashSet::new(), From c972c15d0fd526e070edb514dd479e4e74a20134 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:06:25 +0000 Subject: [PATCH 418/674] fix(svg): entity expansion estimate counts every declaration and refuses long names --- crates/svg/src/entities.rs | 52 ++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/crates/svg/src/entities.rs b/crates/svg/src/entities.rs index a055e55fd5..d1eb4cfef7 100644 --- a/crates/svg/src/entities.rs +++ b/crates/svg/src/entities.rs @@ -10,9 +10,14 @@ const MAX_EXPANDED: usize = 16 << 20; /// How deep entities that refer to entities are followed (the reader's own limit is lower). const MAX_NESTING: u32 = 16; -/// The internal general entities declared in `svg`: name → value. -fn declared(svg: &str) -> HashMap<&str, &str> { - let mut map = HashMap::new(); +/// The longest entity name a reference is looked for with ([`references`]). +const MAX_NAME: usize = 256; + +/// The internal general entities declared in `svg`: name → every value declared for it. Text that +/// only looks like a declaration (in a comment, or in another entity's value) is kept too: the +/// largest value counts, so it can only make the estimate larger. +fn declared(svg: &str) -> HashMap<&str, Vec<&str>> { + let mut map: HashMap<&str, Vec<&str>> = HashMap::new(); for (at, _) in svg.match_indices(" HashMap<&str, &str> { let rest = rest.trim_start(); let Some(quote) = rest.chars().next().filter(|q| matches!(q, '"' | '\'')) else { continue }; let Some(value) = rest.get(1..).and_then(|r| r.split_once(quote)).map(|(v, _)| v) else { continue }; - map.entry(name).or_insert(value); + map.entry(name).or_default().push(value); } map } @@ -34,27 +39,31 @@ fn references(text: &str) -> impl Iterator { text.match_indices('&').filter_map(|(at, _)| { let rest = text.get(at + 1..)?; // Look no further than the longest name: a file of `&`s without `;` would be read quadratically. - let end = rest.bytes().take(257).position(|b| b == b';')?; + let end = rest.bytes().take(MAX_NAME + 1).position(|b| b == b';')?; let name = rest.get(..end)?; - (!name.is_empty() && name.len() <= 256 && !name.starts_with('#') && !name.contains(char::is_whitespace)).then_some(name) + (!name.is_empty() && name.len() <= MAX_NAME && !name.starts_with('#') && !name.contains(char::is_whitespace)).then_some(name) }) } /// What entity `name` expands to (bytes), references in its value followed. -fn expanded<'a>(name: &'a str, entities: &HashMap<&'a str, &'a str>, memo: &mut HashMap<&'a str, usize>, depth: u32) -> usize { +fn expanded<'a>(name: &'a str, entities: &HashMap<&'a str, Vec<&'a str>>, memo: &mut HashMap<&'a str, usize>, depth: u32) -> usize { if let Some(n) = memo.get(name) { return *n; } - let Some(value) = entities.get(name) else { return 0 }; + let Some(values) = entities.get(name) else { return 0 }; if depth >= MAX_NESTING { return usize::MAX; } - let mut total = value.len(); - for inner in references(value) { - total = total.saturating_add(expanded(inner, entities, memo, depth + 1)); + let mut most = 0usize; + for value in values { + let mut total = value.len(); + for inner in references(value) { + total = total.saturating_add(expanded(inner, entities, memo, depth + 1)); + } + most = most.max(total); } - memo.insert(name, total); - total + memo.insert(name, most); + most } /// Whether the references to the entities `svg` declares expand to more than [`MAX_EXPANDED`] @@ -64,6 +73,10 @@ pub(crate) fn expansion_too_large(svg: &str) -> bool { if entities.is_empty() { return false; } + // A reference to a longer name isn't looked for: refuse such a declaration instead. + if entities.keys().any(|name| name.len() > MAX_NAME) { + return true; + } let mut memo = HashMap::new(); let mut total = 0usize; for name in references(svg) { @@ -96,4 +109,17 @@ mod tests { assert!(!expansion_too_large(&ersands)); assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); } + + #[test] + fn declarations_in_comments_and_long_names_cannot_hide_a_large_entity() { + let big = "x".repeat(1 << 20); + let refs = "&a;".repeat(20); + let commented = format!(" -->]>"); + assert!(expansion_too_large(&commented)); + let in_value = format!("\">]>"); + assert!(expansion_too_large(&in_value)); + let long = "n".repeat(MAX_NAME + 1); + let long_name = format!("]>"); + assert!(expansion_too_large(&long_name)); + } } From 0086c85bc7dfb9f421aea6a84a74ada9b6464b01 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:01:42 +0000 Subject: [PATCH 419/674] fix(svg): glyphs keep only typed raster data URLs and no links --- crates/svg/src/glyph.rs | 25 +++++++++++++++++++------ crates/svg/tests/it/svg_glyphs.rs | 22 +++++++++++++++++++--- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/crates/svg/src/glyph.rs b/crates/svg/src/glyph.rs index 9c0ac5d5a5..c019f9b0a8 100644 --- a/crates/svg/src/glyph.rs +++ b/crates/svg/src/glyph.rs @@ -99,10 +99,18 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option { // Edits: byte ranges to cut and what to put in their place, in order. let mut edits: Vec<(Range, String)> = vec![]; // Cut with the left-out elements: images of SVG documents, as the table asks (a glyph draws no - // documents inside it). Their link is `href`, else `xlink:href`, as the importer reads it. + // documents inside it). Their link is `href`, else `xlink:href`, as the importer reads it. Any + // data URL not typed as a raster goes too: the importer reads an untyped one (`text/plain`) as + // SVG, SVGZ as well, when its bytes aren't a raster. let svg_image = |n: &roxmltree::Node| { let href = n.attribute("href").or_else(|| n.attribute(("http://www.w3.org/1999/xlink", "href"))); - n.tag_name().name() == "image" && href.and_then(|h| h.trim_start().get(..14)).is_some_and(|v| v.eq_ignore_ascii_case("data:image/svg")) + let data = href.map(|h| h.trim_start()).filter(|h| h.get(..5).is_some_and(|v| v.eq_ignore_ascii_case("data:"))); + let raster = |h: &str| { + ["data:image/png", "data:image/jpeg", "data:image/jpg", "data:image/gif", "data:image/webp"] + .iter() + .any(|t| h.get(..t.len()).is_some_and(|v| v.eq_ignore_ascii_case(t)) && h[t.len()..].starts_with([';', ','])) + }; + n.tag_name().name() == "image" && data.is_some_and(|h| !raster(h)) }; for n in root.descendants().filter(|n| n.is_element() && (LEFT_OUT.contains(&n.tag_name().name()) || svg_image(n))) { edits.push((n.range(), String::new())); @@ -172,13 +180,18 @@ fn edited(svg: &str, range: Range, edits: &[(Range, String)]) -> O Some(out) } -/// `n` as art of its own, made from `doc` (the glyph's document): no ids (they aren't a document's), -/// its members' neither, and its images holding the pixels `doc` keeps for them, named by their -/// content. A linked image, or one whose pixels `doc` doesn't hold, is left out (`None` when `n` -/// is one). +/// `n` as art of its own, made from `doc` (the glyph's document): no ids (they aren't a document's) +/// or links, its members' neither, and its images holding the pixels `doc` keeps for them, named +/// by their content. A linked image, or one whose pixels `doc` doesn't hold, is left out (`None` +/// when `n` is one). fn own_art(n: &Node, doc: &Document) -> Option { let mut n = n.clone(); n.id = NodeId(u64::MAX); + // A glyph is drawn, not followed: an ``'s link (a `javascript:` one too) would be written + // as a link again when its text is exported as outlines. + if n.url().is_some() { + n.edit_attrs(|a| a.url.clear()); + } if let NodeKind::Image(im) = &mut n.kind { // A glyph's images are embedded: a link (to no file of the font's) shows nothing. let blob = doc.images.get(&im.key).filter(|b| im.link.is_none() && !b.bytes.is_empty())?; diff --git a/crates/svg/tests/it/svg_glyphs.rs b/crates/svg/tests/it/svg_glyphs.rs index 1bf1753679..20e5342412 100644 --- a/crates/svg/tests/it/svg_glyphs.rs +++ b/crates/svg/tests/it/svg_glyphs.rs @@ -210,8 +210,8 @@ fn images_are_in_the_art_with_their_pixels() { assert!(b.x0.abs() < 1e-6 && (b.width() - 500.0).abs() < 1e-6 && (b.y0 + 500.0).abs() < 1e-6, "in font units: {b:?}"); } -/// An image whose data is an SVG document is left out, as the `SVG ` table asks: a glyph draws no -/// documents inside it. +/// An image whose data is an SVG document, or a data URL not typed as a raster, is left out, as +/// the `SVG ` table asks: a glyph draws no documents inside it. #[test] fn svg_images_are_left_out() { let inner = r##""##; @@ -220,9 +220,13 @@ fn svg_images_are_left_out() { + + "##, vectorcraft_svg::base64_encode(inner.as_bytes()), - vectorcraft_svg::xml_escape(&inner.replace('#', "%23")) + vectorcraft_svg::xml_escape(&inner.replace('#', "%23")), + vectorcraft_svg::base64_encode(inner.as_bytes()), + vectorcraft_svg::base64_encode(inner.as_bytes()) ); let fills = fills(&art(&doc, 1).unwrap()); assert!(fills.contains(&Paint::solid(Color::rgb8(0, 0, 255))), "the glyph's own art"); @@ -255,3 +259,15 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() { assert_eq!(images(image("png", "svg+xml")), 1, "the PNG stays"); assert_eq!(images(image("svg+xml", "png")), 0, "the document goes"); } + +/// A glyph's `` draws its art but keeps no link: outlined text must not export a +/// `javascript:` link from a font. +#[test] +fn links_in_a_glyph_are_left_out() { + let doc = r##""##; + let art = art(doc, 1).unwrap(); + assert!(fills(&art).contains(&Paint::solid(Color::rgb8(0, 0, 255)))); + let mut urls = vec![]; + art.walk(&mut |n| urls.extend(n.url().map(str::to_string))); + assert!(urls.is_empty(), "{urls:?}"); +} From cfd31b50104e2369787f2729d9c571b9117bba47 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 23:29:31 +0700 Subject: [PATCH 420/674] CSS export: line breaks and angle brackets in names can't end a CSS string Squashed from #5408 onto main. --- crates/svg/src/css.rs | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 05ab3ce55a..1b19da8019 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -26,7 +26,28 @@ pub(crate) fn declarations<'a>(props: impl IntoIterator String { - format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) + quoted(s, '"') +} + +/// `s` as a CSS string in `quote`s. A backslash and the quote are escaped, and so are line breaks +/// and other control characters (a newline would end the string and let the rest be rules) and +/// `<` and `>` (which could end a `"), r#""w\d \"\3c /style\3e ""#); + assert_eq!(css_string("wght"), "\"wght\""); + } } From bcc26d28a63bed69143ec336efc99526396f7631 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:04:36 +0000 Subject: [PATCH 421/674] fix(pdf): bound marked-content lookup, ASCII85, editing hash, image decodes and ink warnings --- crates/pdf/src/editing.rs | 47 +++++++++++++++++++-------- crates/pdf/src/images.rs | 33 +++++++++++++++++-- crates/pdf/src/import/builder.rs | 4 +-- crates/pdf/src/import/device.rs | 5 +-- crates/pdf/src/import/state.rs | 5 +-- crates/pdf/src/print/plates.rs | 37 ++++++++++++++------- crates/pdf/src/streams.rs | 18 +++++++--- crates/pdf/src/tests/colorize.rs | 12 +++++++ crates/pdf/src/tests/compression.rs | 29 +++++++++++++++++ crates/pdf/src/tests/editing.rs | 45 ++++++++++++++++++++++--- crates/pdf/src/tests/import_layers.rs | 12 +++++++ 11 files changed, 204 insertions(+), 43 deletions(-) diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index 9b56008293..a8dd48628c 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -6,7 +6,8 @@ use std::collections::HashSet; use std::sync::Arc; use craft_pdf::syntax::Pdf; -use craft_pdf::syntax::object::{Array, Dict, Object, ObjectIdentifier, Stream, String as PdfString}; +use craft_pdf::syntax::object::{Array, Dict, MaybeRef, Object, ObjectIdentifier, Stream, String as PdfString}; +use craft_pdf::syntax::xref::XRef; use craft_pdf::write::backend as krilla; use krilla::embed::{AssociationKind, EmbeddedFile, MimeType}; use krilla::metadata::DateTime; @@ -81,7 +82,7 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { let xref = pdf.xref(); let catalog = xref.get::>(xref.root_id())?; let tree = catalog.get::>(b"Names")?.get::>(b"EmbeddedFiles")?; - let spec = editing_spec(&tree, 0, &mut HashSet::new())?; + let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -97,7 +98,7 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { /// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect /// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet) -> Option> { +fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { let mut items = names.iter::>(); while let (Some(_), Some(spec)) = (items.next(), items.next()) { @@ -112,12 +113,15 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). - items(&kids).zip(kids.iter::>()).find_map(|(raw, kid)| { - if raw.as_obj_ref().is_some_and(|r| !seen.insert(r.into())) { - return None; - } - editing_spec(&kid, depth + 1, seen) + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + items(&kids).find_map(|raw| { + let kid = match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, + MaybeRef::NotRef(Object::Dict(kid)) => kid, + _ => return None, + }; + editing_spec(&kid, depth + 1, seen, xref) }) } @@ -130,9 +134,26 @@ fn is_editing_file(spec: &Dict<'_>) -> bool { }) } -/// FNV-1a of the pages' media boxes and decoded content, as 16 hex digits. +/// The most decoded page content [`page_hash`] reads in all (bytes). +const MAX_HASHED: usize = 256 << 20; + +/// FNV-1a of the pages' media boxes and decoded content, as 16 hex digits. Past [`MAX_HASHED`] +/// bytes of content in all (pages sharing a stream count it each time) a marker stands for the +/// rest, so writing and reading a file hash it the same way within bounded work. fn page_hash(pdf: &Pdf) -> String { let fnv = |h: u64, bytes: &[u8]| bytes.iter().fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)); + let mut left = MAX_HASHED; + let mut content = |h: u64, stream: &Stream<'_>| { + if left > 0 + && let Ok(data) = stream.decoded_within(left) + && data.len() < left + { + left -= data.len(); + return fnv(h, &data); + } + left = 0; + fnv(h, b"\0past the hashed content") + }; let mut h = 0xcbf29ce484222325; for page in pdf.pages().iter() { let b = page.media_box(); @@ -141,12 +162,10 @@ fn page_hash(pdf: &Pdf) -> String { // page's copy for as long as the PDF lives, even when pages share one stream. let contents = page.raw(); if let Some(stream) = contents.get::>(b"Contents") { - h = fnv(h, stream.decoded().as_deref().unwrap_or_default()); + h = content(h, &stream); } else if let Some(array) = contents.get::>(b"Contents") { for stream in array.iter::>() { - if let Ok(data) = stream.decoded() { - h = fnv(fnv(h, &data), b" "); - } + h = fnv(content(h, &stream), b" "); } } } diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index c75a28a60f..9319443846 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -229,7 +229,11 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in let keep = Recoded { image: None, warning: None }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); - let Ok(decoder) = reader.into_decoder() else { return keep }; + let Ok(mut decoder) = reader.into_decoder() else { return keep }; + // What the header declares is decoded within the image allowance, not whatever it asks for. + if decoder.set_limits(limits()).is_err() { + return keep; + } let dims = decoder.dimensions(); use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); @@ -249,7 +253,7 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in if kept(&rule, dims, size, jpeg) && convert.is_none() { return Recoded { image: None, warning: rule.instead }; } - let Some(img) = pixels.or_else(|| image::load_from_memory(bytes).ok()) else { return keep }; + let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep }; let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8(); if kind == Kind::Mono { // Resampling greys the edges: back to black and white. @@ -345,6 +349,23 @@ pub(crate) fn recode_cmyk( Recoded { image, warning: rule.instead } } +/// The most one image read here may allocate (bytes), as the image reader allows by default. +const MAX_DECODE: u64 = 512 << 20; + +/// The decoder limits of an image read here: [`MAX_DECODE`] bytes. +fn limits() -> image::Limits { + let mut l = image::Limits::default(); + l.max_alloc = Some(MAX_DECODE); + l +} + +/// `bytes` decoded within [`limits`]: an image whose header asks for more is not decoded. +fn decoded(bytes: &[u8]) -> Option { + let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + r.limits(limits()); + r.decode().ok() +} + /// The alpha an opacity mask whose art is greyscale image `blob` alone gives the image of /// `width` × `height` pixels it covers pixel for pixel: the mask's luminance, over black where the /// mask image is transparent when it clips (`clip`), else over white. `None` when `blob` isn't @@ -353,7 +374,13 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool) if blob.is_cmyk() { return None; } - let img = image::load_from_memory(&blob.bytes).ok()?.into_rgba8(); + // The size from the header first: a mask of another size, or too large to hold as RGBA, is + // not decoded at all. + let reader = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?; + if reader.into_dimensions().ok()? != (width, height) || u64::from(width) * u64::from(height) * 4 > MAX_DECODE { + return None; + } + let img = decoded(&blob.bytes)?.into_rgba8(); if img.dimensions() != (width, height) || !neutral(img.as_raw()) { return None; } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index f0049787f8..86a4a89a37 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -173,8 +173,8 @@ impl<'p> Builder<'p> { } /// The group art drawn now belongs to (the innermost marked as one). - fn current_group(&self) -> Option { - self.marked.iter().rev().find_map(|g| *g) + pub(super) fn current_group(&self) -> Option { + self.marked.last().and_then(|(_, current)| *current) } /// Add `n` to the open frame; `group`: the optional content group it was drawn in, if it diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index f89deaaf95..84d8885a0b 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -363,7 +363,8 @@ impl<'a> Device<'a> for Builder<'_> { { f.group.get_or_insert(g); } - self.marked.push(group); + let current = group.or_else(|| self.current_group()); + self.marked.push((group, current)); } fn end_marked_content(&mut self) { @@ -371,7 +372,7 @@ impl<'a> Device<'a> for Builder<'_> { return; } // The runs gathered within a layer's sequence are its art: finish them before it ends. - if self.marked.last().copied().flatten().is_some() { + if self.marked.last().is_some_and(|(group, _)| group.is_some()) { self.flush(); } self.marked.pop(); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index f2d974f159..abf7499d05 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -136,8 +136,9 @@ pub(super) struct Builder<'p> { /// Some groups are hidden or don't print: art in marked content whose group can't be told /// (once the scan and the interpreter part) is [`UNSORTED`] rather than the page's. pub(super) unsure: bool, - /// The marked-content sequences open: the group each marks. - pub(super) marked: Vec>, + /// The marked-content sequences open: the group each marks, and the innermost group marked + /// at or around it (kept per level, so art drawn deep in sequences finds its group at once). + pub(super) marked: Vec<(Option, Option)>, pub(super) nested: u32, /// Reading an alpha soft mask's art: images are read white with their own alpha, so the /// mask's luminance is their alpha, as whitened vector art's is (cairo, and so Inkscape, diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 9025f342f4..7c84996427 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -14,15 +14,20 @@ use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; use super::{DEFAULT_FREQUENCY, PrintInk, PrintSettings}; /// The inks of a separation of `doc`: the process inks, then one per spot swatch (none when -/// spots print as process), with the options of [`super::PrintOutput::inks`]; and a warning for -/// each option naming no ink. +/// spots print as process), with the options of [`super::PrintOutput::inks`]; and a warning +/// naming the options that name no ink. pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec, Vec) { let out = &set.output; + // Options by ink name, the first for a name winning: looked up, not searched for each ink. + let mut options = std::collections::HashMap::new(); + for o in &out.inks { + options.entry(o.name.as_str()).or_insert(o); + } let list: Vec = plates(doc) .into_iter() .filter(|p| !(p.spot && out.spots_to_process)) .map(|p| { - let o = out.inks.iter().find(|i| i.name == p.name); + let o = options.get(p.name.as_str()).copied(); PrintInk { print: o.is_none_or(|o| o.print), frequency: o.and_then(|o| o.frequency).unwrap_or(DEFAULT_FREQUENCY), @@ -32,17 +37,27 @@ pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec, Vec>().join(", ")) - }) - .collect(); + // One warning for all the options naming no ink, each list cut short: the options and the + // inks both come from the file. + let names: BTreeSet<&str> = list.iter().map(|p| p.name.as_str()).collect(); + let unknown: Vec<&str> = out.inks.iter().map(|i| i.name.as_str()).filter(|n| !names.contains(n)).collect(); + let warnings = if unknown.is_empty() { + vec![] + } else { + let few = |all: Vec<&str>| { + let more = all.len().saturating_sub(MAX_NAMED); + let shown = all.into_iter().take(MAX_NAMED).map(|n| format!("`{n}`")).collect::>().join(", "); + if more > 0 { format!("{shown} and {more} more") } else { shown } + }; + let inks = few(list.iter().map(|p| p.name.as_str()).collect()); + vec![format!("there is no ink named {} to print (inks: {inks})", few(unknown))] + }; (list, warnings) } +/// The most names a warning of [`print_inks`] lists. +const MAX_NAMED: usize = 10; + /// The colour settings separations of `doc` convert with: the document's colour spaces /// ([`crate::output::document_cms`]), with the printer profile as their CMYK profile when it is a /// CMYK one. diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index b2142ace36..8fb57198fe 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -116,7 +116,7 @@ fn hex(data: &[u8]) -> Vec { } /// `data` decoded from base-85 (white space skipped, `z` for four zeros, up to `~>`). -fn base85(data: &[u8]) -> Vec { +fn base85(data: &[u8], max: usize) -> Vec { let (mut out, mut group) = (vec![], vec![]); let flush = |group: &mut Vec, out: &mut Vec| { let n = group.len(); @@ -128,6 +128,10 @@ fn base85(data: &[u8]) -> Vec { group.clear(); }; for &c in data.iter().take_while(|c| **c != b'~') { + // Past `max` the caller refuses it: stop growing (a `z` is four bytes from one). + if out.len() > max { + break; + } match c { b'z' if group.is_empty() => out.extend([0; 4]), b'!'..=b'u' => { @@ -144,13 +148,15 @@ fn base85(data: &[u8]) -> Vec { } /// The most data of `len` bytes can grow to through `filters`: 1,032 times through Flate (its -/// largest ratio), 3,641 through LZW (4,096 bytes from a 9-bit code), 64 through run-length. +/// largest ratio), 3,641 through LZW (4,096 bytes from a 9-bit code), 64 through run-length, 4 +/// through ASCII85 (`z`). fn most_after(len: usize, filters: &[Name<'_>]) -> u128 { filters.iter().fold(len as u128, |n, f| { n.saturating_mul(match f.as_ref() { b"FlateDecode" | b"Fl" => 1032, b"LZWDecode" | b"LZW" => 3641, b"RunLengthDecode" | b"RL" => 64, + b"ASCII85Decode" | b"A85" => 4, _ => 1, }) }) @@ -213,7 +219,7 @@ fn decode(data: &[u8], dict: &Dict<'_>, keep: bool) -> Result>, T b"LZWDecode" | b"LZW" => lzw(&data, early, max), b"RunLengthDecode" | b"RL" => Some(run_length(&data, max)), b"ASCIIHexDecode" | b"AHx" => Some(hex(&data)), - b"ASCII85Decode" | b"A85" => Some(base85(&data)), + b"ASCII85Decode" | b"A85" => Some(base85(&data, max)), _ => None, }; match out { @@ -740,8 +746,10 @@ mod tests { #[test] fn the_decoders_read_what_the_specification_writes() { assert_eq!(hex(b"48 65 6c6C6\n>junk"), b"Hell`"); - assert_eq!(base85(b"87cURD]i,\"Ebo80~>"), b"Hello World!"); - assert_eq!(base85(b"z!!~>"), [0, 0, 0, 0, 0]); + assert_eq!(base85(b"87cURD]i,\"Ebo80~>", usize::MAX), b"Hello World!"); + assert_eq!(base85(b"z!!~>", usize::MAX), [0, 0, 0, 0, 0]); + // Zeros past the allowance are not written: a little over it, and the caller refuses it. + assert!(base85(&[b'z'; 1 << 20], 1000).len() <= 1004); assert_eq!(run_length(&[2, b'a', b'b', b'c', 254, b'x', 128, b'q'], MAX_DECODED), b"abcxxx"); let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); std::io::Write::write_all(&mut e, &[7; 1000]).unwrap(); diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 91ee3d5f22..406ae08b81 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -179,3 +179,15 @@ fn a_pixelated_colorized_image_asks_viewers_not_to_smooth_it() { assert_eq!(String::from_utf8_lossy(&out).contains("/Interpolate"), !pixelated, "pixelated: {pixelated}"); } } + +/// Ink options naming no ink give one warning, its lists cut short, however many there are. +#[test] +fn ink_options_naming_no_ink_give_one_short_warning() { + let d = doc(ColorMode::Cmyk, None); + let inks: Vec = (0..10_000).map(|i| serde_json::json!({"name": format!("Missing {i}")})).collect(); + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations", "inks": inks}})).unwrap(); + let (list, warnings) = print_inks(&d, &settings); + assert!(list.iter().any(|i| i.name == "Cyan")); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("`Missing 0`") && warnings[0].contains("and 9990 more") && warnings[0].len() < 500, "{}", warnings[0]); +} diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index ab70e4521c..9e012e330a 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -158,3 +158,32 @@ fn codecs_the_writer_lacks_are_zip_with_a_warning() { // The codecs of other kinds of images say nothing. assert!(pdf(&png, json!({"mono": {"compression": "ccittG4"}})).1.is_empty()); } + +/// A PNG whose header declares `w` × `h` grey pixels and whose data holds a few: what a file can +/// declare, not what it holds. +fn declared_png(w: u32, h: u32) -> Vec { + let chunk = |kind: &[u8], data: &[u8]| { + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + [&(data.len() as u32).to_be_bytes()[..], kind, data, &crc.sum().to_be_bytes()].concat() + }; + let ihdr = [&w.to_be_bytes()[..], &h.to_be_bytes(), &[8, 0, 0, 0, 0]].concat(); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, &[0; 64]).unwrap(); + let idat = z.finish().unwrap(); + [&b"\x89PNG\r\n\x1a\n"[..], &chunk(b"IHDR", &ihdr), &chunk(b"IDAT", &idat), &chunk(b"IEND", &[])].concat() +} + +/// Images a document holds are decoded within the decode allowance: a header declaring billions of +/// pixels is refused before they are allocated, as an opacity mask and when recoded. +#[test] +fn images_declaring_more_than_the_allowance_are_not_decoded() { + let png = declared_png(60_000, 60_000); + let blob = ImageBlob::new("image/png", png.clone()); + assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None); + assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all"); + let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap(); + let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None); + assert!(r.image.is_none(), "kept as it is"); +} diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index 69dbbc538b..3a9fe2a3a6 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -131,18 +131,25 @@ fn pdf_a_carries_no_editing_data() { /// A tiny PDF made of the given objects (numbered from 1), with the cross-reference table written. fn raw_pdf(objects: &[String]) -> Vec { + raw_pdf_bytes(objects.iter().map(|o| o.clone().into_bytes())) +} + +/// [`raw_pdf`] of objects that may hold binary data. +fn raw_pdf_bytes(objects: impl IntoIterator>) -> Vec { let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); - for (i, body) in objects.iter().enumerate() { + for (i, body) in objects.into_iter().enumerate() { offsets.push(out.len()); - out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(&body); + out.extend_from_slice(b"\nendobj\n"); } let xref = out.len(); - out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); for at in offsets { out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes()); } - out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); out } @@ -168,6 +175,36 @@ fn a_name_tree_node_shared_by_many_kids_is_searched_once() { assert_eq!((e.data.as_slice(), e.intact), (&b"hello"[..], true)); } +#[test] +fn pages_sharing_a_large_content_stream_are_hashed_within_a_budget() { + use std::io::Write; + // 300 pages showing one stream of 1 MiB of spaces: 300 MiB decoded, past the 256 MiB hashed. + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + z.write_all(&vec![b' '; 1 << 20]).unwrap(); + let packed = z.finish().unwrap(); + let pages = 300; + let kids: String = (0..pages).map(|i| format!("{} 0 R ", 7 + i)).collect(); + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + format!("<< /Type /Pages /Kids [{kids}] /Count {pages} >>"), + "<< /Names [(a) 4 0 R] >>".to_string(), + format!("<< /Type /Filespec /UF ({EDITING_FILE}) /Desc (hash 0000000000000000) /EF << /F 5 0 R >> >>"), + "<< /Length 5 >>\nstream\nhello\nendstream".to_string(), + String::new(), + ]; + for _ in 0..pages { + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Contents 6 0 R >>".to_string()); + } + let mut stream = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", packed.len()).into_bytes(); + stream.extend_from_slice(&packed); + stream.extend_from_slice(b"\nendstream"); + let bytes = raw_pdf_bytes(objects.into_iter().enumerate().map(|(i, o)| if i == 5 { stream.clone() } else { o.into_bytes() })); + let start = std::time::Instant::now(); + let e = editing(&bytes).unwrap(); + assert_eq!((e.data.as_slice(), e.intact), (&b"hello"[..], false)); + assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); +} + #[test] fn direct_name_tree_kids_are_all_searched() { // Direct kids report the object holding them as their id; none of them may be taken as seen. diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 8ddeb2f834..86e1a88fb1 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -448,3 +448,15 @@ fn private_data_reads_without_a_pdf_part_that_cant_be_read() { assert!(illustrator_data_without_pdf_part(&pdf, None).is_none(), "{odd}"); } } + +/// Art in ordinary tags nested inside a layer's sequence goes to that layer; the group is kept +/// with each level, not searched for through the tags for each object. +#[test] +fn art_deep_in_tags_inside_a_layer_reaches_it() { + let (objs, catalog, ids) = groups(1, "/OFF [{B}]"); + let content = format!("/OC /MC0 BDC {} 1 0 0 rg 10 10 30 30 re f {} EMC 0 1 0 rg 0 0 5 5 re f", "/Span BMC ".repeat(200), "EMC ".repeat(200)); + let page = PdfPage { resources: format!("/Properties << /MC0 {} 0 R /MC1 {} 0 R >>", ids[0], ids[1]), ..PdfPage::new(100.0, 100.0, &content) }; + let d = import(&pdf_with_catalog(&[page], &[&objs[0], &objs[1]], &catalog, None)).unwrap(); + let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); + assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); +} From c3f1a17ad1c8e3d89375e491a44ce41b13eb6744 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 15:39:30 +0000 Subject: [PATCH 422/674] test(pdf): keep the offsets for the trailer --- crates/pdf/src/tests/editing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index 3a9fe2a3a6..9cc77ff689 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -146,7 +146,7 @@ fn raw_pdf_bytes(objects: impl IntoIterator>) -> Vec { } let xref = out.len(); out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); - for at in offsets { + for at in &offsets { out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes()); } out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); From 1597bc378bef21c7eb328b8049e506dfa139fd58 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 12:59:05 +0000 Subject: [PATCH 423/674] fix(tools): count hatch scanlines; compact liquify simplification --- crates/tools/src/builder/map.rs | 11 +++-- crates/tools/src/builder/tests.rs | 7 +++ crates/tools/src/distort/liquify.rs | 70 ++++++++++++++++++++--------- 3 files changed, 65 insertions(+), 23 deletions(-) diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index e217d6980d..b2a37c0a75 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -448,9 +448,15 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { y1 = y1.max(a.y.max(c.y)); } let gap = gap.max((y1 - y0) / 400.0).max(1e-6); - let mut y = (y0 / gap).floor() * gap + gap * 0.5; + let start = (y0 / gap).floor() * gap + gap * 0.5; let mut xs: Vec = vec![]; - while y < y1 { + // Counted, not summed: far from the origin `y + gap` can round back to `y`. The gap is at least + // a 400th of the height, so 402 lines cover it. + for i in 0..402u32 { + let y = start + f64::from(i) * gap; + if !(y < y1) { + break; + } xs.clear(); for (a, c) in &edges { if (a.y <= y) != (c.y <= y) { @@ -462,7 +468,6 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { out.move_to(unrot(Point::new(pair[0], y))); out.line_to(unrot(Point::new(pair[1], y))); } - y += gap; } out } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index acaac0ec83..2104609cf7 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -713,6 +713,13 @@ fn hatch_stays_inside_region() { assert!(h.elements().len() > 10); } +#[test] +fn hatch_far_from_the_origin_ends() { + // At 1e17 a 4-point gap is below the coordinates' precision: adding it doesn't move the line. + let bp = shapes::rectangle(Rect::new(0.0, 1e17, 64.0, 1e17 + 64.0)).to_bezpath(); + assert!(hatch(&bp, 4.0).elements().len() <= 2 * 402); +} + /// An empty hidden sources group for a Live Paint group made in a test. fn empty_sources(d: &mut Document) -> Arc { let mut g = Node::group(d.alloc_id(), vec![]); diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index 3e23b769d1..efc68132a1 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -508,31 +508,46 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) { if tol <= 0.0 { return; } + let min = if sp.closed { 4 } else { 3 }; + let src = std::mem::take(&mut sp.anchors); + let n = src.len(); + // Compacted into `out`, each anchor moved once: removing them from the middle one by one + // shifts the rest every time. + let mut out: Vec = Vec::with_capacity(n); + let mut src = src.into_iter().peekable(); + out.extend(src.next()); + let last = if sp.closed { n } else { n.saturating_sub(1) }; let mut i = 1; - loop { - let n = sp.anchors.len(); - let min = if sp.closed { 4 } else { 3 }; - if n < min { - return; - } - let last = if sp.closed { n } else { n - 1 }; - if i >= last { - return; - } - let (pa, k, pb) = (sp.anchors[i - 1], sp.anchors[i], sp.anchors[(i + 1) % n]); - let flat = region.contains(k.p) + while let Some(k) = src.next() { + // Anchors left if `k` stays: those kept, `k`, and those not yet looked at. + let left = out.len() + 1 + src.len(); + let Some(&pa) = out.last() else { break }; + let pb = match src.peek() { + Some(pb) => *pb, + None => out[0], + }; + let flat = i < last + && left >= min + && region.contains(k.p) && [k.p, k.h_in, k.h_out, pa.h_out, pb.h_in].iter().all(|q| dist_seg(*q, pa.p, pb.p) <= tol) && (k.p - pa.p).dot(pb.p - k.p) > 0.0; - if flat { - let lab = pa.p.distance(pb.p); - let (lak, lkb) = (pa.p.distance(k.p).max(1e-9), k.p.distance(pb.p).max(1e-9)); - sp.anchors[i - 1].h_out = pa.p + (pa.h_out - pa.p) * (lab / lak); - sp.anchors[(i + 1) % n].h_in = pb.p + (pb.h_in - pb.p) * (lab / lkb); - sp.anchors.remove(i); - } else { - i += 1; + i += 1; + if !flat { + out.push(k); + continue; + } + let lab = pa.p.distance(pb.p); + let (lak, lkb) = (pa.p.distance(k.p).max(1e-9), k.p.distance(pb.p).max(1e-9)); + if let Some(a) = out.last_mut() { + a.h_out = pa.p + (pa.h_out - pa.p) * (lab / lak); + } + let h_in = pb.p + (pb.h_in - pb.p) * (lab / lkb); + match src.peek_mut() { + Some(b) => b.h_in = h_in, + None => out[0].h_in = h_in, } } + sp.anchors = out; } /// Apply a liquify stroke (its dabs, at the brush's intensity) to `path`. `salt` decorrelates @@ -888,6 +903,21 @@ mod tests { LiquifyParams { intensity: 1.0, ..LiquifyParams::new(kind) } } + #[test] + fn simplify_drops_flat_anchors_and_keeps_the_ends() { + let pts: Vec = (0..200_000).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut open = SubPath::polyline(&pts, false); + let start = std::time::Instant::now(); + simplify(&mut open, 0.5, Rect::new(-1.0, -1.0, 1e6, 1.0)); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); + assert_eq!(open.anchors.iter().map(|a| a.p).collect::>(), [pts[0], pts[199_999]]); + // A closed square with a flat midpoint on each side keeps its four corners. + let ring = [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (10.0, 5.0), (10.0, 10.0), (5.0, 10.0), (0.0, 10.0), (0.0, 5.0)]; + let mut closed = SubPath::polyline(&ring.map(|(x, y)| Point::new(x, y)), true); + simplify(&mut closed, 0.5, Rect::new(-1.0, -1.0, 11.0, 11.0)); + assert_eq!(closed.anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(), [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + } + #[test] fn dabs_are_evenly_spaced() { let d = dabs(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], 10.0); From ca1c317644f415871d1af6ca29415e8c80f77efa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 15:39:30 +0000 Subject: [PATCH 424/674] fix(tools): clippy-friendly scanline bound --- crates/tools/src/builder/map.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index b2a37c0a75..ddcbcb310e 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -454,7 +454,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { // a 400th of the height, so 402 lines cover it. for i in 0..402u32 { let y = start + f64::from(i) * gap; - if !(y < y1) { + if y.partial_cmp(&y1) != Some(std::cmp::Ordering::Less) { break; } xs.clear(); From 8f8d04e5b5bf9322e6745027d6ebfe35db412f97 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:02:50 +0000 Subject: [PATCH 425/674] fix(trace): empty and mismatched rasters, swatch dedupe by set --- crates/trace/src/mosaic.rs | 10 +++++++--- crates/trace/src/quantize.rs | 7 ++++++- crates/trace/src/quantize/palette.rs | 10 +++------- crates/trace/src/tests.rs | 23 +++++++++++++++++++++++ 4 files changed, 39 insertions(+), 11 deletions(-) diff --git a/crates/trace/src/mosaic.rs b/crates/trace/src/mosaic.rs index b8bd46a370..74ded42b50 100644 --- a/crates/trace/src/mosaic.rs +++ b/crates/trace/src/mosaic.rs @@ -7,13 +7,14 @@ const MAX_SIDE: u32 = 4096; /// Average colour (straight RGBA) of each of `cols` × `rows` tiles covering `img`, row by row. /// Transparent pixels count by their alpha, so a tile over transparency fades out. Tiles over the -/// same pixels (more tiles than pixels) are averaged once, and a raster whose bytes are not -/// `width * height * 4` gives transparent tiles. +/// same pixels (more tiles than pixels) are averaged once, and an empty raster or one whose bytes +/// are not `width * height * 4` gives transparent tiles. pub fn mosaic(img: &Raster, cols: u32, rows: u32) -> Vec<[u8; 4]> { let (cols, rows) = (cols.clamp(1, MAX_SIDE), rows.clamp(1, MAX_SIDE)); let tiles = cols as usize * rows as usize; let (w, h) = (img.width as usize, img.height as usize); - if w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) { + // An empty raster has nothing to average (its rows would still be walked, up to 2^32 of them). + if w == 0 || h == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(img.rgba.len()) { return vec![[0; 4]; tiles]; } let mut out = Vec::with_capacity(tiles); @@ -89,6 +90,9 @@ mod tests { // Bytes that are not the raster's size: transparent. let short = Raster { width: 4, height: 4, rgba: vec![] }; assert_eq!(mosaic(&short, 2, 2), vec![[0; 4]; 4]); + // No pixels at all, however tall: transparent, with no rows walked. + let empty = Raster { width: 0, height: u32::MAX, rgba: vec![] }; + assert_eq!(mosaic(&empty, 2, 2), vec![[0; 4]; 4]); // Transparency. let clear = Raster::from_fn(2, 2, |_, _| [9, 9, 9, 0]); assert_eq!(mosaic(&clear, 1, 1), vec![[0, 0, 0, 0]]); diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index a7dac9b2a6..9452671def 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -34,8 +34,13 @@ pub(crate) fn luma(p: [u8; 4]) -> u8 { ((p[0] as u32 * 299 + p[1] as u32 * 587 + p[2] as u32 * 114 + 500) / 1000) as u8 } -/// Reduce `img` to a palette according to `params.mode`. +/// Reduce `img` to a palette according to `params.mode`. A raster whose bytes are not +/// `width * height * 4` (its fields are public) has no pixels to reduce: no labels, no palette. pub fn quantize(img: &Raster, params: &TraceParams) -> Quantized { + let want = (img.width as usize).checked_mul(img.height as usize).and_then(|n| n.checked_mul(4)); + if want != Some(img.rgba.len()) { + return Quantized { labels: vec![], palette: vec![] }; + } quantize_keeping(img, params).0 } diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 8f89a7c960..accffc87e5 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -202,13 +202,9 @@ const FLAT_BINS: usize = 96; /// Document Library: the `k` swatches (at most) that the most pixels are nearest to (see /// [`nearest_library`]). fn library_colors(used: &[Used], swatches: &[[u8; 3]], k: usize) -> Vec<[f64; 3]> { - let mut all: Vec<[f64; 3]> = vec![]; - for s in swatches { - let c = s.map(f64::from); - if !all.contains(&c) { - all.push(c); - } - } + // Each colour once, in their order: looked up in a set, not in the colours kept so far. + let mut seen = std::collections::HashSet::new(); + let all: Vec<[f64; 3]> = swatches.iter().filter(|s| seen.insert(**s)).map(|s| s.map(f64::from)).collect(); let mut weight = vec![0.0; all.len()]; let all_labs = labs(&all); for (_, c, n) in used { diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index f5a10d494a..bcc2242b32 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -428,6 +428,29 @@ fn a_cut_out_edge_leaves_the_color_of_the_art_inside_it_alone() { assert_eq!(q.palette.get(q.labels[12] as usize), Some(&[255, 255, 255]), "{q:?}"); } +#[test] +fn a_library_of_many_repeated_swatches_is_read_once_per_color() { + let img = Raster::from_fn(2, 1, |x, _| if x == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + // 200,000 swatches of 50,000 distinct colours: compared against those kept so far, billions of steps. + let swatches: Vec<[u8; 3]> = (0..200_000u32) + .map(|i| { + let c = i % 50_000; + [(c >> 16) as u8, (c >> 8) as u8, c as u8] + }) + .collect(); + let params = TraceParams { mode: Mode::Color, palette: Palette::DocumentLibrary, swatches, colors: 2, ..TraceParams::default() }; + let start = std::time::Instant::now(); + let q = quantize(&img, ¶ms); + assert!(start.elapsed() < std::time::Duration::from_secs(30), "{:?}", start.elapsed()); + assert_eq!(q.labels.len(), 2); +} + +#[test] +fn a_raster_whose_bytes_are_not_its_size_quantizes_to_nothing() { + let short = Raster { width: 60_000, height: 60_000, rgba: vec![0; 4] }; + assert_eq!(quantize(&short, &TraceParams::default()), Quantized { labels: vec![], palette: vec![] }); +} + #[test] fn a_semi_transparent_stripe_beside_a_cut_out_edge_keeps_its_own_color() { // Columns: transparent, a half-opaque gray edge (white blended with the background), a From 670968f60a51a8626521f32bb2fe852f77100e66 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 12:59:45 +0000 Subject: [PATCH 426/674] perf(text): look only at a paragraph's own runs --- crates/text/src/layout.rs | 9 +++++++-- crates/text/src/shape.rs | 8 +++++++- crates/text/src/tests.rs | 13 +++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 6697776876..9d7ed666ea 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -140,7 +140,9 @@ impl Ctx<'_> { /// stretch. fn char_directions(&self, r: &Range) -> Vec<(Range, ParaDirection)> { let mut out: Vec<(Range, ParaDirection)> = Vec::new(); - for (rr, st) in &self.runs { + // Only the paragraph's own runs (they are in order), not every run of the text. + let first = self.runs.partition_point(|(rr, _)| rr.end <= r.start); + for (rr, st) in self.runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); let Some(d) = st.char_direction.filter(|_| a < b) else { continue }; let (a, b) = (a - r.start, b - r.start); @@ -212,7 +214,10 @@ impl Ctx<'_> { fn prepend_marker(&self, pr: &Range, para: &ParaStyle, text: Option<&str>, rtl: bool, sg: &mut Vec) -> usize { let Some(text) = text.filter(|_| para.list.is_some() && !pr.is_empty()) else { return 0 }; let st = vectorcraft_doc::text::ParaList::marker_style(self.style_at(pr.start)); - let Some(run) = self.runs.iter().position(|(r, _)| r.start <= pr.start && pr.start < r.end) else { return 0 }; + let run = self.runs.partition_point(|(r, _)| r.end <= pr.start); + if !self.runs.get(run).is_some_and(|(r, _)| r.start <= pr.start && pr.start < r.end) { + return 0; + } // The paragraph's direction: the marker starts a right-to-left paragraph at its right. let level = if rtl { Level::rtl() } else { Level::ltr() }; let mut marker = Vec::with_capacity(text.len() + 1); diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index c5f82071d8..a257a3ae84 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -375,7 +375,13 @@ pub(crate) fn shape_range( art: Option<&'a InlineArt>, } let mut spans: Vec> = Vec::new(); - for (ri, (rr, st)) in runs.iter().enumerate() { + // The runs are in order: start at the first that ends inside the range and stop past it, so + // that each paragraph looks only at its own runs. + let first = runs.partition_point(|(rr, _)| rr.end <= range.start); + for (ri, (rr, st)) in runs.iter().enumerate().skip(first) { + if rr.start >= range.end { + break; + } let a = rr.start.max(range.start); let b = rr.end.min(range.end); if a >= b || text.get(a..b).is_none() { diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 3f86a85bdc..002e4b921d 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -555,6 +555,19 @@ fn multiple_runs_and_styles() { assert_ne!(l.glyphs[0].font_id, l.glyphs[3].font_id); } +#[test] +fn many_paragraphs_of_their_own_runs_lay_out_in_linear_time() { + // 20,000 one-letter paragraphs, each a run of its own: every paragraph looking through every + // run would be 400 million steps. + let n = 20_000; + let mut t = point("", style(10.0)); + t.runs = (0..n).map(|i| TextRun { text: "a\n".into(), style: style(if i % 2 == 0 { 10.0 } else { 11.0 }), inline: None }).collect(); + let start = std::time::Instant::now(); + let l = layout(db(), &t); + assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + assert!(l.glyphs.iter().any(|g| g.run == n - 1)); +} + #[test] fn layout_is_fast() { let text: String = LOREM.chars().cycle().take(1000).collect(); From 05bdd182b850dea713943fec96c15a1b3f2959ce Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:01:04 +0000 Subject: [PATCH 427/674] fix(render): charge fx symbol instances, admit CMYK decodes, checked Targa size --- crates/render/src/blobs.rs | 13 +++++++++++-- crates/render/src/encode/tga.rs | 3 ++- crates/render/src/fx/renderer.rs | 16 ++++++++++++++++ crates/render/src/tests.rs | 14 ++++++++++++++ crates/render/src/tests/objectfx.rs | 14 ++++++++++++++ 5 files changed, 57 insertions(+), 3 deletions(-) diff --git a/crates/render/src/blobs.rs b/crates/render/src/blobs.rs index 4ff88e36be..88d7216380 100644 --- a/crates/render/src/blobs.rs +++ b/crates/render/src/blobs.rs @@ -38,8 +38,17 @@ pub(crate) fn blob_pixmap(blob: &vectorcraft_doc::ImageBlob, touch: bool) -> Opt paint::add_decode_failures(1); return None; } - // Decoded outside the lock: other renderers carry on meanwhile. - let pm = match lut.and_then(|lut| ink::cmyk_pixmap(blob, &lut)) { + // Decoded outside the lock: other renderers carry on meanwhile. The inks and the pixels + // shown from them are admitted together, as other images are, before either is made: + // without room the image is read as other images are (which reduces it). + let room = || { + image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())) + .with_guessed_format() + .ok() + .and_then(|r| r.into_dimensions().ok()) + .is_some_and(|(w, h)| paint::within_allowance(w, h.saturating_mul(2))) + }; + let pm = match lut.filter(|_| room()).and_then(|lut| ink::cmyk_pixmap(blob, &lut)) { Some(pm) => pm, None => match paint::decode_pixmap_or_why(&blob.bytes) { Ok(pm) => pm, diff --git a/crates/render/src/encode/tga.rs b/crates/render/src/encode/tga.rs index abac01dba4..031b5f1b61 100644 --- a/crates/render/src/encode/tga.rs +++ b/crates/render/src/encode/tga.rs @@ -34,7 +34,8 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result().0; diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 9512d89d62..987499710f 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -378,6 +378,9 @@ impl Renderer { /// What [`Self::draw_object_fx`] draws inside the object's transparency group. fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc, cache: bool) { + if !self.charge_fx_instance(f.doc, a) { + return; + } let art = self.fx_art(f.doc, a, cache); // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); @@ -410,6 +413,19 @@ impl Renderer { self.made_again = outer; } + /// Whether the frame has room for the art of `a` when it is a symbol instance, charged to the + /// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose + /// effects reshape its art draws through here, and nested instances would otherwise expand + /// without a limit. True for any other object. + pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool { + let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true }; + let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64); + let mut used = self.symbol_nodes; + let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some(); + self.symbol_nodes = used; + room + } + /// The art [`Self::draw_object_fx`] draws for `a` (cached by `Arc` identity when `cache`): /// reshaped by its geometry effects, else type, images and paths as themselves and the others /// as their evaluated art (groups and layers: [`effects::evaluate_container`], keeping their diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 81a91d8ea8..e1ded30c8e 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1322,6 +1322,20 @@ fn a_kept_decoded_image_is_drawn_without_decoding_it() { assert!(!image_cached(&cmyk)); } +/// A CMYK image's inks and the pixels shown from them are admitted against the decode allowance +/// before either is made: past it, the image is read as other images are (reduced), not whole. +#[test] +fn cmyk_images_past_the_allowance_are_not_decoded_whole() { + use vectorcraft_doc::ImageBlob; + use vectorcraft_doc::cmyk::Inks; + let cmyk = ImageBlob::cmyk_tiff(&Inks::new(64, 48, [11, 22, 33, 44].repeat(64 * 48)).unwrap()).unwrap(); + let whole = with_allowance(1 << 20, || crate::blobs::blob_pixmap(&cmyk, false)).map(|(_, pm)| (pm.width(), pm.height())); + assert_eq!(whole, Some((64, 48)), "within the allowance, whole"); + let other = ImageBlob::cmyk_tiff(&Inks::new(64, 48, [12, 22, 33, 44].repeat(64 * 48)).unwrap()).unwrap(); + let small = with_allowance(64 * 48 * 4 - 1, || crate::blobs::blob_pixmap(&other, false)).map(|(_, pm)| (pm.width(), pm.height())); + assert_ne!(small, Some((64, 48)), "past it, not decoded whole"); +} + /// An image drawn larger than its pixels samples smoothly, or with `smooth_images` off each screen /// pixel takes its nearest image pixel (Pixel Preview with File Handling › Display Bitmaps as /// Anti-aliased Images off, #394). diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 85f7505dde..edc044f0ad 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -884,3 +884,17 @@ fn darkness_adjusts_gradient_stop_colors_before_interpolation() { } } } + +/// A symbol instance with object effects is charged to the frame's symbol budget like one +/// without: past the budget it isn't expanded. +#[test] +fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() { + let d = symbol_doc(vec![fx("distort.roughen", json!({}))]); + let inst = d.layers[0].children().unwrap()[0].clone(); + let mut r = Renderer::new(); + r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1; + assert!(r.charge_fx_instance(&d, &inst), "one object fits"); + assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); + assert!(!r.charge_fx_instance(&d, &inst), "the next does not"); + assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); +} From c9d73ece85f636e963612c219e48965e86740d71 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:05:47 +0000 Subject: [PATCH 428/674] fix(fonts): confine craft-fonts manifest paths and publish licences as text --- crates/text/build.rs | 5 ++++ crates/text/build/web_fonts.rs | 4 ++- xtask/src/web_fonts.rs | 54 ++++++++++++++++++++++++++++------ 3 files changed, 53 insertions(+), 10 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index 25544a3a60..412c471c11 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -81,6 +81,7 @@ fn craft_fonts(dir: &Path) -> Result { println!("cargo::rerun-if-changed={}", manifest.display()); let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); + let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; let mut out = String::new(); for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { let f: Vec<&str> = line.split(" | ").map(str::trim).collect(); @@ -91,6 +92,10 @@ fn craft_fonts(dir: &Path) -> Result { continue; } let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; + // The manifest is supplier data: embed only regular files inside the checkout. + if !path.starts_with(&root) || !path.is_file() { + return Err(format!("{file}: not a file inside the font checkout")); + } println!("cargo::rerun-if-changed={}", path.display()); let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( diff --git a/crates/text/build/web_fonts.rs b/crates/text/build/web_fonts.rs index a2e2a8054e..ccd387afab 100644 --- a/crates/text/build/web_fonts.rs +++ b/crates/text/build/web_fonts.rs @@ -69,7 +69,8 @@ pub fn sri(hex: &str) -> Option { /// name>`. Relative, so the site works under any path; content-addressed, so it can be cached /// forever. pub fn url(sha256: &str, file: &str) -> String { - let name = file.rsplit('/').next().unwrap_or(file); + // Either separator: on Windows a backslash in supplier data would otherwise pick a folder. + let name = file.rsplit(['/', '\\']).next().unwrap_or(file); format!("fonts/{}/{name}", sha256.get(..16).unwrap_or(sha256)) } @@ -98,6 +99,7 @@ mod tests { fn url_is_relative_and_content_addressed() { let sha = "63111b5b2e074dd48cc67692e0a2726d86ee94c1c37fe8598257b7b4e87e869e"; assert_eq!(url(sha, "fonts/noto-sans-arabic/NotoSansArabic.ttf"), "fonts/63111b5b2e074dd4/NotoSansArabic.ttf"); + assert_eq!(url(sha, "fonts\\..\\..\\NotoSansArabic.ttf"), "fonts/63111b5b2e074dd4/NotoSansArabic.ttf"); assert!(!url(sha, "x.ttf").starts_with('/')); } diff --git a/xtask/src/web_fonts.rs b/xtask/src/web_fonts.rs index 4399913a83..b5f3e42d2e 100644 --- a/xtask/src/web_fonts.rs +++ b/xtask/src/web_fonts.rs @@ -51,7 +51,8 @@ fn copy(list_path: &Path, dir: &Path, site: &Path) -> Result<(usize, Vec let (Some(file), Some(licence), Some(sha)) = (row.get(2), row.get(5), row.get(6)) else { return Err(format!("malformed manifest row for {} {}", e.family, e.style)); }; - let bytes = std::fs::read(dir.join(file)).map_err(|err| format!("{file}: {err}"))?; + let root = std::fs::canonicalize(dir).map_err(|err| format!("{}: {err}", dir.display()))?; + let bytes = std::fs::read(inside(&root, file)?).map_err(|err| format!("{file}: {err}"))?; let got = sha256::hex(&bytes); if got != *sha { return Err(format!("{file}: sha256 {got}, manifest says {sha}")); @@ -60,19 +61,29 @@ fn copy(list_path: &Path, dir: &Path, site: &Path) -> Result<(usize, Vec let folder = dest.parent().ok_or_else(|| format!("{}: no parent folder", dest.display()))?; std::fs::create_dir_all(folder).map_err(|err| format!("{}: {err}", folder.display()))?; std::fs::write(&dest, &bytes).map_err(|err| format!("{}: {err}", dest.display()))?; - let licence_name = Path::new(licence).file_name().ok_or_else(|| format!("{licence}: not a file"))?; - // The manifest is supplier data: the licence must be a file inside the checkout. - let root = std::fs::canonicalize(dir).map_err(|err| format!("{}: {err}", dir.display()))?; - let src = std::fs::canonicalize(dir.join(licence)).map_err(|err| format!("{licence}: {err}"))?; - if !src.starts_with(&root) || !src.is_file() { - return Err(format!("{licence}: not a file inside the font checkout")); - } - std::fs::copy(&src, folder.join(licence_name)).map_err(|err| format!("{licence}: {err}"))?; + let src = inside(&root, licence)?; + // Served as plain text whatever the supplier named it: a `.html` licence would be a page. + let stem = src.file_stem().ok_or_else(|| format!("{licence}: not a file"))?.to_string_lossy(); + std::fs::copy(&src, folder.join(format!("{stem}.txt"))).map_err(|err| format!("{licence}: {err}"))?; copied += 1; } Ok((copied, skipped)) } +/// The biggest font or licence file copied (bytes). +const MAX_FILE: u64 = 64 << 20; + +/// Manifest path `file` (supplier data) as a regular file of at most [`MAX_FILE`] bytes inside the +/// canonical checkout `root`: no `..`, absolute path or symlink out of it, and no device or FIFO. +fn inside(root: &Path, file: &str) -> Result { + let src = std::fs::canonicalize(root.join(file)).map_err(|err| format!("{file}: {err}"))?; + let meta = std::fs::metadata(&src).map_err(|err| format!("{file}: {err}"))?; + if !src.starts_with(root) || !meta.is_file() || meta.len() > MAX_FILE { + return Err(format!("{file}: not a file of at most {MAX_FILE} bytes inside the font checkout")); + } + Ok(src) +} + #[cfg(test)] mod tests { use super::*; @@ -127,6 +138,31 @@ mod tests { assert!(e.contains("inside the font checkout"), "{e}"); } + #[test] + fn a_font_path_that_leaves_the_checkout_or_is_no_file_is_refused() { + let (list, dir, site, _) = fixture("font-escape", None); + let m = dir.join("fonts/manifest.txt"); + let manifest = std::fs::read_to_string(&m).unwrap(); + let outside = dir.parent().unwrap().join("secret.ttf"); + std::fs::write(&outside, b"secret").unwrap(); + for path in ["../secret.ttf", outside.to_str().unwrap(), "fonts/a"] { + std::fs::write(&m, manifest.replace("fonts/a/A-Regular.ttf", path)).unwrap(); + let e = copy(&list, &dir, &site).unwrap_err(); + assert!(e.contains("inside the font checkout"), "{path}: {e}"); + } + } + + #[test] + fn a_licence_is_published_as_text() { + let (list, dir, site, sha) = fixture("html-licence", None); + std::fs::write(dir.join("fonts/a/LICENSE.html"), b"