From 1c7fc27b42a1a8438c868b704dc45eb933b8f6f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:18:13 -0800 Subject: [PATCH 01/36] Scripts: app.selectTool picks a tool app.selectTool(name) takes a tool's id (pen), its label (Pen Tool) or a tool name in the form scripts pass, returns true, and makes that tool the current tool when the run ends without an error. The tool chosen last in a run counts, and a run that fails leaves the tool as it was. An unknown name throws, a name that is not a string throws a TypeError, and a name over 4,096 bytes throws a RangeError. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 77 ++++++++++++++++++++++++++- crates/engine/src/script/mod.rs | 8 +++ crates/engine/src/tests/script_dom.rs | 29 ++++++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 5 files changed, 121 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cb901014b5..a3456e8590 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -25,6 +25,9 @@ //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. +//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at +//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an +//! error. A run that fails leaves the tool as it was. //! - Members the help pages list that are not here yet throw an error that says so. use std::cell::{Cell, RefCell}; @@ -88,7 +91,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the lists of page items and the /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is -/// open, and the settings of each `DocumentPreset` the run made. +/// open, the settings of each `DocumentPreset` the run made, and the tool `app.selectTool` chose +/// last. #[derive(Default)] pub(super) struct State { coords: Cell, @@ -96,6 +100,7 @@ pub(super) struct State { locked: RefCell>, saving: Cell, presets: RefCell>>, + tool: Cell>, } impl State { @@ -103,6 +108,12 @@ impl State { pub(super) fn saving(&self) -> bool { self.saving.get() } + + /// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool + /// when the run ends without an error. + pub(super) fn chosen_tool(&self) -> Option<&'static str> { + self.tool.get() + } } /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every @@ -732,6 +743,69 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(open)) } +/// The start of the tool names that scripts pass to `app.selectTool`, as the list at +/// gives them. +const TOOL_NAME_PREFIX: &str = "Adobe "; // brand-ok: the start of the tool names scripts pass + +/// The names on that list, without [`TOOL_NAME_PREFIX`], whose words differ from the label of the +/// VectorCraft tool they choose, with that tool's id. Names whose words are a VectorCraft tool's +/// label (`Pen Tool`) choose that tool without a row here. The pairs are VectorCraft's own. +const TOOL_NAMES: &[(&str, &str)] = &[ + ("Select Tool", "selection"), + ("Direct Select Tool", "directSelection"), + ("Direct Object Select Tool", "groupSelection"), + ("Direct Lasso Tool", "lasso"), + ("Path Type Tool", "typeOnPath"), + ("Vertical Path Type Tool", "verticalTypeOnPath"), + ("Line Tool", "lineSegment"), + ("Shape Construction Regular Polygon Tool", "polygon"), + ("Shape Construction Star Tool", "star"), + ("Shape Construction Spiral Tool", "spiral"), + ("Brush Tool", "paintbrush"), + ("Freehand Tool", "pencil"), + ("Freehand Smooth Tool", "smooth"), + ("Freehand Erase Tool", "pathEraser"), + ("Corner Join Tool", "join"), + ("Knife Tool", "knife"), + ("New Twirl Tool", "twirl"), + ("Cyrstallize Tool", "crystallize"), + ("Planar Paintbucket Tool", "livePaintBucket"), + ("Planar Face Select Tool", "livePaintSelection"), + ("Mesh Editing Tool", "mesh"), + ("Gradient Vector Tool", "gradient"), + ("Crop Tool", "artboard"), + ("Slice Select Tool", "sliceSelection"), + ("Scroll Tool", "hand"), + ("Page Tool", "printTiling"), +]; + +/// The id of the tool `name` names: a tool's id (`pen`), its label (`Pen Tool`), or a name of the +/// list [`TOOL_NAME_PREFIX`] cites. +fn tool_named(name: &str) -> Option<&'static str> { + let tools = || vectorcraft_tools::catalog::all_tools(); + if let Some(t) = tools().find(|t| t.id == name || t.label == name) { + return Some(t.id); + } + let rest = name.strip_prefix(TOOL_NAME_PREFIX)?; + if let Some((_, id)) = TOOL_NAMES.iter().find(|(n, _)| *n == rest) { + return vectorcraft_tools::tool_info(id).map(|t| t.id); + } + tools().find(|t| t.label == rest).map(|t| t.id) +} + +/// `app.selectTool(name)`: chooses the tool `name` names ([`tool_named`]) and gives `true`. The +/// tool becomes the current tool when the run ends without an error, as a choice on the toolbar +/// does; the tool chosen last in a run is the one that counts. A name no tool has throws. +fn app_select_tool(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("selectTool needs a tool name, as a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the tool name is too long".into())); + } + let id = tool_named(name).ok_or_else(|| HostError::Error(format!("No tool is named \"{name}\"")))?; + h.dom.tool.set(Some(id)); + Ok(Data::Bool(true)) +} + // ---- Documents ---- fn docs_length(h: &Host, _: &[Data]) -> Answer { @@ -1948,6 +2022,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("selectTool", method(l, app_select_tool)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index affacab584..dc4bd20008 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2291,7 +2291,15 @@ impl Session { }); host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); + let tool = host.dom.chosen_tool(); self.end_job(job, false); + // The tool `app.selectTool` chose last becomes the current tool, as a choice on the + // toolbar makes it; the run's changes are kept when the tool cannot be chosen. + if let Some(id) = tool + && let Err(e) = self.select_tool(id, self.last_view) + { + report["toolError"] = json!(e.to_string()); + } self.script_report = Some(report.clone()); Ok(report) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 60e3a71521..a0c6e8afbc 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1314,6 +1314,35 @@ fn prototype_changes_cannot_forge_a_page_item() { assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); } +#[test] +fn select_tool_makes_the_named_tool_current_when_the_run_ends() { + let (mut s, _, _) = doc(); + assert_eq!(s.tool_id(), "selection"); + // A tool's id, its label and a name in the form scripts pass all choose it; the last one counts. + assert_eq!(log(&mut s, "vc.log(app.selectTool('pen'));"), vec![json!(true)]); + assert_eq!(s.tool_id(), "pen"); + log(&mut s, "app.selectTool('Rectangle Tool');"); + assert_eq!(s.tool_id(), "rectangle"); + log(&mut s, "app.selectTool('Adobe Ellipse Tool'); app.selectTool('Adobe Direct Select Tool');"); + assert_eq!(s.tool_id(), "directSelection"); + log(&mut s, "app.selectTool('Adobe Select Tool');"); + assert_eq!(s.tool_id(), "selection"); + // An unknown name throws, a caught error chooses nothing, and a run that fails leaves the tool. + assert!(failure(&mut s, "app.selectTool('No Such Tool');").contains("No tool is named \"No Such Tool\"")); + assert!(failure(&mut s, "app.selectTool('Adobe ');").contains("No tool is named")); + let out = log(&mut s, "try { app.selectTool('pencil tool'); } catch (e) { vc.log(e.message); }"); + assert_eq!(out, vec![json!("No tool is named \"pencil tool\"")]); + assert!(failure(&mut s, "app.selectTool('pen'); throw new Error('stop');").contains("stop")); + let out = log(&mut s, "try { app.selectTool(5); } catch (e) { vc.log(e.name); }"); + assert_eq!(out, vec![json!("TypeError")]); + assert!(failure(&mut s, "app.selectTool(new Array(5000).join('a'));").contains("too long")); + assert_eq!(s.tool_id(), "selection"); + // With no document open the tool is chosen too. + let mut empty = Session::new(); + log(&mut empty, "app.selectTool('Adobe Freehand Tool');"); + assert_eq!(empty.tool_id(), "pencil"); +} + #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 4685f408d7..5b4d5b342b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,7 +2622,13 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem`, `app.getIsFileOpen(path)` and `app.selectTool(name)`. `selectTool` + (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942) takes a tool's id + (`pen`), its label (`Pen Tool`) or a tool name in the form that thread lists, returns `true`, and makes the tool it + names the current tool when the run ends without an error; the tool chosen last in a run is the one that counts, + and a run that fails leaves the tool as it was. A name no tool has throws `No tool is named ""`, a name that + is not a string throws a `TypeError`, and a name of more than 4,096 bytes throws a `RangeError`. Which tool each + name in that thread chooses is VectorCraft's own reading; names with no VectorCraft tool throw. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..607fd49b5e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). `app.selectTool(name)` makes the named tool the current tool when the run ends (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 24d91e2acf564c5124618e7357e6f0abe202fa19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:31:57 -0800 Subject: [PATCH 02/36] Script checker: app.selectTool counts as the document model, not a feature only the reference app has --- crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/tests.rs | 2 +- docs/mcp.md | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..c1203504ca 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -181,7 +181,7 @@ features! { ScriptuiDrawing "scriptui.drawing" Dialogs, ScriptuiPalette "scriptui.palette" HostOnly, ScriptuiWindow "scriptui.window" Dialogs, - SelectTool "selectTool" HostOnly, + SelectTool "selectTool" Dom, Socket "socket" HostOnly, UnitValue "unitValue" Language, Xml "xml" HostOnly, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 6985791fe1..2d57f40f94 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1521,7 +1521,7 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { fn application_methods_are_features_not_members() { let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n"); assert!(r.members.is_empty(), "{:?}", r.members); - assert_eq!(r.needs, [Need::MenuCommands, Need::HostOnly]); + assert_eq!(r.needs, [Need::Dom, Need::MenuCommands]); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 350d017c4f..6902e16314 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2563,9 +2563,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's - document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions - and `selectTool`). + document model, `app.selectTool` included), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the + reference app has: palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, + reflection and actions). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and `locale`. A directive is read where it starts a line, written `#name` or `//@name`. From 7f7effc8fbd8695a9ba30e649a14b7fc687ffe1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:59:51 -0800 Subject: [PATCH 03/36] Scripts: New Document profiles are read without following a link, and review fixes - A New Document profile is opened without following a link (O_NOFOLLOW on Unix, FILE_FLAG_OPEN_REPARSE_POINT on Windows), and its kind and bytes are read from that open file. A link put in the profile's place after the plain-file check is refused instead of read. - Page item and layer handles go stale when their document is reverted. - controlBounds holds the control points of the object's paths. - PageItems.toString() throws Stale document for a collection kept from an earlier run. - Assigning an object the opacity it reports runs no command, except on a graph mark or label whose graph keeps another opacity. - An object-model edit and the steps that restore the selection, layer and active document succeed or fail together. - hasOwnProperty and propertyIsEnumerable stop at an unavailable member that hides one of a parent class. - Assigning a name that a non-extensible host object inherits no longer looks the name up with the object's indexer. - The Application prototype inventory lists selectTool. - docs/mcp.md names the Stale document error, and the parity line says the tool changes only when the run ends without an error. --- crates/engine/Cargo.toml | 7 +- crates/engine/src/cmd/newdoc.rs | 6 +- crates/engine/src/script/dom.rs | 80 +++++++++++++++---- crates/engine/src/store.rs | 46 +++++++++++ crates/engine/src/tests/script_dom.rs | 77 ++++++++++++++++-- crates/engine/src/tests/store.rs | 18 +++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/host_classes.rs | 14 +++- crates/js/src/host_tests.rs | 19 +++++ crates/js/src/interp.rs | 13 +-- docs/mcp.md | 7 +- docs/target-app-parity.md | 2 +- 12 files changed, 252 insertions(+), 39 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 7e6028b045..bb8277a9ab 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -70,10 +70,11 @@ serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } -# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in -# Cargo.lock (tempfile, ui-egui), so this adds no new crate. +# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a +# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile, +# ui-egui), so this adds no new crate. [target.'cfg(unix)'.dependencies] -rustix = { workspace = true, features = ["std", "process"] } +rustix = { workspace = true, features = ["std", "process", "fs"] } # Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), # and whether two paths a script names are one file (`script::files`). Already in Cargo.lock diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 8272f7d8cb..47dd425555 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -1017,11 +1017,13 @@ impl Session { match std::fs::symlink_metadata(&path) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), // A link is refused: the script's gate does not check where it leads. - Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), + Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()), _ => {} } crate::file_access::check_read(&file).map_err(denied)?; - crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + // Read without following a link, so a link put in the file's place since the check + // above is refused too. + crate::store::read_capped_plain(&path, MAX_PROFILE_BYTES).map(Some) })?; let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1f4d8de478..ca7bc3ba77 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -367,6 +367,14 @@ fn find_doc(h: &Host, run: f64, uid: f64) -> Option { s.documents().iter().position(|d| d.uid == uid).map(|index| Doc { index, uid }) } +/// [`find_doc`] for the handle of an object in a document: none as well when the document was +/// reverted since the handle was made, as its objects were read again from its file. +fn find_doc_of_object(h: &Host, run: f64, uid: f64, reverts: f64) -> Option { + let doc = find_doc(h, run, uid)?; + let s = h.session.borrow(); + (whole(reverts) == Some(s.documents()[doc.index].reverts)).then_some(doc) +} + /// The document `d` names: a `Document` or a `PageItems` object. fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result { let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; @@ -379,8 +387,8 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc_of_object(h, *run, *uid, *reverts).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; @@ -418,8 +426,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), }, None => Data::Null, } @@ -653,12 +661,24 @@ fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> /// commands changed it (commands given ids select them first), direct-selected anchors, segments, /// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic /// symbol instance or an Objects on Path group included, less the objects that are now deleted, -/// hidden or locked. +/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together +/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s +/// changes are undone as well. fn on_doc( h: &Host, uid: u64, keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + atomically(h, |h| on_doc_steps(h, uid, keep_selection, f)) +} + +/// The steps of [`on_doc`]. +fn on_doc_steps( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { let (index, active, before, layer) = { let s = h.session.borrow(); @@ -1452,6 +1472,11 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("PageItems")) } +fn items_to_string(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("[PageItems]")) +} + fn items_parent(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) @@ -1654,9 +1679,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - // A value the getter reports for the item's opacity sends the opacity it has, and - // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still - // replaces the one the graph keeps for its series or kind. + // A value the getter reports for the item's opacity runs no command, unless the item is a graph + // mark or label whose graph keeps another opacity for its series or kind: then the opacity the + // item has is sent, and replaces the one the graph keeps. // The opacity the item already has may be assigned while its layer is hidden or locked, unless // it would still replace the opacity a graph keeps for the item's series or kind. let item = this_item(h, a)?; @@ -1671,7 +1696,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if now.is_none() || keeps_other { refuse_in_closed_layer(h, item)?; } - set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) + set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { @@ -1717,6 +1742,31 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds, grown to hold the control points of the item's paths. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = with_doc(h, item.doc, |_, st| { + let control = st.doc.node(item.id).and_then(control_points_box); + Ok::<_, HostError>((vectorcraft_geom::union_opt(st.doc.bounds_of(&[item.id], true), control), frame(st)?)) + })?; + match r { + Some(r) => Ok(f.bounds(h.dom.coords.get(), r)), + None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } +} + +/// The box of the control points of the paths in `n`, the visible members of its groups and +/// compound paths included; none for other art. +fn control_points_box(n: &crate::doc::Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Group { .. } | NodeKind::Compound { .. } => { + n.children()?.iter().filter(|c| c.visible).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, control_points_box(c))) + } + _ => None, + } +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; match item_rect(h, item, false)? { @@ -1895,13 +1945,13 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(&[run, uid, reverts, high, low]) = handle.as_deref() else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let doc = find_doc_of_object(h, run, uid, reverts).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } @@ -2069,8 +2119,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let doc = find_doc_of_object(h, *run, *uid, *reverts).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } @@ -2223,7 +2273,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("index", method(l, items_index)), ("getByName", method(l, items_by_name)), ("removeAll", method(l, items_remove_all)), - ("toString", class_text("PageItems")), + ("toString", method(l, items_to_string)), ]), Some(function(l, items_at)), )); @@ -2243,7 +2293,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 7afab7426d..703597dc45 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -187,6 +187,52 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { Ok(bytes) } +/// What [`read_capped_plain`] tells a path that is not a plain file. +pub(crate) const NOT_PLAIN: &str = "not a plain file"; + +/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without +/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and +/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check +/// is refused with [`NOT_PLAIN`] rather than read. +pub(crate) fn read_capped_plain(path: &Path, max: u64) -> Result, String> { + let file = open_no_link(path).map_err(|e| match std::fs::symlink_metadata(path) { + Ok(m) if !m.file_type().is_file() || reparse_point(&m) => NOT_PLAIN.to_string(), + _ => e.to_string(), + })?; + let m = file.metadata().map_err(|e| e.to_string())?; + if !m.file_type().is_file() || reparse_point(&m) { + return Err(NOT_PLAIN.to_string()); + } + let mut bytes = vec![]; + file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > max { + return Err(too_large(max)); + } + Ok(bytes) +} + +/// `path` opened for reading, without following a link there. A pipe put in its place does not hold +/// the open up. +#[cfg(unix)] +fn open_no_link(path: &Path) -> std::io::Result { + use std::os::unix::fs::OpenOptionsExt; + let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK; + std::fs::OpenOptions::new().read(true).custom_flags(flags.bits() as i32).open(path) +} + +/// `path` opened for reading; a link or junction there is opened itself, not its target. +#[cfg(windows)] +fn open_no_link(path: &Path) -> std::io::Result { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path) +} + +#[cfg(not(any(unix, windows)))] +fn open_no_link(path: &Path) -> std::io::Result { + std::fs::File::open(path) +} + /// What a file over its cap is told (a detail after the file's name, in the log or an error). fn too_large(max: u64) -> String { format!("larger than {max} bytes") diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4deef14b04..516992c07e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -155,6 +155,27 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); } +/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the +/// visible bounds. +#[test] +fn control_bounds_hold_the_handles_of_a_curve() { + let (mut s, _, _) = doc(); + s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, c = p[0], r = p[1];\ + function h(b) { return b[1] - b[3]; }\ + vc.log([h(c.visibleBounds), h(c.controlBounds), c.controlBounds[0] <= c.visibleBounds[0]]);\ + vc.log(String(r.controlBounds) === String(r.visibleBounds));", + ); + let heights = out[0].as_array().unwrap(); + let (visible, control) = (heights[0].as_f64().unwrap(), heights[1].as_f64().unwrap()); + // The curve rises 75 pt and its handles 100 pt; half the stroke's weight reaches above the curve. + assert!(control - visible > 20.0 && control - visible <= 25.0 + 1e-6, "{out:?}"); + assert_eq!(heights[2], json!(true), "{out:?}"); + assert_eq!(out[1], json!(true), "{out:?}"); +} + #[test] fn convert_coordinate_pair_is_inverse_and_y_up() { let mut s = Session::new(); @@ -270,6 +291,7 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(out, vec![json!(33.3333)]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); + assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command"); // A value close to the reported one but not equal to it is still applied. s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); @@ -285,6 +307,14 @@ fn selection_assignment_is_atomic_across_invalid_items() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); assert!(e.contains("Cannot select PathItem"), "{e}"); assert!(s.active().unwrap().selection.objects.is_empty()); + // With the valid item first and the error caught, the run sees the selection unchanged. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems; try { d.selection = [p[1], p[0]]; vc.log('assigned'); }\ + catch (e) { vc.log(String(e).indexOf('Cannot select PathItem') >= 0); } vc.log(d.selection.length);", + ); + assert_eq!(out, vec![json!(true), json!(0)]); + assert!(s.active().unwrap().selection.objects.is_empty()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log( &mut s, @@ -680,9 +710,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); - for (member, message) in - [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] - { + for (member, message) in [ + ("d.typename", "Stale document"), + ("d.parent", "Stale document"), + ("p.typename", "Stale document"), + ("p.toString()", "Stale document"), + ("l.typename", "Stale"), + ] { let e = failure(&mut s, &format!("#targetengine keep\n{member};")); assert!(e.contains(message), "{member}: {e}"); } @@ -1192,6 +1226,27 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +/// Reverting a document reads its objects again from its file, so the page items and layers taken +/// before the revert are stale, even where the file has an object under the same id. +#[test] +fn page_items_and_layers_go_stale_when_their_document_is_reverted() { + let (mut s, _, _) = doc(); + let path = std::env::temp_dir().join(format!("vc-dom-revert-{}.{}", std::process::id(), vectorcraft_format::EXTENSION)); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for (taken, read, message) in [("p[0]", "i.name", "Stale page item"), ("p[0].parent", "i.typename", "Stale")] { + let source = format!("var p = app.activeDocument.pageItems, i = {taken}; p[1].name = 'x'; vc.run('file.revert', {{}}); {read};"); + let e = failure(&mut s, &source); + assert!(e.contains(message), "{taken}: {e}"); + } + let out = log( + &mut s, + "app.activeDocument.pageItems[1].name = 'x'; vc.run('file.revert', {}); var p = app.activeDocument.pageItems;\ + vc.log([p.length, p[0].typename, p[1].name]);", + ); + assert_eq!(out, vec![json!([2, "PathItem", ""])]); + let _ = std::fs::remove_file(path); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); @@ -1199,6 +1254,14 @@ fn remove_all_refuses_locked_art_before_deleting_anything() { let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); assert!(e.contains(&b.0.to_string()), "{e}"); assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + // With the error caught, the run that goes on still has both objects. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; try { p.removeAll(); vc.log('removed'); }\ + catch (e) { vc.log(String(e).indexOf('cannot delete hidden or locked objects') >= 0); } vc.log(p.length);", + ); + assert_eq!(out, vec![json!(true), json!(2)]); + assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); // A locked object inside an unlocked group stops it too. s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); @@ -1345,8 +1408,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy(); + let (saved, other) = (json!(p), json!(format!("{p}.other"))); + let query = format!("vc.log(app.getIsFileOpen({saved})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. @@ -1652,6 +1716,9 @@ fn a_collection_read_with_a_name_gives_the_named_object() { vc.log(m);", ); assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); + // A name the collection inherits is not looked up as an object's name when it is assigned. + let out = log(&mut s, "Object.prototype.tag = 1; var p = app.activeDocument.pageItems; p.tag = 2; vc.log(p.tag);"); + assert_eq!(out, vec![json!(1)]); } /// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index 21967473bb..dfc603dc59 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -157,6 +157,24 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() { assert!(holds(&[][..], &[])); } +#[cfg(unix)] +#[test] +fn a_plain_capped_read_refuses_a_link_and_reads_a_plain_file() { + use crate::store::{NOT_PLAIN, read_capped_plain}; + let root = fresh_dir("plain-read"); + let target = root.join("target.bin"); + std::fs::write(&target, b"outside").unwrap(); + let link = root.join("profile.vectorcraft"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert_eq!(read_capped_plain(&link, 100), Err(NOT_PLAIN.to_string())); + let folder = root.join("folder"); + std::fs::create_dir(&folder).unwrap(); + assert_eq!(read_capped_plain(&folder, 100), Err(NOT_PLAIN.to_string())); + assert_eq!(read_capped_plain(&target, 100), Ok(b"outside".to_vec())); + assert_eq!(read_capped_plain(&target, 7), Ok(b"outside".to_vec())); + assert!(read_capped_plain(&target, 6).is_err()); +} + #[test] fn a_saved_preset_replaces_an_oversized_file_in_its_place() { let root = fresh_dir("oversized-put"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 4368ce29b7..aacf3017d5 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -83,7 +83,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection selection= toString typename", + selection selection= selectTool toString typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..a25e0e531a 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -91,6 +91,9 @@ pub(crate) struct Entry { parent: Option, /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. own: Rc>, + /// The names of the unavailable members, which hide a member of the same name that a parent + /// class has. + unavailable: Rc>, } impl Entry { @@ -143,7 +146,8 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { impl Interp { /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host - /// class, and `k` names an available member of that class or of a class it descends from. + /// class, and `k` names an available member of the nearest class that declares `k`, that class + /// or one it descends from. pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult { let Class::Host(h) = &self.object(id)?.class else { return Ok(false) }; let mut class = Some(h.class); @@ -152,6 +156,9 @@ impl Interp { if e.own.contains(k) { return Ok(true); } + if e.unavailable.contains(k) { + return Ok(false); + } class = e.parent; } Ok(false) @@ -307,7 +314,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + let (unavailable, members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_))); i.host_classes.push(Entry { name: class.name.as_str().into(), proto, @@ -315,7 +322,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { index: class.index, family, parent: parent_class, - own: Rc::new(members), + own: Rc::new(members.into_iter().map(|(name, _)| key(name)).collect()), + unavailable: Rc::new(unavailable.into_iter().map(|(name, _)| key(name)).collect()), }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index ba0e005ce0..ce695b7e06 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -717,6 +717,25 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() { ); } +#[test] +fn an_unavailable_member_hides_the_member_its_parent_class_has() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let class = |name: &str, parent: Option<&str>, member: HostMember| HostClass { + name: name.into(), + parent: parent.map(Into::into), + members: vec![("size".to_string(), member)], + index: None, + construct: None, + }; + let classes = vec![class("Base", None, HostMember::Get(value)), class("Leaf", Some("Base"), HostMember::Unavailable(missing))]; + let objects = vec![("it".into(), host_ref("Leaf", &[1.0])), ("base".into(), host_ref("Base", &[2.0]))]; + r.define_host_classes(classes, objects).unwrap(); + r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), base.hasOwnProperty('size')].join()").unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into())); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f7cb2896a2..f10f0e9566 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1859,16 +1859,17 @@ impl Interp { None => {} } let proto = self.object(id)?.proto; - match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { + let inherited = match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), - _ => {} - } + found => found.is_some(), + }; if !self.object(id)?.extensible { - // A name that an object of a host class with an indexer lacks is read with the indexer - // first, so assigning it throws what reading it throws. - if array_index(&k).is_none() + // A name that an object of a host class with an indexer lacks, on it and its prototypes, + // is read with the indexer first, so assigning it throws what reading it throws. + if !inherited + && array_index(&k).is_none() && let Some(f) = self.host_indexer(id)? { self.host_index(&f, id, Self::indexer_key(&k), false)?; diff --git a/docs/mcp.md b/docs/mcp.md index 6902e16314..e221d601d1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2709,7 +2709,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, + visible bounds, grown to hold the control points of the object's paths), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs @@ -2761,8 +2761,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers - panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was - deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that + panel rows as they were before the change. A bad value throws an error and changes nothing. A page item that was + deleted, or that a named engine kept from an earlier run, throws `Stale page item`, and a document or a page item + collection that a named engine kept from an earlier run throws `Stale document`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7d6ec78683..db38ae94f7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1033,7 +1033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.selectTool(name)` makes the named tool the current tool when the run ends (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 4021d27d5a9d71269baf7107e4d8e92a8e3015eb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 11:27:37 -0800 Subject: [PATCH 04/36] Format the native layer appearance regressions --- crates/ui-egui/src/panels/layers/tests.rs | 31 +++++++++++++++-------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 6ca4cefe9c..29ea72202a 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -797,10 +797,13 @@ fn appearance_diamond(shape: &egui::Shape) -> Option<(egui::Pos2, f32, f32)> { fn target_marks_painted(panel: &mut crate::tests::panel_harness::Panel, name: &str) -> Vec<(f32, bool, f32)> { let center = panel.rect(name).center(); let (shapes, _) = panel.paint_at(1.0); - let ink = shapes.iter().find_map(|shape| match shape { - egui::Shape::Circle(circle) if circle.center.distance(center) < 0.01 && (circle.radius - 5.0).abs() < 1e-4 => Some(circle.stroke.color), - _ => None, - }).expect("the cell's outer target ring"); + let ink = shapes + .iter() + .find_map(|shape| match shape { + egui::Shape::Circle(circle) if circle.center.distance(center) < 0.01 && (circle.radius - 5.0).abs() < 1e-4 => Some(circle.stroke.color), + _ => None, + }) + .expect("the cell's outer target ring"); for shape in &shapes { if appearance_diamond(shape).is_some_and(|(at, _, _)| at.distance(center) < 0.01) && let egui::Shape::Path(path) = shape @@ -809,11 +812,17 @@ fn target_marks_painted(panel: &mut crate::tests::panel_harness::Panel, name: &s assert_eq!(path.stroke.kind, egui::StrokeKind::Middle, "the diamond's stroke is centered on its outline"); } } - let mut marks: Vec<_> = shapes.iter().filter_map(|shape| match shape { - egui::Shape::Circle(circle) if circle.center.distance(center) < 0.01 && circle.radius < 5.0 - && circle.fill == egui::Color32::TRANSPARENT => Some((circle.radius, false, circle.stroke.width)), - shape => appearance_diamond(shape).filter(|(at, _, _)| at.distance(center) < 0.01).map(|(_, r, width)| (r, true, width)), - }).collect(); + let mut marks: Vec<_> = shapes + .iter() + .filter_map(|shape| match shape { + egui::Shape::Circle(circle) + if circle.center.distance(center) < 0.01 && circle.radius < 5.0 && circle.fill == egui::Color32::TRANSPARENT => + { + Some((circle.radius, false, circle.stroke.width)) + } + shape => appearance_diamond(shape).filter(|(at, _, _)| at.distance(center) < 0.01).map(|(_, r, width)| (r, true, width)), + }) + .collect(); marks.sort_by(|a, b| a.0.total_cmp(&b.0)); marks } @@ -845,7 +854,9 @@ fn a_targeted_circle_with_an_appearance_shows_both_ring_and_dot() { assert!((alone.0 - 2.5).abs() < 1e-4); let looks = [&neither, &targeted, &styled, &both]; for (i, x) in looks.iter().enumerate() { - for y in &looks[i + 1..] { assert_ne!(x, y, "all four actual cell looks differ"); } + for y in &looks[i + 1..] { + assert_ne!(x, y, "all four actual cell looks differ"); + } } } From f26086c58b2f0bf08ccfa2fe9cb8acc4c3a861c5 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 12:30:14 -0800 Subject: [PATCH 05/36] Describe the hollow diamond in current Layers feature rows --- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index f8ada20777..b4f19e07a8 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -188,7 +188,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller hollow diamond (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); 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; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), 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; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e0c7ac9998..c763d8e4b6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -796,7 +796,7 @@ since 2026-10-01. - **Ctrl/Cmd-click and Shift-click on Layers panel target circles (#8639):** the target circles follow the same modifier rules as the row names, as the help page describes for selecting objects in the Layers panel: Shift for adjacent objects, Ctrl or Command for non-adjacent ones ([Move objects to different layers](https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/move-objects-to-different-layers.html)). Ctrl/Cmd-click adds the item (a layer: its art) to the selection or takes it out, which Shift-click did before (#913); Shift-click selects the art of every row from the last circle clicked (else the targeted row) to this one, and Shift+Ctrl/Cmd-click adds it (`layer.target {range, add?}`). Hidden or locked art and art outside the isolated group in the range is left out, and nothing stays targeted. Regression tests: `clicking_a_target_circle_targets_the_layer` and `shift_clicking_a_target_circle_selects_a_range_of_rows` in `crates/ui-egui/src/panels/layers/tests.rs`. - **Shift-click in the Layers panel's selection column selects the art of a range of rows:** after a selection square is clicked, Shift-clicking another selects the art of every row listed from the last square clicked to this one, down or up and across sublayers and groups, and Shift+Ctrl/Cmd-click adds that art to the selection (`layer.selectAll {range, add?}`). Hidden and locked rows and art outside the isolated group are left out, and a range does not move where the next Shift-click starts. Ctrl/Cmd-click adds one row's art or takes it out, and so does Shift-click before any square was clicked. The panel menu's Select Art of Highlighted Rows (`layer.selectHighlighted`) selects the art of the highlighted rows by the same rules. These are VectorCraft's own rules. Regression tests: `shift_clicking_a_selection_square_selects_the_art_of_a_range_of_rows` and `shift_clicking_the_first_selection_square_adds_or_removes_one_row` in `crates/ui-egui/src/panels/layers/tests.rs`, `the_selection_column_selects_the_art_of_a_range_of_rows` and `select_highlighted_selects_the_art_of_the_highlighted_rows` in `crates/engine/src/tests/layers.rs`. - **Layers added to the selection from their target circles show as targeted (#8646):** with several items picked from their circles (nothing targeted), a layer or sublayer's circle shows its inner ring while all of its visible, unlocked art is selected, as an object's circle does while the object is selected. A layer is never selected itself, only its art, so its circle used to keep a single ring. Regression test: `a_layer_added_from_its_target_circle_shows_as_targeted` in `crates/ui-egui/src/panels/layers/tests.rs`. -- **A targeted item with an appearance of its own shows both marks (#8711):** its target circle keeps the inner ring of a targeted item, with the appearance dot drawn smaller inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) do. The dot used to cover the ring. Regression test: `a_targeted_circle_with_an_appearance_shows_both_ring_and_dot` in `crates/ui-egui/src/panels/layers/tests.rs`. +- **A targeted item with an appearance of its own shows both marks (#8711):** its target circle keeps the inner ring of a targeted item, with the hollow diamond drawn smaller inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) do. The dot used to cover the ring. Regression test: `a_targeted_circle_with_an_appearance_shows_both_ring_and_dot` in `crates/ui-egui/src/panels/layers/tests.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. From 07378009102db84ab7221fa2f6742047088675d2 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 12:55:01 -0800 Subject: [PATCH 06/36] test: assert Layers target button pressed state --- crates/ui-egui/src/panels/layers/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 29ea72202a..205a9d0f74 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -882,7 +882,7 @@ fn appearance_marker_names_its_state_and_keeps_targeting_actions() { let active = "Target appearance: targeted, additional appearance or transparency"; assert_eq!(panel.description("Target A").as_deref(), Some(idle)); assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: not targeted, basic appearance")); - assert!(!panel.selected("Target A")); + assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(false))); let before = { let app = panel.app(); (app.session.active().unwrap().selection.clone(), undo_len(&app)) @@ -899,11 +899,11 @@ fn appearance_marker_names_its_state_and_keeps_targeting_actions() { panel.click("Target A"); assert_eq!(targeted(&panel.app()), (Some(a), vec![a])); assert_eq!(panel.description("Target A").as_deref(), Some(active)); - assert!(panel.selected("Target A")); + assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(true))); panel.click("Target B"); assert_eq!(panel.description("Target A").as_deref(), Some(idle)); assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: targeted, basic appearance")); - assert!(panel.selected("Target B")); + assert_eq!(panel.toggled("Target B"), Some(craft::behavior::Mixed::Same(true))); assert!(target_marks_painted(&mut panel, "Target A").iter().any(|m| m.1), "the appearance stays after targeting other art"); } From d48ea9a3c06ebdf5d2b567cc255483066ece432a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 13:03:54 -0800 Subject: [PATCH 07/36] Remove the unused test selection helper --- crates/ui-egui/src/tests/panel_harness.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 7251c04291..b596f3a1c8 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -378,11 +378,6 @@ impl Panel { tree.keys().into_iter().any(|key| tree.value_of(key).is_some_and(&matches)) } - /// Whether the control named `name` reports selected state. - pub(crate) fn selected(&self, name: &str) -> bool { - self.fixture.tree().selected_of(self.look(name).node).unwrap_or(false) - } - /// The toggle state of the control named `name`. // PLAN: assumed the facade re-exports the behavior crate's `Mixed` as `craft::behavior::Mixed`. pub(crate) fn toggled(&self, name: &str) -> Option> { From 53c57248adb0c1c926a3a677978c7eac0b21c5d1 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 15:02:33 -0800 Subject: [PATCH 08/36] Use the current stroke paint API in Properties --- crates/ui-egui/src/panels/properties/appearance_section.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index cd71a0f035..e2ae112143 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -102,7 +102,7 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[( /// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or /// the Live Paint Bucket is active, when the list edits the stroke the panel shows. fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool { - if panels::character::text_editing(app).is_some() || app.session.bucket_paints() { + if panels::character::text_editing(app).is_some() || app.session.tool_paints(true) { return false; } let Some(st) = app.session.active() else { return false }; From eb1407217f2e3c72fe66587ba21bbc1f0a019505 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:05:55 +0000 Subject: [PATCH 09/36] feat: Object > Step and Repeat for print-and-cut sheets Grid or fill-sheet layout with per-axis gaps measured on a chosen cut path, optional 180-degree alternation of columns or rows, scriptable as object.stepAndRepeat. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/stepandrepeat.rs | 214 ++++++++++++++++++ crates/engine/src/cmd/stepandrepeat/tests.rs | 132 +++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs/object_dialogs.rs | 6 +- .../src/dialogs/rearrange_artboards.rs | 2 +- crates/ui-egui/src/dialogs/step_repeat.rs | 147 ++++++++++++ crates/ui-egui/src/menus/tree.rs | 1 + 9 files changed, 504 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/stepandrepeat.rs create mode 100644 crates/engine/src/cmd/stepandrepeat/tests.rs create mode 100644 crates/ui-egui/src/dialogs/step_repeat.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 009fc4efd8..17132f9b5a 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -109,6 +109,7 @@ mod textedit; pub use textedit::effective_kerning; mod retype; +mod stepandrepeat; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; @@ -325,6 +326,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(layerpanel::specs()); v.extend(draw2::specs()); v.extend(xform::specs()); + v.extend(stepandrepeat::specs()); v.extend(effectcmd::specs()); v.extend(bevels::specs()); v.extend(wireframe::specs()); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 612cf436b7..b4ffedbd77 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -415,6 +415,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.textWrap.release", "object.transform", "object.transformAgain", + "object.stepAndRepeat", "object.transformEach", "object.ungroup", "object.unlockAll", diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs new file mode 100644 index 0000000000..cc66e04a69 --- /dev/null +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -0,0 +1,214 @@ +//! Object › Step and Repeat: lays out copies of the selection on a grid or fills a sheet, for +//! print-and-cut work (stickers, labels). + +use serde_json::{Value, json}; +use vectorcraft_geom::{Rect, Vec2, rotate_deg}; + +use super::edit::{copy_above, selected_roots}; +use super::object::group_nodes; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or}; +use crate::EngineError; +use vectorcraft_doc::Scaling; + +const CMD: &str = "object.stepAndRepeat"; +const MAX_CELLS: usize = 10_000; +const EPS: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "object.stepAndRepeat", + "Step and Repeat…", + ["Object", "Transform"], + None, + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + has_selection, + step_and_repeat + )] +} + +/// Which cells of the grid are turned by 180°. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Alternate { + None, + Columns, + Rows, +} + +/// One cell of a layout: its place in the grid, the offset of its top-left corner from the first +/// cell's, and whether its copy is turned by 180° about the cell's center. +#[derive(Clone, Copy, PartialEq, Debug)] +pub struct Cell { + pub row: usize, + pub col: usize, + pub dx: f64, + pub dy: f64, + pub turned: bool, +} + +/// How many items of `size` with `gap` between them fit in `room` (all at least 0). +pub fn fit_count(room: f64, size: f64, gap: f64) -> usize { + if !(room.is_finite() && size.is_finite() && gap.is_finite()) || size <= 0.0 || room < size - EPS { + return 0; + } + (((room + gap) / (size + gap)) + EPS).floor().max(0.0) as usize +} + +/// The `(rows, columns)` of items `w` × `h` with gaps `gx`, `gy` that fit a sheet `sw` × `sh` +/// inside `margin` on every side. +pub fn fill_counts(sw: f64, sh: f64, margin: f64, w: f64, h: f64, gx: f64, gy: f64) -> (usize, usize) { + let m = margin.max(0.0); + (fit_count(sh - 2.0 * m, h, gy), fit_count(sw - 2.0 * m, w, gx)) +} + +/// The cells of a `rows` × `cols` grid of items `w` × `h` with gaps `gx` between columns and `gy` +/// between rows, in reading order. +pub fn layout(w: f64, h: f64, gx: f64, gy: f64, rows: usize, cols: usize, alt: Alternate) -> Vec { + (0..rows) + .flat_map(|row| (0..cols).map(move |col| (row, col))) + .map(|(row, col)| Cell { + row, + col, + dx: col as f64 * (w + gx), + dy: row as f64 * (h + gy), + turned: match alt { + Alternate::None => false, + Alternate::Columns => col % 2 == 1, + Alternate::Rows => row % 2 == 1, + }, + }) + .collect() +} + +fn count_param(p: &Value, key: &str) -> Result { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(1), + Some(v) => v + .as_u64() + .filter(|n| (1..=MAX_CELLS as u64).contains(n)) + .map(|n| n as usize) + .ok_or_else(|| bad(CMD, format!("`{key}` must be a whole number from 1 to {MAX_CELLS}"))), + } +} + +fn sheet_param(p: &Value) -> Result> { + let Some(v) = p.get("sheet").filter(|v| !v.is_null()) else { return Ok(None) }; + let n = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(CMD, format!("`sheet.{k}` must be a number"))); + let (x, y, w, h) = (n("x")?, n("y")?, n("width")?, n("height")?); + if w <= 0.0 || h <= 0.0 { + return Err(bad(CMD, "`sheet` needs a positive width and height")); + } + Ok(Some(Rect::new(x, y, x + w, y + h))) +} + +fn step_and_repeat(s: &mut Session, p: &Value) -> Result { + check_numbers(p, &["gap", "gapX", "gapY", "margin"], CMD)?; + check_switches(p, &["patterns"], CMD)?; + let fill = switch_or(p, "fill", false, CMD)?; + let alt = match p.get("rotate").filter(|v| !v.is_null()) { + None => Alternate::None, + Some(v) => match v.as_str() { + Some("none") => Alternate::None, + Some("columns") => Alternate::Columns, + Some("rows") => Alternate::Rows, + _ => return Err(bad(CMD, "`rotate` must be \"none\", \"columns\" or \"rows\"")), + }, + }; + let gap = super::f64_or(p, "gap", 0.0); + let (gx, gy) = (super::f64_or(p, "gapX", gap), super::f64_or(p, "gapY", gap)); + let margin = super::f64_or(p, "margin", 0.0); + if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) { + return Err(bad(CMD, "gaps and margin must be finite")); + } + let (rows, cols) = (count_param(p, "rows")?, count_param(p, "columns")?); + let sheet = sheet_param(p)?; + let mut roots = selected_roots(s)?; + if roots.is_empty() { + return Err(EngineError::Other("nothing selected".into())); + } + let d = &s.doc()?.doc; + let cut = match p.get("cutPath").filter(|v| !v.is_null()) { + None => None, + Some(v) => { + let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutPath` must be an object id"))?); + let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| { + let mut found = false; + n.walk(&mut |c| found |= c.id == id); + found + }); + if !held { + return Err(bad(CMD, "`cutPath` must be part of the selection")); + } + Some(id) + } + }; + let measured = cut.map_or_else(|| roots.clone(), |id| vec![id]); + let b = d.bounds_of(&measured, false); + let b = b.ok_or_else(|| EngineError::Other("the selection has no bounds".into()))?; + let (w, h) = (b.width(), b.height()); + if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(EngineError::Other("the selection has no area to repeat".into())); + } + let anchor = if fill { + let sheet = sheet.or_else(|| { + let c = b.center(); + d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect) + }); + let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?; + Some((sheet, margin.max(0.0))) + } else { + None + }; + let (rows, cols) = match anchor { + Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy), + None => (rows, cols), + }; + if rows == 0 || cols == 0 { + return Err(EngineError::Other("the selection does not fit the sheet".into())); + } + if rows.saturating_mul(cols) > MAX_CELLS { + return Err(bad(CMD, format!("more than {MAX_CELLS} copies"))); + } + let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); + let cells = layout(w, h, gx, gy, rows, cols, alt); + let center = b.center().to_vec2(); + let place = |c: &Cell| -> Affine { + let t = Affine::translate(origin + Vec2::new(c.dx, c.dy)); + if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t } + }; + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; + let ids = s.edit("Step and Repeat", |d, sel| { + if roots.len() > 1 { + roots = vec![group_nodes(d, &roots)?]; + } + let mut copied: Vec = vec![]; + let mut first = Affine::IDENTITY; + for c in &cells { + let m = place(c); + if c.row == 0 && c.col == 0 { + first = m; + continue; + } + let copies = copy_above(d, &roots, |_, _, n| { + n.transform(m, sc); + super::object::keep_pixel_aligned(n, sc); + })?; + copied.extend(copies); + } + if first != Affine::IDENTITY { + for id in &roots { + if let Some(n) = d.node_mut(*id) { + n.transform(first, sc); + super::object::keep_pixel_aligned(n, sc); + } + } + } + let mut out: Vec = roots.clone(); + out.extend(copied); + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "rows": rows, "columns": cols, "count": ids.len() })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs new file mode 100644 index 0000000000..e2addab74b --- /dev/null +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -0,0 +1,132 @@ +use serde_json::json; + +use super::*; + +const A4: (f64, f64) = (210.0, 297.0); + +#[test] +fn fills_a4_with_50_by_30_items_and_3_gap() { + assert_eq!(fill_counts(A4.0, A4.1, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 4)); + assert_eq!(fill_counts(A4.0, A4.1, 5.0, 50.0, 30.0, 3.0, 3.0), (8, 3)); + assert_eq!(fill_counts(40.0, 297.0, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 0)); +} + +#[test] +fn layout_places_cells_at_the_pitch_and_alternates_rotation() { + let c = layout(50.0, 30.0, 3.0, 3.0, 9, 4, Alternate::Columns); + assert_eq!(c.len(), 36); + let at = |r: usize, k: usize| c[r * 4 + k]; + assert_eq!((at(0, 0).dx, at(0, 0).dy), (0.0, 0.0)); + assert_eq!((at(2, 3).dx, at(2, 3).dy), (159.0, 66.0)); + assert_eq!(c.iter().filter(|c| c.turned).count(), 18); + assert!(at(4, 1).turned && at(4, 3).turned && !at(4, 0).turned && !at(4, 2).turned); + let rows = layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::Rows); + assert_eq!(rows.iter().map(|c| c.turned).collect::>(), [false, false, true, true, false, false]); + assert!(layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::None).iter().all(|c| !c.turned)); +} + +fn setup() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + (s, id) +} + +fn bounds(s: &Session, id: u64) -> (f64, f64, f64, f64) { + let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0, b.x1, b.y1) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() { + let (mut s, _) = setup(); + let (before, steps) = (s.doc().unwrap().doc.clone(), undo_steps(&s)); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gap": 3})).unwrap(); + assert_eq!((r["count"].clone(), r["rows"].clone(), r["columns"].clone()), (json!(6), json!(2), json!(3))); + assert_eq!(undo_steps(&s), steps + 1); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!(bounds(&s, ids[0]), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(bounds(&s, ids[4]), (53.0, 33.0, 103.0, 63.0)); + assert_eq!(bounds(&s, ids[5]), (106.0, 33.0, 156.0, 63.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let d = &s.doc().unwrap().doc; + assert_eq!(d.artboards.len(), before.artboards.len()); + assert!(d.node(NodeId(ids[0])).is_some()); + assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none())); +} + +#[test] +fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() { + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 0})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(9), json!(4), json!(36))); + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5})).unwrap(); + assert_eq!(r["count"], json!(24)); + let first = r["ids"][0].as_u64().unwrap(); + assert_eq!(bounds(&s, first), (5.0, 5.0, 55.0, 35.0)); +} + +#[test] +fn fill_places_every_cell_from_the_original_when_it_starts_away_from_the_margin() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 40, "width": 50, "height": 30})).unwrap(); + let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5, "rotate": "columns"})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(8), json!(3))); + assert_eq!(bounds(&s, ids[0]), (5.0, 5.0, 55.0, 35.0)); + assert_eq!(bounds(&s, ids[1]), (58.0, 5.0, 108.0, 35.0)); + assert_eq!(bounds(&s, ids[2]), (111.0, 5.0, 161.0, 35.0)); + assert_eq!(bounds(&s, ids[3]), (5.0, 38.0, 55.0, 68.0)); +} + +#[test] +fn alternate_columns_turn_by_180_degrees_about_the_cell_center() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let id = s.execute("shape.polygon", &json!({"cx": 25, "cy": 15, "radius": 10, "sides": 3})).unwrap()["id"].as_u64().unwrap(); + let b0 = bounds(&s, id); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gap": 4, "rotate": "columns"})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let (w, b1) = (b0.2 - b0.0, bounds(&s, ids[1])); + assert!((b1.0 - (b0.0 + w + 4.0)).abs() < 1e-6 && ((b1.2 - b1.0) - w).abs() < 1e-6); + assert!((b1.1 - b0.1).abs() < 1e-6 && (b1.3 - b0.3).abs() < 1e-6); + let tri = |s: &Session, id: u64| format!("{:?}", s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind); + assert_ne!(tri(&s, ids[0]), tri(&s, ids[1])); +} + +#[test] +fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() { + let (mut s, art) = setup(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutPath": cut})).unwrap(); + assert_eq!(r["count"], json!(3)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let n = d.node(NodeId(id.as_u64().unwrap())).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. })); + let mut paths = 0; + n.walk(&mut |c| paths += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }))); + assert_eq!(paths, 2); + } +} + +#[test] +fn rejects_bad_params_and_a_selection_that_does_not_fit() { + let (mut s, _) = setup(); + assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err()); + assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err()); + assert!(s.execute(CMD, &json!({"cutPath": 999999})).is_err()); + assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err()); + let mut e = Session::new(); + e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert!(e.execute(CMD, &json!({})).is_err()); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0e5e2100ba..8046049528 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -146,6 +146,7 @@ pub mod shortcut_import; pub(crate) mod simplify_slider; pub mod slices; pub mod smart_punctuation; +pub mod step_repeat; pub(crate) mod smooth_slider; pub mod spot_colors; pub mod svg_filter; diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index df0c1be3ed..ee26844185 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -4,7 +4,7 @@ use super::path_ops::PathOp; use super::simplify_slider::StripKind; use super::{ blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form, - path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, transform, transform_each, + path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, step_repeat, transform, transform_each, width_point, }; use crate::VectorcraftApp; @@ -16,6 +16,8 @@ pub(crate) struct ObjectDialogs { pub transform: Option, /// The open Transform Each dialog's preview record. pub each: Option, + /// The open Step and Repeat dialog's preview record. + pub step: Option, /// The open Average, Average & Join, Offset Path and Simplify dialogs' preview records. pub path: Vec, /// The open Split Into Grid dialog's record. @@ -47,6 +49,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { sync(app); transform::pump(app, ctx); transform_each::pump(app, ctx); + step_repeat::pump(app, ctx); path_ops::pump(app, ctx); shapes::pump(app, ctx); flare_options::pump(app, ctx); @@ -75,6 +78,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> bool { } match id { "object.transformEach" => transform_each::open(app), + step_repeat::CMD => step_repeat::open(app), "path.average" => path_ops::open(app, PathOp::Average), "path.averageJoin" => path_ops::open(app, PathOp::AverageJoin), "object.path.offsetPath" => path_ops::open(app, PathOp::OffsetPath), diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index 3926501a05..d567dd3363 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -110,7 +110,7 @@ impl RearrangeValues { } /// The length unit a document unit shows as. -fn length_kind(unit: Unit) -> UnitKind { +pub(super) fn length_kind(unit: Unit) -> UnitKind { match unit { Unit::Picas => UnitKind::Picas, Unit::Inches => UnitKind::Inches, diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs new file mode 100644 index 0000000000..442c25da18 --- /dev/null +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -0,0 +1,147 @@ +//! Object → Step and Repeat: copies of the selection on a grid or filling a sheet, with the gaps +//! between the cut paths, every other column or row turned by 180° (`object.stepAndRepeat`), +//! previewed live on the canvas. +//! +//! Fields: `rows`, `columns`, `gapX`, `gapY` (pt), `margin` (pt), `fill` (as many as fit the +//! artboard), `rotate` (`none`, `columns` or `rows`), `cutPath` (an object of the selection, or +//! empty for the selection itself). + +use craft::ui::contract::Bind; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; +use serde_json::{Map, Value, json}; + +use super::host::{HeldOptions, open_held_with}; +use super::preview::LivePreview; +use crate::VectorcraftApp; + +pub(crate) const CMD: &str = "object.stepAndRepeat"; + +pub(crate) struct Open { + pub id: DialogId, + pub preview: LivePreview, +} + +fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { + let mut out = vec![(String::new(), Label::from(tl!("Selection")))]; + let Some(st) = app.session.active() else { return out }; + let single = st.selection.objects.len() == 1; + for id in &st.selection.objects { + let Some(n) = st.doc.node(*id) else { continue }; + out.push((id.0.to_string(), Label::from(n.display_name()))); + if single { + for c in &n.children { + out.push((c.id.0.to_string(), Label::from(c.display_name()))); + } + } + } + out +} + +fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec { + let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths.clone()); + vec![ + Param::new("rows", tl!("Rows"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), + Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), + len("gapX", tl!("Horizontal Gap")), + len("gapY", tl!("Vertical Gap")), + Param::new("cutPath", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))), + Param::new("fill", tl!("Fill the Artboard"), ParamKind::bool(false)), + len("margin", tl!("Margin")).enabled_when("fill", true), + Param::new( + "rotate", + tl!("Rotate 180°"), + ParamKind::choice( + vec![ + ("none".into(), Label::from(tl!("None"))), + ("columns".into(), Label::from(tl!("Every Other Column"))), + ("rows".into(), Label::from(tl!("Every Other Row"))), + ], + Some("none".into()), + ), + ), + ] +} + +pub fn fields() -> DialogFields { + DialogFields::from_pairs([ + ("rows", FieldValue::Int(2)), + ("columns", FieldValue::Int(2)), + ("gapX", FieldValue::Number(12.0)), + ("gapY", FieldValue::Number(12.0)), + ("margin", FieldValue::Number(0.0)), + ("fill", FieldValue::Bool(false)), + ("cutPath", FieldValue::Text(String::new())), + ("rotate", FieldValue::Text("none".into())), + ]) +} + +fn count(f: &DialogFields, key: &str) -> u64 { + f.int(key).or_else(|| f.number(key).map(|n| n as i64)).unwrap_or(1).max(1) as u64 +} + +fn params(f: &DialogFields) -> Value { + let mut p = Map::new(); + p.insert("rows".into(), json!(count(f, "rows"))); + p.insert("columns".into(), json!(count(f, "columns"))); + for k in ["gapX", "gapY", "margin"] { + p.insert(k.into(), json!(f.number(k).unwrap_or(0.0))); + } + p.insert("fill".into(), json!(f.bool("fill").unwrap_or(false))); + p.insert("rotate".into(), json!(f.text("rotate").unwrap_or("none"))); + if let Some(id) = f.text("cutPath").and_then(|t| t.parse::().ok()) { + p.insert("cutPath".into(), json!(id)); + } + Value::Object(p) +} + +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let ctx = app.ui_ctx.clone().ok_or("no window")?; + let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0); + let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); + let cuts = cut_options(app); + let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| { + ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths.clone(), cuts.clone())).previews(true).values(Bind::bound(fields)) + }); + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; + let done = std::mem::take(&mut open.preview).commit(app, CMD, params(&result.fields)); + if done.is_err() { + app.object_dialogs.step = Some(open); + } + done.map(|_| ()) + }; + let cancel: Box = Box::new(|app| { + if let Some(open) = app.object_dialogs.step.take() { + open.preview.cancel(app); + } + }); + let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; + app.object_dialogs.step = Some(Open { id, preview: LivePreview::default() }); + Ok(Value::Null) +} + +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(mut open) = app.object_dialogs.step.take() else { return }; + let shown = app.dialogs().and_then(|host| { + host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields())))) + }); + if let Some((on, p)) = shown { + let _ = open.preview.run(app, on, "Step and Repeat", CMD, &p); + } + app.object_dialogs.step = Some(open); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cut_path_is_sent_only_when_one_is_chosen() { + let mut f = fields(); + assert!(params(&f).get("cutPath").is_none()); + f.set("cutPath", FieldValue::Text("42".into())); + assert_eq!(params(&f)["cutPath"], json!(42)); + } +} diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index b2757b3cbd..c8f67c81d7 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -847,6 +847,7 @@ pub(super) fn transform_items() -> Vec { c("Shear…", "object.shear"), Sep, c("Transform Each…", "object.transformEach"), + c("Step and Repeat…", "object.stepAndRepeat"), Sep, c("Reset Bounding Box", "object.resetBoundingBox"), cp("Rotate Bounding Box…", "object.rotateBoundingBox", json!({"angle": 0})), From 9ddc0aef3aa42c553a61c57755ee2c5cbcb6dc79 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:36:42 +0000 Subject: [PATCH 10/36] fix: step and repeat dialog on the hosted form, cut path choice, sorted review list --- crates/engine/src/cmd/plugin_call/reviewed.rs | 2 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/object_dialogs.rs | 4 ++-- crates/ui-egui/src/dialogs/step_repeat.rs | 17 ++++++++++------- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index b4ffedbd77..cd7d1db8ae 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -405,6 +405,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.stepAndRepeat", "object.tag.add", "object.tag.remove", "object.tag.removeAll", @@ -415,7 +416,6 @@ pub(super) const ALLOWED: &[&str] = &[ "object.textWrap.release", "object.transform", "object.transformAgain", - "object.stepAndRepeat", "object.transformEach", "object.ungroup", "object.unlockAll", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8046049528..eee24e9a47 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -146,9 +146,9 @@ pub mod shortcut_import; pub(crate) mod simplify_slider; pub mod slices; pub mod smart_punctuation; -pub mod step_repeat; pub(crate) mod smooth_slider; pub mod spot_colors; +pub mod step_repeat; pub mod svg_filter; pub(crate) mod svg_options; pub mod swatch_conflict; diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index ee26844185..4ef12e9828 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -4,8 +4,8 @@ use super::path_ops::PathOp; use super::simplify_slider::StripKind; use super::{ blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form, - path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, step_repeat, transform, transform_each, - width_point, + path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, step_repeat, transform, + transform_each, width_point, }; use crate::VectorcraftApp; diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 442c25da18..8828f2e172 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -31,7 +31,7 @@ fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { let Some(n) = st.doc.node(*id) else { continue }; out.push((id.0.to_string(), Label::from(n.display_name()))); if single { - for c in &n.children { + for c in n.children().into_iter().flatten() { out.push((c.id.0.to_string(), Label::from(c.display_name()))); } } @@ -40,7 +40,7 @@ fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { } fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec { - let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths.clone()); + let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths); vec![ Param::new("rows", tl!("Rows"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), @@ -96,13 +96,17 @@ fn params(f: &DialogFields) -> Value { Value::Object(p) } -pub(crate) fn open(app: &mut VectorcraftApp) -> Result { +pub(crate) fn open(app: &mut VectorcraftApp) { + let _ = try_open(app); +} + +fn try_open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0); let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); let cuts = cut_options(app); let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| { - ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths.clone(), cuts.clone())).previews(true).values(Bind::bound(fields)) + ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields)) }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; @@ -124,9 +128,8 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.object_dialogs.step.take() else { return }; - let shown = app.dialogs().and_then(|host| { - host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields())))) - }); + let shown = + app.dialogs().and_then(|host| host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields()))))); if let Some((on, p)) = shown { let _ = open.preview.run(app, on, "Step and Repeat", CMD, &p); } From 8074d6fbc0cad89db688107aaebb94ea42cde631 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:31:58 +0000 Subject: [PATCH 11/36] fix: say which way Step and Repeat rotate turns --- crates/engine/src/cmd/stepandrepeat.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index cc66e04a69..7109d6a766 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] From e5cb0d8dcaec63230fe2d50e528e8600612eea97 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:09:38 +0000 Subject: [PATCH 12/36] fix: name the Step and Repeat cut object param cutId --- crates/engine/src/cmd/stepandrepeat.rs | 8 ++++---- crates/engine/src/cmd/stepandrepeat/tests.rs | 4 ++-- crates/ui-egui/src/dialogs/step_repeat.rs | 16 ++++++++-------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 7109d6a766..b83ebbb28a 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutPath`, else of the selection, not between centers), cutPath?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -126,17 +126,17 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("nothing selected".into())); } let d = &s.doc()?.doc; - let cut = match p.get("cutPath").filter(|v| !v.is_null()) { + let cut = match p.get("cutId").filter(|v| !v.is_null()) { None => None, Some(v) => { - let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutPath` must be an object id"))?); + let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutId` must be an object id"))?); let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| { let mut found = false; n.walk(&mut |c| found |= c.id == id); found }); if !held { - return Err(bad(CMD, "`cutPath` must be part of the selection")); + return Err(bad(CMD, "`cutId` must be part of the selection")); } Some(id) } diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index e2addab74b..73948bd664 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -106,7 +106,7 @@ fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() { let (mut s, art) = setup(); let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); - let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutPath": cut})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutId": cut})).unwrap(); assert_eq!(r["count"], json!(3)); let d = &s.doc().unwrap().doc; for id in r["ids"].as_array().unwrap() { @@ -124,7 +124,7 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err()); assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err()); - assert!(s.execute(CMD, &json!({"cutPath": 999999})).is_err()); + assert!(s.execute(CMD, &json!({"cutId": 999999})).is_err()); assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err()); let mut e = Session::new(); e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 8828f2e172..b057d1b320 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -3,7 +3,7 @@ //! previewed live on the canvas. //! //! Fields: `rows`, `columns`, `gapX`, `gapY` (pt), `margin` (pt), `fill` (as many as fit the -//! artboard), `rotate` (`none`, `columns` or `rows`), `cutPath` (an object of the selection, or +//! artboard), `rotate` (`none`, `columns` or `rows`), `cutId` (an object of the selection, or //! empty for the selection itself). use craft::ui::contract::Bind; @@ -46,7 +46,7 @@ fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec { Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false), len("gapX", tl!("Horizontal Gap")), len("gapY", tl!("Vertical Gap")), - Param::new("cutPath", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))), + Param::new("cutId", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))), Param::new("fill", tl!("Fill the Artboard"), ParamKind::bool(false)), len("margin", tl!("Margin")).enabled_when("fill", true), Param::new( @@ -72,7 +72,7 @@ pub fn fields() -> DialogFields { ("gapY", FieldValue::Number(12.0)), ("margin", FieldValue::Number(0.0)), ("fill", FieldValue::Bool(false)), - ("cutPath", FieldValue::Text(String::new())), + ("cutId", FieldValue::Text(String::new())), ("rotate", FieldValue::Text("none".into())), ]) } @@ -90,8 +90,8 @@ fn params(f: &DialogFields) -> Value { } p.insert("fill".into(), json!(f.bool("fill").unwrap_or(false))); p.insert("rotate".into(), json!(f.text("rotate").unwrap_or("none"))); - if let Some(id) = f.text("cutPath").and_then(|t| t.parse::().ok()) { - p.insert("cutPath".into(), json!(id)); + if let Some(id) = f.text("cutId").and_then(|t| t.parse::().ok()) { + p.insert("cutId".into(), json!(id)); } Value::Object(p) } @@ -143,8 +143,8 @@ mod tests { #[test] fn cut_path_is_sent_only_when_one_is_chosen() { let mut f = fields(); - assert!(params(&f).get("cutPath").is_none()); - f.set("cutPath", FieldValue::Text("42".into())); - assert_eq!(params(&f)["cutPath"], json!(42)); + assert!(params(&f).get("cutId").is_none()); + f.set("cutId", FieldValue::Text("42".into())); + assert_eq!(params(&f)["cutId"], json!(42)); } } From 7583602d8fae63e99e714ceb256ba6c25267d106 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:12:39 +0000 Subject: [PATCH 13/36] fix: step and repeat ignores counts when filling, keeps exact spacing, lists nested cut objects --- crates/engine/src/cmd/stepandrepeat.rs | 6 ++-- crates/engine/src/cmd/stepandrepeat/tests.rs | 18 ++++++++++ crates/ui-egui/src/dialogs/step_repeat.rs | 38 ++++++++++++++------ 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index b83ebbb28a..27ee3504c9 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); spacing is exact: copies are not snapped to the pixel grid; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -119,7 +119,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) { return Err(bad(CMD, "gaps and margin must be finite")); } - let (rows, cols) = (count_param(p, "rows")?, count_param(p, "columns")?); + let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) }; let sheet = sheet_param(p)?; let mut roots = selected_roots(s)?; if roots.is_empty() { @@ -190,7 +190,6 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } let copies = copy_above(d, &roots, |_, _, n| { n.transform(m, sc); - super::object::keep_pixel_aligned(n, sc); })?; copied.extend(copies); } @@ -198,7 +197,6 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { for id in &roots { if let Some(n) = d.node_mut(*id) { n.transform(first, sc); - super::object::keep_pixel_aligned(n, sc); } } } diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 73948bd664..dcf5009ca5 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -130,3 +130,21 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); assert!(e.execute(CMD, &json!({})).is_err()); } + +#[test] +fn fill_ignores_explicit_counts() { + let (mut s, _) = setup(); + let r = s.execute(CMD, &json!({"fill": true, "rows": 0, "columns": 0, "gap": 3})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(9), json!(4))); + assert!(s.execute(CMD, &json!({"rows": 0})).is_err()); +} + +#[test] +fn a_pixel_aligned_copy_keeps_the_requested_fractional_gap() { + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": 0.5})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + assert_eq!(bounds(&s, ids[1]).0, 50.5); + assert_eq!(bounds(&s, ids[2]).0, 101.0); +} diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index b057d1b320..927b344d8d 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -23,18 +23,20 @@ pub(crate) struct Open { pub preview: LivePreview, } +fn cut_ids(doc: &vectorcraft_doc::Document, selected: &[vectorcraft_doc::NodeId]) -> Vec<(u64, String)> { + let mut out = vec![]; + for id in selected { + if let Some(n) = doc.node(*id) { + n.walk(&mut |c| out.push((c.id.0, c.display_name()))); + } + } + out +} + fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> { let mut out = vec![(String::new(), Label::from(tl!("Selection")))]; - let Some(st) = app.session.active() else { return out }; - let single = st.selection.objects.len() == 1; - for id in &st.selection.objects { - let Some(n) = st.doc.node(*id) else { continue }; - out.push((id.0.to_string(), Label::from(n.display_name()))); - if single { - for c in n.children().into_iter().flatten() { - out.push((c.id.0.to_string(), Label::from(c.display_name()))); - } - } + if let Some(st) = app.session.active() { + out.extend(cut_ids(&st.doc, &st.selection.objects).into_iter().map(|(id, name)| (id.to_string(), Label::from(name)))); } out } @@ -147,4 +149,20 @@ mod tests { f.set("cutId", FieldValue::Text("42".into())); assert_eq!(params(&f)["cutId"], json!(42)); } + + #[test] + fn cut_choices_reach_objects_nested_in_groups() { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [inner, c]})).unwrap(); + let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let ids: Vec = cut_ids(doc, &[vectorcraft_doc::NodeId(outer)]).into_iter().map(|(i, _)| i).collect(); + assert!([outer, inner, a, b, c].iter().all(|i| ids.contains(i))); + } } From 7f821d39de46511df638852f1c089963d8e076eb Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:00:33 +0000 Subject: [PATCH 14/36] test: cover fractional gaps with pixel-aligned objects, document the contract --- crates/engine/src/cmd/stepandrepeat.rs | 4 +++- crates/engine/src/cmd/stepandrepeat/tests.rs | 21 +++++++++++++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 27ee3504c9..620f64a9a7 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); spacing is exact: copies are not snapped to the pixel grid; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -190,6 +190,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } let copies = copy_above(d, &roots, |_, _, n| { n.transform(m, sc); + super::object::keep_pixel_aligned(n, sc); })?; copied.extend(copies); } @@ -197,6 +198,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { for id in &roots { if let Some(n) = d.node_mut(*id) { n.transform(first, sc); + super::object::keep_pixel_aligned(n, sc); } } } diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index dcf5009ca5..c25953d598 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -140,11 +140,18 @@ fn fill_ignores_explicit_counts() { } #[test] -fn a_pixel_aligned_copy_keeps_the_requested_fractional_gap() { - let (mut s, id) = setup(); - s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); - let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": 0.5})).unwrap(); - let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); - assert_eq!(bounds(&s, ids[1]).0, 50.5); - assert_eq!(bounds(&s, ids[2]).0, 101.0); +fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_grid() { + let gap = |aligned: bool| { + let (mut s, id) = setup(); + if aligned { + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + } + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": 0.5})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let (a, c) = (bounds(&s, ids[0]), bounds(&s, ids[1])); + (c.0 - a.2, c.0 - a.0) + }; + assert!((gap(false).0 - 0.5).abs() < 1e-9); + let pitch = gap(true).1; + assert!((pitch - pitch.round()).abs() < 1e-9); } From c77fd87964946795ae9c20f3a7711a3eca7006ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 01:29:38 -0800 Subject: [PATCH 15/36] Brushes: Brush Options and Apply Brush that change nothing add no undo step brush.options with params and a newName that leave the brush as it is stored the library again, raised the document revision and added an Undo step; only the Brush Options dialog skipped an unchanged OK. save_library now returns without an edit when the library it is given equals the document's and nothing is renamed, as brush.move already does. brush.apply of the brush the strokes and the current brush already have runs through edit_if_changed and records nothing. --- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/brushes.rs | 10 +++- crates/engine/src/tests/brushsym.rs | 56 +++++++++++++++++++++++ docs/mcp.md | 4 +- 4 files changed, 69 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 3828d67d0c..2de3ddfcfe 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Apply Brush", [], None, - "{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current → {ids}", + "{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current; when the strokes already have it and it is already current, nothing changes and no undo step is recorded → {ids}", has_doc, brush_apply ), @@ -170,7 +170,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update); params and a newName that leave the brush as it is change nothing and record no undo step → {name}", has_doc, brush_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index af71b2dae9..18eb440f3a 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -80,10 +80,11 @@ pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result { } let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); let stroke = stroke_paint(s); - s.edit("Apply Brush", |d, _| { + crate::cmd::colorcmds::edit_if_changed(s, "Apply Brush", |before, d| { d.unknown.insert(brush::CURRENT_KEY.into(), json!(name)); apply_brush(d, &ids, &name, &stroke); - Ok(()) + let changed = brush::current(before).as_deref() != Some(name.as_str()) || ids.iter().any(|id| before.node(*id) != d.node(*id)); + Ok(((), changed)) })?; Ok(json!({ "ids": ids_json(&ids) })) } @@ -213,7 +214,12 @@ fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Opt } } +/// Stores `lib` and applies `renames` as one undo step named `label`. A `lib` equal to the +/// document's library, with no renames, leaves the document and its undo history as they are. fn save_library(s: &mut Session, label: &str, mut lib: Vec, renames: &[(String, Option)]) -> Result<()> { + if renames.is_empty() && lib == brush::library(&s.doc()?.doc) { + return Ok(()); + } s.edit(label, |d, _| { for (from, to) in renames { rename_brush_strokes(d, &mut lib, from, to.as_deref()); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 032e3ddb8c..86074c2a6b 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -913,6 +913,62 @@ fn brush_options_rename_duplicate_and_delete_update_strokes() { assert!(s.execute("brush.delete", &json!({"name": "5 pt. Round"})).is_err()); } +/// `brush.options` that leaves the brush as it is changes neither the document nor its revision, +/// and records no undo step, whether the library is stored or still the defaults. +#[test] +fn brush_options_that_change_nothing_record_no_undo_step() { + let mut s = session(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.revision, st.history.undo.len()) + }; + let before = state(&s); + s.execute("brush.options", &json!({"name": "Arrow", "params": {}})).unwrap(); + assert_eq!(state(&s), before, "unchanged options of a default library change nothing"); + s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 110.25}})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1, "a changed option is one undo step"); + let before = state(&s); + for p in [ + json!({"name": "Arrow"}), + json!({"name": "Arrow", "params": {}}), + json!({"name": "Arrow", "params": {"width": 110.25}}), + json!({"name": "Arrow", "newName": " Arrow "}), + json!({"name": "Arrow", "newName": ""}), + ] { + assert_eq!(s.execute("brush.options", &p).unwrap()["name"], "Arrow"); + assert_eq!(state(&s), before, "{p} changes nothing"); + } + s.execute("brush.options", &json!({"name": "Arrow", "newName": "Arrow 2"})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step"); +} + +/// `brush.apply` of the brush that the strokes and the current brush already have changes neither +/// the document nor its revision, and records no undo step. +#[test] +fn brush_apply_that_changes_nothing_records_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.revision, st.history.undo.len()) + }; + let before = state(&s); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1); + let before = state(&s); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap(); + assert_eq!(state(&s), before, "applying the brush again changes nothing"); + s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap(); + assert_eq!(undo_steps(&s), before.2 + 1, "making the brush current again is one undo step"); + assert_eq!(s.execute("brush.list", &json!({})).unwrap()["current"], "Charcoal"); + let b = rect(&mut s, 80.0, 10.0, 50.0, 50.0); + let steps = undo_steps(&s); + s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0, b.0]})).unwrap(); + assert_eq!((brush_of(&s, a).as_deref(), brush_of(&s, b).as_deref()), (Some("Charcoal"), Some("Charcoal"))); + assert_eq!(undo_steps(&s), steps + 1, "a new stroke to paint is one undo step"); +} + /// A document whose brushes repeat a name opens with the later brush numbered: strokes of the name /// keep the first brush, and renaming or deleting one brush leaves the other and its strokes alone. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..b22bc55ef5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5179,7 +5179,9 @@ already walks Image Trace. Short agent entry points: `brush.new` or `brush.options` without a `key` takes the color that the art's fills and strokes use most (on a tie, the one found first), or black when they use no solid color. `brush.options` changes only the fields of `colorization` and of an art brush's `scale` that `params` gives, so `{colorization: {method: "hueShift"}}` keeps a - Hue Shift brush's key. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the + Hue Shift brush's key. A `brush.options` whose `params` and `newName` leave the brush as it is, and a + `brush.apply` whose strokes already have the brush while it is already current, do not change the document or + its revision and record no undo step. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the default, leaves every copy's colors as the colorization gives them) turns the hue of each copy's solid fills and strokes, its type's characters included, by that copy's own amount between minus and plus that many degrees. The turn comes after the colorization: with None it turns the art's own colors, with Tints and Tints and Shades the From 2fa64c33a2bc5f4207c5a015f797af6ec0903db7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 06:17:06 -0800 Subject: [PATCH 16/36] Tests: the six slowest interface tests run in a fraction of the time - Menu entries and Help search look up every shortcut in one keymap read. While a shortcut change waits for the next frame, each lookup cloned the whole keymap, so a Help search after shortcuts.set took about 4 s in a debug build. - The Insert Menu Item test and the Alt chord test make a new app for each item in one shared window. The Alt chord test releases each chord after its checks. - The palette test picks into one app per case while a pick changes nothing, and compares the tool's state as well. - The 3D row test reopens the dialog in one window for each row. --- crates/ui-egui/src/dialogs/revolve/tests.rs | 22 ++++++++--- crates/ui-egui/src/menus/entries.rs | 28 +++++++++---- crates/ui-egui/src/menus/tests.rs | 2 +- crates/ui-egui/src/palette.rs | 35 ++++++++++++----- .../ui-egui/src/panels/actions/tests_edits.rs | 4 +- .../src/panels/actions/tests_support.rs | 17 ++++++-- crates/ui-egui/src/panels/discover.rs | 10 ++++- crates/ui-egui/src/shortcuts/tests.rs | 39 +++++++++++++++---- crates/ui-egui/src/testing.rs | 15 ++++++- 9 files changed, 132 insertions(+), 40 deletions(-) diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index ceb96018f7..f48f65b38d 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -114,22 +114,32 @@ fn rows() -> Vec<(&'static str, &'static str, &'static str, Value)> { #[test] fn a_3d_row_sets_its_param_previews_and_applies_in_one_step() { + // One window serves every row: Cancel, and OK followed by Undo, leave the drawing as the dialog found it, and each + // row opens the dialog again over it. + let mut shown: Option = None; for (effect, page, key, value) in rows() { let name = format!("{effect}.{key}"); for confirm in [false, true] { - let mut h = drawn(SQUARE, effect); - let before = source(&h); + let p = json!({"effect": effect, "item": null}); + let h = match shown.as_mut() { + Some(h) => { + reopen(h, p); + h + } + None => shown.insert(opened(app_with(SQUARE), p)), + }; + let before = source(h); h.set("__page", json!(page)); h.set(key, value.clone()); - assert!(same(&stored(&h, effect)[key], &value), "{name}: the preview follows the row"); + assert!(same(&stored(h, effect)[key], &value), "{name}: the preview follows the row"); if confirm { h.ok(); - assert!(same(&stored(&h, effect)[key], &value), "{name}: OK keeps it"); - undo(&h); + assert!(same(&stored(h, effect)[key], &value), "{name}: OK keeps it"); + undo(h); } else { h.cancel(); } - assert_eq!(doc(&h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" }); + assert_eq!(doc(h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" }); } } } diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 69722bd1ae..66353c55be 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -1,7 +1,9 @@ +use craft::keymap::{Chord, CommandRef}; + use super::context::context_items; -use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label}; +use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut_in, spelling_item_label, unlock_item_label}; use super::slots::{recent_readable, recent_slot}; -use super::state::{shortcut_of, shown_state}; +use super::state::{command_shortcuts, shown_state}; use super::tree::{Listed, menu_tree_named}; use super::{Node, Serialize, Value, VectorcraftApp, unbound}; @@ -32,8 +34,9 @@ pub struct MenuEntry { /// Flattened menu for `ui.menu.list`. pub fn menu_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; + let chord = command_shortcuts(app); for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english, &Listed::of(app)) { - flatten(app, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out); + flatten(app, &chord, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out); } out } @@ -41,7 +44,7 @@ pub fn menu_entries(app: &VectorcraftApp) -> Vec { /// Flattened canvas context menu for `ui.contextMenu.list` (paths are its submenus). pub fn context_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; - flatten(app, vec![], vec![], &context_items(app), &mut out); + flatten(app, &command_shortcuts(app), vec![], vec![], &context_items(app), &mut out); out } @@ -166,7 +169,15 @@ pub fn insertable_items(english_names: bool, listed: &Listed) -> Vec, shown: Vec, nodes: &[Node], out: &mut Vec) { +/// `nodes` flattened into `out`, each item's shortcut looked up in `chord` ([`command_shortcuts`]). +pub(super) fn flatten( + app: &VectorcraftApp, + chord: &dyn Fn(&CommandRef) -> Option, + path: Vec, + shown: Vec, + nodes: &[Node], + out: &mut Vec, +) { for node in nodes { match node { Node::Item(it) if unbound(&it.command.id) => out.push(MenuEntry { @@ -197,7 +208,10 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec, shown: Vec, shown: Vec {} } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index adaa0b488c..4ecd9e690c 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -394,7 +394,7 @@ fn menu_entry_shown_paths_keep_script_folder_names() { let items = vec![sub("Scripts", vec![sub("File", folder), cp("Other Script…", "ui.runScript", Value::Null)])]; let mut out = vec![]; crate::i18n::set_current(de); - flatten(&app, vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out); + flatten(&app, &super::command_shortcuts(&app), vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out); crate::i18n::set_current(crate::i18n::Lang::EN); let script = out.iter().find(|e| e.command.as_deref() == Some(crate::scripts_menu::COMMAND)).unwrap(); assert_eq!(script.path, ["File", "Scripts", "File"]); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 9079b40a5d..f4ea2715bb 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1753,8 +1753,8 @@ mod tests { /// the menu bar, and commands that need a value no menu item gives, with a menu path of their own /// or without one. A pick of each one it leaves /// out (with no document, one object selected or several) changes neither the document, its - /// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still - /// listed. + /// selection, history and layer state, the tool's state, nor the interface. Every [`PICK_RUNS`] + /// query is still listed. #[test] fn the_palette_leaves_out_the_commands_a_pick_cannot_run() { let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect(); @@ -1785,16 +1785,33 @@ mod tests { (st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone()) }); // A modeless dialog (Find and Replace) blocks nothing, so `any_dialog_open` leaves it out: the host lists it. - (doc, app.session.script_console().lines().len(), (app.any_dialog_open(), crate::tests::picks::open_dialogs(app).len()), ui) + // The tool's own state: the tool, a gesture or an input method's text in progress, and an interaction the + // session holds open. + let tool = (app.session.tool_id().to_owned(), app.session.tool_composing(), app.session.pointer_held(), app.session.in_interaction()); + (doc, app.session.script_console().lines().len(), (app.any_dialog_open(), crate::tests::picks::open_dialogs(app).len()), ui, tool) }; - let acts = |id: &str| { - [Session::new(), Fixture::Single.session(), Fixture::Multi.session()].into_iter().any(|session| { - let mut app = app_on(session); - let before = look(&app); - pick(&mut app, id); - look(&app) != before + // One app for each of the three cases, picked in one after another while a pick changes nothing that `look` + // sees; a pick that changes something is recorded, and its case starts again from a new app. + let fresh = |case: usize| { + app_on(match case { + 0 => Session::new(), + 1 => Fixture::Single.session(), + _ => Fixture::Multi.session(), }) }; + let mut apps: Vec = (0..3).map(fresh).collect(); + let mut acts = |id: &str| { + let mut changed = false; + for (case, app) in apps.iter_mut().enumerate() { + let before = look(app); + pick(app, id); + if look(app) != before { + changed = true; + *app = fresh(case); + } + } + changed + }; let changed: Vec<&str> = ids.iter().copied().filter(|id| acts(id)).collect(); assert!(changed.is_empty(), "a pick of these does something: {changed:?}"); for c in &dropped { diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index 1fe2f13711..208c293b70 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -927,8 +927,10 @@ fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() { fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { // The View menu's proof items change the whole process's proof view. let _view = crate::testing::DefaultProofView::new(); + // A new app for each item, all in one window. + let window = crate::testing::window_context(); for item in crate::menus::insertable_items(false, &crate::menus::Listed::default()) { - let (mut app, _) = app_with_three_moves(); + let (mut app, _) = three_moves_in(new_app_in(&window)); app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap(); let held = steps(&app, 0, 0)[3].1.clone(); let start = app.session.journal.len(); diff --git a/crates/ui-egui/src/panels/actions/tests_support.rs b/crates/ui-egui/src/panels/actions/tests_support.rs index 610e180bf0..3f763ad877 100644 --- a/crates/ui-egui/src/panels/actions/tests_support.rs +++ b/crates/ui-egui/src/panels/actions/tests_support.rs @@ -20,9 +20,14 @@ use crate::VectorcraftApp; /// An app with the built-in set, in a window whose dialog host the tests drive and which has drawn its first frame, so /// the window's keymap holds the app's commands. pub(crate) fn new_app() -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - let ctx = app.ui_ctx.clone().expect("a window"); - crate::testing::app_frame(&mut app, &ctx, Default::default()); + new_app_in(&crate::testing::window_context()) +} + +/// [`new_app`] in the window of `ctx` ([`crate::testing::window_context`]), which a test can reuse for a new app at +/// each step. +pub(crate) fn new_app_in(ctx: &egui::Context) -> VectorcraftApp { + let mut app = crate::testing::windowed_in(VectorcraftApp::new(Session::new(), Default::default()), ctx); + crate::testing::app_frame(&mut app, ctx, Default::default()); app } @@ -251,7 +256,11 @@ pub(crate) fn cancel_dialog(app: &mut VectorcraftApp) { /// A document with one rectangle selected and the set "Moves" with one action that moves it /// right three times, by 1, 2 and 4 pt → (the app, the rectangle's left edge as it moves). pub(crate) fn app_with_three_moves() -> (VectorcraftApp, impl Fn(&VectorcraftApp) -> f64) { - let mut app = new_app(); + three_moves_in(new_app()) +} + +/// [`app_with_three_moves`] made from `app`, a new app such as [`new_app_in`] gives. +pub(crate) fn three_moves_in(mut app: VectorcraftApp) -> (VectorcraftApp, impl Fn(&VectorcraftApp) -> f64) { app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let id = vectorcraft_doc::NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); diff --git a/crates/ui-egui/src/panels/discover.rs b/crates/ui-egui/src/panels/discover.rs index 649727d609..58c9bb5c12 100644 --- a/crates/ui-egui/src/panels/discover.rs +++ b/crates/ui-egui/src/panels/discover.rs @@ -52,7 +52,12 @@ pub struct View { /// The text of a tool's shortcut in the window's keymap, empty when it has none. fn tool_shortcut(app: &VectorcraftApp, id: &str) -> String { - menus::shortcut_of(app, &format!("tool:{id}")).map_or_else(String::new, |chord| chord.display(crate::keymap::platform())) + tool_shortcut_in(&menus::command_shortcuts(app), id) +} + +/// [`tool_shortcut`] looked up in `chord` ([`menus::command_shortcuts`]). +fn tool_shortcut_in(chord: &dyn Fn(&craft::keymap::CommandRef) -> Option, id: &str) -> String { + chord(&crate::keymap::command_of(&format!("tool:{id}"))).map_or_else(String::new, |chord| chord.display(crate::keymap::platform())) } /// Updates the retained results' labels, menu paths and shortcuts after the menu state changes (a @@ -109,6 +114,7 @@ fn refresh(app: &mut VectorcraftApp) { /// The tools, each with the entry the search ranks it by. fn tool_hits(app: &VectorcraftApp) -> Vec<(HelpEntry, Hit)> { let lang = crate::i18n::current(); + let chord = menus::command_shortcuts(app); vectorcraft_tools::catalog::all_tools() .map(|tool| { let label: String = crate::i18n::tr(lang, tool.label).into(); @@ -120,7 +126,7 @@ fn tool_hits(app: &VectorcraftApp) -> Vec<(HelpEntry, Hit)> { id: tool.id.into(), label, path: vec![], - shortcut: tool_shortcut(app, tool.id), + shortcut: tool_shortcut_in(&chord, tool.id), english_label: tool.label.into(), english_path: vec![], params: Value::Null, diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index f5cd51ebb5..f33216e978 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -210,6 +210,18 @@ fn editing_hi() -> (VectorcraftApp, u64) { (app, id) } +/// [`editing_hi`] in the window of `ctx`, which a test can reuse for a new app at each step, after the frames +/// [`typing_ready`] runs. +fn editing_hi_in(ctx: &egui::Context) -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + key_frame(&mut app, ctx, vec![]); + let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + edit(&mut app, 2, 2); + idle(&mut app, ctx, 2); + (app, id) +} + /// Starts editing the selected type object with the Type tool and selects `start..end`. fn edit(app: &mut VectorcraftApp, start: u64, end: u64) { app.select_tool("type"); @@ -901,22 +913,33 @@ fn alt_chords_type_special_characters_while_editing_text() { return; } let mut wrong = vec![]; + // A new app for each chord, all in one window. + let ctx = crate::testing::ui_context(); for (key, shift, own, character) in ALT_CHARACTER_CHORDS { for typed in [None, Some(own), Some(own.to_uppercase().as_str())] { - let (mut app, id) = editing_hi(); - let ctx = typing_ready(&mut app); + let (mut app, id) = editing_hi_in(&ctx); key_frame(&mut app, &ctx, alt_press(key, shift, typed)); let case = format!("{key:?} shift={shift} text={typed:?}"); let text = text_and_layers(&mut app, id).0; if text != format!("Hi{character}") { wrong.push(format!("{case}: text = {text:?}")); - continue; - } - app.session.execute("edit.undo", &json!({})).unwrap(); - let undone = text_and_layers(&mut app, id).0; - if undone != "Hi" { - wrong.push(format!("{case}: after Undo = {undone:?}")); + } else { + app.session.execute("edit.undo", &json!({})).unwrap(); + let undone = text_and_layers(&mut app, id).0; + if undone != "Hi" { + wrong.push(format!("{case}: after Undo = {undone:?}")); + } } + // The window keeps a key held from one app to the next: the release makes the next chord a new press. + let m = if shift { Modifiers::ALT | Modifiers::SHIFT } else { Modifiers::ALT }; + key_frame( + &mut app, + &ctx, + vec![ + egui::Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: m }, + egui::Event::ModifiersChanged(Modifiers::NONE), + ], + ); } } assert!(wrong.is_empty(), "{wrong:#?}"); diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index 6098a8467a..89a74801bc 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -22,10 +22,21 @@ pub(crate) fn install(ctx: &egui::Context) { /// `app` shown in a window of its own: its context is the one every frame of the test runs on, so its dialogs open on /// the window's host, focus and drags last from frame to frame, and the access tree is on for the tests that find a /// control by its role. -pub(crate) fn windowed(mut app: crate::VectorcraftApp) -> crate::VectorcraftApp { +pub(crate) fn windowed(app: crate::VectorcraftApp) -> crate::VectorcraftApp { + windowed_in(app, &window_context()) +} + +/// The context of a window [`windowed`] shows an app in, with the access tree on. A test that makes a new app for each +/// item can show each one in the same window with [`windowed_in`]. +pub(crate) fn window_context() -> egui::Context { let ctx = ui_context(); ctx.enable_accesskit(); - app.ui_ctx = Some(ctx); + ctx +} + +/// `app` shown in the window of `ctx`, as [`windowed`] shows it in a window of its own. +pub(crate) fn windowed_in(mut app: crate::VectorcraftApp, ctx: &egui::Context) -> crate::VectorcraftApp { + app.ui_ctx = Some(ctx.clone()); app } From bd0d0149ac2c83b3c7a14129a09ebb8f709ac6e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:00:26 -0800 Subject: [PATCH 17/36] Brushes: Apply Brush text says it clears a stroke's own settings brush.apply clears the brush settings of each path's top stroke, and clearing them is one undo step. The command text and docs/mcp.md now limit the no-op to a current brush whose top strokes already have it, paint, a width above 0 and no settings of their own. A new test applies the current brush to a stroke with its own settings and checks that they are cleared as one undo step. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/tests/brushsym.rs | 15 +++++++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 2de3ddfcfe..84f7c5ed3b 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Apply Brush", [], None, - "{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current; when the strokes already have it and it is already current, nothing changes and no undo step is recorded → {ids}", + "{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current; the brush settings of each path's top stroke (brush.objectOptions) are cleared, and clearing them is one undo step; when the brush is already current and applying it leaves every path as it was (its top stroke already has the brush, paint, a width above 0 and no settings of its own), nothing changes and no undo step is recorded → {ids}", has_doc, brush_apply ), diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 86074c2a6b..33363119c1 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -969,6 +969,21 @@ fn brush_apply_that_changes_nothing_records_no_undo_step() { assert_eq!(undo_steps(&s), steps + 1, "a new stroke to paint is one undo step"); } +/// Applying the current brush again to a stroke with settings of its own clears them as one undo step. +#[test] +fn brush_apply_clears_object_options_as_one_undo_step() { + let mut s = session(); + let a = line(&mut s); + select(&mut s, &[a]); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + let steps = undo_steps(&s); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + assert_eq!(own_options(&s, a), json!({}), "applying the brush clears the stroke's own settings"); + assert_eq!(undo_steps(&s), steps + 1, "clearing the settings is one undo step"); +} + /// A document whose brushes repeat a name opens with the later brush numbered: strokes of the name /// keep the first brush, and renaming or deleting one brush leaves the other and its strokes alone. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index b22bc55ef5..14e4d45f77 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5180,8 +5180,9 @@ already walks Image Trace. Short agent entry points: the one found first), or black when they use no solid color. `brush.options` changes only the fields of `colorization` and of an art brush's `scale` that `params` gives, so `{colorization: {method: "hueShift"}}` keeps a Hue Shift brush's key. A `brush.options` whose `params` and `newName` leave the brush as it is, and a - `brush.apply` whose strokes already have the brush while it is already current, do not change the document or - its revision and record no undo step. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the + `brush.apply` of the current brush whose paths' top strokes already have the brush, paint, a width above 0 and no + settings of their own, do not change the document or its revision and record no undo step. `brush.apply` clears the own settings + (`brush.objectOptions`) of each path's top stroke, and clearing them is one undo step; lower strokes keep theirs. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the default, leaves every copy's colors as the colorization gives them) turns the hue of each copy's solid fills and strokes, its type's characters included, by that copy's own amount between minus and plus that many degrees. The turn comes after the colorization: with None it turns the art's own colors, with Tints and Tints and Shades the From cddc75cf5c06e310c71473477a8b672958ccd492 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:27:30 -0800 Subject: [PATCH 18/36] Brushes: only Brush Options skips an unchanged library save The equality check that skips the undo step now sits in brush.options, which compares the edited brush with the stored one. New, Delete, Move, Duplicate and Replace Brush Art save the library as they do on main, without decoding it a second time. docs/target-app-parity.md lists the no-op rules for Brush Options and Apply Brush with their tests. --- crates/engine/src/cmd/brushsym/brushes.rs | 15 ++++++++------- docs/target-app-parity.md | 1 + 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 18eb440f3a..eaebecf11e 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -214,12 +214,8 @@ fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Opt } } -/// Stores `lib` and applies `renames` as one undo step named `label`. A `lib` equal to the -/// document's library, with no renames, leaves the document and its undo history as they are. +/// Stores `lib` and applies `renames` as one undo step named `label`. fn save_library(s: &mut Session, label: &str, mut lib: Vec, renames: &[(String, Option)]) -> Result<()> { - if renames.is_empty() && lib == brush::library(&s.doc()?.doc) { - return Ok(()); - } s.edit(label, |d, _| { for (from, to) in renames { rename_brush_strokes(d, &mut lib, from, to.as_deref()); @@ -509,8 +505,13 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { v["name"] = json!(name); } v["type"] = json!(lib[i].kind.type_id()); - lib[i] = parse_brush(C, v)?; - let out = lib[i].name.clone(); + let edited = parse_brush(C, v)?; + let out = edited.name.clone(); + // Options that leave the brush as it is change nothing and add no undo step. + if new_name.is_none() && edited == lib[i] { + return Ok(json!({ "name": out })); + } + lib[i] = edited; let rename = new_name.map(|nn| (name, Some(nn))); save_library(s, "Brush Options", lib, rename.as_slice())?; Ok(json!({ "name": out })) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..c06f4e5922 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2243,6 +2243,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Pattern Brush Options' Scale has a menu of Fixed, Pressure, Tilt, Bearing, Rotation and Stylus Wheel with a second scale beside it, in the library brush's dialog and in Options of Selected Object, from the pen tablet options the Pattern brush options section of the help page (, archived copy) lists for Scale (`brush.options` and `brush.objectOptions` `scale_mode` and `scale_max`). The tiles go from Scale where the pen reads 0 to the second scale where it reads 1, over the same ranges as Art Brush Options' Width, and half way on a stroke without that input. Each side, start and end tile is as tall as the scale at each point of the stroke, and the tile is as long as the scale at its middle; a corner tile takes the scale at its corner. Stretch to Fit stretches the tiles and gaps of each run to fill it, Add Space to Fit shares out what is left between the tiles, and Approximate Path centers them on the run. The help page does not say how the pen maps to the scale or how the tiles are measured along the stroke, so those rules are VectorCraft's own. A brush with a fixed scale draws as before. `.ai` files do not read or write the pattern scale's mode, and the Width tool does not turn the pen's data into width points. Evidence: `tests::pattern_brush_scale_follows_the_pressure`, `tests::pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel`, `tests::pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles` (vectorcraft-brush), `tests::brushsym::options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes`, `tests::brushsym::pattern_brush_scale_mode_goes_through_the_brush_commands` (vectorcraft-engine), `dialogs::brush_options::tests::pattern_options_scale_follows_the_pen`, `dialogs::brush_options::tests::options_of_selected_object_set_one_paths_pattern_scale_mode` (vectorcraft-ui-egui). - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, on macOS from AppKit's `tangentialPressure`, and in the web build from Pointer Events' `tangentialPressure` (), for each move of a pen including the positions a fast stroke's events coalesce. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still, no packet has come for longer, or another tablet's cursor has been read since, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS and in the web build; the web build reads the wheel afresh for another pen, the other end, a canceled press and a pen that left the hover range. These are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `pencil::tests::an_airbrush_wheel_goes_into_the_feed`, `pencil::tests::coalesced_moves_keep_their_wheel` and `pencil::tests::the_wheel_is_read_afresh_for_each_pen_and_end` (vectorcraft-web), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). + - **Brush edits that change nothing add no undo step:** Brush Options that leave a brush as it is, and Apply Brush of the current brush to paths whose top strokes already have it, paint, a width above 0 and no settings of their own, leave the document and its undo history as they are. Apply Brush clears the settings of the top stroke (Options of Selected Object), and clearing them is one undo step. Evidence: `tests::brushsym::brush_apply_that_changes_nothing_records_no_undo_step` and `tests::brushsym::brush_apply_clears_object_options_as_one_undo_step` (vectorcraft-engine). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From d3e02f41a18d29e51628c13ba70769c8d8009f1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:52:49 -0800 Subject: [PATCH 19/36] Performance: Properties rows read a large selection once per edit After an edit the selection keeps no record of its paints, so the Fill and Stroke chips and the Stroke and Width Profile rows looked up the groups around every selected object for Live Paint faces and edges each time they were drawn. DocState::live_paint_covered_kept keeps an empty answer for that version of the document and those objects. The Recolor quick action listed and sorted every color of the selection to see whether it held more than one. Session::several_colors_used reads the same objects and pattern tiles and stops at the second color. --- crates/engine/src/cmd.rs | 3 + crates/engine/src/cmd/paint.rs | 5 +- crates/engine/src/cmd/paint/tests.rs | 52 +++++++++ crates/engine/src/cmd/recolor.rs | 133 ++++++++++++++++++++++++ crates/engine/src/doc_state.rs | 34 ++++++ crates/ui-egui/src/panels/properties.rs | 8 +- 6 files changed, 229 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 43d6e3a7d4..3641f82d6b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -874,6 +874,9 @@ pub(crate) use vectorcraft_doc::range::parse_range; /// What the fill and stroke proxies read from the selected objects, kept with the selection /// ([`crate::doc_state::SelectionRecord`]). pub(crate) use paint::SelectionPaints; +/// The faces and edges of Live Paint groups among objects that count with their group +/// ([`crate::DocState::live_paint_covered_kept`] keeps an empty answer). +pub(crate) use paint::live_paint_covered; #[cfg(test)] pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ}; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index c722e2a58b..2a61f7fb74 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1470,12 +1470,13 @@ fn in_live_paint(d: &Document, id: NodeId) -> bool { impl DocState { /// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none - /// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group. + /// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group, + /// else as [`DocState::live_paint_covered_kept`] keeps it for this version of the document. pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet { if self.selection_paints().is_some_and(|p| !p.in_live_paint()) { return std::collections::HashSet::new(); } - live_paint_covered(&self.doc, ids) + self.live_paint_covered_kept(ids) } } diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs index ec8f02f700..9b0fb393df 100644 --- a/crates/engine/src/cmd/paint/tests.rs +++ b/crates/engine/src/cmd/paint/tests.rs @@ -242,6 +242,58 @@ fn the_question_marks_read_only_the_selected_objects() { assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); } +/// How many times this thread read the groups around selected objects for their Live Paint faces +/// and edges ([`DocState::live_paint_covered_kept`]). +fn cover_reads() -> usize { + crate::doc_state::LIVE_PAINT_COVER_READS.with(Cell::get) +} + +/// After an edit the selection keeps no record of what it holds, and the proxies, the Stroke panel +/// and the "?" ask on every frame whether its objects lie in a Live Paint group. They read the +/// objects' groups once for each version of the document and selection, not once for each question. +/// A Live Paint group selected with one of its faces still counts the face with its group. +#[test] +fn live_paint_faces_are_looked_for_once_per_document_version() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ids: Vec = (0..20).map(|i| rect(&mut s, 10.0 + 30.0 * f64::from(i), "#ff0000", "#000000")).collect(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + assert!(s.active().unwrap().selection_paints().is_none(), "the edit leaves the selection without a record"); + let ask = |s: &Session| { + for _ in 0..3 { + s.proxy_paints(); + s.shown_stroke(); + s.proxy_mixed(); + s.active().unwrap().stroke_mixed(); + } + }; + let before = cover_reads(); + ask(&s); + assert_eq!(cover_reads() - before, 1, "one read for this version of the document"); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = cover_reads(); + ask(&s); + assert_eq!(cover_reads() - before, 1, "an edit reads them again, once"); + s.execute("select.set", &json!({"ids": [ids[0].0, ids[1].0]})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = cover_reads(); + ask(&s); + assert_eq!(cover_reads() - before, 1, "another selection reads them again, once"); + + // A Live Paint group with one of its edges selected too: the edge counts with its group on every ask. + s.execute("livePaint.make", &json!({"ids": [ids[2].0, ids[3].0]})).unwrap(); + let group = s.active().unwrap().selection.objects[0]; + let edge = vectorcraft_tools::builder::edges(s.active().unwrap().doc.node(group).unwrap())[0].id; + s.execute("select.set", &json!({"ids": [group.0, edge.0]})).unwrap(); + let st = s.active().unwrap(); + let covered = live_paint_covered(&st.doc, &st.selection.objects); + assert!(covered.contains(&edge)); + for _ in 0..2 { + assert_eq!(st.selection_live_paint_covered(&st.selection.objects), covered); + } +} + /// Random selections of a document with nested groups answer as a walk does. #[test] fn random_selections_match_a_walk_of_the_document() { diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index b4ad26400b..174f90ecb0 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -1027,6 +1027,76 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> used.into_iter().map(|(_, u)| u).collect() } +#[cfg(test)] +thread_local! { + /// Tests: how many objects [`several_colors`] read on this thread. + static SEVERAL_COLORS_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether [`used_colors`] lists more than one color for the objects `ids`. The objects are read +/// until a second color turns up. +fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> bool { + struct Seen<'a> { + first: Option, + several: bool, + patterns: Vec<&'a str>, + } + impl<'a> Seen<'a> { + fn read(&mut self, m: &'a Node) { + #[cfg(test)] + SEVERAL_COLORS_READS.with(|c| c.set(c.get() + 1)); + let (first, several) = (&mut self.first, &mut self.several); + paints( + m, + &mut |c, _, _, _| { + let k = ColorKey::of(c); + match first { + None => *first = Some(k), + Some(f) => *several |= *f != k, + } + }, + &mut self.patterns, + ); + } + fn read_tree(&mut self, n: &'a Node, only: Option<&BTreeSet>) { + if self.several || only.is_some_and(|o| !o.contains(&n.id)) { + return; + } + self.read(n); + for c in n.children().into_iter().flatten() { + self.read_tree(c, only); + } + } + } + let mut seen = Seen { first: None, several: false, patterns: vec![] }; + for n in ids.iter().filter_map(|id| d.node(*id)) { + seen.read_tree(n, only); + } + let mut next = 0; + while !seen.several + && let Some(&name) = seen.patterns.get(next) + { + next += 1; + for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() { + a.walk(&mut |m| { + if !seen.several { + seen.read(m); + } + }); + } + } + seen.several +} + +impl Session { + /// Whether the objects `recolor.colors` reads without `ids` use more than one color: the + /// selection, or with nothing selected the objects Select All takes. False without a document. + pub fn several_colors_used(&self) -> bool { + let Ok((ids, only)) = scope_ids(self, &Value::Null, "recolor.colors") else { return false }; + self.doc().is_ok_and(|st| several_colors(&st.doc, &ids, only.as_ref())) + } +} + /// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint /// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and /// add the patterns it is painted with to `patterns`. @@ -2050,6 +2120,69 @@ mod tests { assert!(has(&t, RED), "P100 read again at the top"); } + /// How many objects [`several_colors`] read on this thread. + fn several_reads() -> usize { + SEVERAL_COLORS_READS.with(std::cell::Cell::get) + } + + /// Whether more than one color is used ([`Session::several_colors_used`]), checked against the + /// length of `recolor.colors`'s list, with how many objects the answer read. + fn several(s: &mut Session, what: &str) -> (bool, usize) { + let before = several_reads(); + let several = s.several_colors_used(); + let reads = several_reads() - before; + let listed = s.execute("recolor.colors", &json!({})).unwrap()["colors"].as_array().map_or(0, Vec::len); + assert_eq!(several, listed > 1, "{what}: {listed} colors listed"); + (several, reads) + } + + /// The Recolor quick action asks on every change whether the selection uses more than one + /// color. The answer matches `recolor.colors`, pattern tiles and Select All's objects included, + /// and the objects are read only until a second color turns up. + #[test] + fn several_colors_stop_at_the_second_color() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ids: Vec = (0..30) + .map(|i| { + let id = + s.execute("shape.rectangle", &json!({"x": 10 + 20 * i, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + id + }) + .collect(); + s.execute("select.all", &json!({})).unwrap(); + assert_eq!(several(&mut s, "one red"), (false, 30), "one color: every object is read"); + // A blue object in the middle: the objects are read up to it, from either end. + s.execute("paint.setFill", &json!({"ids": [ids[15]], "color": "#0000ff"})).unwrap(); + let (found, reads) = several(&mut s, "a blue in the middle"); + assert!(found && matches!(reads, 15 | 16), "{reads} objects read"); + s.execute("paint.setFill", &json!({"ids": [ids[0], ids[29]], "color": "#00ff00"})).unwrap(); + assert_eq!(several(&mut s, "green at both ends"), (true, 2), "the second object holds the second color"); + s.execute("select.set", &json!({"ids": &ids[1..15]})).unwrap(); + assert!(!several(&mut s, "the red ones").0); + s.execute("select.none", &json!({})).unwrap(); + assert!(several(&mut s, "Select All's objects").0); + + // A red object filled with a pattern too: its tile's color counts. + for (tile, expect) in [(BLUE, true), (RED, false)] { + let filled = NodeId(ids[1]); + s.edit("t", |d, _| { + let art = square(d, 0.0, Paint::solid(tile)); + d.patterns.retain(|p| p.name != "Tile"); + d.patterns.push(PatternDef::new("Tile", vec![art])); + if let Some(n) = d.node_mut(filled) { + n.appearance.set_fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY }); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [ids[1], ids[2]]})).unwrap(); + assert_eq!(several(&mut s, "a pattern tile").0, expect, "a tile of {tile:?}"); + } + } + /// A pattern tile's symbol instances charge the same limit as the art around it. #[test] fn pattern_tiles_charge_the_symbol_limit() { diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index e1bb6df83a..8307b6a8b1 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -203,6 +203,18 @@ pub struct DocState { /// The selected objects as [`crate::Session::select`] last checked them or the proxies last /// read them, with the document they were checked in ([`SelectionRecord`]). Not saved. pub(crate) selection_record: Option, + /// The objects that [`DocState::live_paint_covered_kept`] last found no face or edge of a Live + /// Paint group among, with the document it read. Not saved. + outside_live_paint: std::cell::RefCell>, +} + +/// Objects that hold no face or edge of a Live Paint group that counts with its group +/// ([`cmd::live_paint_covered`] is empty for them), with the document they were read in, held as +/// [`EmptyArtboards::doc`] holds it. +#[derive(Clone, Debug)] +struct OutsideLivePaint { + doc: std::sync::Weak, + ids: Vec, } /// A selection of objects alone ([`objects_only`]) with the document it was checked or read in: @@ -302,6 +314,8 @@ thread_local! { pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread. pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times [`DocState::live_paint_covered_kept`] read the objects' groups on this thread. + pub(crate) static LIVE_PAINT_COVER_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -522,6 +536,7 @@ impl DocState { measured_in_own: None, inline_resolved: None, selection_record: None, + outside_live_paint: Default::default(), } } /// The [`SelectionRecord`] of the selection now: `None` when the document or the selected @@ -539,6 +554,25 @@ impl DocState { pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> { self.selection_record().and_then(|r| r.paints.as_ref()) } + /// The faces and edges of Live Paint groups among `ids` that count with their group + /// ([`cmd::live_paint_covered`]). An empty answer is kept for this version of the document and + /// these objects, so the proxies and the Stroke panel, which ask on every frame, read the + /// objects' groups once after an edit. + pub(crate) fn live_paint_covered_kept(&self, ids: &[NodeId]) -> std::collections::HashSet { + let kept = |k: &OutsideLivePaint| std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) && k.ids == ids; + if self.outside_live_paint.try_borrow().is_ok_and(|k| k.as_ref().is_some_and(kept)) { + return std::collections::HashSet::new(); + } + #[cfg(test)] + LIVE_PAINT_COVER_READS.with(|c| c.set(c.get() + 1)); + let covered = cmd::live_paint_covered(&self.doc, ids); + if covered.is_empty() + && let Ok(mut k) = self.outside_live_paint.try_borrow_mut() + { + *k = Some(OutsideLivePaint { doc: Arc::downgrade(&self.doc), ids: ids.to_vec() }); + } + covered + } /// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with /// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same /// document: the objects that leave the selection are taken out of its paints and the objects diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 7e3caa1a43..b137711d0d 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -291,8 +291,9 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool { }) } -/// Whether the selection uses more than one colour (`recolor.colors`), which offers the Recolor -/// quick action; memoised per document revision. +/// Whether the selection uses more than one colour (`recolor.colors` lists more than one, +/// [`vectorcraft_engine::Session::several_colors_used`]), which offers the Recolor quick action; +/// memoised per document revision. pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool { let Some(st) = app.session.active() else { return false }; let key = (st.uid, st.revision); @@ -301,8 +302,7 @@ pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool { { return multi; } - let r = app.session.execute("recolor.colors", &json!({})).unwrap_or_default(); - let multi = r["colors"].as_array().is_some_and(|c| c.len() > 1); + let multi = app.session.several_colors_used(); app.canvas.multi_color = Some((key, multi)); multi } From 4bee2eef9cacb5582ed1621cc2849ea74b796de6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:09:54 -0800 Subject: [PATCH 20/36] Properties: a selection change draws the window in one pass When the selection changed, the Properties panel placed its sections by the sizes kept from the last selection, measured the new ones while drawing, and asked for the frame to be discarded and drawn again. Every selection change and the release of a move then drew the canvas and the other panels twice. The panel now shows the inspector's Panel itself and, when the document, its revision, the selection, the tool or isolation mode changed since the last frame, measures its sections with `measure_in` before showing them, so the first pass places them at their new sizes. Field ids and the scroll position stay keyed by the document as before. Selections that add labeled rows still ask for a second pass for the rows' baselines until the craft-libs pin includes craft-libs#4311. --- crates/ui-egui/src/panels/properties.rs | 40 +++++++++++-- crates/ui-egui/src/panels/properties/tests.rs | 60 +++++++++++++++++++ 2 files changed, 95 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 7e3caa1a43..c1b6f36d94 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1,13 +1,13 @@ //! The Properties panel: sections that change with the selection. -use craft::behavior::{ColumnWidth, IconId}; +use craft::behavior::{ColumnWidth, IconId, Proposal}; use craft::ui::buttons::{Button, IconButton}; -use craft::ui::contract::{LabelScheme, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{BodyCx, LabelScheme, Pad, Props as _, Show as _, ShowContainer as _}; use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::panels::Inspector; use craft::ui::runtime::commands::CommandRef; -use craft::ui::sections::HeaderStrength; +use craft::ui::sections::{HeaderStrength, Panel}; use egui::Ui; use serde_json::json; use vectorcraft_doc::{LiveShape, Node, NodeKind}; @@ -27,6 +27,8 @@ pub struct PropertiesUi { pub edited_profiled: Option<(ProfiledKey, bool)>, /// The Quick Actions last listed, with the [`quick_actions_key`] they were listed at. quick_actions: Option<(u64, Vec)>, + /// The [`content_key`] the sections were last shown for. + content: Option, } /// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). @@ -63,7 +65,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Ruler guides selected on their own (a click on one): their position. let guides = super::transform::selected_guides(app); let header = heading(first.as_deref(), n_sel, editing_artboards, guides.is_some()); - inspector.target(key).header(header).show(ui, |ui, _| { + let content = content_key(app); + let changed = app.ui.properties_panel.content.replace(content) != Some(content); + let mut sections = |ui: &mut Ui, _: &mut BodyCx<'_>| { // The reference panel's labels end in a colon beside fields that keep their own width. Stack::new().fill_width().labels(LabelScheme::Form).show(ui, |ui, _| { if editing_artboards { @@ -77,7 +81,33 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { body(app, ui, first.as_deref(), n_sel, anchors); } }); - }); + }; + // The panel `Inspector::show` makes, shown here so that new sections are measured before they are placed and the + // frame is not discarded and drawn again. + let mut panel = Panel::new(header).titled().strength(HeaderStrength::Quiet).labels(LabelScheme::Inspector).pad(Pad::None); + panel = panel.id_salt(egui::IdSalt::new(key)); + if changed { + let _ = panel.measure_in(ui, Proposal::Size(ui.available_size()), &mut sections); + } + panel.show(ui, sections); +} + +/// What the sections show: the document and its revision, the selection, the tool and isolation mode. +fn content_key(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + app.session.tool_id().hash(&mut h); + if let Some(st) = app.session.active() { + let selection = &st.selection; + (st.uid, st.revision, st.isolation, &selection.objects, selection.key, selection.target, &selection.slices).hash(&mut h); + for (id, anchors) in &selection.anchors { + (id, anchors.len()).hash(&mut h); + } + for (id, segments) in &selection.segments { + (id, segments.len()).hash(&mut h); + } + } + h.finish() } /// The document's uid: production's field ids do not change with the selection, so neither does the key and the diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 4a8158364a..f10c38ae6a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -130,6 +130,66 @@ fn one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top() { assert_eq!(selected(&panel), std::slice::from_ref(&mask), "Edit Clipping Path selects the clipping path"); } +/// Selecting a second object, and going back to one, draws the panel in one pass: the sections are measured for the +/// new selection before they are placed, so the frame is not discarded and drawn again. The frame after each change +/// and a frame with no change take one pass too. +#[test] +fn a_selection_change_draws_the_panel_in_one_pass() { + let mut app = new_app(); + let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 120.0, 20.0, 60.0, 30.0)); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut panel = Panel::new(app, show); + let passes = |panel: &mut Panel| { + let before = panel.ctx().cumulative_pass_nr(); + panel.frame(); + panel.ctx().cumulative_pass_nr() - before + }; + panel.frame(); + assert_eq!(passes(&mut panel), 1, "a settled frame"); + for round in 0..2 { + for (what, ids) in [("select two", json!([a, b])), ("select one", json!([b])), ("select the other", json!([a]))] { + panel.app().run("select.set", json!({ "ids": ids })).unwrap(); + assert_eq!(passes(&mut panel), 1, "{what}, round {round}"); + assert_eq!(passes(&mut panel), 1, "the frame after {what}, round {round}"); + } + } +} + +/// The same selection changes in the whole window, with the Properties panel docked: each frame takes one pass, so +/// the canvas and the other panels are drawn once. +#[test] +fn a_selection_change_draws_the_window_in_one_pass() { + let mut app = new_app(); + let (a, b) = (rect(&mut app, 20.0, 20.0, 40.0, 40.0), rect(&mut app, 120.0, 20.0, 60.0, 30.0)); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + let mut passes = |app: &mut VectorcraftApp| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + ..Default::default() + }; + let before = ctx.cumulative_pass_nr(); + let _ = crate::testing::app_frame(app, &ctx, raw); + ctx.cumulative_pass_nr() - before + }; + for _ in 0..4 { + passes(&mut app); + } + assert_eq!(passes(&mut app), 1, "a settled frame"); + for round in 0..2 { + for (what, ids) in [("select two", json!([a, b])), ("select one", json!([b])), ("select the other", json!([a]))] { + app.run("select.set", json!({ "ids": ids })).unwrap(); + assert_eq!(passes(&mut app), 1, "{what}, round {round}"); + assert_eq!(passes(&mut app), 1, "the frame after {what}, round {round}"); + } + } +} + /// Start Global Edit in Quick Actions starts it on the one selected path, the button then reads /// Stop Global Edit, and Escape stops it. Selected type has no Start Global Edit button. #[test] From 3aa41526e2009af448624f9c93cceb6a7a7fed59 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:02:34 -0800 Subject: [PATCH 21/36] Performance: the color check stops walking objects after a second color several_colors kept looking up the remaining ids, walking the remaining children of a group and the rest of a pattern tile after it had found two colors. It now stops as soon as the second color turns up. --- crates/engine/src/cmd/recolor.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 174f90ecb0..a0ba6d243c 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -1065,12 +1065,18 @@ fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) self.read(n); for c in n.children().into_iter().flatten() { self.read_tree(c, only); + if self.several { + return; + } } } } let mut seen = Seen { first: None, several: false, patterns: vec![] }; for n in ids.iter().filter_map(|id| d.node(*id)) { seen.read_tree(n, only); + if seen.several { + return true; + } } let mut next = 0; while !seen.several @@ -1078,11 +1084,13 @@ fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) { next += 1; for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() { - a.walk(&mut |m| { - if !seen.several { - seen.read(m); - } + let _ = a.try_walk(&mut |m| { + seen.read(m); + if seen.several { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) } }); + if seen.several { + break; + } } } seen.several From 42f973a5bc04d84293c9896edde56e70adc2920e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:50:38 -0800 Subject: [PATCH 22/36] xtask: the cache warm builds integration tests too `cargo xtask ci warm` built each test shard with `--lib --bins --no-run`, while the shards run `--lib --bins --tests`. The warm build left out the integration test executables the shards then build, and cargo warned `unused dependency vectorcraft-testkit` for apps/vectorcraft-cli, whose only use is in tests/it. The warm build now selects the same targets as the test shards, through one `TARGETS` list that both use. --- xtask/src/main.rs | 45 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 08a55df09a..5484c0d3e9 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -267,12 +267,14 @@ fn cmd_test() -> Result<(), String> { test_packages(&["--workspace".to_owned()], "--workspace", None) } +/// The test targets that [`test_packages`] runs and `ci warm` builds. +const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; + /// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`; /// with `part`, only that part's share of their tests (xtask/src/shards.rs), which needs nextest. /// A part runs its counted share, then its pinned tests, each with nextest's default thread count. /// Every run finishes before the first error is returned. fn test_packages(select: &[String], shown: &str, part: Option) -> Result<(), String> { - const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; if let Some(part) = part { if !has_nextest() { return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest")); @@ -393,11 +395,13 @@ fn cmd_ci_shard() -> Result<(), String> { run_steps(&steps) } -/// `cargo xtask ci warm`: for each test shard, builds its crates' library and binary tests without -/// running them, then builds what the checks shard builds, so one dependency-cache entry holds the -/// dependencies of every shard with the features that shard builds them with (cargo resolves -/// features over the packages each command selects). The integration tests are left out: they -/// build no dependency that the library tests do not, since both take the crate's dev-dependencies. +/// `cargo xtask ci warm`: for each test shard, builds its crates' library, binary and integration +/// tests without running them, then builds what the checks shard builds, so one dependency-cache +/// entry holds the dependencies of every shard with the features that shard builds them with (cargo +/// resolves features over the packages each command selects). The test builds select the same +/// targets as the test shards ([`TARGETS`]), so the cache also holds the test executables the +/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that +/// only an integration test uses. /// /// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` /// (xtask/src/cache_units.rs), xtask's own build included. @@ -414,9 +418,8 @@ fn cmd_ci_warm() -> Result<(), String> { steps.push(( "build tests", Box::new(move || { - let mut c = cargo(); - c.arg("test").args(shards::select(&crates)).args(["--lib", "--bins", "--no-run"]); - cache_units::run(c, &format!("cargo test --lib --bins --no-run ({})", shards::names(&crates))) + let (c, what) = warm_tests(&crates); + cache_units::run(c, &what) }), )); } @@ -447,6 +450,13 @@ fn cmd_ci_warm() -> Result<(), String> { run_steps(&steps) } +/// The command `ci warm` builds one test shard's tests with, and its description. +fn warm_tests(crates: &[shards::Member]) -> (Command, String) { + let mut c = cargo(); + c.arg("test").args(shards::select(crates)).args(TARGETS).arg("--no-run"); + (c, format!("cargo test {} --no-run ({})", TARGETS.join(" "), shards::names(crates))) +} + /// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed /// and, after a failure, the one that failed and those skipped. fn run_steps(steps: &[Step]) -> Result<(), String> { @@ -588,3 +598,20 @@ fn i18n_report_packages(select: &[String], shown: &str) -> Result<(), String> { c.arg("test").args(select).args(["--lib", "--bins", "--tests", "--", "i18n::tests::untranslated_report", "--exact", "--nocapture"]); run(c, &format!("cargo test {shown} --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture")) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn warm_builds_the_test_targets_the_shards_run() { + let crates = [shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }]; + let (c, what) = warm_tests(&crates); + let args: Vec = c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + assert_eq!(args, ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); + for target in TARGETS { + assert!(args.iter().any(|a| a == target), "ci warm does not build {target}"); + } + assert_eq!(what, "cargo test --lib --bins --tests --no-run (a)"); + } +} From 8e68c5edcf092ecd8993ea6aed7c630c2f921903 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:43:37 -0800 Subject: [PATCH 23/36] Shape Builder: Pick Color From defaults to Color Swatches While the Shape Builder is active, a fill picked from a swatch or a color changes only the current fill, and the selected art keeps its own. With Pick Color From set to Artwork, a merge takes the look of the art, so the picked color never reached the merged shape and the tool looked as if it could not fill. Pick Color From now defaults to Color Swatches: a merge fills with the picked color, and the Left and Right arrow keys step through the color swatches. A pickColorFrom saved with the preferences is kept, so a saved Artwork stays Artwork; preferences saved without one take Color Swatches. The shapeBuilder.merge command still defaults to artwork when its pickColorFrom is left out. Docs: docs/mcp.md and the tool options params text. --- crates/engine/src/tests/build.rs | 30 ++++++++++++++++++++++- crates/engine/src/tests/toolsettings.rs | 25 +++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/builder.rs | 6 ++--- crates/ui-egui/src/dialogs/option_form.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 9 ++++--- 7 files changed, 65 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 6ccdfad0a5..adb5d04af5 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1753,7 +1753,8 @@ fn shape_builder_swatches_keep_the_current_fill_and_the_first_covered_objects_lo } /// The Shape Builder tool sends the point where the drag started first and the point where it -/// ended last, so a drag from the hole into the square takes the square's look. +/// ended last, so with Pick Color From Artwork a drag from the hole into the square takes the +/// square's look. #[test] fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() { let mut s = session(); @@ -1762,6 +1763,7 @@ fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() { select_ids(&mut s, &bars.iter().copied().chain([red]).collect::>()); let v = ViewInfo::default(); s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Drag, 85.0, 50.0), v).unwrap(); s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 50.0), v).unwrap(); @@ -1853,6 +1855,7 @@ fn shape_builder_arrow_keys_step_the_current_fill_through_the_swatches() { let v = ViewInfo::default(); s.select_tool("shapeBuilder", v).unwrap(); let chips = |s: &mut Session| s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Swatch { .. })).count(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap(); assert!(!s.tool_claims_key(ToolKey::Right, v), "Artwork leaves the arrows to nudging"); let values = json!({"pickColorFrom": "swatches", "cursorSwatchPreview": true}); s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": values})).unwrap(); @@ -2071,6 +2074,31 @@ fn shape_builder_fill_preview_is_put_back_by_a_cancel() { assert_eq!(s.paint.fill, before, "the cancel puts the fill back"); } +/// With the Shape Builder's default options, a fill picked while it is active (a swatch or a +/// color) fills the next merge: the tool sends `pickColorFrom: "swatches"`, and the merged shape +/// is not the red or blue of the art. +#[test] +fn shape_builder_default_merge_fills_with_the_picked_fill() { + let v = ViewInfo::default(); + for pick in [json!({"swatch": "Leaf"}), json!({"color": "#ff8800"})] { + let mut s = session(); + two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + s.select_tool("shapeBuilder", v).unwrap(); + s.execute("paint.setFill", &pick).unwrap(); + let picked = s.paint.fill.clone(); + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap(); + let (cmd, params) = s.journal.last().unwrap().clone(); + assert_eq!((cmd.as_str(), ¶ms["pickColorFrom"]), ("shapeBuilder.merge", &json!("swatches")), "{pick}"); + let d = &s.doc().unwrap().doc; + let fills: Vec = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect(); + assert_eq!(fills, vec![picked], "{pick}: the two squares merged into one shape with the picked fill"); + } +} + /// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder /// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient. #[test] diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 7a28a84ec7..76fda42a5b 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -698,3 +698,28 @@ fn a_parametric_shape_kind_and_its_values_set_together() { assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing"); } } + +/// The Shape Builder picks colors from the color swatches by default: a fresh session, and saved +/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`. A +/// saved `artwork` (or `swatches`) is kept. +#[test] +fn shape_builder_pick_color_from_defaults_to_swatches_and_keeps_a_saved_choice() { + let mut s = session(); + select(&mut s, "shapeBuilder"); + assert_eq!(s.tool_options()["pickColorFrom"], json!("swatches"), "a fresh session"); + for (saved, want) in [ + (json!({"highlightFill": false}), "swatches"), + (json!({"pickColorFrom": "artwork"}), "artwork"), + (json!({"pickColorFrom": "swatches"}), "swatches"), + ] { + let mut prefs = s.prefs.clone(); + prefs.tool_settings.insert("shapeBuilder".into(), saved.as_object().unwrap().clone()); + let saved_text = serde_json::to_string(&prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved_text).unwrap()); + select(&mut next, "shapeBuilder"); + assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {saved}"); + select(&mut next, "selection"); + assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {saved}"); + } +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..b6f0866d96 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index cdc7f6f7dc..42886ec013 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -66,11 +66,11 @@ pub struct ShapeBuilderOptions { /// region as if an invisible edge closed it. When it is off, the path cuts the regions it crosses /// as a line does. pub open_filled_as_closed: bool, - /// Pick Color From Color Swatches (`pickColorFrom: "swatches"`; off: `"artwork"`): a merge + /// Pick Color From Color Swatches (`pickColorFrom: "swatches"`, on; off: `"artwork"`): a merge /// fills the new shape with the current fill, and the Left and Right arrow keys step the current /// fill through the document's color swatches. With Artwork, the shape takes the look of the /// object where the drag starts, else of the one where it ends, else of the front-most selected - /// object. + /// object. A saved `pickColorFrom` is kept; preferences without one take Color Swatches. pub swatches: bool, /// Cursor Swatch Preview (`cursorSwatchPreview`, off): with Color Swatches, the current fill /// and the swatches before and after it show as chips above the pointer while no drag is on. @@ -105,7 +105,7 @@ impl Default for ShapeBuilderOptions { fn default() -> Self { Self { open_filled_as_closed: true, - swatches: false, + swatches: true, cursor_swatch_preview: false, straight_line: false, highlight_fill: true, diff --git a/crates/ui-egui/src/dialogs/option_form.rs b/crates/ui-egui/src/dialogs/option_form.rs index fde3f40932..7b1bf40418 100644 --- a/crates/ui-egui/src/dialogs/option_form.rs +++ b/crates/ui-egui/src/dialogs/option_form.rs @@ -631,7 +631,7 @@ pub(super) mod tests { tool: "shapeBuilder", opens_on: vec![ ("openFilledAsClosed", json!(true)), - ("pickColorFrom", json!("artwork")), + ("pickColorFrom", json!("swatches")), ("cursorSwatchPreview", json!(false)), ("selection", json!("freeform")), ("highlightFill", json!(true)), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..e76772d154 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..5ec8ceafd4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15725,10 +15725,11 @@ a flare into a plain group of its parts. The document saves a flare's settings. The Shape Builder tool's options are its Shape Builder Tool Options (dialog `shapeBuilderOptions`): `openFilledAsClosed` (on: a filled open path bounds a region as if an invisible edge closed it; a path counts as filled when any of its fill rows is shown, painted and above 0% opacity, whichever row is on top; off: it cuts regions -as an unfilled path does), `pickColorFrom` (`artwork`, the default: a merged shape takes the appearance, opacity and -blending mode of the front-most selected object under the drag's first point, else of the one under its last point, -else of the front-most selected object; `swatches`: the current fill, and the Left and Right arrow keys without -Shift, Alt or Cmd/Ctrl step the current fill through the document's color swatches), `cursorSwatchPreview` (off; with `swatches`, chips above the +as an unfilled path does), `pickColorFrom` (`swatches`, the default: a merged shape fills with the current fill, and +the Left and Right arrow keys without Shift, Alt or Cmd/Ctrl step the current fill through the document's color +swatches; `artwork`: a merged shape takes the appearance, opacity and blending mode of the front-most selected object +under the drag's first point, else of the one under its last point, else of the front-most selected object; a +`pickColorFrom` saved with the preferences is kept, and preferences saved without one take `swatches`), `cursorSwatchPreview` (off; with `swatches`, chips above the pointer show the current fill and the swatches before and after it), `selection` (`freeform`, the default, or `straightLine`: a drag touches what the line from its first point to the pointer crosses), `highlightFill` (on by default; when it is off, merge mode shades no regions), `gapDetection` (off) with `gapLength` (pt, 0 to 72; 3), `clickStrokeSplitsPath` (In Merge Mode, From 03dd80a887691a6cafee4e608a4b72dfa1156554 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:37:36 -0800 Subject: [PATCH 24/36] Tests: menu and Quick Actions rebuild counts run in a process of their own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The menus' key (`state_key`, crates/ui-egui/src/menus/model.rs) holds the installed plug-ins' revision and the fonts' generation. Both are the whole process's. In a parallel `cargo test` run, a plug-in that another test installs moves the revision, the menus are rebuilt, and the new catalog makes the window build a new keymap, whose address is also in the key, so the next pass rebuilds them again. `a_key_press_rebuilds_the_menus_once` then counted those rebuilds on its idle frames ("idle frames keep the menus", left 4 to 7, right 3 to 5) in 6 of 6 runs of `cargo test -p vectorcraft-ui-egui --lib -- addons menus i18n`, and `quick_actions_are_listed_again_only_after_a_change`, whose key holds the menus' key, failed in the same way in 2 of 2 runs. In the app these values change only when a plug-in is installed or removed or the fonts change, and the menus list both, so the rebuild is kept. - Both tests run through `testing::in_own_process`, as the tests that load color profiles do, and wait for the installed fonts' scan, whose end moves the fonts' generation, before their first frames. - `a_new_font_rebuilds_the_menus` adds a font and checks that the menus are rebuilt with no input, that Type › Font lists it, and that idle frames after that keep the menus. --- crates/ui-egui/src/menus/tests.rs | 42 +++++++++++++++++-- crates/ui-egui/src/panels/properties/tests.rs | 9 +++- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index b21b2e8ccf..7d27d6be1a 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -164,15 +164,29 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() { assert_eq!(menu.toggled("Pixel Snapping Options…"), None); } -/// A key press builds the menus' states again once: the frames after it, with no press, keep them. -#[test] -fn a_key_press_rebuilds_the_menus_once() { +/// An app with a new document whose installed fonts are cataloged, after the frames that build its first menus and the +/// window's keymap. It runs in a process of its own ([`crate::testing::in_own_process`]): the menus' key holds the +/// installed plug-ins' revision and the fonts' generation, which are the whole process's, so a plug-in that another test +/// installs, or a font it adds, rebuilds this app's menus. `None` in the parent process. +fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> { + if !crate::testing::in_own_process(test) { + return None; + } let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends: wait for it. + vectorcraft_text::FontDb::global().family_list(); app.run("file.new", json!({})).unwrap(); let ctx = crate::testing::ui_context(); for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); } + Some((app, ctx)) +} + +/// A key press builds the menus' states again once: the frames after it, with no press, keep them. +#[test] +fn a_key_press_rebuilds_the_menus_once() { + let Some((mut app, ctx)) = settled_app("menus::tests::a_key_press_rebuilds_the_menus_once") else { return }; let before = app.menus.rebuilds; for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); @@ -187,6 +201,28 @@ fn a_key_press_rebuilds_the_menus_once() { assert_eq!(app.menus.rebuilds, before + 1); } +/// A font added to the fonts the whole process shares builds the menus again with no input, Type › Font then lists it, +/// and the idle frames after that keep the menus. +#[test] +fn a_new_font_rebuilds_the_menus() { + const FAMILY: &str = "Menurebuild Sans"; + let Some((mut app, ctx)) = settled_app("menus::tests::a_new_font_rebuilds_the_menus") else { return }; + let lists = + |app: &VectorcraftApp| app.menus.bar.items().into_iter().any(|it| it.command.id == "text.setStyle" && it.command.params["font"] == FAMILY); + assert!(!lists(&app)); + let font = vectorcraft_text::test_fonts::named_copy(false, (FAMILY, "Regular", "Version 1.000", "MenurebuildSans-Regular")); + let before = app.menus.rebuilds; + assert_eq!(vectorcraft_text::FontDb::global().add_font(font.expect("the test font builds")), 1); + app_frame(&mut app, &ctx, vec![]); + assert!(app.menus.rebuilds > before, "the new font rebuilds the menus"); + assert!(lists(&app), "Type › Font lists {FAMILY}"); + let after = app.menus.rebuilds; + for _ in 0..3 { + app_frame(&mut app, &ctx, vec![]); + } + assert_eq!(app.menus.rebuilds, after, "idle frames keep the menus"); +} + #[test] fn help_f1_opens_discover_without_a_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 4a8158364a..ed4147744e 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1084,10 +1084,17 @@ fn quick_actions_follow_the_selection() { } } -/// The panel lists the Quick Actions once per change of what they depend on, not in every frame. +/// The panel lists the Quick Actions once per change of what they depend on, not in every frame. It runs in a process +/// of its own ([`crate::testing::in_own_process`]): what they depend on holds the menus' key, with the installed +/// plug-ins' revision and the fonts' generation, which are the whole process's. #[test] fn quick_actions_are_listed_again_only_after_a_change() { + if !crate::testing::in_own_process("panels::properties::tests::quick_actions_are_listed_again_only_after_a_change") { + return; + } let mut app = new_app(); + // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends: wait for it. + vectorcraft_text::FontDb::global().family_list(); rect(&mut app, 10.0, 10.0, 40.0, 40.0); rect(&mut app, 80.0, 10.0, 40.0, 40.0); let ctx = crate::testing::ui_context(); From 2be42e79864534c8ac43d52e1adaee13f5b17c17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:52:59 -0800 Subject: [PATCH 25/36] Shape Builder: saved Artwork from earlier versions switches to Color Swatches once Leaving the Shape Builder saved every one of its options, so preferences from earlier versions hold pickColorFrom "artwork" whether or not it was picked, and kept the old default after Color Swatches became the default. The preferences now carry toolSettingsVersion, written as 1 once a tool setting is stored. Applying preferences without it changes a saved Shape Builder pickColorFrom "artwork" to "swatches" and writes the version, so Artwork picked after that is kept at the next launch. A saved "swatches" and preferences without a saved pickColorFrom are unchanged. Docs: docs/mcp.md and the tool options params text. --- crates/engine/src/cmd/prefscmds.rs | 2 + crates/engine/src/prefs.rs | 36 ++++++++++++++++ crates/engine/src/tests/toolsettings.rs | 55 ++++++++++++++++++------- crates/engine/src/tooling.rs | 1 + crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/builder.rs | 3 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 +- 8 files changed, 86 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 27d38e158f..8420e67d30 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -725,6 +725,8 @@ impl Session { for e in self.prefs.keep_folders(&mut p) { log::warn!("{e}"); } + // Tool settings saved by an earlier version are updated once. + p.migrate_tool_settings(); // Saved gradient presets get names no built-in preset or other saved one has. for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) { log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name"); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1a7b78a91b..3c2f3e3299 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -438,6 +438,12 @@ pub struct Prefs { /// resetting the preferences keeps them; `tool.setOption` edits them. #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub tool_settings: std::collections::BTreeMap>, + /// The version of [`Self::tool_settings`]: [`TOOL_SETTINGS_VERSION`] once this version stores + /// or updates a tool setting, 0 while none is stored and in preferences saved without one. + /// [`Prefs::migrate_tool_settings`] updates older tool settings once. Not a Preferences dialog + /// field: resetting the preferences keeps it. + #[serde(default, skip_serializing_if = "is_zero")] + pub tool_settings_version: u32, /// View → Perspective Grid presets: the user's (the built-in ones aren't stored). A local /// library, not a Preferences dialog field: resetting the preferences keeps it; /// `perspective.presets.*` edit it. @@ -464,7 +470,36 @@ pub const KEY_HOLD_DELAY: f64 = 0.35; /// The range of the Hold Shortcut Delay, in seconds. pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0); +/// The version of the tool settings these preferences write ([`Prefs::tool_settings_version`]). +/// Version 1 makes Color Swatches the Shape Builder's Pick Color From. +pub const TOOL_SETTINGS_VERSION: u32 = 1; + +fn is_zero(v: &u32) -> bool { + *v == 0 +} + impl Prefs { + /// Update tool settings saved by an earlier version to [`TOOL_SETTINGS_VERSION`], once. Before + /// version 1, leaving the Shape Builder saved its `pickColorFrom` whether or not it was + /// changed, so a saved `artwork` becomes `swatches`. Without tool settings, nothing changes; a + /// version newer than this one is kept. + pub fn migrate_tool_settings(&mut self) { + if self.tool_settings_version < 1 + && let Some(saved) = self.tool_settings.get_mut("shapeBuilder") + && saved.get("pickColorFrom").and_then(Value::as_str) == Some("artwork") + { + saved.insert("pickColorFrom".into(), Value::from("swatches")); + } + self.mark_tool_settings_current(); + } + + /// Record that [`Self::tool_settings`], when any is stored, is in this version's form. + pub(crate) fn mark_tool_settings_current(&mut self) { + if !self.tool_settings.is_empty() { + self.tool_settings_version = self.tool_settings_version.max(TOOL_SETTINGS_VERSION); + } + } + /// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences /// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own. pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value { @@ -672,6 +707,7 @@ impl Default for Prefs { use_registration_point_for_symbol: false, show_on_shape_creation: false, tool_settings: Default::default(), + tool_settings_version: 0, perspective_presets: vec![], blend_options: None, perspective_widget: Default::default(), diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 76fda42a5b..db1fc01a30 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -700,26 +700,53 @@ fn a_parametric_shape_kind_and_its_values_set_together() { } /// The Shape Builder picks colors from the color swatches by default: a fresh session, and saved -/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`. A -/// saved `artwork` (or `swatches`) is kept. +/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`. +/// Preferences saved without `toolSettingsVersion` read a saved `artwork` as `swatches` once and +/// are then written with the version, so a later `artwork` is kept. A saved `swatches` is kept. #[test] -fn shape_builder_pick_color_from_defaults_to_swatches_and_keeps_a_saved_choice() { +fn shape_builder_pick_color_from_defaults_to_swatches_and_migrates_a_saved_artwork_once() { let mut s = session(); select(&mut s, "shapeBuilder"); assert_eq!(s.tool_options()["pickColorFrom"], json!("swatches"), "a fresh session"); - for (saved, want) in [ - (json!({"highlightFill": false}), "swatches"), - (json!({"pickColorFrom": "artwork"}), "artwork"), - (json!({"pickColorFrom": "swatches"}), "swatches"), - ] { - let mut prefs = s.prefs.clone(); - prefs.tool_settings.insert("shapeBuilder".into(), saved.as_object().unwrap().clone()); - let saved_text = serde_json::to_string(&prefs).unwrap(); + select(&mut s, "selection"); + assert_eq!(s.prefs.to_json()["toolSettingsVersion"], json!(1), "stored settings are written with the version"); + let load = |version: Option, saved: &Value| { + let mut prefs = Prefs::default().to_json(); + prefs["toolSettings"] = json!({ "shapeBuilder": saved }); + let fields = prefs.as_object_mut().unwrap(); + match version { + Some(v) => fields.insert("toolSettingsVersion".into(), json!(v)), + None => fields.remove("toolSettingsVersion"), + }; let mut next = session(); - next.apply_prefs(serde_json::from_str(&saved_text).unwrap()); + next.apply_prefs(serde_json::from_str(&prefs.to_string()).unwrap()); + next + }; + for (version, saved, want) in [ + (None, json!({"highlightFill": false}), "swatches"), + (None, json!({"pickColorFrom": "artwork"}), "swatches"), + (None, json!({"pickColorFrom": "swatches"}), "swatches"), + (Some(1), json!({"pickColorFrom": "artwork"}), "artwork"), + (Some(1), json!({"pickColorFrom": "swatches"}), "swatches"), + (Some(1), json!({"highlightFill": false}), "swatches"), + ] { + let mut next = load(version, &saved); + assert_eq!(next.prefs.tool_settings_version, 1, "the version is written: {version:?} {saved}"); select(&mut next, "shapeBuilder"); - assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {saved}"); + assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {version:?} {saved}"); select(&mut next, "selection"); - assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {saved}"); + assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {version:?} {saved}"); + } + // Artwork picked after the update, or in a session that started without saved settings, is + // kept at the next launch. + for mut next in [load(None, &json!({"pickColorFrom": "artwork"})), session()] { + select(&mut next, "shapeBuilder"); + next.set_tool_option("pickColorFrom", &json!("artwork")); + select(&mut next, "selection"); + let saved_text = serde_json::to_string(&next.prefs).unwrap(); + let mut later = session(); + later.apply_prefs(serde_json::from_str(&saved_text).unwrap()); + select(&mut later, "shapeBuilder"); + assert_eq!(later.tool_options()["pickColorFrom"], json!("artwork"), "picked after the update: {saved_text}"); } } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 422caab5ec..94f72f6441 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -581,6 +581,7 @@ impl Session { } } } + prefs.mark_tool_settings_current(); } /// Keep the active tool's persistent options for the next time it, or a tool sharing them, is diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b6f0866d96..e933df1e5f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept, except that preferences saved by an earlier version read it as swatches once), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 42886ec013..7451fd0226 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -70,7 +70,8 @@ pub struct ShapeBuilderOptions { /// fills the new shape with the current fill, and the Left and Right arrow keys step the current /// fill through the document's color swatches. With Artwork, the shape takes the look of the /// object where the drag starts, else of the one where it ends, else of the front-most selected - /// object. A saved `pickColorFrom` is kept; preferences without one take Color Swatches. + /// object. A saved `pickColorFrom` is kept, except that preferences saved by an earlier version + /// read a saved Artwork as Color Swatches once; preferences without one take Color Swatches. pub swatches: bool, /// Cursor Swatch Preview (`cursorSwatchPreview`, off): with Color Swatches, the current fill /// and the swatches before and after it show as chips above the pointer while no drag is on. diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e76772d154..a4620e2a5b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (swatches; a saved artwork is kept, except that preferences saved by an earlier version read it as swatches once), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/mcp.md b/docs/mcp.md index 5ec8ceafd4..d2c7096762 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15729,7 +15729,8 @@ as an unfilled path does), `pickColorFrom` (`swatches`, the default: a merged sh the Left and Right arrow keys without Shift, Alt or Cmd/Ctrl step the current fill through the document's color swatches; `artwork`: a merged shape takes the appearance, opacity and blending mode of the front-most selected object under the drag's first point, else of the one under its last point, else of the front-most selected object; a -`pickColorFrom` saved with the preferences is kept, and preferences saved without one take `swatches`), `cursorSwatchPreview` (off; with `swatches`, chips above the +`pickColorFrom` saved with the preferences is kept, except that preferences saved by an earlier version, without +`toolSettingsVersion`, read a saved `artwork` as `swatches` once; preferences saved without one take `swatches`), `cursorSwatchPreview` (off; with `swatches`, chips above the pointer show the current fill and the swatches before and after it), `selection` (`freeform`, the default, or `straightLine`: a drag touches what the line from its first point to the pointer crosses), `highlightFill` (on by default; when it is off, merge mode shades no regions), `gapDetection` (off) with `gapLength` (pt, 0 to 72; 3), `clickStrokeSplitsPath` (In Merge Mode, From 07b4332dfc601de36b57d683ff7e5617660d80e4 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:42:16 +0000 Subject: [PATCH 26/36] fix: Step and Repeat fill picks the artboard from the whole selection; rustfmt --- crates/engine/src/cmd/stepandrepeat.rs | 2 +- crates/engine/src/cmd/stepandrepeat/tests.rs | 21 ++++++++++++++++++++ crates/ui-egui/src/dialogs/object_dialogs.rs | 4 ++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 620f64a9a7..9ba4666598 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -150,7 +150,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } let anchor = if fill { let sheet = sheet.or_else(|| { - let c = b.center(); + let c = d.bounds_of(&roots, false).unwrap_or(b).center(); d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect) }); let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index c25953d598..991800d964 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -155,3 +155,24 @@ fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_ let pitch = gap(true).1; assert!((pitch - pitch.round()).abs() < 1e-9); } + +#[test] +fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() { + let first_x = |sheet: Option| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 105, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [art, cut]})).unwrap(); + let mut p = json!({"fill": true, "cutId": cut}); + if let Some(sh) = sheet { + p["sheet"] = sh; + } + let r = s.execute(CMD, &p).unwrap(); + bounds(&s, r["ids"][0].as_u64().unwrap()).0 + }; + let default = first_x(None); + let explicit = first_x(Some(json!({"x": 100, "y": 0, "width": 100, "height": 100}))); + assert!((explicit - default - 100.0).abs() < 1e-9); +} diff --git a/crates/ui-egui/src/dialogs/object_dialogs.rs b/crates/ui-egui/src/dialogs/object_dialogs.rs index 3f3b69da54..ee0867d0dd 100644 --- a/crates/ui-egui/src/dialogs/object_dialogs.rs +++ b/crates/ui-egui/src/dialogs/object_dialogs.rs @@ -4,8 +4,8 @@ use super::path_ops::PathOp; use super::simplify_slider::StripKind; use super::{ blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form, - path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, step_repeat, transform, - transform_each, width_point, + path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, step_repeat, transform, transform_each, + width_point, }; use crate::VectorcraftApp; From a6c530518a3d8acdbb4496075cd3b75e0995a47d Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 15:35:56 +0100 Subject: [PATCH 27/36] Scroll overflowing panel forms inside their dock group --- crates/ui-egui/src/dock.rs | 12 +++++++++++- crates/ui-egui/src/panels/pattern_options.rs | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index fdaaebcee1..6a70094ac2 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1,6 +1,8 @@ //! Panel bodies: what the dock area ([`crate::panel_docking`]) draws inside a docked, floating or //! flyout panel. +use craft::ui::contract::{Props as _, Scroll, ShowContainer as _}; +use craft::ui::layout_components::Stack; use egui::Ui; use crate::state::DockTab; @@ -13,6 +15,14 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { Some(DockTab::Properties) => panels::properties::show(app, ui), Some(DockTab::Layers) => panels::layers::show(app, ui), Some(DockTab::Libraries) => panels::libraries(app, ui), - None => panels::show_icon_panel(app, ui, id), + None => { + // The dock clips the group at its assigned height. Keep the panel's own collection + // viewport bounded while allowing a form that exceeds that height to scroll. + let height = ui.available_height(); + Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| { + ui.set_max_height(height); + panels::show_icon_panel(app, ui, id); + }); + } } } diff --git a/crates/ui-egui/src/panels/pattern_options.rs b/crates/ui-egui/src/panels/pattern_options.rs index 93e93681f2..0bd03fac9c 100644 --- a/crates/ui-egui/src/panels/pattern_options.rs +++ b/crates/ui-egui/src/panels/pattern_options.rs @@ -267,6 +267,26 @@ mod tests { Panel::new(app, show) } + #[test] + fn scrolling_a_short_docked_form_reaches_its_last_action() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("object.pattern.make", json!({"name": "Dots"})).unwrap(); + let mut panel = Panel::new(app, |app, ui| crate::dock::panel_body(app, ui, "patternOptions")); + panel.room(egui::vec2(300.0, 200.0)); + panel.frame(); + panel.frame(); + assert!(!panel.in_view("Done")); + for _ in 0..20 { + panel.scroll_at(egui::pos2(150.0, 100.0), -120.0); + panel.frame(); + } + assert!(panel.in_view("Done")); + panel.click("Done"); + assert!(editing(&panel.app()).is_none()); + } + /// Shift+Enter in the Name field renames the pattern and keeps the field active; Enter then /// renames it again and ends the editing. #[test] From 1cb4193974223fb394e250c63b3bf2f19dc907c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:48:25 -0800 Subject: [PATCH 28/36] Fix #6192: Curvature, a point dragged far out narrows toward it Dragging a point of a selected path with the Curvature tool gave the point the handles of the circle through it and its neighbors, while the neighbors kept their own tangents. Stretching a circle's top point far up made those handles reach well past the circle's sides, so the shape swung out wider than the circle before it narrowed toward the point. Each handle of the moved point is now no longer than the handle of the circular arc tangent to it and to the neighbor's handle on that segment. Where the neighbor is on the circle the tool follows, that arc is the circle and the handles do not change. The shortening fades out as the two handle lines meet near the neighbor or turn parallel, so the handles change continuously during a drag. --- crates/tools/src/draw2/curvature.rs | 48 +++++++++++- crates/tools/src/draw2/curvature/tests.rs | 92 +++++++++++++++++++++++ 2 files changed, 138 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 06ad1c1230..e4c15c4784 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -136,7 +136,9 @@ fn neighbours(sp: &SubPath, i: usize) -> [Option; 2] { /// Move anchor `i` of `sp` to `q` as the Curvature tool drags a point: only the two segments at it /// change. A smooth anchor takes the Curvature tool's own handles ([`smooth_handles`]: along the /// circle through it and its neighbours; at an end of an open path the one [`end_handle`] into the -/// curve). The neighbours' handles on those segments, and a corner's own +/// curve), each no longer than [`fit_to_tangent`] allows against the neighbor's handle on its +/// segment, so a point dragged far out narrows toward it instead of swinging wide around that +/// circle (#6192). The neighbors' handles on those segments, and a corner's own /// handles, keep their directions, their lengths scaling with their segment's chord, so the /// segments beyond don't move and a corner without handles keeps none. /// @@ -163,7 +165,7 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool { match ends { [Some(prev), Some(next)] => { if let Some((h_in, h_out)) = smooth_handles(prev.p, q, next.p) { - (m.h_in, m.h_out) = (h_in, h_out); + (m.h_in, m.h_out) = (fit_to_tangent(q, h_in, prev.p, prev.h_out), fit_to_tangent(q, h_out, next.p, next.h_in)); } } // An end of an open path has one segment: its handle only, and a corner like the @@ -179,6 +181,48 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool { true } +/// cos 75°: [`fit_to_tangent`] shortens a handle in full up to a turn of 150°, and less toward a +/// half turn. +const FADE_HALF_TURN: f64 = 0.258_819_045_102_520_8; + +/// Handle `h` of the point `q` on its segment to `b`, whose handle there is `hb`, shortened toward +/// the handle of the circular arc tangent to both handle lines: `2/3 · (1 − tan²(θ/4))` of `q`'s +/// distance `r` to where the lines meet, `θ` the turn between them. A longer handle swings the +/// segment out past `b`'s tangent line. The shortening applies in full while the lines meet at +/// least half the chord ahead of `b` and the turn is at most 150°, and fades to none as the meeting +/// point comes back to `b` or the turn nears a half turn, so the handle changes continuously as `q` +/// moves. Where `b` is on the circle [`smooth_handles`] +/// follows, the arc is the circle's and `h` is unchanged; `h` is also unchanged when `b` has no +/// handle there or the lines are parallel. +fn fit_to_tangent(q: Point, h: Point, b: Point, hb: Point) -> Point { + let (d, t) = (h - q, hb - b); + let (ld, lt) = (d.hypot(), t.hypot()); + let w = b - q; + let chord = w.hypot(); + if !(ld > 1e-9 && lt > 1e-9 && chord > 1e-9) { + return h; + } + let (d, t) = (d / ld, t / lt); + let den = d.cross(t); + if den.abs() <= 1e-12 { + return h; + } + // q + r·d = b + s·t. + let (r, s) = (w.cross(t) / den, w.cross(d) / den); + // The curve leaves `b` along `t` and comes into `q` along −d. + let cos_half = ((1.0 - t.dot(d)) / 2.0).clamp(0.0, 1.0).sqrt(); + // A circular arc under a half turn meets its tangents at least half its chord out. Toward a + // half turn the lines meet ever further away, on one side or the other, and the shortening + // fades out. + let weight = (2.0 * s / chord).clamp(0.0, 1.0) * (cos_half / FADE_HALF_TURN).min(1.0); + let tan2 = (1.0 - cos_half) / (1.0 + cos_half); + let cap = 2.0 / 3.0 * (1.0 - tan2) * r.abs(); + if !(weight > 0.0 && cap.is_finite() && ld > cap) { + return h; + } + q + d * (ld + (cap - ld) * weight) +} + /// Add a smooth anchor at `t` on segment `seg` of `sp` without changing its shape: the new anchor's /// index. On a straight segment its handles lie along it, each a third of its own part of the /// segment ([`curvature_smooth`]: a line is a circle's limit), so a drag bends the line evenly; a drag then moves it as a diff --git a/crates/tools/src/draw2/curvature/tests.rs b/crates/tools/src/draw2/curvature/tests.rs index 50ef2281d1..f59e0ed77b 100644 --- a/crates/tools/src/draw2/curvature/tests.rs +++ b/crates/tools/src/draw2/curvature/tests.rs @@ -139,6 +139,98 @@ fn moving_a_corner_without_handles_keeps_its_sides_straight() { assert_eq!(sp.anchors[0], Anchor::corner(pt(80.0, 70.0))); } +/// A circle's top point dragged far up stretches it into a shape that narrows from its sides +/// toward the point (#6192), instead of swinging out wider than the circle first. The moved point +/// stays smooth, and its segments meet the neighbors' unchanged tangents. +#[test] +fn stretching_a_circle_narrows_toward_the_dragged_point() { + let k = 100.0 * 0.552_284_749_830_793_4; + let circle = SubPath::new( + vec![ + Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)), + Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)), + Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)), + ], + true, + ); + // On the circle, the neighbors' tangents match it, and the point keeps the circle's handles. + let mut near = circle.clone(); + assert!(curvature_move(&mut near, 0, pt(0.0, -100.0))); + for (a, b) in near.anchors.iter().zip(&circle.anchors) { + assert!(a.h_in.distance(b.h_in) < 1e-6 && a.h_out.distance(b.h_out) < 1e-6, "{a:?} != {b:?}"); + } + for top in [-150.0, -250.0, -400.0, -800.0] { + let mut sp = circle.clone(); + assert!(curvature_move(&mut sp, 0, pt(0.0, top))); + let a = sp.anchors[0]; + assert_eq!(a.kind, AnchorKind::Smooth); + assert!(collinear(a.h_in - a.p, a.h_out - a.p) && (a.h_in - a.p).dot(a.h_out - a.p) < 0.0); + // Segment 0 runs from the top to the right point, segment 3 from the left point to the top. + for (seg, side) in [(0, 1.0), (3, -1.0)] { + let c = sp.segment(seg); + let mut last: Option = None; + for j in 0..=200 { + let t = j as f64 / 200.0; + let p = c.eval(if side > 0.0 { t } else { 1.0 - t }); + assert!(p.x.abs() <= 100.0 + 1e-9, "top {top}: segment {seg} swings out to x = {}", p.x); + // From the top down to the side the width only grows. + if let Some(l) = last { + assert!(p.x.abs() >= l - 1e-9, "top {top}: segment {seg} narrows again at t = {t}"); + } + last = Some(p.x.abs()); + } + } + } +} + +/// The moved point's handles change continuously while it crosses a neighbor's tangent line, while +/// the line its own handle runs along passes through the neighbor, and while the two lines turn +/// parallel. +#[test] +fn a_moved_point_s_handles_change_continuously() { + let handles = |sp: &SubPath, q: Point| -> (Vec2, Vec2) { + let mut sp = sp.clone(); + assert!(curvature_move(&mut sp, 1, q)); + (sp.anchors[1].h_in - q, sp.anchors[1].h_out - q) + }; + let near = |a: (Vec2, Vec2), b: (Vec2, Vec2)| (a.0 - b.0).hypot() < 0.05 && (a.1 - b.1).hypot() < 0.05; + // The neighbor's handle points away from the moved point: its line passes through it at y = 0. + let away = SubPath::new( + vec![ + Anchor::corner(pt(-100.0, 0.0)), + Anchor::with_handles(pt(0.0, -20.0), pt(-30.0, -20.0), pt(30.0, -20.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(200.0, 10.0), pt(0.0, -10.0)), + ], + false, + ); + assert!(near(handles(&away, pt(0.0, -0.001)), handles(&away, pt(0.0, 0.001)))); + // The neighbor's handle runs the same way as the moved point's: their lines are parallel at x = 0. + let parallel = SubPath::new( + vec![ + Anchor::corner(pt(-100.0, 0.0)), + Anchor::with_handles(pt(0.0, -50.0), pt(-30.0, -50.0), pt(30.0, -50.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(150.0, 0.0), pt(50.0, 0.0)), + ], + false, + ); + assert!(near(handles(¶llel, pt(-0.001, -50.0)), handles(¶llel, pt(0.001, -50.0)))); + // A circle's top dragged across the right point's tangent line, x = 100. + let k = 100.0 * 0.552_284_749_830_793_4; + let circle = SubPath::new( + vec![ + Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)), + Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)), + Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)), + Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)), + ], + true, + ); + for y in [-150.0, -300.0] { + assert!(near(handles(&circle, pt(99.999, y)), handles(&circle, pt(100.001, y))), "y {y}"); + } +} + #[test] fn going_on_from_an_end_keeps_the_old_segments() { let before = wave(); From d69f9c041c09bfc43d3121ba2b8c0dfb2bcfc6a3 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 16:07:02 +0100 Subject: [PATCH 29/36] Keep collection panels and their fixed footers in their own viewport --- crates/ui-egui/src/dock.rs | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 6a70094ac2..dcff2191a4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -15,14 +15,28 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { Some(DockTab::Properties) => panels::properties::show(app, ui), Some(DockTab::Layers) => panels::layers::show(app, ui), Some(DockTab::Libraries) => panels::libraries(app, ui), - None => { - // The dock clips the group at its assigned height. Keep the panel's own collection - // viewport bounded while allowing a form that exceeds that height to scroll. - let height = ui.available_height(); - Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| { - ui.set_max_height(height); - panels::show_icon_panel(app, ui, id); - }); + None if matches!( + id, + "align" + | "attributes" + | "blend" + | "character" + | "color" + | "magicWand" + | "openType" + | "paragraph" + | "pathfinder" + | "patternOptions" + | "stroke" + | "tabs" + | "transform" + | "transparency" + ) => + { + // These panels lay out forms. Collection panels own their scrolling viewport + // and reserve their own footer outside it. + Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| panels::show_icon_panel(app, ui, id)); } + None => panels::show_icon_panel(app, ui, id), } } From ede596a7ed8d6dc6ad6e1c308d4174f6d41b2b05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:28:17 -0800 Subject: [PATCH 30/36] =?UTF-8?q?Fix=20#3211:=20Text=20Wrap=20=E2=80=BA=20?= =?UTF-8?q?Make=20wraps=20the=20area=20type=20selected=20with=20the=20obje?= =?UTF-8?q?ct?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Make set the wrap option on every selected object, the area type included, and the wrap resolver never wraps an object that has the option, so selecting the object and the type together and choosing Make left the type as it was. - Make leaves a selected type object with another selected object above it in its layer out of the wrap objects, and takes the option off it if an earlier Make set it there. Text Wrap Options leaves it out too. - Make warns in the status bar when no area type lies below any of its wrap objects (the object is below the type, or the type is point type). - Make and Options record no undo step when nothing changes. Docs: docs/mcp.md, the text_wrap tool description and the command params text. --- crates/engine/src/cmd/textwrap.rs | 179 ++++++++++++++++++++++++++-- crates/mcp/src/tools/definitions.rs | 2 +- docs/mcp.md | 2 +- 3 files changed, 169 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/textwrap.rs b/crates/engine/src/cmd/textwrap.rs index 9ff48848af..ade875b4c9 100644 --- a/crates/engine/src/cmd/textwrap.rs +++ b/crates/engine/src/cmd/textwrap.rs @@ -4,6 +4,8 @@ //! resolves, for each area text object, the outlines of the wrap objects above it into //! `TextObject::wrap` (text space); the layout engine subtracts them from each line's span. +use std::collections::{HashMap, HashSet}; + use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap}; @@ -17,7 +19,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Text Wrap"], None, - "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}", + "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a selected type object with another selected object above it in its layer is the text to wrap, not a wrap object, and loses a wrap it had; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids (the wrap objects), warning? (no area type lies below any of them)}", has_selection, make ), @@ -27,13 +29,16 @@ pub fn specs() -> Vec { "Text Wrap Options…", ["Object", "Text Wrap"], None, - "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}", + "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects, leaving out the type selected below them as Make does (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}", has_selection, options ), ] } +/// The warning Make gives when no area type lies below any of its wrap objects in their layer. +pub const NO_AREA_TYPE_BELOW: &str = "Text Wrap: no area type lies below these objects in their layer, so no text wraps around them. Move the objects above the area type with Object › Arrange › Bring to Front. Point type does not wrap."; + /// The Offset a wrap object takes, in points. pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive = -1000.0..=1000.0; @@ -51,20 +56,70 @@ fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result { Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? }) } +/// The type objects of `ids` that lie below another of `ids` in their layer: the text Make wraps +/// when the wrap objects and the type are selected together. Make leaves them out of the wrap +/// objects, and takes the wrap off any of them that has one. +fn type_to_wrap(d: &Document, ids: &[NodeId]) -> HashSet { + let wanted: HashSet = ids.iter().copied().collect(); + // One pass in paint order: each selected type object with its layer and place, and the place of + // the topmost selected object other than a layer in each layer. + let mut texts = vec![]; + let mut top: HashMap = HashMap::new(); + let mut at = 0usize; + for (layer, l) in d.layers.iter().enumerate() { + l.walk(&mut |n| { + if wanted.contains(&n.id) { + match n.kind { + NodeKind::Layer { .. } => {} + NodeKind::Text(_) => { + texts.push((n.id, layer, at)); + top.insert(layer, at); + } + _ => { + top.insert(layer, at); + } + } + } + at += 1; + }); + } + texts.into_iter().filter(|(_, layer, at)| top.get(layer).is_some_and(|t| t > at)).map(|(id, _, _)| id).collect() +} + fn make(s: &mut Session, p: &Value) -> Result { let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?; let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?; - s.edit("Make Text Wrap", |d, _| { - for id in &ids { - let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; - if matches!(n.kind, NodeKind::Layer { .. }) { + let (objects, text, changed) = { + let d = &s.doc()?.doc; + let text = type_to_wrap(d, &ids); + let objects: Vec = ids.iter().copied().filter(|i| !text.contains(i)).collect(); + for id in &objects { + if d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. })) { return Err(EngineError::Other("layers can't be wrap objects".into())); } - n.extras_mut().wrap = Some(w); } - Ok(()) - })?; - Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) + let changed = objects.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap != Some(w))) + || text.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap.is_some())); + (objects, text, changed) + }; + if changed { + s.edit("Make Text Wrap", |d, _| { + for id in &objects { + d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = Some(w); + } + for id in &text { + d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = None; + } + Ok(()) + })?; + } + let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::>() }); + let mut wraps = false; + vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id))); + if !wraps { + out["warning"] = json!(NO_AREA_TYPE_BELOW); + } + Ok(out) } fn release(s: &mut Session, p: &Value) -> Result { @@ -91,14 +146,25 @@ fn release(s: &mut Session, p: &Value) -> Result { fn options(s: &mut Session, p: &Value) -> Result { let ids = checked_ids_or_selection(s, p, "object.textWrap.options")?; - let current = { + // The type selected below the wrap objects is the text they wrap, as in Make. + let (ids, current) = { let d = &s.doc()?.doc; - ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default() + let text = type_to_wrap(d, &ids); + let ids: Vec = ids.into_iter().filter(|i| !text.contains(i)).collect(); + let current = ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default(); + (ids, current) }; if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) { return Ok(json!({ "offset": current.offset, "invert": current.invert })); } let w = wrap_param(p, current, "object.textWrap.options")?; + let changed = { + let d = &s.doc()?.doc; + ids.iter().any(|i| d.node(*i).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. }) && n.extras().wrap != Some(w))) + }; + if !changed { + return Ok(json!({ "offset": w.offset, "invert": w.invert })); + } s.edit("Text Wrap Options", |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) @@ -287,6 +353,95 @@ mod tests { assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true})); } + fn wrap_of(s: &Session, id: u64) -> Option { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap + } + + fn area_type(s: &mut Session) -> u64 { + s.execute("text.create", &json!({"x": 0, "y": 0, "text": "word ".repeat(300), "size": 12, "area": {"width": 400, "height": 400}})) + .unwrap()["id"] + .as_u64() + .unwrap() + } + + fn ellipse(s: &mut Session) -> u64 { + s.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap() + } + + /// Make with the wrap object and the area type below it selected together wraps the type: the + /// type is the text to wrap, not another wrap object (#3211). + #[test] + fn make_with_the_area_type_selected_wraps_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let t = area_type(&mut s); + let plain = lines(&s, t); + let c = ellipse(&mut s); + s.execute("select.set", &json!({"ids": [c, t]})).unwrap(); + let r = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert_eq!(r, json!({"ids": [c]}), "{r}"); + assert!(wrap_of(&s, c).is_some()); + assert!(wrap_of(&s, t).is_none(), "the area type became a wrap object"); + assert_ne!(lines(&s, t), plain, "the area type did not wrap"); + // Make again with the same options changes nothing and records no undo step. + let steps = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("object.textWrap.make", &json!({})).unwrap(), json!({"ids": [c]})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + // Text Wrap Options with both still selected sets the wrap object's options only, and the + // type keeps wrapping; the same options again record no undo step. + let wrapped = lines(&s, t); + assert_eq!(s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap()["offset"], json!(30.0)); + assert_eq!(wrap_of(&s, c).map(|w| w.offset), Some(30.0)); + assert!(wrap_of(&s, t).is_none(), "Options made the area type a wrap object"); + assert_ne!(lines(&s, t), wrapped, "the type did not follow the new offset"); + assert_ne!(lines(&s, t), plain); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + s.execute("edit.undo", &json!({})).unwrap(); + // One undo takes the wrap off again. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(wrap_of(&s, c).is_none()); + assert_eq!(lines(&s, t), plain); + } + + /// Make with the object below the area type warns that no text wraps. After Bring to Front, + /// Make with both selected wraps the type, and the type that the first Make made a wrap object + /// is the text to wrap again (#3211). + #[test] + fn make_warns_when_the_object_is_below_the_type_and_wraps_after_bring_to_front() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let c = ellipse(&mut s); + let t = area_type(&mut s); + let plain = lines(&s, t); + s.execute("select.set", &json!({"ids": [c, t]})).unwrap(); + let r = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert_eq!(r["warning"], json!(super::NO_AREA_TYPE_BELOW), "{r}"); + assert_eq!(lines(&s, t), plain); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [c, t]})).unwrap(); + let r = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert!(r.get("warning").is_none(), "{r}"); + assert!(wrap_of(&s, t).is_none(), "the area type is still a wrap object"); + assert_ne!(lines(&s, t), plain, "the area type did not wrap"); + } + + /// Point type below a wrap object does not wrap, so Make warns. + #[test] + fn make_warns_over_point_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let p = s.execute("text.create", &json!({"x": 0, "y": 100, "text": "point type", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 80, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r, p]})).unwrap(); + let out = s.execute("object.textWrap.make", &json!({})).unwrap(); + assert_eq!(out["warning"], json!(super::NO_AREA_TYPE_BELOW), "{out}"); + assert!(wrap_of(&s, r).is_some()); + assert!(wrap_of(&s, p).is_none(), "the point type became a wrap object"); + } + #[test] fn text_flows_on_both_sides_of_a_centred_object() { let mut s = Session::new(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d9bf1c8d98..98267484e0 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -514,7 +514,7 @@ pub fn tool_definitions() -> Vec { tool( "text_wrap", "Text wrap", - "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.", + "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). A type object in `ids` below another of them is the text to wrap, not a wrap object. A `warning` says when no area type lies below them. `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..84950b4b17 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -821,7 +821,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | -| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | +| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: From 8cd5376786d912bd6da594611d54bff32c282e56 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 16:33:21 +0100 Subject: [PATCH 31/36] Route selected Zoom to canvas navigation and keep freehand edges stationary --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 2 + .../ui-egui/src/canvas/tests_edge_scroll.rs | 60 ++++++++++++++++++- crates/ui-egui/src/canvas/tool_adapter.rs | 26 ++++++-- 4 files changed, 82 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 228a01b2f6..b2e2fa1331 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -140,6 +140,7 @@ impl VectorcraftApp { text_nodes: Default::default(), momentary: None, hand: None, + zoom_tool: None, selection_box: None, selection_bounds: None, selection_marks: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index cdf59a99f8..06c564f4c8 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -82,6 +82,8 @@ pub struct CanvasCache { /// passes; the tool adapter takes it out for its call and puts it back. pub momentary: Option, pub hand: Option, + /// The selected Zoom tool keeps its press and drag rectangle between canvas passes. + pub zoom_tool: Option, /// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and /// Measure Type by Glyph Bounds). pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, diff --git a/crates/ui-egui/src/canvas/tests_edge_scroll.rs b/crates/ui-egui/src/canvas/tests_edge_scroll.rs index 167f938861..405d14a4e0 100644 --- a/crates/ui-egui/src/canvas/tests_edge_scroll.rs +++ b/crates/ui-egui/src/canvas/tests_edge_scroll.rs @@ -9,7 +9,12 @@ use vectorcraft_geom::Point; /// One headless canvas frame on an 800 × 600 window. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { - let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + frame_with_modifiers(app, ctx, events, Default::default()); +} + +fn frame_with_modifiers(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: egui::Modifiers) { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, modifiers, ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| show(app, ui)); out.textures_delta.clear(); } @@ -139,3 +144,56 @@ fn a_hand_drag_held_near_the_edge_does_not_scroll_on() { assert_eq!(center(&app), c0); frame(&mut app, &ctx, vec![button(edge, false)]); } + +#[test] +fn a_freehand_stroke_at_the_edge_keeps_the_artwork_stationary() { + let (mut app, ctx, original) = zoomed_in("pencil"); + let rect = app.canvas_view().unwrap().rect; + let start = rect.center() - vec2(120.0, 60.0); + let edge = pos2(rect.right() - 2.0, start.y + 40.0); + let initial = center(&app); + let nodes = |app: &VectorcraftApp| { + let mut count = 0; + app.session.active().unwrap().doc.walk(|_| count += 1); + count + }; + let before = nodes(&app); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(15.0, 25.0))]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]); + for _ in 0..5 { + frame(&mut app, &ctx, vec![]); + assert_eq!(center(&app), initial); + } + frame(&mut app, &ctx, vec![button(edge, false)]); + assert!(nodes(&app) > before, "the pencil drew a new path"); + assert!(app.session.active().unwrap().doc.node(original).is_some()); +} + +#[test] +fn selected_zoom_tool_clicks_option_clicks_and_drags_a_marquee() { + let (mut app, ctx, _) = zoomed_in("zoom"); + app.session.prefs.animated_zoom = false; + let rect = app.canvas_view().unwrap().rect; + let position = rect.center(); + let zoom = |app: &VectorcraftApp| app.view().unwrap().zoom; + let initial = zoom(&app); + for pressed in [true, false] { + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(position), button(position, pressed)]); + } + let enlarged = zoom(&app); + assert!(enlarged > initial, "click should zoom in: {initial} -> {enlarged}"); + let modifiers = egui::Modifiers::ALT; + for pressed in [true, false] { + let event = egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_with_modifiers(&mut app, &ctx, vec![event], modifiers); + } + let reduced = zoom(&app); + assert!(reduced < enlarged, "Option-click should zoom out: {enlarged} -> {reduced}"); + let start = position - vec2(90.0, 65.0); + let end = position + vec2(80.0, 55.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]); + frame(&mut app, &ctx, vec![button(end, false)]); + assert!(zoom(&app) > reduced, "the marquee should fit its region to the view"); +} diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index cc2750f2a4..2e33ef9cf8 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -590,7 +590,9 @@ impl CanvasTool for SessionTool<'_> { } fn autoscrolls(&self) -> bool { - !self.carrying.get() && !self.view_only() + // Sampled freehand tools trace the pointer on the artwork. Scrolling + // under a held pen would extend the stroke without another sample. + !self.carrying.get() && !self.view_only() && !self.app().session.tool_wants_samples() } fn view_only(&self) -> bool { @@ -651,18 +653,30 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too let mut picked = ToolHostResponse::default(); let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) { picked - } else if app.session.tool_id() == "hand" && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() { + } else if matches!(app.session.tool_id(), "hand" | "zoom") && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() { let options = crate::app::view::navigation(&app.session.prefs); - let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options)); - hand.options = options; - let response = host_run(app, ui, pass, &mut hand); + let response = if app.session.tool_id() == "zoom" { + app.canvas.hand = None; + let mut zoom = app.canvas.zoom_tool.take().unwrap_or_else(|| craft::ui::canvas::ZoomTool::new(options)); + zoom.options = options; + let response = host_run(app, ui, pass, &mut zoom); + app.canvas.zoom_tool = Some(zoom); + response + } else { + app.canvas.zoom_tool = None; + let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options)); + hand.options = options; + let response = host_run(app, ui, pass, &mut hand); + app.canvas.hand = Some(hand); + response + }; if response.gesture.is_some() && !view_tool_held(app) && ui.input(|i| i.pointer.primary_down() || i.pointer.primary_pressed()) { crate::shortcuts::note_tool_use(app); } - app.canvas.hand = Some(hand); response } else { app.canvas.hand = None; + app.canvas.zoom_tool = None; let mut tool = SessionTool::new(app, view_info, ui); let response = host_run_session(&mut tool, ui, pass); drop(tool); From 2baca48a3dccb2a218c286ccdd3ecf79a99910ed Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 16:38:56 +0100 Subject: [PATCH 32/36] Collect macOS menu key equivalents before consuming native key-up --- crates/ui-egui/src/app.rs | 7 ++++++- crates/ui-egui/src/menus/native.rs | 1 - crates/ui-egui/src/tests/nativemenu.rs | 21 +++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 228a01b2f6..246341ef71 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -380,7 +380,12 @@ impl VectorcraftApp { } /// A window's raw input, before egui and the keys read it (the host's `raw_input_hook`). - pub fn raw_input(&self, ctx: &egui::Context, raw: &mut egui::RawInput) { + pub fn raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // AppKit consumes the key-down and winit can already have queued its key-up. + // Poll before the runtime orders the press and release in this frame's input. + if let Some(menu) = self.services.native_menu.as_mut() { + menu.poll(ctx); + } crate::type_editing::keep_layout_text(self, ctx, raw); } diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 0cd3eeaa87..2450a9b201 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -27,7 +27,6 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) { let gate = Gate::default().modal(app.file_dialog_open()).recording_shortcut(recording_shortcut(app)).text_editing(ctx.egui_wants_keyboard_input()); let Some(menu) = app.services.native_menu.as_mut() else { return }; - menu.poll(ctx); menu.set_gate(gate); let clicks = menu.take_clicks(ctx); // A menu opening reads the Scripts folder again. diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index 1fad419639..41b5264479 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -458,3 +458,24 @@ fn a_key_equivalent_paste_pastes_a_picture_from_another_app() { assert_eq!(images(&m), n, "press {n} pastes one picture"); } } + +/// AppKit handles a menu shortcut's key-down before winit delivers the matching key-up. +/// The two must reach the same input batch, even if this frame can have only one pass. +#[test] +fn a_native_undo_and_redo_key_equivalent_each_change_the_canvas_once() { + let mut m = Mac::new(true); + m.ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::MIN); + let id = m.app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + m.frame(vec![]); + for (chord, shift, present) in [("Cmd+Z", false, false), ("Cmd+Shift+Z", true, true)] { + let mut modifiers = if crate::keymap::platform().is_mac() { Modifiers::MAC_CMD } else { Modifiers::CTRL }; + modifiers.command = true; + modifiers.shift = shift; + m.fake.report(MenuEvent::Key(Chord::parse(chord).unwrap())); + m.frame(vec![Event::Key { key: Key::Z, physical_key: Some(Key::Z), pressed: false, repeat: false, modifiers }]); + assert_eq!(m.app.session.active().unwrap().doc.node(id).is_some(), present, "{chord} with the native key-up"); + m.frame(vec![]); + assert_eq!(m.app.session.active().unwrap().doc.node(id).is_some(), present, "{chord} was applied once"); + } +} From c8abbce26b357d668c8018b30c603aff82d5c2b4 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 16:41:07 +0100 Subject: [PATCH 33/36] Deliver Option as a modifier-change event in Zoom regression --- crates/ui-egui/src/canvas/tests_edge_scroll.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests_edge_scroll.rs b/crates/ui-egui/src/canvas/tests_edge_scroll.rs index 405d14a4e0..3a67ee6840 100644 --- a/crates/ui-egui/src/canvas/tests_edge_scroll.rs +++ b/crates/ui-egui/src/canvas/tests_edge_scroll.rs @@ -9,12 +9,7 @@ use vectorcraft_geom::Point; /// One headless canvas frame on an 800 × 600 window. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { - frame_with_modifiers(app, ctx, events, Default::default()); -} - -fn frame_with_modifiers(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: egui::Modifiers) { - let raw = - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, modifiers, ..Default::default() }; + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| show(app, ui)); out.textures_delta.clear(); } @@ -186,8 +181,9 @@ fn selected_zoom_tool_clicks_option_clicks_and_drags_a_marquee() { let modifiers = egui::Modifiers::ALT; for pressed in [true, false] { let event = egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers }; - frame_with_modifiers(&mut app, &ctx, vec![event], modifiers); + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(modifiers), event]); } + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); let reduced = zoom(&app); assert!(reduced < enlarged, "Option-click should zoom out: {enlarged} -> {reduced}"); let start = position - vec2(90.0, 65.0); From dd8e474b64367a3969a0c808bd7aaff78cf3dede Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 16:41:31 +0100 Subject: [PATCH 34/36] Measure the Done button against the compact panel's actual bounds --- crates/ui-egui/src/panels/pattern_options.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/pattern_options.rs b/crates/ui-egui/src/panels/pattern_options.rs index 0bd03fac9c..866588c468 100644 --- a/crates/ui-egui/src/panels/pattern_options.rs +++ b/crates/ui-egui/src/panels/pattern_options.rs @@ -274,15 +274,19 @@ mod tests { app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); app.run("object.pattern.make", json!({"name": "Dots"})).unwrap(); let mut panel = Panel::new(app, |app, ui| crate::dock::panel_body(app, ui, "patternOptions")); - panel.room(egui::vec2(300.0, 200.0)); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0)); + panel.room(viewport.size()); panel.frame(); panel.frame(); - assert!(!panel.in_view("Done")); + let before = panel.rect("Done"); + assert!(before.center().y > viewport.bottom(), "Done starts at {before:?} in {viewport:?}"); for _ in 0..20 { - panel.scroll_at(egui::pos2(150.0, 100.0), -120.0); + panel.scroll_at(egui::pos2(30.0, 30.0), -120.0); + panel.advance(0.2); panel.frame(); } - assert!(panel.in_view("Done")); + let after = panel.rect("Done"); + assert!(viewport.contains(after.center()), "Done moved from {before:?} to {after:?} in {viewport:?}"); panel.click("Done"); assert!(editing(&panel.app()).is_none()); } From dbcd460c53f70b8d2baebf40599e7fa76af0ed8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:56:01 -0800 Subject: [PATCH 35/36] Tests: let the Move dialog close before the units test opens Rectangle dialog_lengths_show_in_the_general_unit confirmed the Move dialog and opened the Rectangle dialog in the same frame. Move holds its OK, so it stays on the stack until the next frame, and Rectangle is laid out once over it and once more, unseen, after Move leaves. The test drew two frames and passed only because the frame after the selection change ran a second pass for the Properties panel. With that panel drawn in one pass, the second frame showed nothing and the assertion failed. The test now draws a frame after OK, so Move has closed before the selection change and the Rectangle dialog. Its assertions are unchanged. --- crates/ui-egui/src/panels/tests_units.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/panels/tests_units.rs b/crates/ui-egui/src/panels/tests_units.rs index ecac244136..d5837ffed5 100644 --- a/crates/ui-egui/src/panels/tests_units.rs +++ b/crates/ui-egui/src/panels/tests_units.rs @@ -101,6 +101,8 @@ fn dialog_lengths_show_in_the_general_unit() { window.type_text("10 mm"); window.key(egui::Key::Tab, egui::Modifiers::NONE); confirm_dialog(&mut window.app()); + // The Move dialog holds its OK, so it leaves the stack in the next frame. + window.frame(); let square = { let app = window.app(); let st = app.session.active().unwrap(); From 2791318a353861d5bb8066b1f961228c59d37687 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 18:15:06 +0100 Subject: [PATCH 36/36] Keep artwork visible behind live effect controls --- crates/ui-egui/src/dialogs/effect.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 06fa47f045..057eac94eb 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -350,9 +350,14 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map // Free Distort's Reset puts the corners back on the box, wherever they were when it opened. let reset_to = (id == super::free_distort::FREE_DISTORT) .then(|| form::fields_of(&rows, &Map::from_iter([("corners".to_string(), json!(super::free_distort::IDENTITY))]))); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, "effect", fields, move |f| { let rows = effect_params(&cx, f); let dialog = ParamDialog::new("effect", title.clone(), rows).values(Bind::bound(f)).previews(true); + let dialog = match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + }; let dialog = match &reset_to { Some(target) => dialog.reset_to(target.clone()), None => dialog,