From 4b4a97ce1e796a1182582f5290bb2b5431ed51a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:43:54 +0700 Subject: [PATCH 01/26] Variables: a second text variable on one type object is refused Squashed from #2642 onto main. --- crates/doc/src/variables.rs | 11 +-- crates/engine/src/cmd/variablecmds.rs | 23 ++++- crates/engine/src/tests/variables.rs | 131 ++++++++++++++++++++++---- docs/mcp.md | 3 +- docs/target-app-parity.md | 1 + 5 files changed, 145 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/variables.rs b/crates/doc/src/variables.rs index efe50d9df9..de37364faa 100644 --- a/crates/doc/src/variables.rs +++ b/crates/doc/src/variables.rs @@ -105,12 +105,11 @@ impl DataSet { /// The variable state of a document: definitions, datasets, bindings /// (object id → the variables bound to it) and which dataset is active. /// -/// An object may be driven by several variables — the reference app binds the selected object -/// to the selected variable, one click at a time, and never says a second binding replaces the -/// first — so a binding is a set. `dataset.select` applies the text values in the order the -/// variables are defined, which is what makes two text variables on one object deterministic: -/// the last one wins, and `applied` counts both. Of two visibility variables on one object, the -/// last one defined wins too. +/// An object may be driven by several variables, so a binding is a set. `variable.bind` and Make +/// Text Dynamic refuse a second text variable on one type object, but a document saved before +/// they did may hold two: `dataset.select` applies the text values in the order the variables +/// are defined, so the last one wins, and `applied` counts both. Of two visibility variables on +/// one object, the last one defined wins too. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Variables { #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 426479070d..16762c1e52 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -181,6 +181,21 @@ fn not_a_target(doc: &vectorcraft_doc::Document, id: NodeId) -> String { } } +/// Refuse to bind the text variable `name` to type that already has a different text variable: +/// a type object holds one text variable. The error names the one it has (the first defined, in +/// a document that holds two). An object already bound to `name` is not refused, and variables +/// of other kinds are not counted. +fn check_one_text_variable(doc: &vectorcraft_doc::Document, ids: &[NodeId], name: &str, cmd: &str) -> Result<()> { + for id in ids { + let Some(bound) = doc.variables.bindings.get(id).filter(|b| !b.contains(name)) else { continue }; + let held = doc.variables.variables.iter().find(|v| v.kind == VariableKind::Text && bound.contains(&v.name)); + if let Some(v) = held { + return Err(bad(cmd, format!("node {} already has the text variable `{}`", id.0, v.name))); + } + } + Ok(()) +} + fn dataset_value(cmd: &str, var: &str, kind: VariableKind, v: &Value) -> Result { match kind { VariableKind::Text => v.as_str().map(|t| DataValue::Text(t.to_string())), @@ -284,6 +299,9 @@ fn make_dynamic(s: &mut Session, kind: VariableKind, stem: &str) -> Result Result { let doc = &s.doc()?.doc; let kind = doc.variables.variable(&name).map(|v| v.kind).ok_or_else(|| bad(C, format!("no variable named `{name}`")))?; check_bindable(doc, &ids, kind, C)?; + if kind == VariableKind::Text { + check_one_text_variable(doc, &ids, &name, C)?; + } // Binding again is not a second binding, and says so rather than counting as a change. let already: Vec = ids.iter().filter(|id| doc.variables.objects_of(&name).contains(id)).map(|id| id.0).collect(); let n = edit_variables(s, "Bind Variable", |v| Ok(ids.iter().filter(|id| v.bind(**id, &name)).count()))?; @@ -738,7 +759,7 @@ pub fn specs() -> Vec { "Bind Variable", ["Window", "Variables"], None, - "{variable, ids?} bind objects (default: the selection) to a variable; text needs type, image needs an image object, graph needs a graph root, locked art is refused. An object may hold several variables, and binding it to one it already has changes nothing → {bound, already}", + "{variable, ids?} bind objects (default: the selection) to a variable; text needs type, image needs an image object, graph needs a graph root, locked art is refused. A type object holds one text variable: binding it to another text variable is refused, and the error names the one it has. Variables of other kinds can share an object, and binding an object to a variable it already has changes nothing → {bound, already}", has_doc, bind ), diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 715bae959b..5566f11586 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -97,7 +97,9 @@ fn applying_a_dataset_reports_the_area_type_it_overflows() { s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0, p.0]})).unwrap(); - s.execute("variable.bind", &json!({"variable": "Title", "ids": [a.0]})).unwrap(); + // `variable.bind` refuses a second text variable on one type object; a document saved + // before it did can hold two. + Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.bind(a, "Title"); s.execute("dataset.new", &json!({"name": "Short", "values": {"Name": "Ann", "Title": "Ann"}})).unwrap(); s.execute("dataset.new", &json!({"name": "Long", "values": {"Name": long, "Title": long}})).unwrap(); @@ -263,6 +265,7 @@ fn a_row_with_no_value_for_a_bound_variable_warns_that_nothing_was_applied() { assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(1), &json!(warning(b))), "{v}"); // Bound to a variable with a value, the row applies it and gives no warning. + s.execute("variable.unbind", &json!({"variable": "Other", "ids": [t.0]})).unwrap(); s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap(); let v = s.execute("dataset.select", &json!({"name": a})).unwrap(); assert_eq!(v["applied"].as_u64(), Some(1), "{v}"); @@ -361,50 +364,146 @@ fn one_object_can_be_driven_by_several_variables() { let t = text(&mut s, "x"); let r = rect(&mut s); s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); - s.execute("variable.define", &json!({"name": "Price", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap(); s.execute("variable.define", &json!({"name": "Badge", "kind": "visibility"})).unwrap(); - // A text object driven by two text variables keeps both. + // A text object driven by a text variable and a visibility variable keeps both. assert_eq!(s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap()["bound"], 1); - let v = s.execute("variable.bind", &json!({"variable": "Price", "ids": [t.0]})).unwrap(); + let v = s.execute("variable.bind", &json!({"variable": "Shown", "ids": [t.0]})).unwrap(); assert_eq!((v["bound"].clone(), v["already"].clone()), (json!(1), json!([])), "Title is untouched"); // A rectangle driven by a visibility variable as well as nothing else yet. s.execute("variable.bind", &json!({"variable": "Badge", "ids": [r.0]})).unwrap(); - s.execute("dataset.new", &json!({"name": "D", "values": {"Title": "Hat", "Price": "9.99", "Badge": false}})).unwrap(); + s.execute("dataset.new", &json!({"name": "D", "values": {"Title": "Hat", "Shown": true, "Badge": false}})).unwrap(); let v = s.execute("dataset.select", &json!({"name": "D"})).unwrap(); assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64()), (Some(3), Some(0)), "every binding applied"); - // Both text variables are counted; the later one in definition order is what is left. - assert_eq!(plain(&s, t), "9.99"); + assert_eq!(plain(&s, t), "Hat"); + assert!(s.doc().unwrap().doc.node(t).unwrap().visible); assert!(!s.doc().unwrap().doc.node(r).unwrap().visible); let vars = s.execute("variable.list", &json!({})).unwrap(); let of = |n: &str| vars["variables"].as_array().unwrap().iter().find(|v| v["name"] == n).unwrap()["bindings"].as_u64(); - assert_eq!((of("Title"), of("Price"), of("Badge")), (Some(1), Some(1), Some(1))); + assert_eq!((of("Title"), of("Shown"), of("Badge")), (Some(1), Some(1), Some(1))); // Binding again to one it already has is not a change, and says so. - let v = s.execute("variable.bind", &json!({"variable": "Price", "ids": [t.0]})).unwrap(); + let v = s.execute("variable.bind", &json!({"variable": "Shown", "ids": [t.0]})).unwrap(); assert_eq!((v["bound"].clone(), v["already"].clone()), (json!(0), json!([t.0]))); // Unbinding one variable leaves the object's others alone. - assert_eq!(s.execute("variable.unbind", &json!({"ids": [t.0], "variable": "Price"})).unwrap()["unbound"], 1); + assert_eq!(s.execute("variable.unbind", &json!({"ids": [t.0], "variable": "Shown"})).unwrap()["unbound"], 1); s.execute("edit.undo", &json!({})).unwrap(); let vars = s.execute("variable.list", &json!({})).unwrap(); assert_eq!(vars["variables"][1]["bindings"], 1, "the other binding is still there"); assert!(s.execute("variable.unbind", &json!({"ids": [t.0], "variable": "Ghost"})).is_err()); // Deleting a variable drops only its own binding. - s.execute("variable.delete", &json!({"names": ["Price"]})).unwrap(); + s.execute("variable.delete", &json!({"names": ["Shown"]})).unwrap(); let vars = s.execute("variable.list", &json!({})).unwrap(); assert_eq!(vars["variables"][0]["bindings"], 1, "Title still drives the text"); } +/// A type object holds one text variable: binding another text variable to it is refused, the +/// error names the one it has, and nothing is bound, not even the other objects of the call. +/// Variables of other kinds still share the object. +#[test] +fn a_type_object_holds_one_text_variable() { + let mut s = session(); + let t = text(&mut s, "x"); + let u = text(&mut s, "y"); + for (name, kind) in [("Title", "text"), ("Price", "text"), ("Shown", "visibility")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap(); + let bindings = |s: &Session, name: &str| s.doc().unwrap().doc.variables.objects_of(name); + + let e = s.execute("variable.bind", &json!({"variable": "Price", "ids": [u.0, t.0]})).unwrap_err().to_string(); + assert!(e.contains("`variable.bind`") && e.contains(&format!("node {} already has the text variable `Title`", t.0)), "{e}"); + assert_eq!((bindings(&s, "Title"), bindings(&s, "Price")), (vec![t], vec![]), "nothing was bound"); + // The same variable again is not a second one, and another type object takes Price. + assert_eq!(s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap()["already"], json!([t.0])); + s.execute("variable.bind", &json!({"variable": "Price", "ids": [u.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Shown", "ids": [t.0, u.0]})).unwrap(); + assert_eq!(bindings(&s, "Shown"), vec![t, u]); + // After Title is unbound from it, the object takes Price. + s.execute("variable.unbind", &json!({"ids": [t.0], "variable": "Title"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Price", "ids": [t.0]})).unwrap(); + assert_eq!(bindings(&s, "Price"), vec![t, u]); +} + +/// Make Text Dynamic refuses type that already has a text variable and defines no variable; +/// Make Visibility Dynamic still binds it. +#[test] +fn make_text_dynamic_refuses_type_that_has_a_text_variable() { + let mut s = session(); + let t = text(&mut s, "Alice"); + s.execute("select.set", &json!({"ids": [t.0]})).unwrap(); + s.execute("variable.makeTextDynamic", &json!({})).unwrap(); + + let e = s.execute("variable.makeTextDynamic", &json!({})).unwrap_err().to_string(); + assert!(e.contains("`variable.makeTextDynamic`") && e.contains(&format!("node {} already has the text variable `Alice`", t.0)), "{e}"); + let vars = s.execute("variable.list", &json!({})).unwrap(); + assert_eq!(vars["variables"].as_array().map(Vec::len), Some(1), "{vars}"); + let v = s.execute("variable.makeVisibilityDynamic", &json!({})).unwrap(); + assert_eq!(v["ids"], json!([t.0])); +} + +/// With unbound type selected before type that has a text variable, Make Text Dynamic is still +/// refused: it defines no variable and binds neither object. +#[test] +fn make_text_dynamic_refuses_a_selection_where_a_later_object_has_a_text_variable() { + let mut s = session(); + let u = text(&mut s, "Bob"); + let t = text(&mut s, "Alice"); + s.execute("select.set", &json!({"ids": [t.0]})).unwrap(); + s.execute("variable.makeTextDynamic", &json!({})).unwrap(); + + s.execute("select.set", &json!({"ids": [u.0, t.0]})).unwrap(); + let e = s.execute("variable.makeTextDynamic", &json!({})).unwrap_err().to_string(); + assert!(e.contains(&format!("node {} already has the text variable `Alice`", t.0)), "{e}"); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.variables.variables.len(), 1, "no variable was defined"); + assert!(!doc.variables.bindings.contains_key(&u), "the unbound object stays unbound"); + assert_eq!(doc.variables.bindings[&t].iter().collect::>(), ["Alice"]); +} + +/// A document saved with two text variables on one type object opens with both bindings, and +/// applying a row still writes both, the later one defined last. Binding either again changes +/// nothing, and binding a third is refused with the first one named. +#[test] +fn a_document_with_two_text_variables_on_one_type_object_opens_unchanged() { + let mut s = session(); + let t = text(&mut s, "x"); + let u = text(&mut s, "y"); + for name in ["Title", "Price", "Note"] { + s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap(); + } + s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap(); + Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.bind(t, "Price"); + s.execute("dataset.new", &json!({"name": "D", "values": {"Title": "Hat", "Price": "9.99"}})).unwrap(); + let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "two.vectorcraft", "dataBase64": saved})).unwrap(); + let held: Vec = o.doc().unwrap().doc.variables.bindings[&t].iter().cloned().collect(); + assert_eq!(held, ["Price", "Title"]); + let v = o.execute("dataset.select", &json!({"name": "D"})).unwrap(); + assert_eq!(v["applied"], json!(2), "{v}"); + assert_eq!(plain(&o, t), "9.99"); + for name in ["Title", "Price"] { + let v = o.execute("variable.bind", &json!({"variable": name, "ids": [t.0, u.0]})).unwrap(); + assert_eq!((&v["bound"], &v["already"]), (&json!(1), &json!([t.0])), "{name}: {v}"); + o.execute("edit.undo", &json!({})).unwrap(); + } + let e = o.execute("variable.bind", &json!({"variable": "Note", "ids": [t.0]})).unwrap_err().to_string(); + assert!(e.contains(&format!("node {} already has the text variable `Title`", t.0)), "{e}"); +} + /// `unbound` counts what was actually dropped, like `variable.delete` does. #[test] fn unbind_reports_what_it_actually_removed() { let mut s = session(); let t = text(&mut s, "x"); s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); - s.execute("variable.define", &json!({"name": "Price", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "Price", "kind": "visibility"})).unwrap(); s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap(); s.execute("variable.bind", &json!({"variable": "Price", "ids": [t.0]})).unwrap(); assert_eq!(s.execute("variable.unbind", &json!({"ids": [t.0], "variable": "Title"})).unwrap()["unbound"], 1); @@ -552,8 +651,9 @@ fn making_a_selection_dynamic_names_and_binds_it() { let v = s.execute("variable.makeVisibilityDynamic", &json!({})).unwrap(); assert_eq!(v["kind"], "visibility"); - // The same object twice takes a number rather than colliding with the first variable. - s.execute("select.set", &json!({"ids": [t.0]})).unwrap(); + // Type with the same name takes a number rather than colliding with the first variable. + let twin = text(&mut s, "Alice"); + s.execute("select.set", &json!({"ids": [twin.0]})).unwrap(); let again = s.execute("variable.makeTextDynamic", &json!({})).unwrap(); assert_eq!(again["name"], "Alice 2"); let vars = s.execute("variable.list", &json!({})).unwrap(); @@ -1254,8 +1354,7 @@ fn a_row_writes_type_inside_a_group_it_shows_or_hides() { assert!(!s.doc().unwrap().doc.node(g).unwrap().visible); } -/// Of two visibility variables on one object, the one defined later decides whether it shows, -/// as with two text variables. +/// Of two visibility variables on one object, the one defined later decides whether it shows. #[test] fn the_later_visibility_variable_on_an_object_wins() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 9220b1c620..ae04c16472 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1812,7 +1812,8 @@ already walks Image Trace. Short agent entry points: first value at −180° to its second at 180°. A stroke without that input draws the brush's own value (a Scatter brush's value half way between the two). - Variables: `variable.list`, `variable.define {name, kind: text|visibility|image|graph}`, `variable.bind {variable, ids?}`, - `variable.makeTextDynamic`, `variable.makeVisibilityDynamic`, `variable.makeImageDynamic`, `variable.makeGraphDynamic`, + `variable.makeTextDynamic`, `variable.makeVisibilityDynamic`, `variable.makeImageDynamic`, `variable.makeGraphDynamic` + (`variable.bind` and `variable.makeTextDynamic` refuse type that already has another text variable and name it), `variable.unbind`, `variable.rename`, `variable.delete`, `variable.highlight` (image values are file paths, graph values CSV as `graph.setData`). `variable.lock {locked?}` (Lock Variables) locks or unlocks the variables; without `locked` it toggles, and the lock is saved with the document. While the variables are locked, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ad1ecc9210..ec7b76edf9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -655,6 +655,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a text variable the library also declares, which stays bound so the library's data sets change its objects (#4136); then the library's other text variables are defined, unbound, and its data sets take the text of each value's `p` elements, one paragraph each. Variables of other kinds are left out with a warning that names their kinds. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's text variables and data sets as a variable library's XML file, which Load Variable Library reads back with the same text variables, data set names and text values. Variables of other kinds are left out with a warning that names their kinds. - JSON-lines control channel with real egui pointer and keyboard injection. + - Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both. - 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. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. From 7c813e71710836158626ba1d3b87a9b90875845b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:44:34 +0700 Subject: [PATCH 02/26] Document: document.compare measures how far an artboard's render is from an image Squashed from #3995 onto main. --- crates/engine/src/cmd/edit.rs | 158 ++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/compare.rs | 276 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + docs/mcp.md | 16 ++ 29 files changed, 581 insertions(+) create mode 100644 crates/engine/src/tests/compare.rs diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index dbe3d4509b..21bd4f9bc7 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -41,6 +41,15 @@ pub fn specs() -> Vec { cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect), cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node), cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), + cmd!( + query "document.compare", + "Compare with Image", + [], + None, + "{path: an image file (PNG, JPEG, WebP, TIFF or BMP), artboard?: index=0, background?: \"#rrggbb\"=\"#ffffff\" (the render and the image are both flattened on it), threshold?: 0.08 (0–1), diffPath?: a PNG to write (each pixel's absolute R, G and B differences)} render the artboard at the image's size (the image's width in pixels over the artboard's width in points), drawn as document.export draws a PNG (linked images and placed documents from their files), and compare it with the image; an image whose height differs by more than a pixel from the artboard's height at that scale is refused (not in the browser) → {width, height, rmse: the root mean square of the R, G and B differences, 0–1 (6 decimals), over: the pixels with a channel that differs by more than threshold, total: the pixels, threshold, diffPath?, warnings?: as a PNG export's (type that doesn't fit its frame, an image that couldn't be decoded, type in a font or style that isn't available, previews drawn because a linked file can't be read)}", + has_doc, + doc_compare + ), cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))), cmd!( "document.setUnits", @@ -385,6 +394,155 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result { }) } +/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed +/// documents from their files, with the export's warnings), and measure how far the +/// two are apart: both flattened on `background`, the root mean square of the R, G and B +/// differences (0–1), and the pixels with a channel that differs by more than `threshold`. +#[cfg(not(target_arch = "wasm32"))] +fn doc_compare(s: &mut Session, p: &Value) -> Result { + use vectorcraft_render::encode::{RasterExportOptions, RasterFormat, png}; + const C: &str = "document.compare"; + let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; + let diff_path = match p.get("diffPath") { + None | Some(Value::Null) => None, + Some(Value::String(v)) => Some(v.as_str()), + Some(_) => { + let key = "diffPath"; + return Err(bad(C, format!("`{key}` must be a string"))); + } + }; + let background = match p.get("background") { + None | Some(Value::Null) => [255; 3], + Some(v) => match super::fileio::background(v) { + Ok(Some(rgb)) => rgb, + _ => return Err(bad(C, format!("background {v}: a color such as \"#808080\""))), + }, + }; + let threshold = match p.get("threshold") { + None | Some(Value::Null) => 0.08, + Some(v) => v.as_f64().filter(|t| (0.0..=1.0).contains(t)).ok_or_else(|| bad(C, "`threshold` must be a number from 0 to 1"))?, + }; + let doc = &s.doc()?.doc; + let count = doc.artboards.len(); + let i = opt_u64(p, C, "artboard")?.unwrap_or(0); + let region = usize::try_from(i) + .ok() + .and_then(|i| doc.artboards.get(i)) + .map(|a| a.rect) + .ok_or_else(|| bad(C, format!("no artboard {i} (0-based; the document has {count})")))?; + if let Some(d) = diff_path { + crate::file_access::check_write(d).map_err(EngineError::Other)?; + } + let image = compare_image(path)?; + let (iw, ih) = image.dimensions(); + // The image's width sets the scale; its height may differ from the artboard's at that scale by + // the pixel the rounding of a render takes. + let scale = f64::from(iw) / region.width(); + let rendered_height = region.height() * scale; + if iw == 0 || ih == 0 || !rendered_height.is_finite() || (rendered_height - f64::from(ih)).abs() > 1.0 { + let (rw, rh) = (iw, rendered_height.round()); + return Err(bad( + C, + format!("the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ"), + )); + } + vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?; + vectorcraft_render::raster_size(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(iw), f64::from(ih)), 1.0).map_err(|e| bad(C, e))?; + let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0)); + let opts = RasterExportOptions { background: Some(background), ..Default::default() }.render_options(RasterFormat::Png); + // As a PNG export: linked images and placed documents drawn from their files, not the + // previews saved for them. + let (full, linked) = super::place::document::full_documents(doc); + let failed = vectorcraft_render::decode_failures(); + let rendered = vectorcraft_render::Renderer::new().render(&full, iw, ih, view, &opts); + // A canceled render stops drawing: the picture is not whole. + vectorcraft_doc::cancel::check()?; + // As a PNG export says, in its order: type on the artboard that doesn't fit its frame, an image + // the renderer couldn't decode (missing from the render), type in a missing font or style (drawn + // in another one), and linked files drawn from their previews. + let mut warnings: Vec = super::fonts::export_overflow_warning(&full, &full.layers, Some(&[region])).into_iter().collect(); + if let Some(w) = super::rasterfx::undecoded_warning(failed) { + warnings.push(w.into()); + } + if let Some(w) = super::fonts::substitution_warning(&full) { + warnings.push(w); + } + warnings.extend(linked); + let rendered = rendered.to_straight(); + let flat = |px: &[u8; 4]| { + let a = u32::from(px[3]); + [0, 1, 2].map(|k| ((u32::from(px[k]) * a + u32::from(background[k]) * (255 - a) + 127) / 255) as u8) + }; + let row = iw as usize * 4; + let limit = threshold * 255.0; + let (mut squares, mut over) = (0.0f64, 0u64); + let mut diff = diff_path.map(|_| Vec::with_capacity(row * ih as usize)); + for (a, b) in rendered.chunks_exact(row).zip(image.as_raw().chunks_exact(row)) { + vectorcraft_doc::cancel::check()?; + for (pa, pb) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) { + let (fa, fb) = (flat(pa), flat(pb)); + let d = [0, 1, 2].map(|k| fa[k].abs_diff(fb[k])); + squares += d.iter().map(|&x| f64::from(x) * f64::from(x)).sum::(); + if d.iter().any(|&x| f64::from(x) > limit) { + over += 1; + } + if let Some(out) = &mut diff { + out.extend_from_slice(&[d[0], d[1], d[2], 255]); + } + } + } + let total = u64::from(iw) * u64::from(ih); + let rmse = (squares / (total as f64 * 3.0)).sqrt() / 255.0; + let mut out = json!({ + "width": iw, + "height": ih, + "rmse": (rmse * 1e6).round() / 1e6, + "over": over, + "total": total, + "threshold": threshold, + }); + if let (Some(d), Some(pixels)) = (diff_path, diff) { + let bytes = png::encode(&pixels, iw, ih, &png::PngOptions { ppi: None, interlaced: false }).map_err(EngineError::Other)?; + super::fileio::write_file(d, &bytes)?; + out["diffPath"] = json!(d); + } + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) +} + +/// The image `document.compare` reads from `path` (through the automation read root), as straight +/// RGBA: a PNG, JPEG, WebP, TIFF or BMP within the allocation an opened image may take. +#[cfg(not(target_arch = "wasm32"))] +fn compare_image(path: &str) -> Result { + use image::ImageDecoder as _; + const C: &str = "document.compare"; + let bytes = super::fileio::read_file(path)?; + if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(&bytes) { + return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw"))); + } + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(C, format!("{path}: {e}")))?; + let readable = [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::WebP, image::ImageFormat::Tiff, image::ImageFormat::Bmp]; + if !reader.format().is_some_and(|f| readable.contains(&f)) { + return Err(bad(C, format!("{path}: not a PNG, JPEG, WebP, TIFF or BMP image"))); + } + let mut limits = image::Limits::default(); + limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC); + reader.limits(limits); + let decoder = reader.into_decoder().map_err(|e| bad(C, format!("{path}: {e}")))?; + let (w, h) = decoder.dimensions(); + if decoder.total_bytes() > vectorcraft_doc::MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > vectorcraft_doc::MAX_RASTER_ALLOC { + return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw"))); + } + Ok(image::DynamicImage::from_decoder(decoder).map_err(|e| bad(C, format!("{path}: {e}")))?.to_rgba8()) +} + +#[cfg(target_arch = "wasm32")] +fn doc_compare(_: &mut Session, _: &Value) -> Result { + Err(bad("document.compare", "comparing with an image file isn't available in the browser")) +} + /// Document Setup's units (also `document.setup {units}`). fn set_units(s: &mut Session, p: &Value) -> Result { let u = str_param(p, "units").and_then(Unit::named).ok_or_else(|| bad("document.setUnits", "unknown units"))?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b9e247ed9b..b708c25ca0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -31,6 +31,7 @@ mod colorize; pub(super) mod colormgmt; mod colorthemes; mod colourfonts; +mod compare; mod compound_shape; mod compoundpaint; mod constrain_new; diff --git a/crates/engine/src/tests/compare.rs b/crates/engine/src/tests/compare.rs new file mode 100644 index 0000000000..03d788487f --- /dev/null +++ b/crates/engine/src/tests/compare.rs @@ -0,0 +1,276 @@ +//! `document.compare`: an artboard rendered at an image's size, as a PNG export draws it, and +//! measured against the image (RMSE, the pixels over a threshold, a difference image), with the +//! image and the render flattened on one background; images of other proportions, files that +//! can't be read and paths outside the automation roots are errors. + +use serde_json::{Value, json}; + +use crate::Session; + +/// A 40 × 20 pt document with a black 10 × 10 pt square at (10, 5), no stroke. +fn session() -> (Session, Value) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap()["id"].clone(); + (s, id) +} + +fn path_in(dir: &std::path::Path, name: &str) -> String { + dir.join(name).to_string_lossy().into_owned() +} + +/// The artboard exported as a PNG at 2 pixels a point on white. +fn export(s: &mut Session, path: &str) { + s.execute("document.export", &json!({"path": path, "format": "png", "scale": 2, "background": "white"})).unwrap(); +} + +fn compare(s: &mut Session, p: Value) -> Value { + s.execute("document.compare", &p).unwrap_or_else(|e| panic!("document.compare {p}: {e}")) +} + +fn error(s: &mut Session, p: Value) -> String { + s.execute("document.compare", &p).map(|v| panic!("document.compare {p} answered {v}")).unwrap_err().to_string() +} + +#[test] +fn an_export_compares_equal_and_a_moved_square_counts_the_pixels_it_changed() { + let dir = vectorcraft_testkit::temp_dir("compare-moved"); + let png = path_in(&dir, "art.png"); + let (mut s, id) = session(); + export(&mut s, &png); + let before = (s.doc().unwrap().revision, s.doc().unwrap().history.undo.len()); + let r = compare(&mut s, json!({"path": png})); + assert_eq!(r, json!({"width": 80, "height": 40, "rmse": 0.0, "over": 0, "total": 3200, "threshold": 0.08})); + assert_eq!((s.doc().unwrap().revision, s.doc().unwrap().history.undo.len()), before, "comparing doesn't edit the document"); + // 4 pt is 8 pixels: 8 columns of the square's 20 rows turn white and 8 turn black, every + // channel by 255. + s.execute("object.move", &json!({"ids": [id], "dx": 4, "dy": 0})).unwrap(); + let r = compare(&mut s, json!({"path": png})); + let over = 2 * 8 * 20; + assert_eq!((r["over"].as_u64(), r["total"].as_u64()), (Some(over), Some(3200)), "{r}"); + let rmse = ((over as f64 / 3200.0).sqrt() * 1e6).round() / 1e6; + assert_eq!(r["rmse"].as_f64(), Some(rmse), "{r}"); + // Above every difference, nothing is over. + assert_eq!(compare(&mut s, json!({"path": png, "threshold": 1}))["over"], json!(0)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_image_and_the_render_are_flattened_on_the_background() { + let dir = vectorcraft_testkit::temp_dir("compare-background"); + let png = path_in(&dir, "clear.png"); + // Transparent everywhere, with red in the color channels that the alpha hides. + image::RgbaImage::from_pixel(80, 40, image::Rgba([255, 0, 0, 0])).save(&png).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap(); + // Nothing drawn: both are the background alone. + for background in ["#808080", "#ffffff"] { + let r = compare(&mut s, json!({"path": png, "background": background})); + assert_eq!((r["rmse"].as_f64(), r["over"].as_u64()), (Some(0.0), Some(0)), "{background}: {r}"); + } + // A black left half: 128 from gray in every channel of half the pixels, 255 from white. + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + let r = compare(&mut s, json!({"path": png, "background": "#808080"})); + let rmse = |d: f64| ((0.5f64).sqrt() * d / 255.0 * 1e6).round() / 1e6; + assert_eq!((r["rmse"].as_f64(), r["over"].as_u64()), (Some(rmse(128.0)), Some(1600)), "{r}"); + let r = compare(&mut s, json!({"path": png})); + assert_eq!((r["rmse"].as_f64(), r["over"].as_u64()), (Some(rmse(255.0)), Some(1600)), "{r}"); + // A threshold just above 128/255 leaves the gray differences out. + assert_eq!(compare(&mut s, json!({"path": png, "background": "#808080", "threshold": 0.51}))["over"], json!(0)); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_image_of_other_proportions_is_refused_and_one_pixel_is_allowed() { + let dir = vectorcraft_testkit::temp_dir("compare-size"); + let (mut s, _) = session(); + let square = path_in(&dir, "square.png"); + image::RgbaImage::from_pixel(30, 30, image::Rgba([255; 4])).save(&square).unwrap(); + let e = error(&mut s, json!({"path": square})); + assert!(e.contains("30 × 30 pixels") && e.contains("30 × 15 pixels"), "{e}"); + let taller = path_in(&dir, "taller.png"); + image::RgbaImage::from_pixel(80, 41, image::Rgba([255; 4])).save(&taller).unwrap(); + let r = compare(&mut s, json!({"path": taller})); + assert_eq!((r["width"].as_u64(), r["height"].as_u64(), r["total"].as_u64()), (Some(80), Some(41), Some(3280)), "{r}"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_export_whose_height_was_rounded_compares_equal() { + let dir = vectorcraft_testkit::temp_dir("compare-rounded"); + let png = path_in(&dir, "art.png"); + // 20.25 pt at 2 pixels a point is 40.5 rows, which the export rounds to 41. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 20.25})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap(); + export(&mut s, &png); + let r = compare(&mut s, json!({"path": png})); + assert_eq!(r, json!({"width": 80, "height": 41, "rmse": 0.0, "over": 0, "total": 3280, "threshold": 0.08})); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_linked_image_is_drawn_from_its_file_as_a_png_export_draws_it() { + use crate::tests_links::{BLUE, Folder, RED, open, place, png, save, session, write}; + let dir = Folder::new("compare-linked"); + let pic = dir.file("photo.png"); + write(&pic, &png(600, 300, RED)); + let mut s = session(); + place(&mut s, &pic); + let doc_path = dir.file("poster.vectorcraft"); + save(&mut s, &doc_path); + // The file changes after the save: the reopened document shows the red preview saved for it, + // and a PNG export reads the blue file. + write(&pic, &png(600, 300, BLUE)); + open(&mut s, &doc_path); + let out = dir.file("export.png"); + s.execute("document.export", &json!({"path": out, "format": "png", "background": "white"})).unwrap(); + let r = compare(&mut s, json!({"path": out})); + assert_eq!((r["rmse"].as_f64(), r["over"].as_u64(), r.get("warnings")), (Some(0.0), Some(0), None), "{r}"); + // Without the file the preview is drawn, and the reply says so. + std::fs::remove_file(&pic).unwrap(); + let r = compare(&mut s, json!({"path": out})); + assert_eq!(r["over"].as_u64(), r["total"].as_u64(), "{r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.len() == 1 && warnings[0].as_str().unwrap().contains("output as their previews"), "{r}"); + // With type that doesn't fit its frame as well, the warnings come in the export's order. + let overset = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "size": 12, "area": {"width": 100, "height": 20}})).unwrap(); + assert_eq!(overset["overflow"], json!([overset["id"]]), "{overset}"); + let exported = s.execute("document.export", &json!({"path": dir.file("now.png"), "format": "png", "background": "white"})).unwrap(); + let r = compare(&mut s, json!({"path": out})); + assert_eq!(r["warnings"].as_array().map(Vec::len), Some(2), "{r}"); + assert_eq!(r["warnings"], exported["warnings"], "{r}"); +} + +#[test] +fn an_image_that_cannot_be_decoded_and_a_missing_font_warn_as_a_png_export_does() { + let dir = vectorcraft_testkit::temp_dir("compare-warnings"); + let png = path_in(&dir, "art.png"); + let (mut s, _) = session(); + export(&mut s, &png); + assert_eq!(compare(&mut s, json!({"path": png})).get("warnings"), None); + crate::tests_menucmds::place_undecodable_png(&mut s); + s.execute("text.create", &json!({"x": 2, "y": 18, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap(); + let overset = s.execute("text.create", &json!({"x": 22, "y": 2, "text": "Ab\nCd\nEf", "size": 6, "area": {"width": 15, "height": 8}})).unwrap(); + assert_eq!(overset["overflow"], json!([overset["id"]]), "{overset}"); + let exported = s.execute("document.export", &json!({"path": path_in(&dir, "now.png"), "format": "png", "scale": 2})).unwrap(); + let r = compare(&mut s, json!({"path": png})); + assert_eq!(r["warnings"], exported["warnings"], "{r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w == "an image couldn't be decoded and is missing from the picture"), "{r}"); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nonexistent Sans Probe")), "{r}"); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("doesn't fit its frame")), "{r}"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn diff_path_writes_each_pixels_differences() { + let dir = vectorcraft_testkit::temp_dir("compare-diff"); + let png = path_in(&dir, "art.png"); + let diff = path_in(&dir, "diff.png"); + let (mut s, id) = session(); + export(&mut s, &png); + s.execute("object.move", &json!({"ids": [id], "dx": 4, "dy": 0})).unwrap(); + let r = compare(&mut s, json!({"path": png, "diffPath": diff})); + assert_eq!(r["diffPath"], json!(diff)); + let img = image::open(&diff).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (80, 40)); + // The square spanned pixels 20–39 and now spans 28–47, rows 10–29. + for (x, y, want) in [(24, 20, 255), (44, 20, 255), (30, 20, 0), (24, 5, 0), (60, 20, 0)] { + assert_eq!(img.get_pixel(x, y).0, [want, want, want, 255], "({x}, {y})"); + } + let changed = img.pixels().filter(|p| p.0[0] != 0).count(); + assert_eq!(changed as u64, r["over"].as_u64().unwrap()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn missing_unreadable_and_malformed_inputs_are_errors() { + let dir = vectorcraft_testkit::temp_dir("compare-errors"); + let (mut s, _) = session(); + let png = path_in(&dir, "art.png"); + export(&mut s, &png); + let missing = path_in(&dir, "missing.png"); + assert!(error(&mut s, json!({"path": missing})).contains(&missing)); + let text = path_in(&dir, "notes.png"); + std::fs::write(&text, "not an image\n").unwrap(); + assert!(error(&mut s, json!({"path": text})).contains("not a PNG, JPEG, WebP, TIFF or BMP image")); + let gif = path_in(&dir, "art.gif"); + image::RgbaImage::from_pixel(80, 40, image::Rgba([255; 4])).save(&gif).unwrap(); + assert!(error(&mut s, json!({"path": gif})).contains("not a PNG, JPEG, WebP, TIFF or BMP image")); + for (p, want) in [ + (json!({}), "missing `path`"), + (json!({"path": png, "artboard": 3}), "no artboard 3"), + (json!({"path": png, "threshold": 2}), "`threshold` must be a number from 0 to 1"), + (json!({"path": png, "threshold": "low"}), "`threshold` must be a number from 0 to 1"), + (json!({"path": png, "background": "transparent"}), "a color such as"), + (json!({"path": png, "diffPath": 5}), "`diffPath` must be a string"), + ] { + let e = error(&mut s, p.clone()); + assert!(e.contains(want), "{p}: {e}"); + } + let _ = std::fs::remove_dir_all(dir); +} + +/// A planar TIFF whose header claims more strips than the decoder can count (2^31 + 1 rows a strip +/// each, times 5 planes) is refused as too large to draw, without a panic. +#[test] +fn a_tiff_with_more_strips_than_can_be_counted_is_too_large() { + let dir = vectorcraft_testkit::temp_dir("compare-strips"); + let (mut s, _) = session(); + let plane = |v: u16| vec![v; 6]; + let channels = [plane(200), plane(40), plane(10), plane(0), plane(90)]; + let t = vectorcraft_testkit::tiff::Tiff { + width: 3, + height: 2, + photometric: 5, + bits: 8, + extra: &[0], + planar: true, + ppi: Some(150), + channels: &channels, + }; + let mut file = vectorcraft_testkit::tiff::tiff(&t); + // ImageLength (the directory's second entry, its value at offset 30) and RowsPerStrip (the + // eighth, at offset 102). + file[30..34].copy_from_slice(&(1u32 << 31 | 1).to_le_bytes()); + file[102..106].copy_from_slice(&1u32.to_le_bytes()); + assert_eq!(vectorcraft_doc::cmyk::oversized_tiff(&file), Some((3, 1 << 31 | 1))); + let tif = path_in(&dir, "strips.tif"); + std::fs::write(&tif, &file).unwrap(); + let e = error(&mut s, json!({"path": tif})); + assert_eq!(e, "invalid parameters for `document.compare`: an image of 3 × 2147483649 pixels is too large to draw"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_image_and_the_difference_image_stay_inside_the_automation_roots() { + let dir = vectorcraft_testkit::temp_dir("compare-roots"); + for d in ["in", "out", "elsewhere"] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let (mut s, _) = session(); + let inside = path_in(&dir.join("in"), "art.png"); + let outside = path_in(&dir.join("elsewhere"), "art.png"); + export(&mut s, &inside); + export(&mut s, &outside); + let roots = crate::file_access::AutomationRoots::new(&[&dir.join("in")], &[&dir.join("out")]).unwrap().unwrap(); + let mut run = |p: Value| crate::file_access::confine(Some(&roots), || s.execute("document.compare", &p)); + assert!(run(json!({"path": inside})).is_ok()); + let e = run(json!({"path": outside})).unwrap_err().to_string(); + assert!(e.contains("outside the read root"), "{e}"); + let stray = path_in(&dir.join("elsewhere"), "diff.png"); + let e = run(json!({"path": inside, "diffPath": stray})).unwrap_err().to_string(); + assert!(e.contains("outside the write root"), "{e}"); + assert!(!std::path::Path::new(&stray).exists()); + let kept = path_in(&dir.join("out"), "diff.png"); + assert_eq!(run(json!({"path": inside, "diffPath": kept})).unwrap()["diffPath"], json!(kept)); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index e9a219bd54..8bdbf65a92 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1140,6 +1140,7 @@ font-technology Variable Променливи Find Font… Търсене на шрифт… Find Next Търсене на следващ Find Objects Търсене на обекти + Compare with Image Сравняване с изображение First Page Първа страница First-line Left Indent Ляв отстъп на първи ред Fisheye… Рибено око… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ea246b35c8..68c1e81b00 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1580,6 +1580,7 @@ digits Malayalam Malaiàlam Find Linked Files in Folder… Cerca fitxers enllaçats en una carpeta… Find Next Cerca el següent Find Objects Cerca objectes + Compare with Image Compara amb una imatge Fine Dots Punts fins Fine noise hides banding in the gradient fill El soroll fi amaga l’efecte de bandes del farciment de degradat First Primer @@ -5006,6 +5007,11 @@ digits Malayalam Malaiàlam @msg an image has no pixels and was left out una imatge no té píxels i s’ha omès @msg an image of {w} × {h} pixels is shown at reduced size una imatge de {w} × {h} píxels es mostra a mida reduïda @msg an image of {w} × {h} pixels is too large to draw una imatge de {w} × {h} píxels és massa gran per dibuixar-la +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: no és una imatge PNG, JPEG, WebP, TIFF ni BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ la imatge fa {iw} × {ih} píxels i el tauler a aquesta amplada fa {rw} × {rh} píxels: les proporcions són diferents +@msg `threshold` must be a number from 0 to 1 `threshold` ha de ser un nombre de 0 a 1 +@msg background {v}: a color such as "#808080" fons {v}: un color com "#808080" +@msg comparing with an image file isn't available in the browser la comparació amb un fitxer d’imatge no està disponible al navegador @msg an image VectorCraft can't read was left out s’ha omès una imatge que VectorCraft no pot llegir @msg graphs come in as plain art, without their data or settings els gràfics s’importen com a il·lustració normal, sense les seves dades ni la seva configuració @msg an image whose data is cut short was left out s’ha omès una imatge les dades de la qual estan tallades diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e51de2442..e74e240d7b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3316,6 +3316,7 @@ theme Appearance Motiv Document JSON JSON dokumentu Duplicate Duplikovat Find Objects Najít objekty + Compare with Image Porovnat s obrazem Inspect Document Prozkoumat dokument Inspect Object Prozkoumat objekt Begin Undo Group Zahájit skupinu kroků zpět @@ -5512,6 +5513,11 @@ mark-style Japanese Japonské @msg unknown parameter `{key}`; the command takes: {keys} neznámý parametr `{key}`; příkaz přijímá: {keys} Load EPS into Clipboard Načíst EPS do schránky @msg an image of {w} × {h} pixels is too large to draw obraz o velikosti {w} × {h} obrazových bodů je příliš velký na vykreslení +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: není obraz PNG, JPEG, WebP, TIFF ani BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ obraz má {iw} × {ih} obrazových bodů a pracovní plocha v této šířce má {rw} × {rh} obrazových bodů: jejich proporce se liší +@msg `threshold` must be a number from 0 to 1 `threshold` musí být číslo od 0 do 1 +@msg background {v}: a color such as "#808080" pozadí {v}: barva jako "#808080" +@msg comparing with an image file isn't available in the browser porovnání se souborem obrazu není v prohlížeči k dispozici @msg an image of {w} × {h} pixels is shown at reduced size obraz o velikosti {w} × {h} obrazových bodů se zobrazuje ve zmenšené velikosti @msg the image can't be read as a texture obraz nelze načíst jako texturu Fill and Stroke Controls Ovládací prvky výplně a tahu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 84134c8933..d50e862bbe 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3058,6 +3058,7 @@ theme Appearance Udseende Document JSON Dokument-JSON Duplicate Duplikér Find Objects Find objekter + Compare with Image Sammenlign med billede Inspect Document Inspicér dokument Inspect Object Inspicér objekt Begin Undo Group Start fortrydelsesgruppe diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7d0e48fb84..2da4241515 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1155,6 +1155,7 @@ font-technology Variable Variabel Find Font… Schrift suchen… Find Next Weitersuchen Find Objects Objekte suchen + Compare with Image Mit Bild vergleichen First Page Erste Seite First-line Left Indent Einzug links in erster Zeile Fisheye… Fischauge… @@ -5078,6 +5079,11 @@ lighting Light Licht @msg unknown parameter `{key}`; the command takes: {keys} unbekannter Parameter `{key}`; der Befehl akzeptiert: {keys} Load EPS into Clipboard EPS in die Zwischenablage laden @msg an image of {w} × {h} pixels is too large to draw ein Bild mit {w} × {h} Pixeln ist zu groß, um gezeichnet zu werden +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: kein PNG-, JPEG-, WebP-, TIFF- oder BMP-Bild +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ das Bild hat {iw} × {ih} Pixel und die Zeichenfläche in dieser Breite {rw} × {rh} Pixel: ihre Proportionen unterscheiden sich +@msg `threshold` must be a number from 0 to 1 `threshold` muss eine Zahl von 0 bis 1 sein +@msg background {v}: a color such as "#808080" background {v}: eine Farbe wie "#808080" +@msg comparing with an image file isn't available in the browser der Vergleich mit einer Bilddatei ist im Browser nicht verfügbar @msg an image of {w} × {h} pixels is shown at reduced size ein Bild mit {w} × {h} Pixeln wird verkleinert angezeigt @msg the image can't be read as a texture das Bild kann nicht als Struktur gelesen werden Basic Basis diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index be001e2fb7..4d713dfedf 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1113,6 +1113,7 @@ font-technology Variable Μεταβλητές Find Font… Εύρεση γραμματοσειράς… Find Next Εύρεση επόμενου Find Objects Εύρεση αντικειμένων + Compare with Image Σύγκριση με εικόνα First Page Πρώτη σελίδα First-line Left Indent Αριστερή εσοχή πρώτης γραμμής Fisheye… Εφέ ματιού ψαριού… @@ -5256,6 +5257,11 @@ effect Points Σημεία Load EPS into Clipboard Φόρτωση EPS στο πρόχειρο @msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode Άγνωστο στοιχείο ελέγχου `{name}`: fillStroke, coloring, drawMode ή screenMode @msg an image of {w} × {h} pixels is too large to draw Η εικόνα {w} × {h} εικονοστοιχείων είναι υπερβολικά μεγάλη για σχεδίαση +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: δεν είναι εικόνα PNG, JPEG, WebP, TIFF ή BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ η εικόνα είναι {iw} × {ih} εικονοστοιχεία και ο πίνακας σχεδίασης σε αυτό το πλάτος είναι {rw} × {rh} εικονοστοιχεία: οι αναλογίες τους διαφέρουν +@msg `threshold` must be a number from 0 to 1 Το `threshold` πρέπει να είναι αριθμός από 0 έως 1 +@msg background {v}: a color such as "#808080" φόντο {v}: χρώμα όπως "#808080" +@msg comparing with an image file isn't available in the browser η σύγκριση με αρχείο εικόνας δεν είναι διαθέσιμη στο πρόγραμμα περιήγησης @msg an image of {w} × {h} pixels is shown at reduced size Η εικόνα {w} × {h} εικονοστοιχείων εμφανίζεται σε μειωμένο μέγεθος Open Recent File 1 Άνοιγμα πρόσφατου αρχείου 1 Open Recent File 2 Άνοιγμα πρόσφατου αρχείου 2 diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 930ecf0908..8c00c78d2b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1184,6 +1184,7 @@ font-technology Variable Variables Find Font… Buscar fuente… Find Next Buscar siguiente Find Objects Buscar objetos + Compare with Image Comparar con imagen First Page Primera página First-line Left Indent Sangría izquierda en primera línea Fisheye… Ojo de pez… @@ -5452,6 +5453,11 @@ mark-style Japanese Japonesas @msg unknown parameter `{key}`; the command takes: {keys} parámetro desconocido `{key}`; el comando acepta: {keys} Load EPS into Clipboard Cargar EPS en el portapapeles @msg an image of {w} × {h} pixels is too large to draw una imagen de {w} × {h} píxeles es demasiado grande para dibujarse +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: no es una imagen PNG, JPEG, WebP, TIFF ni BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ la imagen mide {iw} × {ih} píxeles y la mesa de trabajo a ese ancho mide {rw} × {rh} píxeles: sus proporciones difieren +@msg `threshold` must be a number from 0 to 1 `threshold` debe ser un número de 0 a 1 +@msg background {v}: a color such as "#808080" fondo {v}: un color como "#808080" +@msg comparing with an image file isn't available in the browser la comparación con un archivo de imagen no está disponible en el navegador @msg an image of {w} × {h} pixels is shown at reduced size una imagen de {w} × {h} píxeles se muestra a tamaño reducido @msg the image can't be read as a texture la imagen no se puede leer como textura Fill and Stroke Controls Controles de relleno y trazo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 99594975db..3491ca30a4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3254,6 +3254,7 @@ theme Appearance Ulkoasu Document JSON Asiakirjan JSON Duplicate Monista Find Objects Etsi objekteja + Compare with Image Vertaa kuvaan Inspect Document Tarkastele asiakirjaa Inspect Object Tarkastele objektia Begin Undo Group Aloita kumoamisryhmä @@ -5396,6 +5397,11 @@ mark-style Japanese Japanilainen @msg unknown parameter `{key}`; the command takes: {keys} tuntematon parametri `{key}`; komennon parametrit: {keys} Load EPS into Clipboard Lataa EPS leikepöydälle @msg an image of {w} × {h} pixels is too large to draw kuva, jonka koko on {w} × {h} pikseliä, on liian suuri piirrettäväksi +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: ei ole PNG-, JPEG-, WebP-, TIFF- tai BMP-kuva +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ kuva on {iw} × {ih} pikseliä ja piirtoalusta tällä leveydellä {rw} × {rh} pikseliä: niiden mittasuhteet eroavat +@msg `threshold` must be a number from 0 to 1 `threshold` on oltava luku väliltä 0–1 +@msg background {v}: a color such as "#808080" tausta {v}: väri, kuten "#808080" +@msg comparing with an image file isn't available in the browser vertailu kuvatiedostoon ei ole käytettävissä selaimessa @msg an image of {w} × {h} pixels is shown at reduced size kuva, jonka koko on {w} × {h} pikseliä, näytetään pienennettynä Fill and Stroke Controls Täytön ja viivan säätimet Coloring Controls Värityksen säätimet diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1aebc348d0..539c0f3ae9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1178,6 +1178,7 @@ font-technology Variable Variables Find Font… Rechercher une police… Find Next Rechercher le suivant Find Objects Rechercher des objets + Compare with Image Comparer à une image First Page Première page First-line Left Indent Retrait gauche de première ligne Fisheye… Fish-eye… @@ -5508,6 +5509,11 @@ mark-style Japanese Japonais theme Appearance Apparence Load EPS into Clipboard Charger un EPS dans le presse-papiers @msg an image of {w} × {h} pixels is too large to draw une image de {w} × {h} pixels est trop grande pour être dessinée +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path} : ce n’est pas une image PNG, JPEG, WebP, TIFF ou BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ l’image fait {iw} × {ih} pixels et le plan de travail à cette largeur fait {rw} × {rh} pixels : leurs proportions diffèrent +@msg `threshold` must be a number from 0 to 1 `threshold` doit être un nombre de 0 à 1 +@msg background {v}: a color such as "#808080" arrière-plan {v} : une couleur comme "#808080" +@msg comparing with an image file isn't available in the browser la comparaison avec un fichier image n’est pas disponible dans le navigateur @msg an image of {w} × {h} pixels is shown at reduced size une image de {w} × {h} pixels est affichée en taille réduite @msg the image can't be read as a texture l'image ne peut pas être lue comme texture Fill and Stroke Controls Commandes de fond et de contour diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a400c495fb..247ffc64ec 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1484,6 +1484,7 @@ digits Malayalam Malajálam Find in Folder… Keresés mappában… Find Next Következő keresése Find Objects Objektumok keresése + Compare with Image Összehasonlítás képpel Fine Dots Finom pontok Simple Egyszerű @@ -5495,6 +5496,11 @@ imageTrace Outline Körvonal @msg unknown parameter `{key}`; the command takes: {keys} ismeretlen paraméter: `{key}`; a parancs ezeket fogadja el: {keys} Load EPS into Clipboard EPS betöltése a vágólapra @msg an image of {w} × {h} pixels is too large to draw egy {w} × {h} pixeles kép túl nagy a kirajzoláshoz +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: nem PNG, JPEG, WebP, TIFF vagy BMP kép +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ a kép {iw} × {ih} pixeles, a rajztábla ilyen szélességben {rw} × {rh} pixeles: az arányaik eltérnek +@msg `threshold` must be a number from 0 to 1 a `threshold` értéke 0 és 1 közötti szám lehet +@msg background {v}: a color such as "#808080" background {v}: egy szín, például "#808080" +@msg comparing with an image file isn't available in the browser a képfájllal való összehasonlítás a böngészőben nem érhető el @msg an image of {w} × {h} pixels is shown at reduced size egy {w} × {h} pixeles kép csökkentett méretben jelenik meg @msg the image can't be read as a texture a kép nem olvasható be textúraként Fill and Stroke Controls Kitöltés és körvonal vezérlői diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0134649ea2..4d03770830 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3058,6 +3058,7 @@ theme Appearance Tampilan Document JSON JSON dokumen Duplicate Duplikatkan Find Objects Cari objek + Compare with Image Bandingkan dengan gambar Inspect Document Periksa dokumen Inspect Object Periksa objek Begin Undo Group Mulai grup urungkan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b19e01f96b..44da4c994d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1185,6 +1185,7 @@ font-technology Variable Variabili Find Font… Trova font… Find Next Trova successivo Find Objects Trova oggetti + Compare with Image Confronta con immagine First Page Prima pagina First-line Left Indent Rientro sinistro prima riga Fisheye… Occhio di pesce… @@ -5120,6 +5121,11 @@ lighting Light Luce @msg unknown parameter `{key}`; the command takes: {keys} parametro sconosciuto `{key}`; il comando accetta: {keys} Load EPS into Clipboard Carica EPS negli appunti @msg an image of {w} × {h} pixels is too large to draw un'immagine di {w} × {h} pixel è troppo grande per essere disegnata +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: non è un'immagine PNG, JPEG, WebP, TIFF o BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ l'immagine è di {iw} × {ih} pixel e la tavola da disegno a quella larghezza è di {rw} × {rh} pixel: le proporzioni sono diverse +@msg `threshold` must be a number from 0 to 1 `threshold` deve essere un numero da 0 a 1 +@msg background {v}: a color such as "#808080" sfondo {v}: un colore come "#808080" +@msg comparing with an image file isn't available in the browser il confronto con un file immagine non è disponibile nel browser @msg an image of {w} × {h} pixels is shown at reduced size un'immagine di {w} × {h} pixel viene mostrata a dimensioni ridotte @msg the image can't be read as a texture l'immagine non può essere letta come texture Basic Base diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 77d50e0a81..07577badfe 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -154,6 +154,7 @@ digits Malayalam マラヤーラム数字 Find and Replace… 検索と置換… Find Next 次を検索 Find Objects オブジェクトを検索 + Compare with Image 画像と比較 Spelling スペルチェック Auto Spell Check 自動スペルチェック Check Spelling… スペルチェック… @@ -5162,6 +5163,11 @@ lighting Light ライト @msg unknown parameter `{key}`; the command takes: {keys} `{key}` は不明なパラメーターです。このコマンドで使えるパラメーター: {keys} Load EPS into Clipboard EPS をクリップボードに読み込む @msg an image of {w} × {h} pixels is too large to draw {w} × {h} ピクセルの画像は大きすぎて描画できません +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: PNG、JPEG、WebP、TIFF、BMP のいずれの画像でもありません +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ 画像は {iw} × {ih} ピクセルで、その幅でのアートボードは {rw} × {rh} ピクセルです: 縦横比が異なります +@msg `threshold` must be a number from 0 to 1 `threshold` には 0 から 1 までの数値を指定してください +@msg background {v}: a color such as "#808080" 背景に {v} は指定できません: 「#808080」のようなカラーを指定してください +@msg comparing with an image file isn't available in the browser 画像ファイルとの比較はブラウザーでは使用できません @msg an image of {w} × {h} pixels is shown at reduced size {w} × {h} ピクセルの画像は縮小して表示されます @msg the image can't be read as a texture この画像はテクスチャとして読み込めません Basic 基本 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c710ee3c54..6a5581ed4f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2876,6 +2876,7 @@ theme Appearance იერსახე Document JSON დოკუმენტის JSON Duplicate დუბლირება Find Objects ობიექტების ძებნა + Compare with Image გამოსახულებასთან შედარება Inspect Document დოკუმენტის შემოწმება Inspect Object ობიექტის შემოწმება Begin Undo Group დაბრუნების ჯგუფის დაწყება @@ -5049,6 +5050,11 @@ imageTrace Outline კონტური @msg {path}: not a file {path}: ფაილი არ არის Load EPS into Clipboard EPS-ის ბუფერში ჩატვირთვა @msg an image of {w} × {h} pixels is too large to draw {w} × {h} პიქსელის გამოსახულება დასახატად ზედმეტად დიდია +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: არ არის PNG, JPEG, WebP, TIFF ან BMP გამოსახულება +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ გამოსახულება არის {iw} × {ih} პიქსელი, ხოლო სამუშაო დაფა ამ სიგანეზე არის {rw} × {rh} პიქსელი: მათი პროპორციები განსხვავდება +@msg `threshold` must be a number from 0 to 1 `threshold` უნდა იყოს რიცხვი 0-დან 1-მდე +@msg background {v}: a color such as "#808080" ფონი {v}: ფერი, მაგალითად "#808080" +@msg comparing with an image file isn't available in the browser გამოსახულების ფაილთან შედარება ბრაუზერში მიუწვდომელია @msg an image of {w} × {h} pixels is shown at reduced size {w} × {h} პიქსელის გამოსახულება შემცირებული ზომით ჩანს A later row takes this shortcut ამ მალსახმობს ქვემოთა სტრიქონი იყენებს Add to the Current Shortcuts მიმდინარე მალსახმობებზე დამატება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c0545a3da7..cce6ce736a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -147,6 +147,7 @@ digits Malayalam 말라얄람어 Find and Replace… 찾기 및 바꾸기… Find Next 다음 찾기 Find Objects 개체 찾기 + Compare with Image 이미지와 비교 Spelling 맞춤법 Auto Spell Check 자동 맞춤법 검사 Check Spelling… 맞춤법 검사… @@ -5081,6 +5082,11 @@ lighting Light 광원 @msg unknown parameter `{key}`; the command takes: {keys} 알 수 없는 매개변수 `{key}`: 이 명령이 받는 매개변수: {keys} Load EPS into Clipboard EPS를 클립보드로 불러오기 @msg an image of {w} × {h} pixels is too large to draw {w} × {h}픽셀 이미지는 너무 커서 그릴 수 없습니다 +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: PNG, JPEG, WebP, TIFF 또는 BMP 이미지가 아닙니다 +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ 이미지는 {iw} × {ih}픽셀이고 그 너비에서 아트보드는 {rw} × {rh}픽셀입니다: 비율이 다릅니다 +@msg `threshold` must be a number from 0 to 1 `threshold`은(는) 0에서 1 사이의 숫자여야 합니다 +@msg background {v}: a color such as "#808080" 배경 {v}: "#808080" 같은 색상이어야 합니다 +@msg comparing with an image file isn't available in the browser 이미지 파일과 비교하는 기능은 브라우저에서 사용할 수 없습니다 @msg an image of {w} × {h} pixels is shown at reduced size {w} × {h}픽셀 이미지는 축소된 크기로 표시됩니다 @msg the image can't be read as a texture 이미지를 텍스처로 읽을 수 없습니다 Basic 기본 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 72d4ea21ae..bd525526b9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3072,6 +3072,7 @@ theme Appearance Vormgeving Document JSON Document-JSON Duplicate Dupliceren Find Objects Objecten zoeken + Compare with Image Vergelijken met afbeelding Inspect Document Document inspecteren Inspect Object Object inspecteren Begin Undo Group Groep voor ongedaan maken beginnen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ff2b9bd6b0..adfb669e8d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3195,6 +3195,7 @@ theme Appearance Wygląd Document JSON JSON dokumentu Duplicate Powiel Find Objects Znajdź obiekty + Compare with Image Porównaj z obrazem Inspect Document Zbadaj dokument Inspect Object Zbadaj obiekt Begin Undo Group Rozpocznij grupę cofania @@ -5350,6 +5351,11 @@ mark-style Japanese Japońskie @msg unknown parameter `{key}`; the command takes: {keys} nieznany parametr `{key}`; polecenie przyjmuje: {keys} Load EPS into Clipboard Wczytaj EPS do schowka @msg an image of {w} × {h} pixels is too large to draw obraz o wymiarach {w} × {h} pikseli jest zbyt duży, aby go narysować +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: to nie jest obraz PNG, JPEG, WebP, TIFF ani BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ obraz ma {iw} × {ih} pikseli, a obszar kompozycji przy tej szerokości ma {rw} × {rh} pikseli: ich proporcje się różnią +@msg `threshold` must be a number from 0 to 1 `threshold` musi być liczbą od 0 do 1 +@msg background {v}: a color such as "#808080" tło {v}: kolor, np. "#808080" +@msg comparing with an image file isn't available in the browser porównywanie z plikiem obrazu nie jest dostępne w przeglądarce @msg an image of {w} × {h} pixels is shown at reduced size obraz o wymiarach {w} × {h} pikseli jest wyświetlany w zmniejszonym rozmiarze Basic Podstawowy Fill and Stroke Controls Elementy sterujące wypełnieniem i obrysem diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 3340597d8d..183d41dc18 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3343,6 +3343,7 @@ font-technology Variable Variáveis Favorites Favoritos Fill (X), double-click for the Color Picker Preenchimento (X), clique duas vezes para o seletor de cores Find Objects Localizar objetos + Compare with Image Comparar com imagem Flare Tool Options Opções da ferramenta Reflexo Halo Halo Rays Raios @@ -5447,6 +5448,11 @@ mark-style Japanese Japonesas @msg The shape is too complex for a 3D effect A forma é complexa demais para um efeito 3D @msg The 3D surface is too complex; simplify the shape A superfície 3D é complexa demais; simplifique a forma @msg an image of {w} × {h} pixels is too large to draw uma imagem de {w} × {h} pixels é grande demais para ser desenhada +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: não é uma imagem PNG, JPEG, WebP, TIFF ou BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ a imagem tem {iw} × {ih} pixels e a prancheta nessa largura tem {rw} × {rh} pixels: as proporções são diferentes +@msg `threshold` must be a number from 0 to 1 `threshold` deve ser um número de 0 a 1 +@msg background {v}: a color such as "#808080" plano de fundo {v}: uma cor como "#808080" +@msg comparing with an image file isn't available in the browser a comparação com um arquivo de imagem não está disponível no navegador @msg an image of {w} × {h} pixels is shown at reduced size uma imagem de {w} × {h} pixels é exibida em tamanho reduzido Fill and Stroke Controls Controles de Preenchimento e Traçado Coloring Controls Controles de Coloração diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3732558f7e..544050c9a4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1182,6 +1182,7 @@ font-technology Variable Вариативные Find Font… Найти шрифт… Find Next Найти далее Find Objects Найти объекты + Compare with Image Сравнить с изображением First Page Первая страница First-line Left Indent Отступ слева в первой строке Fisheye… Рыбий глаз… @@ -5115,6 +5116,11 @@ lighting Light Свет @msg unknown parameter `{key}`; the command takes: {keys} неизвестный параметр `{key}`; команда принимает: {keys} Load EPS into Clipboard Загрузить EPS в буфер обмена @msg an image of {w} × {h} pixels is too large to draw изображение размером {w} × {h} пикселей слишком велико для отрисовки +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: это не изображение PNG, JPEG, WebP, TIFF или BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ размер изображения {iw} × {ih} пикселей, а монтажной области при этой ширине {rw} × {rh} пикселей: их пропорции различаются +@msg `threshold` must be a number from 0 to 1 `threshold` должно быть числом от 0 до 1 +@msg background {v}: a color such as "#808080" фон {v}: цвет, например "#808080" +@msg comparing with an image file isn't available in the browser сравнение с файлом изображения недоступно в браузере @msg an image of {w} × {h} pixels is shown at reduced size изображение размером {w} × {h} пикселей показано в уменьшенном размере @msg the image can't be read as a texture изображение не удаётся прочитать как текстуру Basic Базовый diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 58ceab7016..f007400d9c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1148,6 +1148,7 @@ font-technology Variable Variabla Find Font… Sök typsnitt… Find Next Sök nästa Find Objects Sök objekt + Compare with Image Jämför med bild First Page Första sidan First-line Left Indent Vänsterindrag för första raden Fisheye… Fisköga… @@ -5412,6 +5413,11 @@ mark-style Japanese Japanska theme Appearance Utseende Load EPS into Clipboard Läs in EPS till urklipp @msg an image of {w} × {h} pixels is too large to draw en bild på {w} × {h} pixlar är för stor för att ritas +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: inte en PNG-, JPEG-, WebP-, TIFF- eller BMP-bild +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ bilden är {iw} × {ih} pixlar och ritytan i den bredden är {rw} × {rh} pixlar: proportionerna skiljer sig åt +@msg `threshold` must be a number from 0 to 1 `threshold` måste vara ett tal från 0 till 1 +@msg background {v}: a color such as "#808080" background {v}: en färg som "#808080" +@msg comparing with an image file isn't available in the browser jämförelse med en bildfil är inte tillgänglig i webbläsaren @msg an image of {w} × {h} pixels is shown at reduced size en bild på {w} × {h} pixlar visas i förminskad storlek Fill and Stroke Controls Kontroller för fyllning och kontur Coloring Controls Kontroller för färgläggning diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9385b30cc2..3c28f018cb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1137,6 +1137,7 @@ font-technology Variable Değişken Find Font… Yazı Tipi Bul… Find Next Sonrakini Bul Find Objects Nesneleri Bul + Compare with Image Görüntüyle Karşılaştır First Page İlk Sayfa First-line Left Indent Birinci Satırda Sol Girinti Fisheye… Balıkgözü… @@ -4017,6 +4018,11 @@ axis Both Her İkisi @msg invalid image data for `{0}` `{0}` için geçersiz resim verileri @msg invalid parameters for `{cmd}`: {msg} `{cmd}` için geçersiz parametreler: {msg} @msg is not an image VectorCraft reads VectorCraft'ın okuduğu bir resim değil +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: PNG, JPEG, WebP, TIFF veya BMP resmi değil +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ resim {iw} × {ih} piksel, çalışma yüzeyi bu genişlikte {rw} × {rh} piksel: oranları farklı +@msg `threshold` must be a number from 0 to 1 `threshold` 0 ile 1 arasında bir sayı olmalıdır +@msg background {v}: a color such as "#808080" background {v}: "#808080" gibi bir renk +@msg comparing with an image file isn't available in the browser bir resim dosyasıyla karşılaştırma tarayıcıda kullanılamaz @msg it uses `{at}`, which VectorCraft's PostScript reader doesn't know VectorCraft'ın PostScript okuyucusunun bilmediği `{at}`yi kullanıyor @msg it uses `{at}`, which VectorCraft's PostScript reader doesn't know, in {procs} {procs}'de VectorCraft'ın PostScript okuyucusunun bilmediği `{at}`yi kullanıyor @msg its Windows metafile preview was opened instead, which may simplify the art bunun yerine Windows meta dosyası önizlemesi açıldı, bu da işi basitleştirebilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1b96c235e8..7de17b0fc2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1179,6 +1179,7 @@ font-technology Variable Варіативні Find Font… Знайти шрифт… Find Next Знайти далі Find Objects Знайти об’єкти + Compare with Image Порівняти із зображенням First Page Перша сторінка First-line Left Indent Відступ ліворуч у першому рядку Fisheye… Риб’яче око… @@ -5100,6 +5101,11 @@ lighting Light Світло @msg unknown parameter `{key}`; the command takes: {keys} невідомий параметр `{key}`; команда приймає: {keys} Load EPS into Clipboard Завантажити EPS у буфер обміну @msg an image of {w} × {h} pixels is too large to draw зображення розміром {w} × {h} пікселів завелике для відображення +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: це не зображення PNG, JPEG, WebP, TIFF чи BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ розмір зображення {iw} × {ih} пікселів, а монтажної області за цієї ширини {rw} × {rh} пікселів: їхні пропорції відрізняються +@msg `threshold` must be a number from 0 to 1 `threshold` має бути числом від 0 до 1 +@msg background {v}: a color such as "#808080" фон {v}: колір, наприклад "#808080" +@msg comparing with an image file isn't available in the browser порівняння з файлом зображення недоступне в браузері @msg an image of {w} × {h} pixels is shown at reduced size зображення розміром {w} × {h} пікселів показано в зменшеному розмірі @msg the image can't be read as a texture зображення не вдається прочитати як текстуру Basic Базовий diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ce98bc9784..678eddbcee 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1389,6 +1389,7 @@ digits Malayalam Malayalam Find Linked Files in Folder… Tìm tệp liên kết trong thư mục… Find Next Tìm tiếp Find Objects Tìm đối tượng + Compare with Image So sánh với ảnh Fine Dots Chấm mịn Simple Đơn giản @@ -5104,6 +5105,11 @@ theme Appearance Giao diện @msg {tool} isn't in a toolbar group of several tools {tool} không nằm trong nhóm thanh công cụ có nhiều công cụ Load EPS into Clipboard Tải EPS vào bảng tạm @msg an image of {w} × {h} pixels is too large to draw ảnh {w} × {h} điểm ảnh quá lớn nên không thể vẽ +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: không phải ảnh PNG, JPEG, WebP, TIFF hay BMP +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ ảnh có kích thước {iw} × {ih} điểm ảnh, còn bảng vẽ ở chiều rộng đó có kích thước {rw} × {rh} điểm ảnh: tỉ lệ của chúng khác nhau +@msg `threshold` must be a number from 0 to 1 `threshold` phải là một số từ 0 đến 1 +@msg background {v}: a color such as "#808080" background {v}: màu như "#808080" +@msg comparing with an image file isn't available in the browser không thể so sánh với tệp ảnh trong trình duyệt @msg an image of {w} × {h} pixels is shown at reduced size ảnh {w} × {h} điểm ảnh được hiển thị ở kích thước thu nhỏ Basic Cơ bản Fill and Stroke Controls Điều khiển tô và nét diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a2cf406300..9a33468395 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1125,6 +1125,7 @@ Find Font… 查找字体… Find Next 查找下一个 Find Objects 查找对象 + Compare with Image 与图像比较 First Page 第一页 First-line Left Indent 首行左缩进 Fisheye… 鱼眼… @@ -5386,6 +5387,11 @@ lighting Light 光源 @msg unknown parameter `{key}`; the command takes: {keys} 未知参数 `{key}`;该命令接受:{keys} Load EPS into Clipboard 将 EPS 载入剪贴板 @msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的图像过大,无法绘制 +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}:不是 PNG、JPEG、WebP、TIFF 或 BMP 图像 +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ 图像为 {iw} × {ih} 像素,而画板在该宽度下为 {rw} × {rh} 像素:两者的比例不同 +@msg `threshold` must be a number from 0 to 1 `threshold` 必须是 0 到 1 之间的数字 +@msg background {v}: a color such as "#808080" background {v}:颜色,例如 "#808080" +@msg comparing with an image file isn't available in the browser 浏览器中无法与图像文件进行比较 @msg an image of {w} × {h} pixels is shown at reduced size {w} × {h} 像素的图像以缩小的尺寸显示 Fill and Stroke Controls 填色和描边控件 Coloring Controls 颜色控件 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9440e225f0..4b7107054d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1150,6 +1150,7 @@ font-technology Variable 可變 Find Font… 尋找字體… Find Next 尋找下一個 Find Objects 尋找物件 + Compare with Image 與影像比較 First Page 第一頁 First-line Left Indent 首行左縮排 Fisheye… 魚眼… @@ -5200,6 +5201,11 @@ lighting Light 光源 @msg unknown parameter `{key}`; the command takes: {keys} 未知的參數 `{key}`;此指令接受:{keys} Load EPS into Clipboard 將 EPS 載入剪貼簿 @msg an image of {w} × {h} pixels is too large to draw {w} × {h} 像素的影像過大,無法繪製 +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}:不是 PNG、JPEG、WebP、TIFF 或 BMP 影像 +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ 影像為 {iw} × {ih} 像素,而工作區域在該寬度下為 {rw} × {rh} 像素:兩者的比例不同 +@msg `threshold` must be a number from 0 to 1 `threshold` 必須是 0 到 1 之間的數字 +@msg background {v}: a color such as "#808080" background {v}:顏色,例如 "#808080" +@msg comparing with an image file isn't available in the browser 瀏覽器中無法與影像檔案進行比較 @msg an image of {w} × {h} pixels is shown at reduced size {w} × {h} 像素的影像以縮小的尺寸顯示 Basic 基本 Fill and Stroke Controls 填色和筆畫控制項 diff --git a/docs/mcp.md b/docs/mcp.md index ae04c16472..6b4a6bbeb5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -269,6 +269,22 @@ chain (layer first) and `limit` caps `matches` (default 100; `0` only counts); w `selected`, the number of objects selected. `document.json` stays whole: it is the fidelity path, not the way to look around. +`run_command document.compare {path, artboard?, background?, threshold?, diffPath?}` measures how far an +artboard is from an image file (PNG, JPEG, WebP, TIFF or BMP). It renders the +artboard (default 0) at the image's size, as `export` draws a PNG: the scale is the image's width in pixels over +the artboard's width in points, and an image whose height differs from the artboard's height at that scale by +more than one pixel is an error that names both sizes. The render and the image are both flattened on +`background` (`"#rrggbb"`, default `"#ffffff"`). The reply is `{width, height, rmse, over, total, threshold}`: +`rmse` is the root mean square of the R, G and B differences on a 0 to 1 scale, rounded to 6 decimals, and +`over` counts the pixels with a channel that differs by more than `threshold` (0 to 1, default 0.08) of the +total `total`. `diffPath` writes a PNG of each pixel's absolute R, G and B differences (black where the two +match) and adds `diffPath` to the reply. As in a PNG export, linked images and placed documents are drawn +from their files rather than from the previews saved for them. The reply's `warnings` are a PNG export's, in +the same order: type on the artboard that doesn't fit its frame, an embedded image that couldn't be decoded (it +is missing from the render), type in a font or style that isn't available, and a linked file that can't be read +(its preview is drawn). `path` is read through the automation read root, and `diffPath` is written through the +write root. The command does not change the document, and it is not available in the web app. + ### Completions `completion/complete` answers for a prompt argument (`ref/prompt`) or a template variable From 88881288225438bd14efd5df8fb7eb39211c7a16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:44:09 +0700 Subject: [PATCH 03/26] Image Trace: Flat Logo can trace only the named colors, without a white of its own Squashed from #3946 onto main. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/tests/build.rs | 37 ++++++++++++ crates/trace/src/logo/pipeline.rs | 63 +++++++++++++++----- crates/trace/src/logo/tests.rs | 96 ++++++++++++++++++++++++++++++ crates/trace/src/params.rs | 12 +++- docs/image-trace-adjustments.md | 9 +++ docs/roadmap.md | 1 + docs/target-app-parity.md | 1 + 8 files changed, 204 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 442b68c583..f54752632d 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index b4be82c2ec..9e397975f7 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3825,6 +3825,43 @@ fn image_trace_flat_logo_refuses_a_gradient_and_a_bad_palette() { assert_eq!(r["colors"], 1); } +#[test] +fn image_trace_flat_logo_can_trace_only_the_named_colors() { + // A light disc in a black ring, a blue square on it, and a white spot. + let art = vectorcraft_trace::Raster::from_fn(120, 120, |x, y| { + let (fx, fy) = (f64::from(x) + 0.5, f64::from(y) + 0.5); + let d = (fx - 60.0).hypot(fy - 60.0); + if (fx - 32.0).hypot(fy - 40.0) <= 6.0 { + [255, 255, 255, 255] + } else if (45..75).contains(&x) && (45..75).contains(&y) { + [40, 120, 240, 255] + } else if d <= 46.0 { + [240, 240, 220, 255] + } else if d <= 50.0 { + [0, 0, 0, 255] + } else { + [0, 0, 0, 0] + } + }); + let fills = |logo_white: bool| { + let mut s = session(); + add_image(&mut s, &art, Affine::IDENTITY); + let params = json!({"params": {"mode": "logo", "logoColors": ["#000000", "#F0F0DC", "#2878F0"], "logoWhite": logo_white}}); + let r = s.execute("imageTrace.makeAndExpand", ¶ms).unwrap(); + let g = node(&s, NodeId(r["id"].as_u64().unwrap())); + let mut hex: Vec = g.children().unwrap().iter().filter_map(|n| n.appearance.fill_paint().color()).map(|c| c.to_hex()).collect(); + hex.sort(); + hex.dedup(); + (r["colors"].clone(), hex) + }; + let (colors, hex) = fills(true); + assert_eq!(colors, 4); + assert!(hex.contains(&"#ffffff".to_string()), "{hex:?}"); + let (colors, hex) = fills(false); + assert_eq!(colors, 3); + assert_eq!(hex, ["#000000", "#2878f0", "#f0f0dc"]); +} + #[test] fn image_trace_object_remembers_its_settings() { let mut s = session(); diff --git a/crates/trace/src/logo/pipeline.rs b/crates/trace/src/logo/pipeline.rs index 02955b1463..b8382c5a7f 100644 --- a/crates/trace/src/logo/pipeline.rs +++ b/crates/trace/src/logo/pipeline.rs @@ -353,22 +353,38 @@ fn plane_at(planes: &[Vec], class: usize, i: usize) -> f32 { planes.get(class).and_then(|p| p.get(i)).copied().unwrap_or(0.0) } -/// The unmixing classes for a palette: each colour, then white, then transparent. -fn classes_for(palette: &[[u8; 3]]) -> Vec<[f64; 4]> { +/// The unmixing classes for a palette: each colour, then white (when `own_white`), then transparent. +fn classes_for(palette: &[[u8; 3]], own_white: bool) -> Vec<[f64; 4]> { let mut classes: Vec<[f64; 4]> = palette.iter().map(|c| [f64::from(c[0]) / 255.0, f64::from(c[1]) / 255.0, f64::from(c[2]) / 255.0, 1.0]).collect(); - classes.push([1.0, 1.0, 1.0, 1.0]); + if own_white { + classes.push([1.0, 1.0, 1.0, 1.0]); + } classes.push([0.0, 0.0, 0.0, 0.0]); classes } +/// Whether white is traced as a class of its own: always, unless the caller named the colors and +/// turned [`TraceParams::logo_white`] off. With Ignore White it is, so white areas are left out. +fn own_white(params: &TraceParams) -> bool { + params.logo_white || params.logo_colors.is_empty() || params.ignore_white +} + +/// Without a white class of its own: the palette color that takes white's coverage, the one +/// nearest white (the first of equally near ones). `None` when a named color is white already +/// (closer than [`SAME_COLOUR`]), so white needs no class to unmix with. +fn white_goes_to(palette: &[[u8; 3]]) -> Option { + let (i, d) = palette.iter().enumerate().map(|(i, &c)| (i, distance(c, [255; 3]))).min_by(|a, b| a.1.total_cmp(&b.1))?; + (d >= SAME_COLOUR).then_some(i) +} + fn distance(a: [u8; 3], b: [u8; 3]) -> f64 { (0..3).map(|k| (f64::from(a[k]) - f64::from(b[k])).powi(2)).sum::().sqrt() } type Colours = Vec<[u8; 3]>; -/// The colours to trace: those the caller named (white is always its own class so it is skipped; +/// The colours to trace: those the caller named (white is skipped when it is its own class; /// colours closer than [`SAME_COLOUR`] count as one; at most [`MAX_COLOURS`]) or the ones found, /// the tones of one colour folded into it ([`fold_tones`]); and with them the colours before folding. fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Result<(Colours, Colours), TraceError> { @@ -380,7 +396,7 @@ fn choose_palette(params: &TraceParams, pix: &[Px], w: usize, h: usize) -> Resul for s in ¶ms.logo_colors { // Every entry is checked, but only the first few distinct colours are kept. let c = parse_hex(s).ok_or_else(|| TraceError::BadPalette(s.clone()))?; - let white = c.iter().all(|&v| v >= WHITE_MIN); + let white = own_white(params) && c.iter().all(|&v| v >= WHITE_MIN); if palette.len() < MAX_COLOURS && !white && !palette.iter().any(|&q| distance(q, c) < SAME_COLOUR) { palette.push(c); } @@ -405,7 +421,11 @@ pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) if fraction < MIN_FLAT { return Err(TraceError::NotFlat { fraction }); } - let mut classes = classes_for(&palette); + let own_white = own_white(params); + // Without a white of its own, white is still unmixed as a class, so blended edges split where + // they are, and its coverage is then added to the color it goes to. + let merge_white = if own_white { None } else { white_goes_to(&palette) }; + let mut classes = classes_for(&palette, own_white || merge_white.is_some()); // A very busy image is averaged down further until the unmixing work is bounded. for _ in 0..6 { if count_ambiguous(&pix, &classes) <= EDGE_BUDGET || w * h <= 16_384 { @@ -423,15 +443,28 @@ pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) palette.extend(extra.into_iter().take(MAX_COLOURS - palette.len())); // (A colour nothing explained may be one more tone of a colour that is there.) palette = fold_tones(&pix, palette); - classes = classes_for(&palette); + classes = classes_for(&palette, own_white); unmix(&pix, w, h, &classes).0 } } else { std::mem::take(&mut planes) }; - let (white, transparent) = (palette.len(), palette.len() + 1); + if let Some(to) = merge_white + && palette.len() < planes.len() + { + let white_plane = planes.remove(palette.len()); + if let Some(target) = planes.get_mut(to) { + for (t, v) in target.iter_mut().zip(&white_plane) { + *t += *v; + } + } + } + // Without a white class, `white` is an index no class has. + let (white, transparent) = if own_white { (palette.len(), palette.len() + 1) } else { (usize::MAX, palette.len()) }; let aliased = soften_if_aliased(&mut planes, w, h); - fill_knockouts(&mut planes, w, h, white, transparent); + if own_white { + fill_knockouts(&mut planes, w, h, white, transparent); + } let n = w * h; let dominant: Vec = (0..n) .map(|i| (0..planes.len()).max_by(|&a, &b| plane_at(&planes, a, i).total_cmp(&plane_at(&planes, b, i))).unwrap_or(transparent) as u8) @@ -474,7 +507,7 @@ pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) let to_source = ToSource { factor: factor as f64, work: (w, h), source: (w0, h0) }; let mut shapes: Vec = Vec::new(); let mut anchors_made = 0usize; - for class in 0..=white { + for class in 0..transparent { if class == white && params.ignore_white { continue; } @@ -488,8 +521,9 @@ pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) if a2.abs() / 2.0 < min_area { continue; } - // Holes are cut only under Ignore White; otherwise white and the other colors are traced as their own shapes. - if a2 >= 0.0 && !params.ignore_white { + // Holes are cut only under Ignore White or with no white class; otherwise white and the other colors are + // traced as their own shapes. + if a2 >= 0.0 && !(params.ignore_white || !own_white) { continue; } // More real outlines than we will fit is refused, not silently truncated. @@ -499,8 +533,9 @@ pub(crate) fn trace_logo(img: &Raster, params: &TraceParams, max_anchors: usize) let pts = to_pixels(&lp, u); if a2 < 0.0 { outers.push((a2.abs() / 2.0, pts)) } else { holes.push(pts) } } - // Each hole belongs to the smallest outline that contains it, and to no other. - let owner: Vec> = if params.ignore_white { + // Each hole belongs to the smallest outline that contains it, and to no other. (Holes are + // cut where white does not paint over them: with Ignore White, or with no white class.) + let owner: Vec> = if params.ignore_white || !own_white { holes .iter() .map(|hole| { diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 2335fe77eb..8d3f6a79fc 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -62,6 +62,9 @@ fn render(w: u32, h: u32, blur: f64, shade: impl Fn(f64, f64) -> Option<[u8; 3]> const RED: [u8; 3] = [210, 40, 50]; const BLUE: [u8; 3] = [40, 80, 200]; +const LIGHT: [u8; 3] = [240, 240, 220]; +const SKY: [u8; 3] = [40, 120, 240]; +const WHITE: [u8; 3] = [255, 255, 255]; fn logo_params() -> TraceParams { TraceParams { @@ -205,6 +208,99 @@ fn the_named_palette_is_used_exactly_and_a_bad_one_is_an_error() { assert!(matches!(trace_within(&img, &bad, 1000), Err(TraceError::BadPalette(s)) if s == "red")); } +/// The color of the topmost path at `p` (paths are listed bottom first). +fn top_color(res: &TraceResult, p: Point) -> Option<[u8; 3]> { + res.paths.iter().rev().find(|t| t.path.to_bezpath().winding(p) != 0).map(|t| t.color) +} + +#[test] +fn logo_white_off_traces_only_the_named_colors() { + // A light disc in a black ring, a blue square on it, and two white spots. + let img = render(120, 120, 0.7, |x, y| { + let d = (x - 60.0).hypot(y - 60.0); + if (x - 32.0).hypot(y - 40.0) <= 6.0 || (x - 78.0).hypot(y - 86.0) <= 6.0 { + Some(WHITE) + } else if (45.0..=75.0).contains(&x) && (45.0..=75.0).contains(&y) { + Some(SKY) + } else if d <= 46.0 { + Some(LIGHT) + } else if d <= 50.0 { + Some([0, 0, 0]) + } else { + None + } + }); + let named = TraceParams { logo_colors: vec!["#000000".into(), "#F0F0DC".into(), "#2878F0".into()], ..logo_params() }; + // By default white is a fourth color. + let res = trace(&img, &named); + assert_eq!(res.palette.len(), 4, "{:?}", res.palette); + assert_eq!(top_color(&res, Point::new(32.0, 40.0)), Some(WHITE)); + // Without it, the three named colors only: the white spots take the light color. + let res = trace(&img, &TraceParams { logo_white: false, ..named.clone() }); + assert_eq!(res.palette.len(), 3, "{:?}", res.palette); + assert!(!res.palette.contains(&WHITE)); + for p in [Point::new(32.0, 40.0), Point::new(78.0, 86.0), Point::new(20.0, 60.0)] { + assert_eq!(top_color(&res, p), Some(LIGHT), "at {p:?}"); + } + assert_eq!(top_color(&res, Point::new(60.0, 60.0)), Some(SKY)); + assert_eq!(top_color(&res, Point::new(60.0, 12.0)), Some([0, 0, 0])); + assert!(!covered(&res, Point::new(5.0, 5.0))); + // Ignore White still leaves the white spots out. + let res = trace(&img, &TraceParams { logo_white: false, ignore_white: true, ..named.clone() }); + for p in [Point::new(32.0, 40.0), Point::new(78.0, 86.0)] { + assert!(!covered(&res, p), "at {p:?}"); + } + assert_eq!(top_color(&res, Point::new(20.0, 60.0)), Some(LIGHT)); +} + +#[test] +fn logo_white_off_keeps_a_named_white_and_knockouts_as_holes() { + let disc = render(64, 64, 0.7, |x, y| ((x - 32.0).hypot(y - 32.0) <= 20.0).then_some(WHITE)); + let only_white = TraceParams { logo_colors: vec!["#ffffff".into()], logo_white: false, ..logo_params() }; + let res = trace(&disc, &only_white); + assert_eq!(res.paths.len(), 1); + assert_eq!(res.paths[0].color, WHITE); + // An enclosed transparent area stays a hole: there is no white to paint it with. + let ring = render(64, 64, 0.7, |x, y| (12.0..=25.0).contains(&(x - 32.0).hypot(y - 32.0)).then_some(BLUE)); + let res = trace(&ring, &TraceParams { logo_colors: vec!["#2850c8".into()], logo_white: false, ..logo_params() }); + assert_eq!(res.paths.len(), 1); + assert_eq!(res.paths[0].path.subpaths.len(), 2, "outer outline and a hole"); + assert!(!covered(&res, Point::new(32.0, 32.0)), "the hole must be empty"); + assert!(covered(&res, Point::new(32.0, 32.0 + 18.0)), "the ring itself is filled"); +} + +#[test] +fn logo_white_off_gives_each_white_the_nearest_named_color() { + // Red and blue are equally far from white: the white disc takes the first one named. + let disc = render(64, 64, 0.7, |x, y| ((x - 32.0).hypot(y - 32.0) <= 20.0).then_some(WHITE)); + let params = TraceParams { logo_colors: vec!["#ff0000".into(), "#0000ff".into()], logo_white: false, ..logo_params() }; + let res = trace(&disc, ¶ms); + assert_eq!(top_color(&res, Point::new(32.0, 32.0)), Some([255, 0, 0])); + assert!(!covered(&res, Point::new(5.0, 5.0))); + // Each white takes the named color nearest it, so two named whites both stay. + const OFF: [u8; 3] = [245, 245, 245]; + let two = render(96, 64, 0.7, |x, y| { + if (x - 24.0).hypot(y - 32.0) <= 16.0 { + Some(OFF) + } else if (x - 72.0).hypot(y - 32.0) <= 16.0 { + Some(WHITE) + } else { + None + } + }); + let params = TraceParams { logo_colors: vec!["#f5f5f5".into(), "#ffffff".into()], logo_white: false, ..logo_params() }; + let res = trace(&two, ¶ms); + assert_eq!(top_color(&res, Point::new(24.0, 32.0)), Some(OFF)); + assert_eq!(top_color(&res, Point::new(72.0, 32.0)), Some(WHITE)); + // A white square on blue keeps its edges where they are when it turns red. + let square = render(100, 100, 0.7, |x, y| Some(if (30.0..70.0).contains(&x) && (30.0..70.0).contains(&y) { WHITE } else { [0, 0, 255] })); + let res = trace(&square, &TraceParams { logo_colors: vec!["#ff0000".into(), "#0000ff".into()], logo_white: false, ..logo_params() }); + for (inside, outside) in [(30.3, 29.7), (69.7, 70.3)] { + assert_eq!(top_color(&res, Point::new(inside, 50.0)), Some([255, 0, 0]), "at x {inside}"); + assert_eq!(top_color(&res, Point::new(outside, 50.0)), Some([0, 0, 255]), "at x {outside}"); + } +} + #[test] fn a_large_image_is_traced_at_reduced_size_and_scaled_back() { let (cx, cy, r) = (1200.0, 600.0, 400.0); diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index dd5bc99298..65e5bb5c0d 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -110,9 +110,16 @@ pub struct TraceParams { /// Stroke: the widest feature (px) traced as a stroke. pub stroke_width: f64, /// Flat Logo mode: the flat colours (`#rrggbb`) to use; empty finds them automatically. White is - /// always traced on its own and cannot be named, colours closer than about 12 (RGB distance) - /// count as one, and at most ten are used. (Not `palette`: that is Color mode's colour source.) + /// traced on its own and cannot be named unless [`logo_white`](Self::logo_white) is off, colours + /// closer than about 12 (RGB distance) count as one, and at most ten are used. (Not `palette`: + /// that is Color mode's colour source.) pub logo_colors: Vec, + /// Flat Logo mode with named `logo_colors`: `true` traces white (every channel 245 or more) as a + /// color of its own beside the named ones. `false` traces the named colors only: white areas + /// take the nearest of them, a named white or near-white is used as named, and enclosed + /// transparent areas stay holes. With the colors found automatically, white is always its own, + /// and with [`ignore_white`](Self::ignore_white) white areas are left out whatever this says. + pub logo_white: bool, } impl Default for TraceParams { @@ -141,6 +148,7 @@ impl Default for TraceParams { strokes: false, stroke_width: 10.0, logo_colors: Vec::new(), + logo_white: true, } } } diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 92e5f42acb..d0ac9fda73 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -32,6 +32,15 @@ white beside a cream), at most six; scattered specks of a colour add none. Adobe its own palettes are chosen; this is VectorCraft's own method (see [image-trace-quality.md](image-trace-quality.md#auto-color-keeps-rare-colours)). +**Flat Logo colors.** Flat Logo traces white as a color of its own beside the colors named in +`logoColors`, and takes a named color with every channel 245 or more as that white. Each pixel is read +as a blend of the traced colors and goes to the color with the largest share, so a near-white area can +go to a named light color instead of white. With `"logoWhite": false` in the params of `imageTrace.make` or +`imageTrace.makeAndExpand`, it traces the named colors only: white areas take the nearest named color, +a named white or near-white is used as named, and enclosed transparent areas stay holes instead of +being painted white. When Flat Logo finds the colors itself, `logoWhite` has no effect, and with +`ignoreWhite` white areas are left out whatever `logoWhite` says. + **Document Library color groups.** With Palette › Document Library and Library › Document Swatches, the panel's **Colors** menu traces with every document swatch (**All**) or with the colors of one color group from the Swatches panel, as the public diff --git a/docs/roadmap.md b/docs/roadmap.md index e1a7d33600..5e6ee6dda5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -136,6 +136,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; Flat Logo with named colors can leave out white with `logoWhite: false`; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, a generated Basic Shapes library, User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, four generated libraries, User Defined, Other Library…, Save Brushes); brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol and brush libraries done; brushes/symbols in progress | 23–37 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ec7b76edf9..d1d0c19e61 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1090,6 +1090,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Gradient mesh from an image:** Object › Create Gradient Mesh (`object.mesh.create`) on an embedded image makes a mesh of 1 to 50 rows and columns over the picture's rectangle, placed with the image's transform; each point takes the alpha-weighted average colour and the opacity of the area around it, and Appearance and Highlight apply. A linked image is refused with a message to embed it (#1676). Scores and hours unchanged. - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. +- **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. From 743b8031d3c3b2ead233272a775cf35ca875845a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 8 Nov 2026 23:02:38 +0700 Subject: [PATCH 04/26] Document: the compare test expects main's wording for one missing linked image --- crates/engine/src/tests/compare.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests/compare.rs b/crates/engine/src/tests/compare.rs index 03d788487f..3bd4446d61 100644 --- a/crates/engine/src/tests/compare.rs +++ b/crates/engine/src/tests/compare.rs @@ -138,7 +138,7 @@ fn a_linked_image_is_drawn_from_its_file_as_a_png_export_draws_it() { let r = compare(&mut s, json!({"path": out})); assert_eq!(r["over"].as_u64(), r["total"].as_u64(), "{r}"); let warnings = r["warnings"].as_array().unwrap(); - assert!(warnings.len() == 1 && warnings[0].as_str().unwrap().contains("output as their previews"), "{r}"); + assert!(warnings.len() == 1 && warnings[0].as_str().unwrap().contains("1 linked image output as its preview"), "{r}"); // With type that doesn't fit its frame as well, the warnings come in the export's order. let overset = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "size": 12, "area": {"width": 100, "height": 20}})).unwrap(); From f118cf6aa654721c8ff3a11edbfe34e7ed605932 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:44:44 +0700 Subject: [PATCH 05/26] Image Trace: Expand can group the traced paths by color Squashed from #4058 onto main. --- crates/engine/src/cmd/buildcmds.rs | 4 +- crates/engine/src/cmd/buildcmds/trace.rs | 347 ++++++++++++++++++++++- crates/engine/src/tests/build.rs | 310 ++++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + docs/mcp.md | 11 + 25 files changed, 732 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index f54752632d..1b37ca96fd 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -153,7 +153,7 @@ pub fn specs() -> Vec { "Make and Expand", ["Object", "Image Trace"], None, - "{…as imageTrace.make} same as imageTrace.make, then expand → {id, paths, anchors, colors}", + "{…as imageTrace.make, byColor?: false (each color's paths in a group of their own, as imageTrace.expand)} same as imageTrace.make, then expand → {id, paths, anchors, colors}", has_selection_or_ids, |s, p| trace_make(s, p, true) ), @@ -171,7 +171,7 @@ pub fn specs() -> Vec { "Expand", ["Object", "Image Trace"], None, - "{id?, ids?: [id…] (instead of id)} keep only the traced paths (drop the source image) → {ids}", + "{id?, ids?: [id…] (instead of id), byColor?: false (each color's paths in a group of their own, named by the swatch the color links to or as #rrggbb, gradient fills in one group named Gradients; the groups stack by their lowest path and keep their paths' order; a color whose paths overlap another color's from above and below gets a group for each part, so the art draws the same; refused for a trace made with autoGrouping and for a trace with a live Pathfinder effect)} keep only the traced paths (drop the source image) → {ids}", has_selection_or_ids, trace_expand ), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 00bcc1c830..1924ed4058 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -4,10 +4,16 @@ use vectorcraft_color::Swatch; use vectorcraft_doc::ImageObject; use super::{ - Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point, + Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point, Rect, Result, Session, StrokeLayer, TRACE_NAME, TraceView, Value, bad, fill_only, ids_json, json, root_ids, shape_node, str_param, switch_or, tr, }; +#[cfg(test)] +thread_local! { + static BOX_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static CANDIDATE_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + // ---------- Image Trace ---------- fn is_trace_group(n: &Node) -> bool { @@ -16,6 +22,8 @@ fn is_trace_group(n: &Node) -> bool { && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } +const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor"; + /// The `view` param ([`TraceView`] id), if given. fn view_param(cmd: &str, p: &Value) -> Result> { let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) }; @@ -368,6 +376,156 @@ fn grouped(d: &mut Document, nodes: Vec, parents: &[Option]) -> Vec roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect() } +/// The `byColor` param of an Expand (false when not given). +fn by_color_param(cmd: &str, p: &Value) -> Result { + match p.get("byColor").filter(|v| !v.is_null()) { + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "byColor must be true or false")), + None => Ok(false), + } +} + +/// Expand by color: an expanded trace's `items` (bottom-most first) in a group for each paint, a +/// stroked line counted by its stroke. A solid color's group is named by the swatch it links to (a +/// tint with its percentage) or as `#rrggbb`, and gradient fills share one group, "Gradients". The +/// groups stack in the order of the lowest item in each, and each keeps its items' order. When the +/// paths meet, an item joins its paint's last group only if no item of a later group meets it +/// (by the boxes of everything they paint, effects included, within one point); otherwise it +/// starts another group of that paint, which keeps the stacking order of those items. Items +/// farther apart can still share antialiased pixels at small view or raster-export scales, so +/// their edge pixels may change. A group among `items` (Auto Grouping) is refused. +fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result>> { + use std::collections::{BTreeMap, HashMap}; + use std::ops::Bound::{Excluded, Unbounded}; + use vectorcraft_color::tint_percent; + // Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a + // gradient, or another paint (its label). The name is apart from it: a swatch may be named as + // a color's `#rrggbb` or as "Gradients". + type PaintKey = (u8, String, u32); + struct Run { + name: String, + members: Vec>, + } + // Boxes closer than a point count as overlapping: their antialiased edges can share pixels. + let meet = |a: &Rect, b: &Rect| { + #[cfg(test)] + BOX_TESTS.with(|n| n.set(n.get() + 1)); + let b = b.inflate(1.0, 1.0); + a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1 + }; + // Choose a cell size from the painted extent and path count. A box over more than eight cells + // across but at most eight down (a stripe) is indexed by its rows, one the other way round by + // its columns, and one over more than eight both ways stays in a separate list, keeping the + // index bounded even when a path covers most of the document. + let items: Vec<_> = items + .into_iter() + .map(|item| { + let bounds = vectorcraft_render::painted_bounds(d, &item); + (item, bounds) + }) + .collect(); + let extent = items.iter().filter_map(|(_, b)| *b).reduce(|a, b| a.union(b)); + let cell_size = extent.map_or(1.0, |r| ((r.x1 - r.x0).abs() * (r.y1 - r.y0).abs() / items.len().max(1) as f64).sqrt().max(1.0)); + // The first and last column and row of the cells `r` covers; `None` when it isn't finite. + let span = |r: Rect| -> Option<(i64, i64, i64, i64)> { + let coord = |v: f64| (v / cell_size).floor() as i64; + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then(|| (coord(r.x0), coord(r.y0), coord(r.x1), coord(r.y1))) + }; + let count = |first: i64, last: i64| i128::from(last) - i128::from(first) + 1; + // A box over more cells than this is checked against every box. + const MAX_CELLS: i128 = 1024; + let mut groups: Vec = vec![]; + let mut latest: HashMap = HashMap::new(); + // An item can join an earlier group, so insertion order is not group-index order. Index + // boxes by group to skip older groups without scanning their entries. + let mut spatial: HashMap<(i64, i64), BTreeMap>> = HashMap::new(); + let mut rows: HashMap>> = HashMap::new(); + let mut columns: HashMap>> = HashMap::new(); + let mut large: BTreeMap> = BTreeMap::new(); + let mut all_boxes: BTreeMap> = BTreeMap::new(); + for (item, bounds) in items { + if matches!(item.kind, NodeKind::Group { .. }) { + return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); + } + let paint = match item.appearance.fill_paint() { + Paint::None => item.appearance.stroke_paint(), + fill => fill, + }; + let (key, name) = match &paint { + Paint::Solid { swatch: Some(n), tint, .. } => { + let percent = tint_percent(*tint); + let name = if *tint < 1.0 { format!("{n} {percent}%") } else { n.clone() }; + ((1, n.clone(), tint.to_bits()), name) + } + Paint::Solid { color, .. } => ((0, color.to_hex(), 0), color.to_hex()), + Paint::Gradient(_) => ((2, String::new(), 0), "Gradients".to_string()), + other => ((3, other.label(), 0), other.label()), + }; + // Joining an earlier group moves the item under every later group's items. + let hidden_by_later = |at: usize| { + bounds.is_some_and(|b| { + let overlaps_later = |boxes: &BTreeMap>| { + boxes.range((Excluded(at), Unbounded)).rev().any(|(_, group_boxes)| { + group_boxes.iter().rev().any(|box_bounds| { + #[cfg(test)] + CANDIDATE_VISITS.with(|n| n.set(n.get() + 1)); + meet(box_bounds, &b) + }) + }) + }; + match span(b) { + Some((x0, y0, x1, y1)) if count(x0, x1) * count(y0, y1) <= MAX_CELLS => { + (y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))).filter_map(|c| spatial.get(&c)).any(overlaps_later) + || (y0..=y1).filter_map(|y| rows.get(&y)).any(overlaps_later) + || (x0..=x1).filter_map(|x| columns.get(&x)).any(overlaps_later) + || overlaps_later(&large) + } + _ => overlaps_later(&all_boxes), + } + }) + }; + let at = latest.get(&key).copied().filter(|&at| !hidden_by_later(at)); + let mut started = Run { name, members: vec![] }; + let joins = at.and_then(|at| groups.get_mut(at)); + let new = joins.is_none(); + let g = joins.unwrap_or(&mut started); + g.members.push(item); + if new { + groups.push(started); + latest.insert(key, groups.len() - 1); + } + if let Some(b) = bounds { + let index = if new { groups.len() - 1 } else { at.unwrap_or_default() }; + all_boxes.entry(index).or_default().push(b); + match span(b.inflate(1.0, 1.0)) { + Some((x0, y0, x1, y1)) if count(x0, x1) <= 8 && count(y0, y1) <= 8 => { + for place in (y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))) { + spatial.entry(place).or_default().entry(index).or_default().push(b); + } + } + Some((_, y0, _, y1)) if count(y0, y1) <= 8 => { + for y in y0..=y1 { + rows.entry(y).or_default().entry(index).or_default().push(b); + } + } + Some((x0, _, x1, _)) if count(x0, x1) <= 8 => { + for x in x0..=x1 { + columns.entry(x).or_default().entry(index).or_default().push(b); + } + } + _ => large.entry(index).or_default().push(b), + } + } + } + Ok(groups + .into_iter() + .map(|run| { + let mut g = Node::group(d.alloc_id(), run.members); + g.name = Some(run.name); + Arc::new(g) + }) + .collect()) +} + /// What a trace depends on: the object traced (an image, or an Image Trace object traced again), /// its image, and the settings it is traced with. The tracer makes the same paths of the same /// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own. @@ -398,6 +556,10 @@ struct Prepared { fn prepare(s: &Session, c: &str, p: &Value) -> Result { let mut params = trace_params(s, c, p)?; let view = view_param(c, p)?; + let by_color = c == "imageTrace.makeAndExpand" && by_color_param(c, p)?; + if by_color && params.auto_grouping { + return Err(bad(c, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); + } let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; // The preset's name if the parameters are exactly that preset's or its enhanced version's (a // saved preset's under its saved name), else "Custom". @@ -428,6 +590,9 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { }) .ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))? }; + if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) { + return Err(bad(c, LIVE_PATHFINDER_BY_COLOR)); + } let blob = s.doc()?.doc.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?; let bytes = Arc::clone(&blob.bytes); let library = trace_library(c, s, &mut params)?; @@ -533,6 +698,7 @@ impl TraceRun { pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?; + let group_by_color = expand && by_color_param(c, p)?; // A saved preset's settings join the journal entry, so a replay traces as this run did after // the preset is changed, renamed or deleted. let named = str_param(p, "preset").unwrap_or("Default"); @@ -608,6 +774,9 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result { } pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.expand"; + let by_color = by_color_param(C, p)?; let targets = trace_targets(s, p)?; + if by_color { + // A trace made with Auto Grouping is refused even when none of its paths were grouped. + let d = &s.doc()?.doc; + let grouped = |n: &Node| n.extras().trace.as_deref().and_then(|t| t.pointer("/params/autoGrouping")).and_then(Value::as_bool) == Some(true); + if targets.iter().any(|g| d.node(*g).is_some_and(grouped)) { + return Err(bad(C, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); + } + if targets.iter().any(|g| d.node(*g).is_some_and(vectorcraft_render::effects::has_pathfinder)) { + return Err(bad(C, LIVE_PATHFINDER_BY_COLOR)); + } + } s.edit("Expand Image Trace", |d, sel| { for g in &targets { let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; @@ -715,6 +897,15 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { if let Some(ch) = n.children_mut() { ch.retain(|c| !matches!(c.kind, NodeKind::Image(_))); } + if by_color { + let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default(); + // The paths may have been moved or reshaped since the trace was made, so any trace's + // paths are taken to overlap. + let groups = color_groups(C, d, items)?; + if let Some(ch) = d.node_mut(*g).and_then(Node::children_mut) { + *ch = groups; + } + } } sel.set(targets.iter().copied()); Ok(()) @@ -722,6 +913,160 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&targets) })) } +#[cfg(test)] +mod color_group_tests { + use super::*; + use vectorcraft_geom::{PathData, SubPath}; + + fn area(d: &mut Document, x0: f64, y0: f64, x1: f64, y1: f64, color: Color) -> Arc { + let path = PathData::single(SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true)); + Arc::new(Node::path(d.alloc_id(), path, fill_only(Paint::solid(color)))) + } + + #[test] + fn abutting_color_groups_preserve_order_at_shared_edges() { + let mut d = Document::new(100.0, 100.0); + let a = Color::rgb(1.0, 0.0, 0.0); + let b = Color::rgb(0.0, 0.0, 1.0); + let items = vec![area(&mut d, 0.0, 0.0, 20.0, 20.0, a), area(&mut d, 20.0, 0.0, 40.0, 20.0, b), area(&mut d, 40.0, 0.0, 60.0, 20.0, a)]; + let original: Vec<_> = items.iter().map(|n| n.id).collect(); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let actual: Vec<_> = groups.iter().flat_map(|g| g.children().unwrap().iter().map(|n| n.id)).collect(); + assert_eq!(actual, original, "shared-edge paths changed stacking order"); + } + + #[test] + fn dense_color_groups_use_bounded_box_tests() { + let mut d = Document::new(200.0, 200.0); + let a = Color::rgb(1.0, 0.0, 0.0); + let b = Color::rgb(0.0, 0.0, 1.0); + let items = (0..4000) + .map(|i| { + if i % 2 == 0 { + let x = 100.0 + (i % 40) as f64 * 0.01; + area(&mut d, x, 100.0, x + 0.1, 100.1, a) + } else { + let x = if i % 4 == 1 { 0.0 } else { 198.0 }; + area(&mut d, x, x, x + 2.0, x + 2.0, b) + } + }) + .collect(); + BOX_TESTS.with(|n| n.set(0)); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let tests = BOX_TESTS.with(std::cell::Cell::get); + assert_eq!(groups.iter().map(|g| g.children().map_or(0, Vec::len)).sum::(), 4000); + assert!(tests < 4000 * 32, "{tests} box tests for 4000 paths"); + } + + #[test] + fn overlapping_alternating_colors_visit_bounded_candidates() { + const COUNT: usize = 3000; + let mut d = Document::new(100.0, 100.0); + let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]; + let items = (0..COUNT).map(|i| area(&mut d, 10.0, 10.0, 20.0, 20.0, colors[i % 2])).collect(); + CANDIDATE_VISITS.with(|n| n.set(0)); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let visits = CANDIDATE_VISITS.with(std::cell::Cell::get); + assert_eq!(groups.len(), COUNT); + assert!(visits < COUNT * 16, "{visits} candidate visits for {COUNT} paths"); + } + + #[test] + fn separate_stripes_of_alternating_colors_visit_bounded_candidates() { + const COUNT: usize = 2000; + let mut d = Document::new(1000.0, 4000.0); + let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]; + for tall in [false, true] { + let items = (0..COUNT) + .map(|i| { + let at = i as f64 * 2.0; + if tall { area(&mut d, at, 0.0, at + 0.5, 1000.0, colors[i % 2]) } else { area(&mut d, 0.0, at, 1000.0, at + 0.5, colors[i % 2]) } + }) + .collect(); + CANDIDATE_VISITS.with(|n| n.set(0)); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let visits = CANDIDATE_VISITS.with(std::cell::Cell::get); + assert_eq!(groups.len(), 2, "tall {tall}"); + assert!(visits < COUNT * 32, "tall {tall}: {visits} candidate visits for {COUNT} stripes"); + } + } + + #[test] + fn spatial_color_groups_match_simple_scan() { + let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)]; + for layout in 0..6 { + let mut d = Document::new(200.0, 200.0); + let items: Vec<_> = (0..90) + .map(|i| { + let x = match layout { + 0 => i as f64 * 2.0, + 1 => (i % 10) as f64 * 5.0, + 2 => (i % 7) as f64 * 3.0, + 3 => (i % 13) as f64 * 9.0, + 4 => (i % 4) as f64 * 10.0, + _ => i as f64 * 1.5, + }; + let y = match layout { + 0 => 0.0, + 1 => (i / 10) as f64 * 5.0, + 2 => (i / 7) as f64 * 3.0, + 3 => (i / 13) as f64 * 9.0, + 4 => i as f64 * 1.5, + _ => (i % 4) as f64 * 10.0, + }; + // Layouts 4 and 5: wide and tall stripes, some meeting their neighbors. + let (w, h) = match layout { + 4 => (150.0, 1.0), + 5 => (1.0, 150.0), + _ => (3.0, 3.0), + }; + area(&mut d, x, y, x + w, y + h, colors[i % 3]) + }) + .collect(); + let mut expected: Vec<(String, Vec<(NodeId, Rect)>)> = vec![]; + for item in &items { + let key = item.appearance.fill_paint().color().unwrap().to_hex(); + let bounds = vectorcraft_render::painted_bounds(&d, item).unwrap(); + let previous = expected.iter().rposition(|(k, _)| *k == key); + let can_join = previous.filter(|&at| { + !expected.iter().skip(at + 1).any(|(_, boxes)| { + boxes.iter().any(|(_, m)| { + let b = bounds.inflate(1.0, 1.0); + m.x0 < b.x1 && b.x0 < m.x1 && m.y0 < b.y1 && b.y0 < m.y1 + }) + }) + }); + match can_join.and_then(|at| expected.get_mut(at)) { + Some((_, members)) => members.push((item.id, bounds)), + None => expected.push((key, vec![(item.id, bounds)])), + } + } + let actual = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let actual: Vec> = actual.iter().map(|g| g.children().unwrap().iter().map(|n| n.id).collect()).collect(); + let expected: Vec> = expected.into_iter().map(|(_, members)| members.into_iter().map(|(id, _)| id).collect()).collect(); + assert_eq!(actual, expected, "layout {layout}"); + } + } + + #[test] + fn an_abutting_gradient_stays_above_the_solid_area_it_borders() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let ramp = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops.clone())))); + let mut d = Document::new(100.0, 100.0); + let mut area = |x0: f64, x1: f64, paint: Paint| { + let path = + PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 60.0), Point::new(x0, 60.0)], true)); + Arc::new(Node::path(d.alloc_id(), path, fill_only(paint))) + }; + // A gradient, a solid area beside it and a second gradient beside that, bottom to top. + let items = vec![area(0.0, 50.0, ramp()), area(50.0, 80.0, Paint::solid(Color::rgb(0.2, 0.6, 0.2))), area(80.0, 100.0, ramp())]; + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let names: Vec<_> = groups.iter().map(|g| g.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Gradients", "#339933", "Gradients"]); + } +} + #[cfg(test)] mod trace_limit_tests { use super::{MAX_TRACE_ANCHORS, trace_warnings}; diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 9e397975f7..a94696d161 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3221,6 +3221,316 @@ fn image_trace_release_and_expand() { assert!(s.execute("imageTrace.release", &json!({})).is_err()); } +/// Expand by color: each color's paths in a group of their own, named by the color, the groups +/// stacked by the lowest path in each and the art drawn as before; Release to Layers then gives a +/// sublayer for each color. +#[test] +#[allow(clippy::cognitive_complexity)] // Exercises several color and stacking cases in one trace fixture. +fn image_trace_expand_by_color_groups_each_colors_paths() { + // A light field with a black ring and a red square on it. + let art = vectorcraft_trace::Raster::from_fn(200, 150, |x, y| { + let r = (f64::from(x) + 0.5 - 70.0).hypot(f64::from(y) + 0.5 - 75.0); + if (34.0..=40.0).contains(&r) { + [0, 0, 0, 255] + } else if (130..170).contains(&x) && (55..95).contains(&y) { + [200, 40, 50, 255] + } else { + [240, 240, 220, 255] + } + }); + let names = |n: &Node| n.children().unwrap().iter().map(|c| c.name.clone().unwrap_or_default()).collect::>(); + let hex = |n: &Node| n.appearance.fill_paint().color().unwrap().to_hex(); + let shot = |s: &Session| { + let img = render_doc(s, false); + (0..200).flat_map(|x| (0..150).map(move |y| (x, y))).map(|(x, y)| img.pixel(x, y)).collect::>() + }; + for method in ["abutting", "overlapping"] { + let params = json!({"mode": "color", "palette": "limited", "colors": 3, "method": method}); + let expand = |by_color: bool| { + let mut s = session(); + add_image(&mut s, &art, Affine::IDENTITY); + let r = s.execute("imageTrace.makeAndExpand", &json!({"params": params, "byColor": by_color})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + (s, g) + }; + let (flat, fg) = expand(false); + let (mut s, g) = expand(true); + let paths = node(&flat, fg).children().unwrap().clone(); + // Without byColor (the default) the paths sit in the trace's group, with no group of their own. + assert!(paths.iter().all(|p| !matches!(p.kind, NodeKind::Group { .. })), "{method}"); + let (default, dg) = { + let mut s = session(); + add_image(&mut s, &art, Affine::IDENTITY); + let r = s.execute("imageTrace.makeAndExpand", &json!({"params": params})).unwrap(); + (s, NodeId(r["id"].as_u64().unwrap())) + }; + assert!(*node(&default, dg).children().unwrap() == paths, "{method}: byColor is false when not given"); + // The colors in the order they first come in, bottom to top. + let mut order: Vec = vec![]; + for p in &paths { + if !order.contains(&hex(p)) { + order.push(hex(p)); + } + } + let mut sorted = order.clone(); + sorted.sort(); + assert_eq!(sorted, ["#000000", "#c82832", "#f0f0dc"], "{method}"); + let n = node(&s, g); + assert_eq!(names(&n), order, "{method}"); + // Each group holds its color's paths, and in turn they are the paths of the trace without + // byColor, in their order. + let groups = n.children().unwrap(); + for c in groups { + assert!(matches!(c.kind, NodeKind::Group { .. }), "{method}"); + assert!(c.children().unwrap().iter().all(|m| Some(hex(m)) == c.name), "{method}: {:?}", c.name); + } + let members: Vec> = groups.iter().flat_map(|c| c.children().unwrap().iter().cloned()).collect(); + assert!(members == paths, "{method}"); + assert!(shot(&s) == shot(&flat), "{method}: the art changed"); + // Release to Layers: a sublayer for each color, in the same order. + let r = s.execute("layer.releaseToLayers", &json!({"id": g.0})).unwrap(); + let subs = ids(&r); + assert_eq!(subs.len(), 3, "{method}"); + for (sub, name) in subs.iter().zip(&order) { + let l = node(&s, *sub); + assert!(matches!(l.kind, NodeKind::Layer { .. }), "{method}"); + assert_eq!(names(&l), std::slice::from_ref(name), "{method}"); + } + } + + // imageTrace.expand takes it too, as one undo step. + let mut s = session(); + add_image(&mut s, &art, Affine::IDENTITY); + let params = json!({"mode": "color", "palette": "limited", "colors": 3}); + let g = NodeId(s.execute("imageTrace.make", &json!({"params": params})).unwrap()["id"].as_u64().unwrap()); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("imageTrace.expand", &json!({"byColor": true})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let mut got = names(&node(&s, g)); + got.sort(); + assert_eq!(got, ["#000000", "#c82832", "#f0f0dc"]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, g).name.as_deref(), Some("Image Trace")); + + // A trace of one color gives one group holding every path. + let mut one = session(); + let bar = + vectorcraft_trace::Raster::from_fn(80, 40, |x, y| if (10..70).contains(&x) && (10..30).contains(&y) { [0, 0, 0, 255] } else { [255; 4] }); + add_image(&mut one, &bar, Affine::IDENTITY); + let r = one.execute("imageTrace.makeAndExpand", &json!({"params": {"ignoreWhite": true}, "byColor": true})).unwrap(); + let og = node(&one, NodeId(r["id"].as_u64().unwrap())); + assert_eq!(names(&og), ["#000000"]); + let only = &og.children().unwrap()[0]; + assert!(!only.children().unwrap().is_empty() && only.children().unwrap().iter().all(|m| hex(m) == "#000000")); + + // Auto Grouping's groups are not split: refused, and the trace stays as it was. + let mut grouped = params.clone(); + grouped["autoGrouping"] = json!(true); + let e = s.execute("imageTrace.makeAndExpand", &json!({"id": g.0, "params": grouped, "byColor": true})).unwrap_err().to_string(); + assert!(e.contains("Auto Grouping"), "{e}"); + let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "params": grouped})).unwrap()["id"].as_u64().unwrap()); + let e = s.execute("imageTrace.expand", &json!({"byColor": true})).unwrap_err().to_string(); + assert!(e.contains("Auto Grouping"), "{e}"); + assert_eq!(node(&s, g).name.as_deref(), Some("Image Trace")); + let e = s.execute("imageTrace.expand", &json!({"byColor": "yes"})).unwrap_err().to_string(); + assert!(e.contains("true or false"), "{e}"); + // Refused too when Auto Grouping grouped nothing, as with side-by-side stripes. + let mut s = session(); + let stripes = vectorcraft_trace::Raster::from_fn(60, 60, |x, _| match x / 20 { + 0 => [200, 40, 40, 255], + 1 => [40, 160, 60, 255], + _ => [40, 70, 200, 255], + }); + add_image(&mut s, &stripes, Affine::IDENTITY); + let g = NodeId(s.execute("imageTrace.make", &json!({"params": grouped})).unwrap()["id"].as_u64().unwrap()); + assert!(node(&s, g).children().unwrap().iter().all(|c| !matches!(c.kind, NodeKind::Group { .. }))); + let e = s.execute("imageTrace.expand", &json!({"byColor": true})).unwrap_err().to_string(); + assert!(e.contains("Auto Grouping"), "{e}"); + assert_eq!(node(&s, g).name.as_deref(), Some("Image Trace")); + + // A color linked to a global swatch goes by the swatch's name, a tint with its percentage. + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#c82828", "global": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Sky", "color": "#2846c8", "global": true})).unwrap(); + let r = vectorcraft_trace::Raster::from_fn(60, 60, |x, y| match (x < 30, y < 30) { + (true, _) => [200, 40, 40, 255], + (false, true) => [40, 160, 60, 255], + (false, false) => [40, 70, 200, 255], + }); + add_image(&mut s, &r, Affine::IDENTITY); + let limited = json!({"mode": "color", "palette": "limited", "colors": 3}); + let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap()); + let paths: Vec<(u64, String)> = + node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).map(|c| (c.id.0, hex(c))).collect(); + let mut colors: Vec<&str> = paths.iter().map(|(_, h)| h.as_str()).collect(); + colors.sort(); + colors.dedup(); + assert_eq!(colors, ["#2846c8", "#28a03c", "#c82828"]); + // The red paths link to Ink and the blue ones to Sky at 50%; green stays a plain color. + let pick = |want: &str| paths.iter().filter(|(_, h)| h == want).map(|(id, _)| *id).collect::>(); + s.execute("paint.setFill", &json!({"ids": pick("#c82828"), "swatch": "Ink"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": pick("#2846c8"), "swatch": "Sky", "tint": 50})).unwrap(); + s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap(); + let mut got = names(&node(&s, g)); + got.sort(); + assert_eq!(got, ["#28a03c", "Ink", "Sky 50%"]); + // A swatch named as another color's #rrggbb still gets a group of its own. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "newName": "#28a03c"})).unwrap(); + s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap(); + let mut got = names(&node(&s, g)); + got.sort(); + assert_eq!(got, ["#28a03c", "#28a03c", "Sky 50%"]); + + // Gradient fills share one group, and a stroked line goes by its stroke. + let ramp = vectorcraft_trace::Raster::from_fn(100, 60, |x, _| { + let t = (f64::from(x) + 0.5) / 100.0; + [(20.0 + 200.0 * t) as u8, 40, (220.0 - 180.0 * t) as u8, 255] + }); + let line = + vectorcraft_trace::Raster::from_fn(100, 100, |x, y| if (10..90).contains(&x) && (49..52).contains(&y) { [0, 0, 0, 255] } else { [255; 4] }); + for (art, params, want) in [ + (ramp, json!({"preset": "6 Colors", "params": {"gradients": true}, "byColor": true}), "Gradients"), + (line, json!({"params": {"ignoreWhite": true, "strokes": true, "strokeWidth": 5}, "byColor": true}), "#000000"), + ] { + let mut s = session(); + add_image(&mut s, &art, Affine::IDENTITY); + let res = s.execute("imageTrace.makeAndExpand", ¶ms).unwrap(); + assert_eq!(names(&node(&s, NodeId(res["id"].as_u64().unwrap()))), [want]); + } + + // Flat Logo stacks its shapes biggest first without cutting holes under white: a black ring's + // outline, a white disc on it and a black dot on that. Black keeps a group below white and one + // above it, and the art draws as before, through Make and Expand and through Expand. + let target = vectorcraft_trace::Raster::from_fn(120, 120, |x, y| { + let r = (f64::from(x) + 0.5 - 60.0).hypot(f64::from(y) + 0.5 - 60.0); + if r < 15.0 || (30.0..50.0).contains(&r) { + [0, 0, 0, 255] + } else if r < 30.0 { + [255, 255, 255, 255] + } else { + [0, 0, 0, 0] + } + }); + let logo = json!({"mode": "logo", "logoColors": ["#000000"]}); + let traced = |by_color: bool, expand_after: bool| { + let mut s = session(); + add_image(&mut s, &target, Affine::IDENTITY); + let g = if expand_after { + let g = s.execute("imageTrace.make", &json!({"params": logo})).unwrap()["id"].as_u64().unwrap(); + s.execute("imageTrace.expand", &json!({"byColor": by_color})).unwrap(); + g + } else { + s.execute("imageTrace.makeAndExpand", &json!({"params": logo, "byColor": by_color})).unwrap()["id"].as_u64().unwrap() + }; + (s, NodeId(g)) + }; + for expand_after in [false, true] { + let (flat, fg) = traced(false, expand_after); + let (s, g) = traced(true, expand_after); + let paths = node(&flat, fg).children().unwrap().clone(); + assert_eq!(paths.iter().map(|p| hex(p)).collect::>(), ["#000000", "#ffffff", "#000000"]); + assert_eq!(names(&node(&s, g)), ["#000000", "#ffffff", "#000000"], "expand after: {expand_after}"); + let members: Vec> = node(&s, g).children().unwrap().iter().flat_map(|c| c.children().unwrap().iter().cloned()).collect(); + assert!(members == paths, "expand after: {expand_after}"); + assert!(shot(&s) == shot(&flat), "expand after: {expand_after}: the art changed"); + } + + // An Abutting trace's top path, given the bottom path's color and moved onto the middle one (by + // a move or by a Transform effect), moved clear of it with a drop shadow cast onto it, or moved + // to share a pixel at its edge, before Expand, still draws on top of it. + let stripes = vectorcraft_trace::Raster::from_fn(90, 30, |x, _| match x / 30 { + 0 => [200, 40, 40, 255], + 1 => [40, 160, 60, 255], + _ => [40, 70, 200, 255], + }); + let edited = |by_color: bool, how: &str| { + let mut s = session(); + add_image(&mut s, &stripes, Affine::IDENTITY); + let limited = json!({"mode": "color", "palette": "limited", "colors": 3, "method": "abutting"}); + let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap()); + let paths: Vec> = node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).cloned().collect(); + assert_eq!(paths.len(), 3); + let (first, middle, last) = (&paths[0], &paths[1], &paths[2]); + s.execute("paint.setFill", &json!({"ids": [last.id.0], "color": hex(first)})).unwrap(); + let (to, from) = (middle.visual_bounds().unwrap(), last.visual_bounds().unwrap()); + let (dx, dy) = (to.x0 - from.x0, to.y0 - from.y0); + match how { + "beside" => { + // The middle path and the moved top path end and start inside one pixel. + s.execute("object.move", &json!({"ids": [middle.id.0], "dx": -0.5, "dy": 0})).unwrap(); + s.execute("object.move", &json!({"ids": [last.id.0], "dx": -0.3, "dy": 0})).unwrap() + } + "move" => s.execute("object.move", &json!({"ids": [last.id.0], "dx": dx, "dy": dy})).unwrap(), + "transform" => { + s.execute("effect.apply", &json!({"ids": [last.id.0], "effect": "distort.transform", "params": {"moveH": dx, "moveV": dy}})).unwrap() + } + _ => { + s.execute("object.move", &json!({"ids": [last.id.0], "dx": 40, "dy": 0})).unwrap(); + s.execute("effect.apply", &json!({"ids": [last.id.0], "effect": "stylize.dropShadow", "params": {"x": -70, "y": 0, "blur": 0}})) + .unwrap() + } + }; + s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": by_color})).unwrap(); + (s, g) + }; + for how in ["move", "transform", "shadow", "beside"] { + let (flat, _) = edited(false, how); + let (s, g) = edited(true, how); + assert_eq!(names(&node(&s, g)).len(), 3, "{how}"); + assert!(shot(&s) == shot(&flat), "{how}: the edited art changed"); + } + + // Two tints of one swatch that round to the same percentage are still two colors. + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Sky", "color": "#2846c8", "global": true})).unwrap(); + add_image(&mut s, &stripes, Affine::IDENTITY); + let limited = json!({"mode": "color", "palette": "limited", "colors": 3}); + let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap()); + let paths: Vec = node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).map(|c| c.id.0).collect(); + assert_eq!(paths.len(), 3); + s.execute("paint.setFill", &json!({"ids": [paths[0]], "swatch": "Sky", "tint": 50.1})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [paths[1], paths[2]], "swatch": "Sky", "tint": 50.4})).unwrap(); + s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap(); + let groups = node(&s, g).children().unwrap().clone(); + assert_eq!(names(&node(&s, g)), ["Sky 50%", "Sky 50%"]); + assert_eq!(groups.iter().map(|c| c.children().unwrap().len()).collect::>(), [1, 2]); +} + +#[test] +fn image_trace_expand_by_color_preserves_live_pathfinder_art() { + let mut s = session(); + let art = vectorcraft_trace::Raster::from_fn(100, 60, |x, y| { + if (10..40).contains(&y) && ((10..35).contains(&x) || (65..90).contains(&x)) { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }); + add_image(&mut s, &art, Affine::IDENTITY); + let g = NodeId(s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true}})).unwrap()["id"].as_u64().unwrap()); + let paths: Vec = node(&s, g).children().unwrap().iter().filter(|c| c.path_data().is_some()).map(|c| c.id).collect(); + assert_eq!(paths.len(), 2); + s.execute("select.set", &json!({"ids": [paths[1].0]})).unwrap(); + s.execute("object.move", &json!({"dx": -45, "dy": 0})).unwrap(); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "pathfinder.subtract"})).unwrap(); + let before = render_doc(&s, false); + let before_pixels: Vec<_> = (0..100).flat_map(|x| (0..60).map(move |y| (x, y))).map(|(x, y)| before.pixel(x, y)).collect(); + let original = node(&s, g); + let steps = s.doc().unwrap().history.undo.len(); + let result = s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})); + if let Err(e) = &result { + assert!(e.to_string().contains("Pathfinder"), "{e}"); + assert_eq!(node(&s, g), original); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + } + let after = render_doc(&s, false); + let after_pixels: Vec<_> = (0..100).flat_map(|x| (0..60).map(move |y| (x, y))).map(|(x, y)| after.pixel(x, y)).collect(); + let changed = after_pixels.iter().zip(&before_pixels).filter(|(a, b)| a != b).count(); + assert_eq!(changed, 0, "byColor changed {changed} live Pathfinder pixels: {result:?}"); + assert!(result.is_err(), "byColor must refuse a live Pathfinder operand group"); + let error = s.execute("imageTrace.makeAndExpand", &json!({"id": g.0, "params": {"ignoreWhite": true}, "byColor": true})).unwrap_err(); + assert!(error.to_string().contains("Pathfinder"), "{error}"); + assert_eq!(node(&s, g), original); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); +} + #[test] fn image_trace_make_and_expand_and_color_presets() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 68c1e81b00..0f39585bb6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6127,6 +6127,9 @@ anchor Points: Punts: CMYK Images Imatges CMYK Grayscale Images Imatges en escala de grisos @msg `kind` must be spotColors, colorEffects, rgbImages, cmykImages or grayImages `kind` ha de ser spotColors, colorEffects, rgbImages, cmykImages o grayImages +@msg byColor must be true or false byColor ha de ser true o false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor no pot separar els grups de l'agrupació automàtica: traça sense l'agrupació automàtica +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor no pot tornar a agrupar un traçat amb un efecte Pathfinder actiu: expandeix-lo sense byColor # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Color dels punts de la il·lustració diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e74e240d7b..13700edfa0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5711,6 +5711,9 @@ mark-style Japanese Japonské @msg too many library panels were opened in this session v této relaci bylo otevřeno příliš mnoho panelů knihoven @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Obraz má {_1} × {_2} pixelů, na jedné straně více než {LARGE_TRACE_SIDE}: vektorizuje se, ale pomaleji. Rychleji se vektorizuje s předvolbou nižší věrnosti nebo menší kopie obrazu. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Obraz byl vektorizován v rozlišení {_1} × {_2} pixelů, zmenšený z {_3} × {_4} (nejvýše {_5} megapixelů). +@msg byColor must be true or false byColor musí být true nebo false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor nerozdělí skupiny z Automatického seskupení: vektorizujte bez Automatického seskupení +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor nemůže přeskupit trasování s živým efektem Pathfinder: rozbalte bez byColor Snapping Přichytávání Snap to Tangent Přichytávat k tečně Snap to Perpendicular Přichytávat ke kolmici diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2da4241515..9938513a8e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5290,6 +5290,9 @@ effect Soft Weich @msg too many library panels were opened in this session in dieser Sitzung wurden zu viele Bibliotheksbedienfelder geöffnet @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Das Bild hat {_1} × {_2} Pixel, mehr als {LARGE_TRACE_SIDE} auf einer Seite: Es wird nachgezeichnet, aber langsamer. Eine Vorgabe mit geringerer Detailtreue oder eine kleinere Kopie des Bildes geht schneller. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Das Bild wurde mit {_1} × {_2} Pixeln nachgezeichnet, verkleinert von {_3} × {_4} (höchstens {_5} Megapixel). +@msg byColor must be true or false byColor muss true oder false sein +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor kann Gruppen aus Automatisch gruppieren nicht aufteilen: ohne Automatisch gruppieren nachzeichnen +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor kann eine Nachzeichnung mit einem aktiven Pathfinder-Effekt nicht neu gruppieren: ohne byColor umwandeln Snapping Einrasten Snap to Tangent An Tangente ausrichten Snap to Perpendicular An Senkrechter ausrichten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4d713dfedf..c2330c4bfc 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5662,6 +5662,9 @@ effect Points Σημεία @msg too many library panels were opened in this session άνοιξαν πάρα πολλοί πίνακες βιβλιοθηκών σε αυτή τη συνεδρία @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Η εικόνα είναι {_1} × {_2} εικονοστοιχεία, πάνω από {LARGE_TRACE_SIDE} σε μία πλευρά: ανιχνεύεται, αλλά πιο αργά. Μια προρύθμιση χαμηλότερης πιστότητας ή ένα μικρότερο αντίγραφο της εικόνας ανιχνεύεται γρηγορότερα. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Η εικόνα ανιχνεύτηκε σε {_1} × {_2} εικονοστοιχεία, σμικρυμένη από {_3} × {_4} (το πολύ {_5} megapixel). +@msg byColor must be true or false το byColor πρέπει να είναι true ή false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping το byColor δεν μπορεί να χωρίσει τις ομάδες της Αυτόματης ομαδοποίησης: ανιχνεύστε χωρίς Αυτόματη ομαδοποίηση +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor το byColor δεν μπορεί να αναομαδοποιήσει μια ανίχνευση με ενεργό εφέ Pathfinder: επεκτείνετε χωρίς byColor Snapping Προσκόλληση Snap to Tangent Προσκόλληση σε εφαπτομένη Snap to Perpendicular Προσκόλληση σε κάθετο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8c00c78d2b..e4807fae6c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5652,6 +5652,9 @@ mark-style Japanese Japonesas @msg too many library panels were opened in this session se abrieron demasiados paneles de biblioteca en esta sesión @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. La imagen tiene {_1} × {_2} píxeles, más de {LARGE_TRACE_SIDE} en un lado: se calcará, pero más despacio. Un ajuste preestablecido de menor fidelidad o una copia más pequeña de la imagen se calcan más rápido. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). La imagen se calcó a {_1} × {_2} píxeles, reducida desde {_3} × {_4} ({_5} megapíxeles como máximo). +@msg byColor must be true or false byColor debe ser true o false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor no puede dividir los grupos de Agrupación automática: calque sin Agrupación automática +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor no puede reagrupar un calco con un efecto Pathfinder activo: expanda sin byColor Snapping Ajuste Snap to Tangent Ajustar a tangente Snap to Perpendicular Ajustar a perpendicular diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3491ca30a4..3970072a3a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5674,6 +5674,9 @@ mark-style Japanese Japanilainen @msg too many library panels were opened in this session tässä istunnossa on avattu liian monta kirjastopaneelia @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Kuva on {_1} × {_2} kuvapistettä, yhdeltä sivultaan yli {LARGE_TRACE_SIDE}: se jäljitetään, mutta hitaammin. Pienemmän tarkkuuden esiasetus tai kuvan pienempi kopio jäljittyy nopeammin. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Kuva jäljitettiin kokoon {_1} × {_2} kuvapistettä pienennettynä koosta {_3} × {_4} (enintään {_5} megapikseliä). +@msg byColor must be true or false byColor-arvon on oltava true tai false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor ei voi jakaa Automaattisen ryhmittelyn ryhmiä: jäljitä ilman Automaattista ryhmittelyä +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor ei voi ryhmitellä uudelleen jäljitystä, jossa on aktiivinen Pathfinder-tehoste: laajenna ilman byColor-asetusta Snapping Tartunta Snap to Tangent Kohdista tangenttiin Snap to Perpendicular Kohdista kohtisuoraan diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 539c0f3ae9..1dd0177b65 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5706,6 +5706,9 @@ theme Appearance Apparence @msg too many library panels were opened in this session trop de panneaux de bibliothèque ont été ouverts dans cette session @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. L’image fait {_1} × {_2} pixels, plus de {LARGE_TRACE_SIDE} sur un côté : elle est vectorisée, mais plus lentement. Un paramètre prédéfini moins fidèle ou une copie plus petite de l’image se vectorise plus vite. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). L’image a été vectorisée à {_1} × {_2} pixels, réduite de {_3} × {_4} ({_5} mégapixels au plus). +@msg byColor must be true or false byColor doit être true ou false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor ne peut pas scinder les groupes du Groupement automatique : vectorisez sans Groupement automatique +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor ne peut pas regrouper un tracé avec un effet Pathfinder actif : développez sans byColor Snapping Magnétisme Snap to Tangent Magnétisme de la tangente Snap to Perpendicular Magnétisme de la perpendiculaire diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 247ffc64ec..fe27d894f8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5694,6 +5694,9 @@ imageTrace Outline Körvonal @msg too many library panels were opened in this session ebben a munkamenetben túl sok könyvtárpanel nyílt meg @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. A kép {_1} × {_2} képpont, egyik oldalán több mint {LARGE_TRACE_SIDE}: a vektorizálás megtörténik, de lassabban. Kisebb hűségű előbeállítással vagy a kép kisebb másolatával gyorsabb. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). A kép vektorizálása {_1} × {_2} képponton történt, {_3} × {_4} méretről kicsinyítve (legfeljebb {_5} megapixel). +@msg byColor must be true or false a byColor értéke true vagy false lehet +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping a byColor nem bontja fel az Automatikus csoportosítás csoportjait: vektorizáljon Automatikus csoportosítás nélkül +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor a byColor nem csoportosíthatja át az élő Pathfinder-effektussal rendelkező vektorizálást: bővítse ki byColor nélkül Snapping Illesztés Snap to Tangent Illesztés érintőre Snap to Perpendicular Illesztés merőlegesre diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 44da4c994d..cf88a606ac 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5324,6 +5324,9 @@ lighting Light Luce @msg too many library panels were opened in this session in questa sessione sono stati aperti troppi pannelli libreria @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. L’immagine è di {_1} × {_2} pixel, più di {LARGE_TRACE_SIDE} su un lato: viene vettorializzata, ma più lentamente. Un predefinito a fedeltà più bassa o una copia più piccola dell’immagine è più veloce. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). L’immagine è stata vettorializzata a {_1} × {_2} pixel, ridotta da {_3} × {_4} (al massimo {_5} megapixel). +@msg byColor must be true or false byColor deve essere true o false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor non può dividere i gruppi di Raggruppamento automatico: vettorializza senza Raggruppamento automatico +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor non può raggruppare di nuovo una traccia con un effetto Pathfinder attivo: espandi senza byColor Snapping Aggancio Snap to Tangent Aggancia alla tangente Snap to Perpendicular Aggancia alla perpendicolare diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 07577badfe..d4ee9ab665 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5367,6 +5367,9 @@ lighting Light ライト @msg too many library panels were opened in this session このセッションで開いたライブラリパネルが多すぎます @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. 画像は {_1} × {_2} ピクセルで、一辺が {LARGE_TRACE_SIDE} を超えています。トレースはできますが、時間がかかります。忠実度の低いプリセットや画像の小さいコピーを使うと速くなります。 @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). 画像は {_3} × {_4} から縮小した {_1} × {_2} ピクセルでトレースされました (最大 {_5} メガピクセル)。 +@msg byColor must be true or false byColor は true または false にしてください +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor は自動グループ化のグループを分割できません: 自動グループ化なしでトレースしてください +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor はライブ Pathfinder 効果のあるトレースを再グループ化できません: byColor なしで拡張してください Snapping スナップ Snap to Tangent 接線にスナップ Snap to Perpendicular 垂線にスナップ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6a5581ed4f..f46a2eb142 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5557,6 +5557,9 @@ imageTrace Outline კონტური @msg `colorGroup` needs `mode: "color"` `colorGroup`-ს სჭირდება `mode: "color"` @msg no color group `{name}` in the document (see swatch.list) დოკუმენტში ფერების ჯგუფი `{name}` არ არის (იხ. swatch.list) @msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. ბრტყელი ლოგოს რეჟიმში გამოსახულება ვექტორიზდა {_1} × {_2} პიქსელზე, საშუალოს გამოთვლით შემცირდა {_3} × {_4}-დან. +@msg byColor must be true or false byColor უნდა იყოს true ან false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor ვერ დაყოფს ავტომატური დაჯგუფების ჯგუფებს: ვექტორიზება გააკეთეთ ავტომატური დაჯგუფების გარეშე +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor ვერ გადააჯგუფებს ტრასირებას აქტიური Pathfinder ეფექტით: გააფართოვეთ byColor-ის გარეშე @msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` ბიბლიოთეკის პანელი არ არის (იხ. window.swatchLibrary) @msg `{key}` must be a #rrggbb color `{key}` უნდა იყოს #rrggbb ფერი @msg a key object sits on that point ამ წერტილზე საკვანძო ობიექტი მდებარეობს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cce6ce736a..9b6c840939 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5285,6 +5285,9 @@ lighting Light 광원 @msg too many library panels were opened in this session 이 세션에서 라이브러리 패널을 너무 많이 열었습니다 @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. 이미지가 {_1} × {_2}픽셀로 한 변이 {LARGE_TRACE_SIDE}을 넘습니다. 추적은 되지만 더 느립니다. 충실도가 낮은 사전 설정이나 이미지의 작은 사본을 사용하면 더 빠릅니다. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). 이미지를 {_3} × {_4}에서 축소한 {_1} × {_2}픽셀로 추적했습니다(최대 {_5}메가픽셀). +@msg byColor must be true or false byColor는 true 또는 false여야 합니다 +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor는 자동 그룹화 그룹을 나눌 수 없습니다. 자동 그룹화 없이 추적하세요 +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor는 라이브 Pathfinder 효과가 있는 추적을 다시 그룹화할 수 없습니다. byColor 없이 확장하세요 Snapping 스냅 Snap to Tangent 접선에 스냅 Snap to Perpendicular 수직선에 스냅 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index adfb669e8d..f00ae7858c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5564,6 +5564,9 @@ mark-style Japanese Japońskie @msg too many library panels were opened in this session w tej sesji otwarto zbyt wiele paneli bibliotek @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Obraz ma {_1} × {_2} pikseli, ponad {LARGE_TRACE_SIDE} na jednym boku: zostanie obrysowany, ale wolniej. Ustawienie wstępne o niższej wierności lub mniejsza kopia obrazu obrysuje się szybciej. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Obraz obrysowano w rozdzielczości {_1} × {_2} pikseli, po zmniejszeniu z {_3} × {_4} (najwyżej {_5} megapikseli). +@msg byColor must be true or false byColor musi mieć wartość true lub false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor nie może podzielić grup Automatycznego grupowania: obrysuj bez Automatycznego grupowania +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor nie może ponownie zgrupować obrysu z aktywnym efektem Pathfinder: rozwiń bez byColor Snapping Przyciąganie Snap to Tangent Przyciągaj do stycznych Snap to Perpendicular Przyciągaj do prostopadłych diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 183d41dc18..5d277fab5d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5626,6 +5626,9 @@ mark-style Japanese Japonesas @msg too many library panels were opened in this session foram abertos painéis de biblioteca demais nesta sessão @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. A imagem tem {_1} × {_2} pixels, mais de {LARGE_TRACE_SIDE} em um lado: ela é traçada, mas mais devagar. Uma predefinição de menor fidelidade ou uma cópia menor da imagem traça mais rápido. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). A imagem foi traçada em {_1} × {_2} pixels, reduzida de {_3} × {_4} (no máximo {_5} megapixels). +@msg byColor must be true or false byColor deve ser true ou false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor não pode dividir os grupos de Agrupamento Automático: trace sem Agrupamento Automático +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor não pode reagrupar um traçado com um efeito Pathfinder ativo: expanda sem byColor Snapping Ajuste Snap to Tangent Ajustar à Tangente Snap to Perpendicular Ajustar à Perpendicular diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 544050c9a4..42d30eadd9 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5319,6 +5319,9 @@ lighting Light Свет @msg too many library panels were opened in this session в этом сеансе открыто слишком много панелей библиотек @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Изображение {_1} × {_2} пикселей, больше {LARGE_TRACE_SIDE} по одной стороне: трассировка выполняется, но медленнее. Стиль с меньшей точностью или уменьшенная копия изображения трассируются быстрее. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Изображение трассировано в размере {_1} × {_2} пикселей, уменьшенное с {_3} × {_4} (не более {_5} мегапикселей). +@msg byColor must be true or false byColor должен иметь значение true или false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor не может разделить группы автогруппировки: трассируйте без автогруппировки +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor не может перегруппировать трассировку с действующим эффектом Pathfinder: разверните без byColor Snapping Привязка Snap to Tangent Привязать к касательной Snap to Perpendicular Привязать к перпендикуляру diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f007400d9c..896b59c2e7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5733,6 +5733,9 @@ swatch Yellow Green Gulgrön @msg “{name}” is not a file ”{name}” är inte en fil @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Bilden är {_1} × {_2} pixlar, mer än {LARGE_TRACE_SIDE} på en sida: den vektoriseras, men långsammare. En förinställning med lägre återgivning eller en mindre kopia av bilden går snabbare. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Bilden vektoriserades vid {_1} × {_2} pixlar, nedskalad från {_3} × {_4} (högst {_5} megapixlar). +@msg byColor must be true or false byColor måste vara true eller false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor kan inte dela upp grupper från Automatisk gruppering: vektorisera utan Automatisk gruppering +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor kan inte gruppera om en kalkering med en aktiv Pathfinder-effekt: expandera utan byColor Snapping Fäst Snap to Tangent Fäst mot tangent Snap to Perpendicular Fäst mot vinkelrät diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3c28f018cb..5cf7665d4b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5712,6 +5712,9 @@ theme Appearance Görünüm @msg library panel `{given}` isn't missing its library `{given}` kitaplık panelinin kitaplığı eksik değil @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Görüntü {_1} × {_2} piksel, bir kenarı {LARGE_TRACE_SIDE} değerinden büyük: izlenir, ancak daha yavaş. Daha düşük doğruluklu bir ön ayar veya görüntünün daha küçük bir kopyası daha hızlı izlenir. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Görüntü {_3} × {_4} boyutundan küçültülerek {_1} × {_2} pikselde izlendi (en fazla {_5} megapiksel). +@msg byColor must be true or false byColor true veya false olmalıdır +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor, Otomatik Gruplama gruplarını bölemez: Otomatik Gruplama olmadan izleyin +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor, canlı Pathfinder efekti olan bir izlemeyi yeniden gruplayamaz: byColor olmadan genişletin Gap Length: Boşluk Uzunluğu: @msg `colorGroup` needs `library: "document"` `colorGroup` için `library: "document"` gerekir @msg `colorGroup` needs `palette: "documentLibrary"` `colorGroup` için `palette: "documentLibrary"` gerekir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7de17b0fc2..e7055639b3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5304,6 +5304,9 @@ lighting Light Світло @msg too many library panels were opened in this session у цьому сеансі відкрито забагато панелей бібліотек @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Зображення {_1} × {_2} пікселів, понад {LARGE_TRACE_SIDE} з одного боку: трасування виконується, але повільніше. Стиль із нижчою точністю або менша копія зображення трасуються швидше. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Зображення трасовано в розмірі {_1} × {_2} пікселів, зменшене з {_3} × {_4} (щонайбільше {_5} мегапікселів). +@msg byColor must be true or false byColor має мати значення true або false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor не може розділити групи автогрупування: трасуйте без автогрупування +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor не може перегрупувати трасування з активним ефектом Pathfinder: розгорніть без byColor Snapping Прив’язка Snap to Tangent Прив’язати до дотичної Snap to Perpendicular Прив’язати до перпендикуляра diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 678eddbcee..4b9de70d41 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5305,6 +5305,9 @@ theme Appearance Giao diện @msg too many library panels were opened in this session đã mở quá nhiều bảng thư viện trong phiên này @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Ảnh có kích thước {_1} × {_2} điểm ảnh, hơn {LARGE_TRACE_SIDE} ở một cạnh: ảnh vẫn được dò, nhưng chậm hơn. Một thiết lập sẵn có độ trung thực thấp hơn hoặc một bản sao nhỏ hơn của ảnh sẽ dò nhanh hơn. @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Ảnh đã được dò ở {_1} × {_2} điểm ảnh, thu nhỏ từ {_3} × {_4} (tối đa {_5} megapixel). +@msg byColor must be true or false byColor phải là true hoặc false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor không thể tách các nhóm của Tự động nhóm: hãy dò mà không bật Tự động nhóm +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor không thể nhóm lại bản dò có hiệu ứng Pathfinder đang hoạt động: mở rộng mà không dùng byColor Snapping Hút Snap to Tangent Hút vào tiếp tuyến Snap to Perpendicular Hút vào đường vuông góc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9a33468395..225ca11126 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5542,6 +5542,9 @@ lighting Light 光源 @msg too many library panels were opened in this session 本次会话中打开的库面板过多 @msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. 图像为 {_1} × {_2} 像素,某一边超过 {LARGE_TRACE_SIDE}:会进行描摹,但速度较慢。使用保真度较低的预设或图像的较小副本会更快。 @msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). 图像已按 {_1} × {_2} 像素描摹,由 {_3} × {_4} 缩小而来(最多 {_5} 百万像素)。 +@msg byColor must be true or false byColor 必须是 true 或 false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor 无法拆分自动编组生成的编组:请在不使用自动编组的情况下描摹 +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor 无法重新编组带有实时 Pathfinder 效果的描摹:请不使用 byColor 进行扩展 Snapping 对齐 Snap to Tangent 对齐切线 Snap to Perpendicular 对齐垂线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4b7107054d..e18a0fc585 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2553,6 +2553,9 @@ file-filter Templates 範本 @msg `colorGroup` needs `mode: "color"` `colorGroup` 需要 `mode: "color"` @msg no color group `{name}` in the document (see swatch.list) 文件中沒有顏色群組 `{name}` (請參閱 swatch.list) @msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. 「扁平標誌」模式已以 {_1} × {_2} 像素描圖,由 {_3} × {_4} 平均縮小而來。 +@msg byColor must be true or false byColor 必須是 true 或 false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor 無法拆分自動群組產生的群組:請不使用自動群組來描圖 +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor 無法重新編組帶有即時 Pathfinder 效果的描圖:請不使用 byColor 進行擴充 # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one 「編輯原稿」只能開啟影像與文件檔案;「{name}」不屬於這兩類 @msg only http, https and mailto URLs open in the browser, not “{url}” 只有 http、https 和 mailto URL 會在瀏覽器中開啟,「{url}」不會 diff --git a/docs/mcp.md b/docs/mcp.md index 6b4a6bbeb5..426fb7d880 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2015,6 +2015,17 @@ already walks Image Trace. Short agent entry points: - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. + With `byColor: true`, `imageTrace.expand` and `imageTrace.makeAndExpand` put each color's paths in a group of their + own, named by the global swatch the color links to (a tint with its percentage, as `Sky 50%`) or as `#rrggbb`; + gradient fills share a group named `Gradients`. The groups stack in the order of the lowest path in each, and each + keeps its paths' order. For either Expand command, a path that would move under a path of another + color whose painted bounds, effects and shadows included, come within one document point of it starts another group + of its color instead of joining an earlier one. Paths whose painted bounds come within one document point of an + intervening color stay in separate groups to preserve their stacking order; at small view or raster-export scales, + regrouped paths farther apart can still share antialiased pixels, so edge pixels may differ. In a Flat Logo trace of a + black ring around a white disc around a black dot, black gets two groups. `layer.releaseToLayers` on the expanded group then + gives each group a sublayer. A trace made with `autoGrouping` is refused. Expanding by color also refuses a trace + with a live Pathfinder effect. `imageTrace.presets.save {name?, newName?, preset?, enhanced?, params?}` saves tracing settings as a preset kept with the preferences: `params` over `preset`'s (default: the saved preset `name`, else Default), checked as `imageTrace.make` checks them; without `name` it is a new "Tracing Preset N", and `newName` renames a saved preset (the reply's From 7fd287238fcd0de0fa177c675b780179fd1e06ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 17:28:30 -0700 Subject: [PATCH 06/26] Actions: Batch refuses Save and Close over data sets instead of saving each one over the open document Data sets share one open document, so Save and Close saved every data set over the same file and only the last one survived. action.batch now returns an error for source datasets with destination saveAndClose before it selects a data set or runs a step, and the Batch dialog offers None and Folder for a Data Sets source, moving a Save and Close choice to Folder. --- crates/engine/src/cmd/fileio/action_batch.rs | 76 ++++++++++++++++++++ crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/ui-egui/src/dialogs/action_batch.rs | 42 +++++++++-- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 31 files changed, 145 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index e11b6adcd6..c1b5ae0161 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -73,6 +73,10 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { if !matches!(destination, "none" | "saveAndClose" | "folder") { return Err(bad(C, "`destination` must be `none`, `saveAndClose` or `folder`")); } + // Data sets share one open document, so Save and Close would write every row over one file. + if source == "datasets" && destination == "saveAndClose" { + return Err(bad(C, "Save and Close cannot batch data sets: choose Folder to save each data set to its own file")); + } let dest_folder = str_param(p, "destinationFolder").map(absolute_path); if destination == "folder" { let Some(ref folder) = dest_folder else { @@ -1292,6 +1296,78 @@ mod tests { assert_eq!(file_names(&dest), ["Untitled_A-B-3.vectorcraft", "Untitled_a-b-2.vectorcraft", "Untitled_a-b.vectorcraft"], "{r}"); } + /// A saved document with a text object bound to `Name` and two data sets, `A` and `B`. + fn saved_with_two_data_sets(path: &std::path::Path) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "A"})).unwrap()["id"].as_u64().unwrap(); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [id]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "A"})).unwrap(); + s.execute("text.setText", &json!({"ids": [id], "text": "B"})).unwrap(); + s.execute("dataset.capture", &json!({"name": "B"})).unwrap(); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + s + } + + fn save_and_close_over_data_sets(s: &mut Session) -> Result { + s.execute( + "action.batch", + &json!({"source": "datasets", "destination": "saveAndClose", "commands": [{"command": "object.unlockAll", "params": {}}]}), + ) + } + + #[test] + fn batch_refuses_save_and_close_over_data_sets_before_writing() { + let path = tmp("save-close-sets").join("template.vectorcraft"); + let mut s = saved_with_two_data_sets(&path); + let bytes = std::fs::read(&path).unwrap(); + let (active, revision) = { + let st = s.doc().unwrap(); + (st.doc.variables.active_dataset.clone(), st.revision) + }; + let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string(); + assert!(msg.contains("choose Folder"), "{msg}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the template is not written"); + let st = s.doc().unwrap(); + assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected"); + assert_eq!(st.revision, revision, "no step runs"); + assert_eq!(st.path.as_deref(), Some(path.to_string_lossy().as_ref()), "the template stays open"); + } + + #[test] + fn batch_refuses_save_and_close_over_data_sets_of_an_unsaved_document() { + let mut s = with_data_sets(&["a", "b"]); + let (active, revision) = { + let st = s.doc().unwrap(); + (st.doc.variables.active_dataset.clone(), st.revision) + }; + let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string(); + assert!(msg.contains("choose Folder"), "{msg}"); + let st = s.doc().unwrap(); + assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected"); + assert_eq!(st.revision, revision, "no step runs"); + assert!(st.path.is_none()); + } + + #[test] + fn batch_save_and_close_saves_and_closes_each_source_file() { + let src = tmp("save-close-src"); + let a = write_svg(&src, "a.svg", "#f00"); + let before = std::fs::read(&a).unwrap(); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({"folder": src.to_string_lossy(), "destination": "saveAndClose", "commands": [{"command": "object.unlockAll", "params": {}}]}), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_ne!(std::fs::read(&a).unwrap(), before, "the source file is saved over"); + assert_eq!(file_names(&src), ["a.svg"], "{r}"); + assert!(s.doc().is_err(), "the source file is closed"); + } + #[test] fn batch_refuses_nesting_and_empty_commands() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 011d025e37..0c010de100 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; refused for source datasets: use folder to save each data set to its own file) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", always, action_batch::action_batch ), diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 0d6382e9a8..36369132ad 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -77,7 +77,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(8.0); - form::choice(ui, d, "destination", "Destination:", (LABEL, 200.0), &[("none", "None"), ("saveAndClose", "Save and Close"), ("folder", "Folder")]); + let choices = destinations(&source); + let destination = d.str("destination"); + if !choices.iter().any(|(value, _)| *value == destination) { + d.fields.insert("destination".into(), json!("folder")); + } + form::choice(ui, d, "destination", "Destination:", (LABEL, 200.0), choices); if d.str("destination") == "folder" { widgets::label_row(ui, tl!("Destination Folder:"), LABEL, |ui| { form::text(ui, d, "destinationFolder", 200.0); @@ -95,6 +100,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// The Destination choices for `source`. Data sets share one open document, so Save and Close is +/// offered for a Folder source only. +fn destinations(source: &str) -> &'static [(&'static str, &'static str)] { + if source == "datasets" { + &[("none", "None"), ("folder", "Folder")] + } else { + &[("none", "None"), ("saveAndClose", "Save and Close"), ("folder", "Folder")] + } +} + fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let set = d.fields.get("set").and_then(Value::as_u64).unwrap_or(0) as usize; let action = d.fields.get("action").and_then(Value::as_u64).unwrap_or(0) as usize; @@ -161,6 +176,13 @@ mod tests { use vectorcraft_engine::Session; fn shown(source: &str) -> Vec { + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["source"] = json!(source); + render(&mut d) + } + + /// Draws `d` once and returns the texts it shows. + fn render(d: &mut Dialog) -> Vec { fn collect(shape: &egui::Shape, out: &mut Vec) { match shape { egui::Shape::Text(t) => out.push(t.galley.text().to_string()), @@ -169,12 +191,10 @@ mod tests { } } let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); - d.fields["source"] = json!(source); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut frame = ctx.run_ui(Default::default(), |ui| { - body(&mut app, ui, &mut d); + body(&mut app, ui, d); }); frame.textures_delta.clear(); let mut labels = vec![]; @@ -220,4 +240,18 @@ mod tests { d.fields["source"] = json!("folder"); assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none()); } + + #[test] + fn data_sets_do_not_offer_save_and_close() { + assert!(!destinations("datasets").iter().any(|(value, _)| *value == "saveAndClose")); + assert!(destinations("folder").iter().any(|(value, _)| *value == "saveAndClose")); + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["destination"] = json!("saveAndClose"); + assert!(render(&mut d).iter().any(|label| label == "Save and Close")); + d.fields["source"] = json!("datasets"); + let labels = render(&mut d); + assert!(!labels.iter().any(|label| label == "Save and Close"), "{labels:?}"); + assert!(labels.iter().any(|label| label == "Destination Folder:"), "{labels:?}"); + assert_eq!(params(&d, "Test", vec![])["destination"], "folder"); + } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8bdbf65a92..85c714b789 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6099,6 +6099,7 @@ breakText Glyphs Глифи File + Data Set Name Файл + име на набора от данни Data Set Name Име на набора от данни @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` трябва да е `fileNumber`, `fileDataSetName` или `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Запазване и затваряне“ не може да обработва набори от данни: изберете „Папка“, за да запишете всеки набор от данни в отделен файл @msg no free data set file name in destination folder Няма свободно име за файл на набор от данни в целевата папка # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index ca52bf5172..edd42d7c47 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6111,6 +6111,7 @@ shape Open Otvoren File + Data Set Name Datoteka + naziv skupa podataka Data Set Name Naziv skupa podataka @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` mora biti `fileNumber`, `fileDataSetName` ili `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Sačuvaj i zatvori“ ne može obraditi skupove podataka: odaberite „Folder“ da biste svaki skup podataka sačuvali u zasebnu datoteku @msg no free data set file name in destination folder Nema slobodnog naziva datoteke skupa podataka u odredišnoj mapi # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0f39585bb6..f2b00581a0 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6255,6 +6255,7 @@ breakText Glyphs Glifs File + Data Set Name Fitxer + nom del conjunt de dades Data Set Name Nom del conjunt de dades @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` ha de ser `fileNumber`, `fileDataSetName` o `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Desa i tanca» no pot processar conjunts de dades: trieu «Carpeta» per desar cada conjunt de dades en un fitxer propi @msg no free data set file name in destination folder No hi ha cap nom de fitxer de conjunt de dades lliure a la carpeta de destinació # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 13700edfa0..66aaefa8e2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6274,6 +6274,7 @@ breakText Glyphs Glyfy File + Data Set Name Soubor + název sady dat Data Set Name Název sady dat @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musí být `fileNumber`, `fileDataSetName` nebo `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Uložit a zavřít“ nelze použít pro sady dat: zvolte „Složka“, aby se každá sada dat uložila do vlastního souboru @msg no free data set file name in destination folder V cílové složce není volný název souboru sady dat # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d50e862bbe..3e93895794 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6114,6 +6114,7 @@ breakText Glyphs Glyffer File + Data Set Name Fil + datasætnavn Data Set Name Datasætnavn @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` skal være `fileNumber`, `fileDataSetName` eller `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Gem og luk" kan ikke køre på datasæt: vælg "Mappe" for at gemme hvert datasæt i sin egen fil @msg no free data set file name in destination folder Intet ledigt filnavn til datasættet i destinationsmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9938513a8e..75345b1f71 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5859,6 +5859,7 @@ breakText Glyphs Glyphen File + Data Set Name Datei + Datensatzname Data Set Name Datensatzname @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` muss `fileNumber`, `fileDataSetName` oder `dataSetName` sein +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Speichern und schließen“ kann nicht auf Datensätze angewendet werden: Wählen Sie „Ordner“, um jeden Datensatz in einer eigenen Datei zu speichern @msg no free data set file name in destination folder Kein freier Dateiname für den Datensatz im Zielordner # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c2330c4bfc..cf071420c8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6225,6 +6225,7 @@ breakText Glyphs Γλύφοι File + Data Set Name Αρχείο + όνομα συνόλου δεδομένων Data Set Name Όνομα συνόλου δεδομένων @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` Το `datasetFileNaming` πρέπει να είναι `fileNumber`, `fileDataSetName` ή `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file Η «Αποθήκευση και κλείσιμο» δεν μπορεί να εφαρμοστεί σε σύνολα δεδομένων: επιλέξτε «Φάκελος» για να αποθηκευτεί κάθε σύνολο δεδομένων σε δικό του αρχείο @msg no free data set file name in destination folder Δεν υπάρχει διαθέσιμο όνομα αρχείου συνόλου δεδομένων στον φάκελο προορισμού # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e4807fae6c..29d3457481 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6216,6 +6216,7 @@ breakText Glyphs Glifos File + Data Set Name Archivo + nombre del conjunto de datos Data Set Name Nombre del conjunto de datos @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` debe ser `fileNumber`, `fileDataSetName` o `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Guardar y cerrar» no puede procesar conjuntos de datos: elija «Carpeta» para guardar cada conjunto de datos en su propio archivo @msg no free data set file name in destination folder No hay un nombre de archivo libre para el conjunto de datos en la carpeta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3970072a3a..7e06955927 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6304,6 +6304,7 @@ breakText Glyphs Merkit File + Data Set Name Tiedosto + tietojoukon nimi Data Set Name Tietojoukon nimi @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`-arvon on oltava `fileNumber`, `fileDataSetName` tai `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file ”Tallenna ja sulje” ei voi käsitellä tietojoukkoja: valitse ”Kansio”, niin jokainen tietojoukko tallennetaan omaan tiedostoonsa @msg no free data set file name in destination folder Kohdekansiossa ei ole vapaata tietojoukon tiedostonimeä # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1dd0177b65..69a5d71e7f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6269,6 +6269,7 @@ breakText Glyphs Glyphes File + Data Set Name Fichier + nom du jeu de données Data Set Name Nom du jeu de données @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` doit être `fileNumber`, `fileDataSetName` ou `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file « Enregistrer et fermer » ne peut pas traiter les jeux de données : choisissez « Dossier » pour enregistrer chaque jeu de données dans son propre fichier @msg no free data set file name in destination folder Aucun nom de fichier libre pour le jeu de données dans le dossier de destination # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fe27d894f8..f33c5d7d6b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6258,6 +6258,7 @@ breakText Glyphs Glifák File + Data Set Name Fájl + adatkészlet neve Data Set Name Adatkészlet neve @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` A `datasetFileNaming` értéke `fileNumber`, `fileDataSetName` vagy `dataSetName` lehet +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file A „Mentés és bezárás” nem dolgozhat fel adatkészleteket: válassza a „Mappa” lehetőséget, hogy minden adatkészlet külön fájlba kerüljön @msg no free data set file name in destination folder Nincs szabad adatkészlet-fájlnév a célmappában # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4d03770830..e7b1655d60 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6114,6 +6114,7 @@ breakText Glyphs Glif File + Data Set Name File + nama set data Data Set Name Nama set data @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` harus `fileNumber`, `fileDataSetName`, atau `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Simpan dan tutup" tidak dapat memproses set data: pilih "Folder" untuk menyimpan setiap set data ke file tersendiri @msg no free data set file name in destination folder Tidak ada nama file set data yang tersedia di folder tujuan # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cf88a606ac..231ed0230f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5893,6 +5893,7 @@ breakText Glyphs Glifi File + Data Set Name File + nome set di dati Data Set Name Nome set di dati @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve essere `fileNumber`, `fileDataSetName` o `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Salva e chiudi» non può elaborare i set di dati: scegli «Cartella» per salvare ogni set di dati in un file a sé @msg no free data set file name in destination folder Nessun nome file libero per il set di dati nella cartella di destinazione # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d4ee9ab665..ac6bb51bc9 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5958,6 +5958,7 @@ breakText Glyphs 字形 File + Data Set Name ファイル名 + データセット名 Data Set Name データセット名 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` は `fileNumber`、`fileDataSetName`、`dataSetName` のいずれかである必要があります +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file 「保存して閉じる」ではデータセットをバッチ処理できません:各データセットを個別のファイルに保存するには「フォルダー」を選択してください @msg no free data set file name in destination folder 保存先フォルダーに使用可能なデータセットのファイル名がありません # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f46a2eb142..a0b1d42a6f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6271,6 +6271,7 @@ breakText Glyphs გლიფები File + Data Set Name ფაილი + მონაცემთა ნაკრების სახელი Data Set Name მონაცემთა ნაკრების სახელი @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` უნდა იყოს `fileNumber`, `fileDataSetName` ან `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „შენახვა და დახურვა“ ვერ ამუშავებს მონაცემთა ნაკრებებს: აირჩიეთ „საქაღალდე“, რომ თითოეული მონაცემთა ნაკრები ცალკე ფაილში შეინახოთ @msg no free data set file name in destination folder დანიშნულების საქაღალდეში მონაცემთა ნაკრებისთვის თავისუფალი ფაილის სახელი არ არის # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9b6c840939..c083822b24 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5854,6 +5854,7 @@ breakText Glyphs 글리프 File + Data Set Name 파일 + 데이터 세트 이름 Data Set Name 데이터 세트 이름 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`은 `fileNumber`, `fileDataSetName` 또는 `dataSetName`이어야 합니다 +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file '저장 후 닫기'로는 데이터 세트를 일괄 처리할 수 없습니다: 각 데이터 세트를 별도의 파일로 저장하려면 '폴더'를 선택하세요 @msg no free data set file name in destination folder 대상 폴더에 사용할 수 있는 데이터 세트 파일 이름이 없습니다 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index bd525526b9..5c9bd74f13 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6160,6 +6160,7 @@ breakText Glyphs Glyphs File + Data Set Name Bestand + naam gegevensset Data Set Name Naam gegevensset @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` moet `fileNumber`, `fileDataSetName` of `dataSetName` zijn +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file 'Opslaan en sluiten' kan geen gegevenssets verwerken: kies 'Map' om elke gegevensset in een eigen bestand op te slaan @msg no free data set file name in destination folder Geen vrije bestandsnaam voor de gegevensset in de doelmap # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f00ae7858c..cb934d7843 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6128,6 +6128,7 @@ breakText Glyphs Glify File + Data Set Name Plik + nazwa zestawu danych Data Set Name Nazwa zestawu danych @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musi mieć wartość `fileNumber`, `fileDataSetName` lub `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Zapisz i zamknij” nie może przetwarzać zestawów danych: wybierz „Folder”, aby zapisać każdy zestaw danych w osobnym pliku @msg no free data set file name in destination folder Brak wolnej nazwy pliku zestawu danych w folderze docelowym # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5d277fab5d..8ac21f8e97 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6190,6 +6190,7 @@ breakText Glyphs Glifos File + Data Set Name Arquivo + nome do conjunto de dados Data Set Name Nome do conjunto de dados @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve ser `fileNumber`, `fileDataSetName` ou `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Salvar e fechar" não pode processar conjuntos de dados: escolha "Pasta" para salvar cada conjunto de dados em um arquivo próprio @msg no free data set file name in destination folder Não há nome de arquivo livre para o conjunto de dados na pasta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 42d30eadd9..d436e1b7e0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6251,6 +6251,7 @@ breakText Glyphs Глифы File + Data Set Name Файл + имя набора данных Data Set Name Имя набора данных @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` должно быть `fileNumber`, `fileDataSetName` или `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Сохранить и закрыть» не работает с наборами данных: выберите «Папка», чтобы сохранить каждый набор данных в отдельный файл @msg no free data set file name in destination folder В папке назначения нет свободного имени файла для набора данных # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 896b59c2e7..4438027d80 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6326,6 +6326,7 @@ breakText Glyphs Glyfer File + Data Set Name Fil + datauppsättningens namn Data Set Name Datauppsättningens namn @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` måste vara `fileNumber`, `fileDataSetName` eller `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file ”Spara och stäng” kan inte köras på datauppsättningar: välj ”Mapp” för att spara varje datauppsättning i en egen fil @msg no free data set file name in destination folder Inget ledigt filnamn för datauppsättningen i målmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5cf7665d4b..5157d5bf36 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6231,6 +6231,7 @@ breakText Glyphs Glifler File + Data Set Name Dosya + veri kümesi adı Data Set Name Veri kümesi adı @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` değeri `fileNumber`, `fileDataSetName` veya `dataSetName` olmalıdır +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Kaydet ve Kapat" veri kümelerini toplu işleyemez: her veri kümesini ayrı bir dosyaya kaydetmek için "Klasör" seçeneğini seçin @msg no free data set file name in destination folder Hedef klasörde veri kümesi için boş bir dosya adı yok # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e7055639b3..db7e9ccd2f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5873,6 +5873,7 @@ breakText Glyphs Гліфи File + Data Set Name Файл + назва набору даних Data Set Name Назва набору даних @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` має бути `fileNumber`, `fileDataSetName` або `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Зберегти й закрити» не працює з наборами даних: виберіть «Папка», щоб зберегти кожен набір даних в окремий файл @msg no free data set file name in destination folder У папці призначення немає вільного імені файлу набору даних # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4b9de70d41..f593048091 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5874,6 +5874,7 @@ breakText Glyphs Glyph File + Data Set Name Tệp + tên tập dữ liệu Data Set Name Tên tập dữ liệu @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` phải là `fileNumber`, `fileDataSetName` hoặc `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Lưu và đóng" không thể xử lý các tập dữ liệu: chọn "Thư mục" để lưu mỗi tập dữ liệu vào một tệp riêng @msg no free data set file name in destination folder Không có tên tệp tập dữ liệu còn trống trong thư mục đích # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 225ca11126..379f4dc235 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6115,6 +6115,7 @@ breakText Glyphs 字形 File + Data Set Name 文件 + 数据集名称 Data Set Name 数据集名称 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必须是 `fileNumber`、`fileDataSetName` 或 `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file “存储并关闭”无法批处理数据集:请选择“文件夹”,将每个数据集存储为单独的文件 @msg no free data set file name in destination folder 目标文件夹中没有可用的数据集文件名 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e18a0fc585..46c332bd40 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5911,6 +5911,7 @@ breakText Glyphs 字符 File + Data Set Name 檔案 + 資料集名稱 Data Set Name 資料集名稱 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必須是 `fileNumber`、`fileDataSetName` 或 `dataSetName` +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file 「儲存並關閉」無法批次處理資料集:請選擇「資料夾」,將每個資料集儲存為個別檔案 @msg no free data set file name in destination folder 目的地資料夾中沒有可用的資料集檔案名稱 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/docs/mcp.md b/docs/mcp.md index 426fb7d880..41d5184561 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3514,7 +3514,9 @@ Actions panel plays an action as a `command.batch`, omitting steps whose playbac cleared. An action set saved as `.vcactions` keeps each excluded step with `excluded: true`; loading an earlier version 1 set without that flag includes every step. The Actions panel menu's Batch… runs `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with -destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. For a Data Sets source, +destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. A Data Sets source does not +take `saveAndClose`: `action.batch` refuses it before it selects a data set or runs a step, and the dialog offers +None and Folder only. For a Data Sets source, `datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name (`Alpha`). An omitted parameter keeps File + Data Set Name for existing callers; the dialog starts with File + Number. A folder source ignores this parameter. The folder diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d1d0c19e61..470d368861 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -643,6 +643,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). + - Batch… over data sets offers None and Folder as the destination, and `action.batch` refuses Save and Close for a Data Sets source before it runs a step, so the batch does not save every data set over the open document's file. This is VectorCraft's own rule: [Play actions on a batch of files](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/play-actions-on-a-batch-of-files.html) describes Save and Close as saving "the file in their current location" and does not say what it does over data sets. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. From 8a52d50154d7ea18e3687ab2b4d5342290ca6d87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 17:39:03 -0700 Subject: [PATCH 07/26] i18n: French rows keep the no-break space before punctuation --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 69a5d71e7f..e814e83785 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6269,7 +6269,7 @@ breakText Glyphs Glyphes File + Data Set Name Fichier + nom du jeu de données Data Set Name Nom du jeu de données @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` doit être `fileNumber`, `fileDataSetName` ou `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file « Enregistrer et fermer » ne peut pas traiter les jeux de données : choisissez « Dossier » pour enregistrer chaque jeu de données dans son propre fichier +@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file « Enregistrer et fermer » ne peut pas traiter les jeux de données : choisissez « Dossier » pour enregistrer chaque jeu de données dans son propre fichier @msg no free data set file name in destination folder Aucun nom de fichier libre pour le jeu de données dans le dossier de destination # Path Precision Tools add-on: Path Effects (Effect › Path Effects). From 2ad0268388427bfc2b8a85520ed7b7e790e44172 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 01:06:03 -0700 Subject: [PATCH 08/26] Actions: Batch over data sets keeps Save and Close and warns when each data set saves over one file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Batch… with a Data Sets source offers None, Save and Close and Folder again. Save and Close saves the open document over its own file after each data set. When every data set saves over the same file, the dialog shows a warning and `action.batch` returns `warning`: with Save and Close, or with a recorded step that writes a file and that the batch does not point into the destination folder. A Save step without a path counts when it writes the document's own file; Save As, Save a Copy, Save as Template and Export steps count when they give a path; Export for Screens counts when its folder, given or from its preset, names a folder. Save and Close over the data sets of a document that was never saved is refused with "the document has never been saved" before a data set is selected. --- crates/engine/src/cmd/fileio.rs | 1 + crates/engine/src/cmd/fileio/action_batch.rs | 142 ++++++++++++++++--- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/screens.rs | 2 +- crates/ui-egui/src/dialogs/action_batch.rs | 68 ++++++--- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 33 files changed, 206 insertions(+), 72 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 0c888d13c3..ae2ecde665 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -54,6 +54,7 @@ pub mod zip; use serde_json::{Value, json}; +pub use action_batch::batch_overwrites_one_file; pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings}; pub(crate) use encode::{anti_alias, background, with_single_artboard}; diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index c1b5ae0161..26d6c476e3 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -73,10 +73,6 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { if !matches!(destination, "none" | "saveAndClose" | "folder") { return Err(bad(C, "`destination` must be `none`, `saveAndClose` or `folder`")); } - // Data sets share one open document, so Save and Close would write every row over one file. - if source == "datasets" && destination == "saveAndClose" { - return Err(bad(C, "Save and Close cannot batch data sets: choose Folder to save each data set to its own file")); - } let dest_folder = str_param(p, "destinationFolder").map(absolute_path); if destination == "folder" { let Some(ref folder) = dest_folder else { @@ -99,11 +95,65 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { }; match source { "folder" => batch_folder(s, C, p, override_open, &run), - "datasets" => batch_datasets(s, C, &run), + "datasets" => { + let one_file = batch_overwrites_one_file(s, p); + let mut r = batch_datasets(s, C, &run)?; + if one_file { + r["warning"] = json!(ONE_FILE_WARNING); + } + Ok(r) + } _ => Err(bad(C, "`source` must be `folder` or `datasets`")), } } +/// The `warning` of a Data Sets batch for which [`batch_overwrites_one_file`] holds. +#[cfg(not(target_arch = "wasm32"))] +const ONE_FILE_WARNING: &str = "each data set saves over the same file, which keeps only the last data set"; + +/// Whether an `action.batch` with params `p` plays on data sets of the open document in `s` and +/// writes each data set to the same file. Save and Close saves the open document over its own file +/// after every data set. A step that the batch does not point into `destinationFolder` writes the +/// same file every time when it writes one: a Save, Save As, Save a Copy, Save as Template, Export +/// or Export Selection step that gives a `path`; a Save step without a `path` when the document has +/// a file of its own (saved, and not converted from an older version or restored by Data Recovery) +/// and the step gives no `format` or the document's own; an Export for Screens +/// step whose `folder`, given or from its `exportPreset`, names a folder, whatever the overrides. +/// Other steps return their data instead of writing a file. +pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { + if p.get("source").and_then(Value::as_str) != Some("datasets") { + return false; + } + if p.get("destination").and_then(Value::as_str) == Some("saveAndClose") { + return true; + } + let folder = p.get("destinationFolder").and_then(Value::as_str).is_some(); + let redirected = |key: &str| folder && p.get(key).and_then(Value::as_bool).unwrap_or(true); + let (save, export) = (redirected("overrideSave"), redirected("overrideExport")); + // The format of the open document's own file, which a Save step without a `path` writes. + let own_format = s.active().filter(|st| st.path.is_some() && !st.converted && !st.recovered).map(|st| st.format); + let names = |v: Option<&Value>| v.and_then(Value::as_str).is_some_and(|s| !s.is_empty()); + p.get("commands").and_then(Value::as_array).is_some_and(|cmds| { + cmds.iter().any(|c| { + let params = c.get("params").cloned().unwrap_or_else(|| Value::Object(Default::default())); + let path = names(params.get("path")); + let own_file = || match params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()) { + None => own_format.is_some(), + Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), + }; + match c.get("command").and_then(Value::as_str).unwrap_or("") { + "document.save" | "file.save" => !save && (path || own_file()), + "file.saveAs" => !save && path, + "file.saveCopy" | "file.saveAsTemplate" => path, + "document.export" | "document.exportSelection" => !export && path, + // Override Export sets `path`, which Export for Screens does not read: its `folder` stays. + "document.exportForScreens" => super::screens::with_preset(s, ¶ms).is_ok_and(|p| names(p.get("folder"))), + _ => false, + } + }) + }) +} + #[cfg(not(target_arch = "wasm32"))] fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: &Run<'_>) -> Result { use super::{absolute_path, may_read}; @@ -149,6 +199,9 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { if names.len() > MAX_BATCH_FILES { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } + if run.destination == "saveAndClose" && st.path.is_none() { + return Err(bad(cmd, "the document has never been saved")); + } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; let steps = filter_steps(run.steps, true, false); @@ -1318,21 +1371,76 @@ mod tests { } #[test] - fn batch_refuses_save_and_close_over_data_sets_before_writing() { + fn batch_save_and_close_over_data_sets_saves_each_over_the_template_and_warns() { let path = tmp("save-close-sets").join("template.vectorcraft"); let mut s = saved_with_two_data_sets(&path); - let bytes = std::fs::read(&path).unwrap(); - let (active, revision) = { - let st = s.doc().unwrap(); - (st.doc.variables.active_dataset.clone(), st.revision) - }; - let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string(); - assert!(msg.contains("choose Folder"), "{msg}"); - assert_eq!(std::fs::read(&path).unwrap(), bytes, "the template is not written"); + std::fs::write(&path, b"stale").unwrap(); + let r = save_and_close_over_data_sets(&mut s).unwrap(); + assert_eq!((r["count"].as_u64(), r["failed"].as_u64()), (Some(2), Some(0)), "{r}"); + assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}"); + assert_ne!(std::fs::read(&path).unwrap(), b"stale", "the template's file is saved over"); + assert_eq!(file_names(path.parent().unwrap()), ["template.vectorcraft"], "{r}"); let st = s.doc().unwrap(); - assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected"); - assert_eq!(st.revision, revision, "no step runs"); + assert_eq!(st.doc.variables.active_dataset.as_deref(), Some("B"), "the last data set is applied"); assert_eq!(st.path.as_deref(), Some(path.to_string_lossy().as_ref()), "the template stays open"); + assert!(!st.is_dirty(), "the last data set is saved"); + } + + #[test] + fn batch_warns_when_a_recorded_save_writes_one_file_for_every_data_set() { + let path = tmp("recorded-save-sets").join("template.vectorcraft"); + let mut s = saved_with_two_data_sets(&path); + let save = json!([{"command": "document.save", "params": {}}]); + let r = s.execute("action.batch", &json!({"source": "datasets", "commands": save})).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}"); + let dest = tmp("recorded-save-dest"); + let p = json!({"source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(), "commands": save}); + let r = s.execute("action.batch", &p).unwrap(); + assert!(r.get("warning").is_none(), "Override Save points each save into the folder: {r}"); + let unlock = json!({"source": "datasets", "commands": [{"command": "object.unlockAll", "params": {}}]}); + let r = s.execute("action.batch", &unlock).unwrap(); + assert!(r.get("warning").is_none(), "{r}"); + } + + #[test] + fn one_file_rule_covers_save_and_close_and_steps_left_in_place() { + let saved = saved_with_two_data_sets(&tmp("one-file-rule").join("template.vectorcraft")); + let unsaved = with_data_sets(&["a"]); + let with = |extra: Value| { + let mut p = json!({"source": "datasets", "commands": [{"command": "document.export", "params": {"path": "/x/a.png"}}]}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + batch_overwrites_one_file(&saved, &p) + }; + assert!(with(json!({})), "an export with its own path"); + assert!(!with(json!({"destination": "folder", "destinationFolder": "/out"}))); + assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "overrideExport": false}))); + assert!(!with(json!({"destination": "folder", "destinationFolder": "/out", "overrideSave": false}))); + assert!(!with(json!({"source": "folder"})), "a folder source opens a file per pass"); + assert!(with(json!({"destination": "saveAndClose", "commands": [{"command": "object.unlockAll"}]}))); + let saved_as = json!({"commands": [{"command": "file.saveAs", "params": {"path": "/x/a.svg"}}]}); + assert!(with(saved_as.clone())); + assert!(!with(json!({"destination": "folder", "destinationFolder": "/out", "commands": saved_as["commands"]}))); + assert!(!with(json!({"commands": [{"command": "file.saveAs", "params": {}}]})), "no path: the data comes back"); + assert!(!with(json!({"commands": [{"command": "document.export", "params": {"format": "png"}}]})), "no path: the data comes back"); + let copy = json!([{"command": "file.saveCopy", "params": {"path": "/x/a.vectorcraft"}}]); + assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": copy})), "Override Save leaves copies alone"); + let save = |format: Option<&str>| { + let params = format.map_or(json!({}), |f| json!({"format": f})); + json!({"source": "datasets", "commands": [{"command": "document.save", "params": params}]}) + }; + assert!(batch_overwrites_one_file(&saved, &save(None)), "the document's own file"); + assert!(batch_overwrites_one_file(&saved, &save(Some("vectorcraft"))), "the document's own format"); + assert!(!batch_overwrites_one_file(&unsaved, &save(None)), "a document never saved has no file to write"); + assert!(!batch_overwrites_one_file(&saved, &save(Some("svg"))), "another format without a path: the data comes back"); + assert!(!with(json!({"commands": [{"command": "file.saveCopy", "params": {"folder": "/x"}}]})), "a folder alone: the data comes back"); + let screens = json!([{"command": "document.exportForScreens", "params": {"folder": "/x"}}]); + assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": screens})), "Override Export leaves its folder"); + assert!(!with(json!({"commands": [{"command": "document.exportForScreens", "params": {}}]}))); + let preset = json!([{"command": "document.exportForScreens", "params": {"exportPreset": "Logo Package"}}]); + assert!(!with(json!({"commands": preset})), "a preset without a folder: the data comes back"); } #[test] @@ -1343,7 +1451,7 @@ mod tests { (st.doc.variables.active_dataset.clone(), st.revision) }; let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string(); - assert!(msg.contains("choose Folder"), "{msg}"); + assert!(msg.ends_with("the document has never been saved"), "{msg}"); let st = s.doc().unwrap(); assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected"); assert_eq!(st.revision, revision, "no step runs"); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0c010de100..9b62a5342c 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; refused for source datasets: use folder to save each data set to its own file) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close, or a Save, Save a Copy, Save as Template or Export step that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 201a4b4797..11e878bc13 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -670,7 +670,7 @@ fn find_preset(s: &Session, name: &str) -> Option { } /// `p` over the settings of its `exportPreset`, when it names one (its own keys win). -fn with_preset(s: &Session, p: &Value) -> Result { +pub(super) fn with_preset(s: &Session, p: &Value) -> Result { let Some(name) = str_param(p, "exportPreset") else { return Ok(p.clone()) }; let preset = find_preset(s, name).ok_or_else(|| bad(C, format!("no export preset `{name}` (see document.exportPresets.list)")))?; let mut merged = preset.settings; diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 36369132ad..4e8a3bfae8 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -77,12 +77,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(8.0); - let choices = destinations(&source); - let destination = d.str("destination"); - if !choices.iter().any(|(value, _)| *value == destination) { - d.fields.insert("destination".into(), json!("folder")); - } - form::choice(ui, d, "destination", "Destination:", (LABEL, 200.0), choices); + form::choice(ui, d, "destination", "Destination:", (LABEL, 200.0), &[("none", "None"), ("saveAndClose", "Save and Close"), ("folder", "Folder")]); if d.str("destination") == "folder" { widgets::label_row(ui, tl!("Destination Folder:"), LABEL, |ui| { form::text(ui, d, "destinationFolder", 200.0); @@ -97,17 +92,21 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "overrideSave", "Override Action \"Save\" Commands"); form::check(ui, d, "overrideExport", "Override Action \"Export\" Commands"); form::check(ui, d, "stopOnError", "Stop on Errors"); + if overwrites_one_file(app, d) { + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Each data set saves over the same file, which keeps only the last data set.")).size(11.5).color(t.warning)); + } false } -/// The Destination choices for `source`. Data sets share one open document, so Save and Close is -/// offered for a Folder source only. -fn destinations(source: &str) -> &'static [(&'static str, &'static str)] { - if source == "datasets" { - &[("none", "None"), ("folder", "Folder")] - } else { - &[("none", "None"), ("saveAndClose", "Save and Close"), ("folder", "Folder")] - } +/// Whether the batch the dialog would run saves every data set over the same file +/// ([`vectorcraft_engine::cmd::fileio::batch_overwrites_one_file`]). +fn overwrites_one_file(app: &VectorcraftApp, d: &Dialog) -> bool { + let set = d.fields.get("set").and_then(Value::as_u64).unwrap_or(0) as usize; + let action = d.fields.get("action").and_then(Value::as_u64).unwrap_or(0) as usize; + let steps = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)).map_or(&[][..], |a| &a.steps[..]); + let commands = steps.iter().map(|(c, p)| json!({"command": c, "params": p})).collect(); + vectorcraft_engine::cmd::fileio::batch_overwrites_one_file(&app.session, ¶ms(d, "", commands)) } fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { @@ -183,6 +182,11 @@ mod tests { /// Draws `d` once and returns the texts it shows. fn render(d: &mut Dialog) -> Vec { + render_in(&mut VectorcraftApp::new(Session::new(), Default::default()), d) + } + + /// Draws `d` once over `app` and returns the texts it shows. + fn render_in(app: &mut VectorcraftApp, d: &mut Dialog) -> Vec { fn collect(shape: &egui::Shape, out: &mut Vec) { match shape { egui::Shape::Text(t) => out.push(t.galley.text().to_string()), @@ -190,11 +194,10 @@ mod tests { _ => {} } } - let mut app = VectorcraftApp::new(Session::new(), Default::default()); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut frame = ctx.run_ui(Default::default(), |ui| { - body(&mut app, ui, d); + body(app, ui, d); }); frame.textures_delta.clear(); let mut labels = vec![]; @@ -241,17 +244,36 @@ mod tests { assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none()); } + const ONE_FILE: &str = "Each data set saves over the same file, which keeps only the last data set."; + #[test] - fn data_sets_do_not_offer_save_and_close() { - assert!(!destinations("datasets").iter().any(|(value, _)| *value == "saveAndClose")); - assert!(destinations("folder").iter().any(|(value, _)| *value == "saveAndClose")); + fn data_sets_offer_save_and_close_with_a_warning() { let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); d.fields["destination"] = json!("saveAndClose"); - assert!(render(&mut d).iter().any(|label| label == "Save and Close")); + let labels = render(&mut d); + assert!(labels.iter().any(|label| label == "Save and Close"), "{labels:?}"); + assert!(!labels.iter().any(|label| label == ONE_FILE), "a folder source opens a file per pass: {labels:?}"); d.fields["source"] = json!("datasets"); let labels = render(&mut d); - assert!(!labels.iter().any(|label| label == "Save and Close"), "{labels:?}"); - assert!(labels.iter().any(|label| label == "Destination Folder:"), "{labels:?}"); - assert_eq!(params(&d, "Test", vec![])["destination"], "folder"); + assert!(labels.iter().any(|label| label == "Save and Close"), "{labels:?}"); + assert!(labels.iter().any(|label| label == ONE_FILE), "{labels:?}"); + assert_eq!(params(&d, "Test", vec![])["destination"], "saveAndClose"); + d.fields["destination"] = json!("folder"); + assert!(!render(&mut d).iter().any(|label| label == ONE_FILE)); + } + + #[test] + fn data_sets_warn_about_a_recorded_save_left_in_place() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui.action_sets[0].actions[0].steps.push(("document.save".into(), json!({"path": "/x/a.vectorcraft"}))); + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["source"] = json!("datasets"); + d.fields["destinationFolder"] = json!("/out"); + assert!(!render_in(&mut app, &mut d).iter().any(|label| label == ONE_FILE), "Override Save points the save into the folder"); + d.fields["overrideSave"] = json!(false); + assert!(render_in(&mut app, &mut d).iter().any(|label| label == ONE_FILE)); + d.fields["overrideSave"] = json!(true); + d.fields["destination"] = json!("none"); + assert!(render_in(&mut app, &mut d).iter().any(|label| label == ONE_FILE)); } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 85c714b789..b94e7895c2 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6099,7 +6099,7 @@ breakText Glyphs Глифи File + Data Set Name Файл + име на набора от данни Data Set Name Име на набора от данни @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` трябва да е `fileNumber`, `fileDataSetName` или `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Запазване и затваряне“ не може да обработва набори от данни: изберете „Папка“, за да запишете всеки набор от данни в отделен файл + Each data set saves over the same file, which keeps only the last data set. Всеки набор от данни се записва върху същия файл, в който остава само последният набор от данни. @msg no free data set file name in destination folder Няма свободно име за файл на набор от данни в целевата папка # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index edd42d7c47..176aafe80e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6111,7 +6111,7 @@ shape Open Otvoren File + Data Set Name Datoteka + naziv skupa podataka Data Set Name Naziv skupa podataka @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` mora biti `fileNumber`, `fileDataSetName` ili `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Sačuvaj i zatvori“ ne može obraditi skupove podataka: odaberite „Folder“ da biste svaki skup podataka sačuvali u zasebnu datoteku + Each data set saves over the same file, which keeps only the last data set. Svaki skup podataka se sačuva preko iste datoteke, u kojoj ostaje samo posljednji skup podataka. @msg no free data set file name in destination folder Nema slobodnog naziva datoteke skupa podataka u odredišnoj mapi # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f2b00581a0..2efc35f975 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6255,7 +6255,7 @@ breakText Glyphs Glifs File + Data Set Name Fitxer + nom del conjunt de dades Data Set Name Nom del conjunt de dades @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` ha de ser `fileNumber`, `fileDataSetName` o `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Desa i tanca» no pot processar conjunts de dades: trieu «Carpeta» per desar cada conjunt de dades en un fitxer propi + Each data set saves over the same file, which keeps only the last data set. Cada conjunt de dades es desa sobre el mateix fitxer, que només conserva l'últim conjunt de dades. @msg no free data set file name in destination folder No hi ha cap nom de fitxer de conjunt de dades lliure a la carpeta de destinació # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 66aaefa8e2..5e72b3e661 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6274,7 +6274,7 @@ breakText Glyphs Glyfy File + Data Set Name Soubor + název sady dat Data Set Name Název sady dat @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musí být `fileNumber`, `fileDataSetName` nebo `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Uložit a zavřít“ nelze použít pro sady dat: zvolte „Složka“, aby se každá sada dat uložila do vlastního souboru + Each data set saves over the same file, which keeps only the last data set. Každá sada dat se uloží přes stejný soubor, ve kterém zůstane jen poslední sada dat. @msg no free data set file name in destination folder V cílové složce není volný název souboru sady dat # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3e93895794..516fada6ef 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6114,7 +6114,7 @@ breakText Glyphs Glyffer File + Data Set Name Fil + datasætnavn Data Set Name Datasætnavn @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` skal være `fileNumber`, `fileDataSetName` eller `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Gem og luk" kan ikke køre på datasæt: vælg "Mappe" for at gemme hvert datasæt i sin egen fil + Each data set saves over the same file, which keeps only the last data set. Hvert datasæt gemmes oven i den samme fil, som kun beholder det sidste datasæt. @msg no free data set file name in destination folder Intet ledigt filnavn til datasættet i destinationsmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 75345b1f71..73217a465c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5859,7 +5859,7 @@ breakText Glyphs Glyphen File + Data Set Name Datei + Datensatzname Data Set Name Datensatzname @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` muss `fileNumber`, `fileDataSetName` oder `dataSetName` sein -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Speichern und schließen“ kann nicht auf Datensätze angewendet werden: Wählen Sie „Ordner“, um jeden Datensatz in einer eigenen Datei zu speichern + Each data set saves over the same file, which keeps only the last data set. Jeder Datensatz wird über dieselbe Datei gespeichert, die nur den letzten Datensatz behält. @msg no free data set file name in destination folder Kein freier Dateiname für den Datensatz im Zielordner # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index cf071420c8..1a703f159b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6225,7 +6225,7 @@ breakText Glyphs Γλύφοι File + Data Set Name Αρχείο + όνομα συνόλου δεδομένων Data Set Name Όνομα συνόλου δεδομένων @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` Το `datasetFileNaming` πρέπει να είναι `fileNumber`, `fileDataSetName` ή `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file Η «Αποθήκευση και κλείσιμο» δεν μπορεί να εφαρμοστεί σε σύνολα δεδομένων: επιλέξτε «Φάκελος» για να αποθηκευτεί κάθε σύνολο δεδομένων σε δικό του αρχείο + Each data set saves over the same file, which keeps only the last data set. Κάθε σύνολο δεδομένων αποθηκεύεται πάνω στο ίδιο αρχείο, το οποίο κρατά μόνο το τελευταίο σύνολο δεδομένων. @msg no free data set file name in destination folder Δεν υπάρχει διαθέσιμο όνομα αρχείου συνόλου δεδομένων στον φάκελο προορισμού # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 29d3457481..0e4df7790e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6216,7 +6216,7 @@ breakText Glyphs Glifos File + Data Set Name Archivo + nombre del conjunto de datos Data Set Name Nombre del conjunto de datos @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` debe ser `fileNumber`, `fileDataSetName` o `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Guardar y cerrar» no puede procesar conjuntos de datos: elija «Carpeta» para guardar cada conjunto de datos en su propio archivo + Each data set saves over the same file, which keeps only the last data set. Cada conjunto de datos se guarda sobre el mismo archivo, que solo conserva el último conjunto de datos. @msg no free data set file name in destination folder No hay un nombre de archivo libre para el conjunto de datos en la carpeta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7e06955927..8d1fe5f741 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6304,7 +6304,7 @@ breakText Glyphs Merkit File + Data Set Name Tiedosto + tietojoukon nimi Data Set Name Tietojoukon nimi @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`-arvon on oltava `fileNumber`, `fileDataSetName` tai `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file ”Tallenna ja sulje” ei voi käsitellä tietojoukkoja: valitse ”Kansio”, niin jokainen tietojoukko tallennetaan omaan tiedostoonsa + Each data set saves over the same file, which keeps only the last data set. Jokainen tietojoukko tallennetaan saman tiedoston päälle, johon jää vain viimeinen tietojoukko. @msg no free data set file name in destination folder Kohdekansiossa ei ole vapaata tietojoukon tiedostonimeä # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e814e83785..6f1bc17150 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6269,7 +6269,7 @@ breakText Glyphs Glyphes File + Data Set Name Fichier + nom du jeu de données Data Set Name Nom du jeu de données @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` doit être `fileNumber`, `fileDataSetName` ou `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file « Enregistrer et fermer » ne peut pas traiter les jeux de données : choisissez « Dossier » pour enregistrer chaque jeu de données dans son propre fichier + Each data set saves over the same file, which keeps only the last data set. Chaque jeu de données est enregistré sur le même fichier, qui ne conserve que le dernier jeu de données. @msg no free data set file name in destination folder Aucun nom de fichier libre pour le jeu de données dans le dossier de destination # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f33c5d7d6b..b52b620222 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6258,7 +6258,7 @@ breakText Glyphs Glifák File + Data Set Name Fájl + adatkészlet neve Data Set Name Adatkészlet neve @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` A `datasetFileNaming` értéke `fileNumber`, `fileDataSetName` vagy `dataSetName` lehet -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file A „Mentés és bezárás” nem dolgozhat fel adatkészleteket: válassza a „Mappa” lehetőséget, hogy minden adatkészlet külön fájlba kerüljön + Each data set saves over the same file, which keeps only the last data set. Minden adatkészlet ugyanabba a fájlba mentődik, amely csak az utolsó adatkészletet őrzi meg. @msg no free data set file name in destination folder Nincs szabad adatkészlet-fájlnév a célmappában # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e7b1655d60..176e1da886 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6114,7 +6114,7 @@ breakText Glyphs Glif File + Data Set Name File + nama set data Data Set Name Nama set data @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` harus `fileNumber`, `fileDataSetName`, atau `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Simpan dan tutup" tidak dapat memproses set data: pilih "Folder" untuk menyimpan setiap set data ke file tersendiri + Each data set saves over the same file, which keeps only the last data set. Setiap set data disimpan menimpa file yang sama, sehingga hanya set data terakhir yang tersisa. @msg no free data set file name in destination folder Tidak ada nama file set data yang tersedia di folder tujuan # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 231ed0230f..c9d3169851 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5893,7 +5893,7 @@ breakText Glyphs Glifi File + Data Set Name File + nome set di dati Data Set Name Nome set di dati @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve essere `fileNumber`, `fileDataSetName` o `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Salva e chiudi» non può elaborare i set di dati: scegli «Cartella» per salvare ogni set di dati in un file a sé + Each data set saves over the same file, which keeps only the last data set. Ogni set di dati viene salvato sullo stesso file, che conserva solo l'ultimo set di dati. @msg no free data set file name in destination folder Nessun nome file libero per il set di dati nella cartella di destinazione # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ac6bb51bc9..6dfa754c72 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5958,7 +5958,7 @@ breakText Glyphs 字形 File + Data Set Name ファイル名 + データセット名 Data Set Name データセット名 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` は `fileNumber`、`fileDataSetName`、`dataSetName` のいずれかである必要があります -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file 「保存して閉じる」ではデータセットをバッチ処理できません:各データセットを個別のファイルに保存するには「フォルダー」を選択してください + Each data set saves over the same file, which keeps only the last data set. 各データセットが同じファイルに上書き保存されるため、最後のデータセットだけが残ります。 @msg no free data set file name in destination folder 保存先フォルダーに使用可能なデータセットのファイル名がありません # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a0b1d42a6f..fb53b753da 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6271,7 +6271,7 @@ breakText Glyphs გლიფები File + Data Set Name ფაილი + მონაცემთა ნაკრების სახელი Data Set Name მონაცემთა ნაკრების სახელი @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` უნდა იყოს `fileNumber`, `fileDataSetName` ან `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „შენახვა და დახურვა“ ვერ ამუშავებს მონაცემთა ნაკრებებს: აირჩიეთ „საქაღალდე“, რომ თითოეული მონაცემთა ნაკრები ცალკე ფაილში შეინახოთ + Each data set saves over the same file, which keeps only the last data set. თითოეული მონაცემთა ნაკრები ერთსა და იმავე ფაილზე ინახება, რომელშიც მხოლოდ ბოლო მონაცემთა ნაკრები რჩება. @msg no free data set file name in destination folder დანიშნულების საქაღალდეში მონაცემთა ნაკრებისთვის თავისუფალი ფაილის სახელი არ არის # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c083822b24..81e98bb478 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5854,7 +5854,7 @@ breakText Glyphs 글리프 File + Data Set Name 파일 + 데이터 세트 이름 Data Set Name 데이터 세트 이름 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`은 `fileNumber`, `fileDataSetName` 또는 `dataSetName`이어야 합니다 -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file '저장 후 닫기'로는 데이터 세트를 일괄 처리할 수 없습니다: 각 데이터 세트를 별도의 파일로 저장하려면 '폴더'를 선택하세요 + Each data set saves over the same file, which keeps only the last data set. 각 데이터 세트가 같은 파일에 덮어써지므로 마지막 데이터 세트만 남습니다. @msg no free data set file name in destination folder 대상 폴더에 사용할 수 있는 데이터 세트 파일 이름이 없습니다 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5c9bd74f13..345d7918ef 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6160,7 +6160,7 @@ breakText Glyphs Glyphs File + Data Set Name Bestand + naam gegevensset Data Set Name Naam gegevensset @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` moet `fileNumber`, `fileDataSetName` of `dataSetName` zijn -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file 'Opslaan en sluiten' kan geen gegevenssets verwerken: kies 'Map' om elke gegevensset in een eigen bestand op te slaan + Each data set saves over the same file, which keeps only the last data set. Elke gegevensset wordt over hetzelfde bestand opgeslagen, dat alleen de laatste gegevensset bewaart. @msg no free data set file name in destination folder Geen vrije bestandsnaam voor de gegevensset in de doelmap # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index cb934d7843..1290a0f79a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6128,7 +6128,7 @@ breakText Glyphs Glify File + Data Set Name Plik + nazwa zestawu danych Data Set Name Nazwa zestawu danych @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musi mieć wartość `fileNumber`, `fileDataSetName` lub `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file „Zapisz i zamknij” nie może przetwarzać zestawów danych: wybierz „Folder”, aby zapisać każdy zestaw danych w osobnym pliku + Each data set saves over the same file, which keeps only the last data set. Każdy zestaw danych jest zapisywany w tym samym pliku, który zachowuje tylko ostatni zestaw danych. @msg no free data set file name in destination folder Brak wolnej nazwy pliku zestawu danych w folderze docelowym # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8ac21f8e97..ab767fcc28 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6190,7 +6190,7 @@ breakText Glyphs Glifos File + Data Set Name Arquivo + nome do conjunto de dados Data Set Name Nome do conjunto de dados @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve ser `fileNumber`, `fileDataSetName` ou `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Salvar e fechar" não pode processar conjuntos de dados: escolha "Pasta" para salvar cada conjunto de dados em um arquivo próprio + Each data set saves over the same file, which keeps only the last data set. Cada conjunto de dados é salvo sobre o mesmo arquivo, que mantém apenas o último conjunto de dados. @msg no free data set file name in destination folder Não há nome de arquivo livre para o conjunto de dados na pasta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d436e1b7e0..d126c5dabe 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6251,7 +6251,7 @@ breakText Glyphs Глифы File + Data Set Name Файл + имя набора данных Data Set Name Имя набора данных @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` должно быть `fileNumber`, `fileDataSetName` или `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Сохранить и закрыть» не работает с наборами данных: выберите «Папка», чтобы сохранить каждый набор данных в отдельный файл + Each data set saves over the same file, which keeps only the last data set. Каждый набор данных сохраняется поверх одного и того же файла, в котором остаётся только последний набор данных. @msg no free data set file name in destination folder В папке назначения нет свободного имени файла для набора данных # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4438027d80..4d9e8da510 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6326,7 +6326,7 @@ breakText Glyphs Glyfer File + Data Set Name Fil + datauppsättningens namn Data Set Name Datauppsättningens namn @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` måste vara `fileNumber`, `fileDataSetName` eller `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file ”Spara och stäng” kan inte köras på datauppsättningar: välj ”Mapp” för att spara varje datauppsättning i en egen fil + Each data set saves over the same file, which keeps only the last data set. Varje datauppsättning sparas över samma fil, som bara behåller den sista datauppsättningen. @msg no free data set file name in destination folder Inget ledigt filnamn för datauppsättningen i målmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5157d5bf36..ec0c64cd11 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6231,7 +6231,7 @@ breakText Glyphs Glifler File + Data Set Name Dosya + veri kümesi adı Data Set Name Veri kümesi adı @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` değeri `fileNumber`, `fileDataSetName` veya `dataSetName` olmalıdır -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Kaydet ve Kapat" veri kümelerini toplu işleyemez: her veri kümesini ayrı bir dosyaya kaydetmek için "Klasör" seçeneğini seçin + Each data set saves over the same file, which keeps only the last data set. Her veri kümesi aynı dosyanın üzerine kaydedilir ve dosyada yalnızca son veri kümesi kalır. @msg no free data set file name in destination folder Hedef klasörde veri kümesi için boş bir dosya adı yok # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index db7e9ccd2f..014ee77f09 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5873,7 +5873,7 @@ breakText Glyphs Гліфи File + Data Set Name Файл + назва набору даних Data Set Name Назва набору даних @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` має бути `fileNumber`, `fileDataSetName` або `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file «Зберегти й закрити» не працює з наборами даних: виберіть «Папка», щоб зберегти кожен набір даних в окремий файл + Each data set saves over the same file, which keeps only the last data set. Кожен набір даних зберігається поверх того самого файлу, у якому лишається тільки останній набір даних. @msg no free data set file name in destination folder У папці призначення немає вільного імені файлу набору даних # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f593048091..f79734084c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5874,7 +5874,7 @@ breakText Glyphs Glyph File + Data Set Name Tệp + tên tập dữ liệu Data Set Name Tên tập dữ liệu @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` phải là `fileNumber`, `fileDataSetName` hoặc `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file "Lưu và đóng" không thể xử lý các tập dữ liệu: chọn "Thư mục" để lưu mỗi tập dữ liệu vào một tệp riêng + Each data set saves over the same file, which keeps only the last data set. Mỗi tập dữ liệu được lưu đè lên cùng một tệp, nên tệp chỉ giữ lại tập dữ liệu cuối cùng. @msg no free data set file name in destination folder Không có tên tệp tập dữ liệu còn trống trong thư mục đích # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 379f4dc235..2c6da83739 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6115,7 +6115,7 @@ breakText Glyphs 字形 File + Data Set Name 文件 + 数据集名称 Data Set Name 数据集名称 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必须是 `fileNumber`、`fileDataSetName` 或 `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file “存储并关闭”无法批处理数据集:请选择“文件夹”,将每个数据集存储为单独的文件 + Each data set saves over the same file, which keeps only the last data set. 每个数据集都会存储到同一个文件并覆盖它,该文件只保留最后一个数据集。 @msg no free data set file name in destination folder 目标文件夹中没有可用的数据集文件名 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 46c332bd40..096e8602ac 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5911,7 +5911,7 @@ breakText Glyphs 字符 File + Data Set Name 檔案 + 資料集名稱 Data Set Name 資料集名稱 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必須是 `fileNumber`、`fileDataSetName` 或 `dataSetName` -@msg Save and Close cannot batch data sets: choose Folder to save each data set to its own file 「儲存並關閉」無法批次處理資料集:請選擇「資料夾」,將每個資料集儲存為個別檔案 + Each data set saves over the same file, which keeps only the last data set. 每個資料集都會儲存到同一個檔案並覆寫它,該檔案只保留最後一個資料集。 @msg no free data set file name in destination folder 目的地資料夾中沒有可用的資料集檔案名稱 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/docs/mcp.md b/docs/mcp.md index 41d5184561..78c3082cdb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3514,9 +3514,12 @@ Actions panel plays an action as a `command.batch`, omitting steps whose playbac cleared. An action set saved as `.vcactions` keeps each excluded step with `excluded: true`; loading an earlier version 1 set without that flag includes every step. The Actions panel menu's Batch… runs `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with -destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. A Data Sets source does not -take `saveAndClose`: `action.batch` refuses it before it selects a data set or runs a step, and the dialog offers -None and Folder only. For a Data Sets source, +destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. With a Data Sets source, +`saveAndClose` saves the open document over its own file after each data set, so the file keeps only the last one, +and a document that was never saved is refused before a data set is selected. The result carries `warning` when +every data set saves over the same file: with `saveAndClose`, or with a Save, Save a Copy, Save as Template or +Export step that writes a file and that the batch does not point into `destinationFolder`. The dialog shows the same +warning. For a Data Sets source, `datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name (`Alpha`). An omitted parameter keeps File + Data Set Name for existing callers; the dialog starts with File + Number. A folder source ignores this parameter. The folder diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 470d368861..ac4da65b5d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -643,7 +643,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - - Batch… over data sets offers None and Folder as the destination, and `action.batch` refuses Save and Close for a Data Sets source before it runs a step, so the batch does not save every data set over the open document's file. This is VectorCraft's own rule: [Play actions on a batch of files](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/play-actions-on-a-batch-of-files.html) describes Save and Close as saving "the file in their current location" and does not say what it does over data sets. + - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set. A recorded Save, Save a Copy, Save as Template or Export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy or template step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. `action.batch` refuses Save and Close over the data sets of a document that was never saved. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. From 64cfa8b5531df2ea031baac66328b2cb860359f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:49:25 -0800 Subject: [PATCH 09/26] Actions: Batch over data sets warns about PDF, EPS, DXF and web exports and refuses Save and Close on converted documents A recorded PDF, EPS, DXF, Save for Web or Save for Office Documents step that gives a `path` writes the same file for every data set, because the batch does not point these steps into the destination folder. The one-file rule now counts them, so the dialog and `action.batch` warn. Save and Close over the data sets of a document converted from an older version or restored by Data Recovery is refused with "save the document with Save As before Save and Close" before a data set is selected. Saving such a document does not write its file, so the batch reported success without saving anything. The message has a row in each of the 26 catalogs. --- crates/engine/src/cmd/fileio/action_batch.rs | 53 +++++++++++++++++--- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 7 +-- docs/target-app-parity.md | 2 +- 30 files changed, 78 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 26d6c476e3..5c29ec88f2 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -114,11 +114,12 @@ const ONE_FILE_WARNING: &str = "each data set saves over the same file, which ke /// Whether an `action.batch` with params `p` plays on data sets of the open document in `s` and /// writes each data set to the same file. Save and Close saves the open document over its own file /// after every data set. A step that the batch does not point into `destinationFolder` writes the -/// same file every time when it writes one: a Save, Save As, Save a Copy, Save as Template, Export -/// or Export Selection step that gives a `path`; a Save step without a `path` when the document has -/// a file of its own (saved, and not converted from an older version or restored by Data Recovery) -/// and the step gives no `format` or the document's own; an Export for Screens -/// step whose `folder`, given or from its `exportPreset`, names a folder, whatever the overrides. +/// same file every time when it writes one: a Save, Save As, Save a Copy, Save as Template, Export, +/// Export Selection, PDF, EPS, DXF, Save for Web or Save for Office Documents step that gives a +/// `path`; a Save step without a `path` when the document has a file of its own (saved, and not +/// converted from an older version or restored by Data Recovery) and the step gives no `format` or +/// the document's own; an Export for Screens step whose `folder`, given or from its +/// `exportPreset`, names a folder, whatever the overrides. /// Other steps return their data instead of writing a file. pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { if p.get("source").and_then(Value::as_str) != Some("datasets") { @@ -146,6 +147,8 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { "file.saveAs" => !save && path, "file.saveCopy" | "file.saveAsTemplate" => path, "document.export" | "document.exportSelection" => !export && path, + // The batch does not point these exports into `destinationFolder`. + "document.exportPdf" | "document.exportEps" | "document.exportDxf" | "document.exportForWeb" | "document.exportForOffice" => path, // Override Export sets `path`, which Export for Screens does not read: its `folder` stays. "document.exportForScreens" => super::screens::with_preset(s, ¶ms).is_ok_and(|p| names(p.get("folder"))), _ => false, @@ -199,8 +202,15 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { if names.len() > MAX_BATCH_FILES { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } - if run.destination == "saveAndClose" && st.path.is_none() { - return Err(bad(cmd, "the document has never been saved")); + if run.destination == "saveAndClose" { + if st.path.is_none() { + return Err(bad(cmd, "the document has never been saved")); + } + // `save_plan` writes no file for a document converted from an older version or restored by + // Data Recovery. + if st.converted || st.recovered { + return Err(bad(cmd, "save the document with Save As before Save and Close")); + } } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; @@ -1441,6 +1451,35 @@ mod tests { assert!(!with(json!({"commands": [{"command": "document.exportForScreens", "params": {}}]}))); let preset = json!([{"command": "document.exportForScreens", "params": {"exportPreset": "Logo Package"}}]); assert!(!with(json!({"commands": preset})), "a preset without a folder: the data comes back"); + for id in ["document.exportPdf", "document.exportEps", "document.exportDxf", "document.exportForWeb", "document.exportForOffice"] { + let step = json!([{"command": id, "params": {"path": "/x/a.out"}}]); + assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": step})), "{id} keeps its path"); + assert!(!with(json!({"commands": [{"command": id, "params": {}}]})), "{id} without a path: the data comes back"); + } + } + + #[test] + fn batch_refuses_save_and_close_over_data_sets_of_a_converted_or_recovered_document() { + for converted in [true, false] { + let path = tmp(if converted { "converted-sets" } else { "recovered-sets" }).join("template.vectorcraft"); + let mut s = saved_with_two_data_sets(&path); + let bytes = std::fs::read(&path).unwrap(); + let (active, revision) = { + let st = s.doc_mut().unwrap(); + if converted { + st.converted = true; + } else { + st.recovered = true; + } + (st.doc.variables.active_dataset.clone(), st.revision) + }; + let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string(); + assert!(msg.ends_with("save the document with Save As before Save and Close"), "{msg}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is not written"); + let st = s.doc().unwrap(); + assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected"); + assert_eq!(st.revision, revision, "no step runs"); + } } #[test] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 9b62a5342c..d982b6127c 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close, or a Save, Save a Copy, Save as Template or Export step that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b94e7895c2..d8ada61f0b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6100,6 +6100,7 @@ breakText Glyphs Глифи Data Set Name Име на набора от данни @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` трябва да е `fileNumber`, `fileDataSetName` или `dataSetName` Each data set saves over the same file, which keeps only the last data set. Всеки набор от данни се записва върху същия файл, в който остава само последният набор от данни. +@msg save the document with Save As before Save and Close запазете документа със „Запази като“ преди „Запази и затвори“ @msg no free data set file name in destination folder Няма свободно име за файл на набор от данни в целевата папка # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 176aafe80e..bcd4472804 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6112,6 +6112,7 @@ shape Open Otvoren Data Set Name Naziv skupa podataka @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` mora biti `fileNumber`, `fileDataSetName` ili `dataSetName` Each data set saves over the same file, which keeps only the last data set. Svaki skup podataka se sačuva preko iste datoteke, u kojoj ostaje samo posljednji skup podataka. +@msg save the document with Save As before Save and Close sačuvajte dokument pomoću „Sačuvaj kao“ prije „Sačuvaj i zatvori“ @msg no free data set file name in destination folder Nema slobodnog naziva datoteke skupa podataka u odredišnoj mapi # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2efc35f975..bb3c3a35ae 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6256,6 +6256,7 @@ breakText Glyphs Glifs Data Set Name Nom del conjunt de dades @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` ha de ser `fileNumber`, `fileDataSetName` o `dataSetName` Each data set saves over the same file, which keeps only the last data set. Cada conjunt de dades es desa sobre el mateix fitxer, que només conserva l'últim conjunt de dades. +@msg save the document with Save As before Save and Close deseu el document amb «Desa com a» abans de «Desa i tanca» @msg no free data set file name in destination folder No hi ha cap nom de fitxer de conjunt de dades lliure a la carpeta de destinació # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 5e72b3e661..9991617c3d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6275,6 +6275,7 @@ breakText Glyphs Glyfy Data Set Name Název sady dat @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musí být `fileNumber`, `fileDataSetName` nebo `dataSetName` Each data set saves over the same file, which keeps only the last data set. Každá sada dat se uloží přes stejný soubor, ve kterém zůstane jen poslední sada dat. +@msg save the document with Save As before Save and Close před „Uložit a zavřít“ uložte dokument pomocí „Uložit jako“ @msg no free data set file name in destination folder V cílové složce není volný název souboru sady dat # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 516fada6ef..874d196f01 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6115,6 +6115,7 @@ breakText Glyphs Glyffer Data Set Name Datasætnavn @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` skal være `fileNumber`, `fileDataSetName` eller `dataSetName` Each data set saves over the same file, which keeps only the last data set. Hvert datasæt gemmes oven i den samme fil, som kun beholder det sidste datasæt. +@msg save the document with Save As before Save and Close gem dokumentet med Gem som før Gem og luk @msg no free data set file name in destination folder Intet ledigt filnavn til datasættet i destinationsmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 73217a465c..114657cc75 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5860,6 +5860,7 @@ breakText Glyphs Glyphen Data Set Name Datensatzname @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` muss `fileNumber`, `fileDataSetName` oder `dataSetName` sein Each data set saves over the same file, which keeps only the last data set. Jeder Datensatz wird über dieselbe Datei gespeichert, die nur den letzten Datensatz behält. +@msg save the document with Save As before Save and Close speichern Sie das Dokument mit „Speichern unter“, bevor Sie „Speichern und schließen“ wählen @msg no free data set file name in destination folder Kein freier Dateiname für den Datensatz im Zielordner # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1a703f159b..00dcc70442 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6226,6 +6226,7 @@ breakText Glyphs Γλύφοι Data Set Name Όνομα συνόλου δεδομένων @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` Το `datasetFileNaming` πρέπει να είναι `fileNumber`, `fileDataSetName` ή `dataSetName` Each data set saves over the same file, which keeps only the last data set. Κάθε σύνολο δεδομένων αποθηκεύεται πάνω στο ίδιο αρχείο, το οποίο κρατά μόνο το τελευταίο σύνολο δεδομένων. +@msg save the document with Save As before Save and Close αποθηκεύστε το έγγραφο με «Αποθήκευση ως» πριν από «Αποθήκευση και κλείσιμο» @msg no free data set file name in destination folder Δεν υπάρχει διαθέσιμο όνομα αρχείου συνόλου δεδομένων στον φάκελο προορισμού # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 0e4df7790e..1ae8b7fae0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6217,6 +6217,7 @@ breakText Glyphs Glifos Data Set Name Nombre del conjunto de datos @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` debe ser `fileNumber`, `fileDataSetName` o `dataSetName` Each data set saves over the same file, which keeps only the last data set. Cada conjunto de datos se guarda sobre el mismo archivo, que solo conserva el último conjunto de datos. +@msg save the document with Save As before Save and Close guarde el documento con «Guardar como» antes de «Guardar y cerrar» @msg no free data set file name in destination folder No hay un nombre de archivo libre para el conjunto de datos en la carpeta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 8d1fe5f741..bf26c1cc36 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6305,6 +6305,7 @@ breakText Glyphs Merkit Data Set Name Tietojoukon nimi @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`-arvon on oltava `fileNumber`, `fileDataSetName` tai `dataSetName` Each data set saves over the same file, which keeps only the last data set. Jokainen tietojoukko tallennetaan saman tiedoston päälle, johon jää vain viimeinen tietojoukko. +@msg save the document with Save As before Save and Close tallenna asiakirja komennolla Tallenna nimellä ennen kuin valitset Tallenna ja sulje @msg no free data set file name in destination folder Kohdekansiossa ei ole vapaata tietojoukon tiedostonimeä # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6f1bc17150..455af6aa56 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6270,6 +6270,7 @@ breakText Glyphs Glyphes Data Set Name Nom du jeu de données @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` doit être `fileNumber`, `fileDataSetName` ou `dataSetName` Each data set saves over the same file, which keeps only the last data set. Chaque jeu de données est enregistré sur le même fichier, qui ne conserve que le dernier jeu de données. +@msg save the document with Save As before Save and Close enregistrez le document avec Enregistrer sous avant Enregistrer et fermer @msg no free data set file name in destination folder Aucun nom de fichier libre pour le jeu de données dans le dossier de destination # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index b52b620222..9574c304a9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6259,6 +6259,7 @@ breakText Glyphs Glifák Data Set Name Adatkészlet neve @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` A `datasetFileNaming` értéke `fileNumber`, `fileDataSetName` vagy `dataSetName` lehet Each data set saves over the same file, which keeps only the last data set. Minden adatkészlet ugyanabba a fájlba mentődik, amely csak az utolsó adatkészletet őrzi meg. +@msg save the document with Save As before Save and Close mentse a dokumentumot a „Mentés másként” paranccsal a „Mentés és bezárás” előtt @msg no free data set file name in destination folder Nincs szabad adatkészlet-fájlnév a célmappában # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 176e1da886..2b4ab48e84 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6115,6 +6115,7 @@ breakText Glyphs Glif Data Set Name Nama set data @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` harus `fileNumber`, `fileDataSetName`, atau `dataSetName` Each data set saves over the same file, which keeps only the last data set. Setiap set data disimpan menimpa file yang sama, sehingga hanya set data terakhir yang tersisa. +@msg save the document with Save As before Save and Close simpan dokumen dengan Simpan sebagai sebelum Simpan dan tutup @msg no free data set file name in destination folder Tidak ada nama file set data yang tersedia di folder tujuan # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c9d3169851..1f6d0a139f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5894,6 +5894,7 @@ breakText Glyphs Glifi Data Set Name Nome set di dati @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve essere `fileNumber`, `fileDataSetName` o `dataSetName` Each data set saves over the same file, which keeps only the last data set. Ogni set di dati viene salvato sullo stesso file, che conserva solo l'ultimo set di dati. +@msg save the document with Save As before Save and Close salva il documento con «Salva con nome» prima di «Salva e chiudi» @msg no free data set file name in destination folder Nessun nome file libero per il set di dati nella cartella di destinazione # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6dfa754c72..17b2aa06f4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5959,6 +5959,7 @@ breakText Glyphs 字形 Data Set Name データセット名 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` は `fileNumber`、`fileDataSetName`、`dataSetName` のいずれかである必要があります Each data set saves over the same file, which keeps only the last data set. 各データセットが同じファイルに上書き保存されるため、最後のデータセットだけが残ります。 +@msg save the document with Save As before Save and Close 「保存して閉じる」の前に「別名で保存」でドキュメントを保存してください @msg no free data set file name in destination folder 保存先フォルダーに使用可能なデータセットのファイル名がありません # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index fb53b753da..f9545785b8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6272,6 +6272,7 @@ breakText Glyphs გლიფები Data Set Name მონაცემთა ნაკრების სახელი @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` უნდა იყოს `fileNumber`, `fileDataSetName` ან `dataSetName` Each data set saves over the same file, which keeps only the last data set. თითოეული მონაცემთა ნაკრები ერთსა და იმავე ფაილზე ინახება, რომელშიც მხოლოდ ბოლო მონაცემთა ნაკრები რჩება. +@msg save the document with Save As before Save and Close „შენახვა და დახურვამდე“ შეინახეთ დოკუმენტი „შენახვა როგორც“ ბრძანებით @msg no free data set file name in destination folder დანიშნულების საქაღალდეში მონაცემთა ნაკრებისთვის თავისუფალი ფაილის სახელი არ არის # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81e98bb478..ae73d31acf 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5855,6 +5855,7 @@ breakText Glyphs 글리프 Data Set Name 데이터 세트 이름 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming`은 `fileNumber`, `fileDataSetName` 또는 `dataSetName`이어야 합니다 Each data set saves over the same file, which keeps only the last data set. 각 데이터 세트가 같은 파일에 덮어써지므로 마지막 데이터 세트만 남습니다. +@msg save the document with Save As before Save and Close '저장 후 닫기' 전에 '다른 이름으로 저장'으로 문서를 저장하십시오 @msg no free data set file name in destination folder 대상 폴더에 사용할 수 있는 데이터 세트 파일 이름이 없습니다 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 345d7918ef..c52207339a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6161,6 +6161,7 @@ breakText Glyphs Glyphs Data Set Name Naam gegevensset @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` moet `fileNumber`, `fileDataSetName` of `dataSetName` zijn Each data set saves over the same file, which keeps only the last data set. Elke gegevensset wordt over hetzelfde bestand opgeslagen, dat alleen de laatste gegevensset bewaart. +@msg save the document with Save As before Save and Close sla het document op met Opslaan als voordat u Opslaan en sluiten kiest @msg no free data set file name in destination folder Geen vrije bestandsnaam voor de gegevensset in de doelmap # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1290a0f79a..f3538c540e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6129,6 +6129,7 @@ breakText Glyphs Glify Data Set Name Nazwa zestawu danych @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` musi mieć wartość `fileNumber`, `fileDataSetName` lub `dataSetName` Each data set saves over the same file, which keeps only the last data set. Każdy zestaw danych jest zapisywany w tym samym pliku, który zachowuje tylko ostatni zestaw danych. +@msg save the document with Save As before Save and Close zapisz dokument poleceniem „Zapisz jako” przed „Zapisz i zamknij” @msg no free data set file name in destination folder Brak wolnej nazwy pliku zestawu danych w folderze docelowym # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index ab767fcc28..d1028010bf 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6191,6 +6191,7 @@ breakText Glyphs Glifos Data Set Name Nome do conjunto de dados @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` deve ser `fileNumber`, `fileDataSetName` ou `dataSetName` Each data set saves over the same file, which keeps only the last data set. Cada conjunto de dados é salvo sobre o mesmo arquivo, que mantém apenas o último conjunto de dados. +@msg save the document with Save As before Save and Close salve o documento com Salvar Como antes de Salvar e fechar @msg no free data set file name in destination folder Não há nome de arquivo livre para o conjunto de dados na pasta de destino # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d126c5dabe..f0a56b6132 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6252,6 +6252,7 @@ breakText Glyphs Глифы Data Set Name Имя набора данных @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` должно быть `fileNumber`, `fileDataSetName` или `dataSetName` Each data set saves over the same file, which keeps only the last data set. Каждый набор данных сохраняется поверх одного и того же файла, в котором остаётся только последний набор данных. +@msg save the document with Save As before Save and Close сохраните документ командой «Сохранить как» перед «Сохранить и закрыть» @msg no free data set file name in destination folder В папке назначения нет свободного имени файла для набора данных # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4d9e8da510..9e2a2ce013 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6327,6 +6327,7 @@ breakText Glyphs Glyfer Data Set Name Datauppsättningens namn @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` måste vara `fileNumber`, `fileDataSetName` eller `dataSetName` Each data set saves over the same file, which keeps only the last data set. Varje datauppsättning sparas över samma fil, som bara behåller den sista datauppsättningen. +@msg save the document with Save As before Save and Close spara dokumentet med Spara som före Spara och stäng @msg no free data set file name in destination folder Inget ledigt filnamn för datauppsättningen i målmappen # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ec0c64cd11..7cd9822fd6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6232,6 +6232,7 @@ breakText Glyphs Glifler Data Set Name Veri kümesi adı @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` değeri `fileNumber`, `fileDataSetName` veya `dataSetName` olmalıdır Each data set saves over the same file, which keeps only the last data set. Her veri kümesi aynı dosyanın üzerine kaydedilir ve dosyada yalnızca son veri kümesi kalır. +@msg save the document with Save As before Save and Close Kaydet ve Kapat'tan önce belgeyi Farklı Kaydet ile kaydedin @msg no free data set file name in destination folder Hedef klasörde veri kümesi için boş bir dosya adı yok # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 014ee77f09..2f50e09918 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5874,6 +5874,7 @@ breakText Glyphs Гліфи Data Set Name Назва набору даних @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` має бути `fileNumber`, `fileDataSetName` або `dataSetName` Each data set saves over the same file, which keeps only the last data set. Кожен набір даних зберігається поверх того самого файлу, у якому лишається тільки останній набір даних. +@msg save the document with Save As before Save and Close збережіть документ командою «Зберегти як» перед «Зберегти й закрити» @msg no free data set file name in destination folder У папці призначення немає вільного імені файлу набору даних # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f79734084c..d2dc9a4782 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5875,6 +5875,7 @@ breakText Glyphs Glyph Data Set Name Tên tập dữ liệu @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` phải là `fileNumber`, `fileDataSetName` hoặc `dataSetName` Each data set saves over the same file, which keeps only the last data set. Mỗi tập dữ liệu được lưu đè lên cùng một tệp, nên tệp chỉ giữ lại tập dữ liệu cuối cùng. +@msg save the document with Save As before Save and Close hãy lưu tài liệu bằng Lưu thành trước khi dùng Lưu và đóng @msg no free data set file name in destination folder Không có tên tệp tập dữ liệu còn trống trong thư mục đích # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2c6da83739..100128f3c2 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6116,6 +6116,7 @@ breakText Glyphs 字形 Data Set Name 数据集名称 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必须是 `fileNumber`、`fileDataSetName` 或 `dataSetName` Each data set saves over the same file, which keeps only the last data set. 每个数据集都会存储到同一个文件并覆盖它,该文件只保留最后一个数据集。 +@msg save the document with Save As before Save and Close 请先用“另存为”保存文档,再使用“保存并关闭” @msg no free data set file name in destination folder 目标文件夹中没有可用的数据集文件名 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 096e8602ac..d0f9c079ee 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5912,6 +5912,7 @@ breakText Glyphs 字符 Data Set Name 資料集名稱 @msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` 必須是 `fileNumber`、`fileDataSetName` 或 `dataSetName` Each data set saves over the same file, which keeps only the last data set. 每個資料集都會儲存到同一個檔案並覆寫它,該檔案只保留最後一個資料集。 +@msg save the document with Save As before Save and Close 請先用「另存新檔」儲存文件,再使用「儲存並關閉」 @msg no free data set file name in destination folder 目的地資料夾中沒有可用的資料集檔案名稱 # Path Precision Tools add-on: Path Effects (Effect › Path Effects). diff --git a/docs/mcp.md b/docs/mcp.md index 78c3082cdb..deb110a535 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3516,9 +3516,10 @@ an earlier version 1 set without that flag includes every step. The Actions pane `action.batch`: the same steps on every readable file in a folder (or every data set of the open document), with destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. With a Data Sets source, `saveAndClose` saves the open document over its own file after each data set, so the file keeps only the last one, -and a document that was never saved is refused before a data set is selected. The result carries `warning` when -every data set saves over the same file: with `saveAndClose`, or with a Save, Save a Copy, Save as Template or -Export step that writes a file and that the batch does not point into `destinationFolder`. The dialog shows the same +and a document that was never saved, was converted from an older version or was restored by Data Recovery is +refused before a data set is selected. The result carries `warning` when every data set saves over the same file: +with `saveAndClose`, or with a Save, Save a Copy, Save as Template or export step (PDF, EPS, DXF, Save for Web and +Save for Office Documents included) that writes a file and that the batch does not point into `destinationFolder`. The dialog shows the same warning. For a Data Sets source, `datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name (`Alpha`). An omitted parameter keeps File + Data Set Name diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ac4da65b5d..b932d6cf0b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -643,7 +643,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set. A recorded Save, Save a Copy, Save as Template or Export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy or template step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. `action.batch` refuses Save and Close over the data sets of a document that was never saved. + - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. From 427029def66385d7951f69953147b7e696261124 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:07:20 -0800 Subject: [PATCH 10/26] Actions: Batch Save and Close over data sets follows a redirected Save step With a destination folder and Override Save on, a recorded Save or Save As step writes each data set to its own file in that folder and makes that file the document's own, so Save and Close then saves each data set to its own file. The batch no longer warns that every data set saves over one file in that case, and no longer refuses a document that was never saved, converted or restored, since the recorded step gives it a file first. --- crates/engine/src/cmd/fileio/action_batch.rs | 89 ++++++++++++++------ crates/engine/src/cmd/fileio/commands.rs | 2 +- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 4 files changed, 70 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 5c29ec88f2..942f58e773 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -113,7 +113,8 @@ const ONE_FILE_WARNING: &str = "each data set saves over the same file, which ke /// Whether an `action.batch` with params `p` plays on data sets of the open document in `s` and /// writes each data set to the same file. Save and Close saves the open document over its own file -/// after every data set. A step that the batch does not point into `destinationFolder` writes the +/// after every data set, unless a Save step that Override Save points into `destinationFolder` +/// first makes each data set's file the document's own. A step that the batch does not point into `destinationFolder` writes the /// same file every time when it writes one: a Save, Save As, Save a Copy, Save as Template, Export, /// Export Selection, PDF, EPS, DXF, Save for Web or Save for Office Documents step that gives a /// `path`; a Save step without a `path` when the document has a file of its own (saved, and not @@ -125,38 +126,44 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { if p.get("source").and_then(Value::as_str) != Some("datasets") { return false; } - if p.get("destination").and_then(Value::as_str) == Some("saveAndClose") { - return true; - } let folder = p.get("destinationFolder").and_then(Value::as_str).is_some(); let redirected = |key: &str| folder && p.get(key).and_then(Value::as_bool).unwrap_or(true); let (save, export) = (redirected("overrideSave"), redirected("overrideExport")); + let steps = p.get("commands").and_then(Value::as_array).map_or(&[][..], Vec::as_slice); + if p.get("destination").and_then(Value::as_str) == Some("saveAndClose") && !saves_move_to_each_file(steps, save) { + return true; + } // The format of the open document's own file, which a Save step without a `path` writes. let own_format = s.active().filter(|st| st.path.is_some() && !st.converted && !st.recovered).map(|st| st.format); let names = |v: Option<&Value>| v.and_then(Value::as_str).is_some_and(|s| !s.is_empty()); - p.get("commands").and_then(Value::as_array).is_some_and(|cmds| { - cmds.iter().any(|c| { - let params = c.get("params").cloned().unwrap_or_else(|| Value::Object(Default::default())); - let path = names(params.get("path")); - let own_file = || match params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()) { - None => own_format.is_some(), - Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), - }; - match c.get("command").and_then(Value::as_str).unwrap_or("") { - "document.save" | "file.save" => !save && (path || own_file()), - "file.saveAs" => !save && path, - "file.saveCopy" | "file.saveAsTemplate" => path, - "document.export" | "document.exportSelection" => !export && path, - // The batch does not point these exports into `destinationFolder`. - "document.exportPdf" | "document.exportEps" | "document.exportDxf" | "document.exportForWeb" | "document.exportForOffice" => path, - // Override Export sets `path`, which Export for Screens does not read: its `folder` stays. - "document.exportForScreens" => super::screens::with_preset(s, ¶ms).is_ok_and(|p| names(p.get("folder"))), - _ => false, - } - }) + steps.iter().any(|c| { + let params = c.get("params").cloned().unwrap_or_else(|| Value::Object(Default::default())); + let path = names(params.get("path")); + let own_file = || match params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()) { + None => own_format.is_some(), + Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), + }; + match c.get("command").and_then(Value::as_str).unwrap_or("") { + "document.save" | "file.save" => !save && (path || own_file()), + "file.saveAs" => !save && path, + "file.saveCopy" | "file.saveAsTemplate" => path, + "document.export" | "document.exportSelection" => !export && path, + // The batch does not point these exports into `destinationFolder`. + "document.exportPdf" | "document.exportEps" | "document.exportDxf" | "document.exportForWeb" | "document.exportForOffice" => path, + // Override Export sets `path`, which Export for Screens does not read: its `folder` stays. + "document.exportForScreens" => super::screens::with_preset(s, ¶ms).is_ok_and(|p| names(p.get("folder"))), + _ => false, + } }) } +/// Whether `steps` hold a Save, Save As or `document.save` step that Override Save points at each +/// data set's own file in the destination folder (`redirected`). Such a step makes that file the +/// document's own, so Save and Close then saves each data set to its own file. +fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool { + redirected && steps.iter().any(|c| matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs"))) +} + #[cfg(not(target_arch = "wasm32"))] fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: &Run<'_>) -> Result { use super::{absolute_path, may_read}; @@ -202,7 +209,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { if names.len() > MAX_BATCH_FILES { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } - if run.destination == "saveAndClose" { + if run.destination == "saveAndClose" && !saves_move_to_each_file(run.steps, run.override_save && run.dest_folder.is_some()) { if st.path.is_none() { return Err(bad(cmd, "the document has never been saved")); } @@ -1413,6 +1420,38 @@ mod tests { assert!(r.get("warning").is_none(), "{r}"); } + #[test] + fn batch_save_and_close_after_a_redirected_save_writes_each_data_set_to_its_own_file() { + let save_close = |dest: &std::path::Path| { + json!({ + "source": "datasets", + "destination": "saveAndClose", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {}}] + }) + }; + let path = tmp("redirected-save-close").join("template.vectorcraft"); + let mut s = saved_with_two_data_sets(&path); + let bytes = std::fs::read(&path).unwrap(); + let dest = tmp("redirected-save-close-dest"); + let p = save_close(&dest); + let mut kept = p.clone(); + kept["overrideSave"] = json!(false); + assert!(batch_overwrites_one_file(&s, &kept), "without Override Save the save stays on the template"); + let r = s.execute("action.batch", &p).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert!(r.get("warning").is_none(), "{r}"); + assert_eq!(file_names(&dest), ["template_A.vectorcraft", "template_B.vectorcraft"], "{r}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the template's file stays as it was"); + // A document never saved gets its files from the redirected save too. + let mut unsaved = with_data_sets(&["a", "b"]); + let dest = tmp("redirected-save-close-unsaved"); + let r = unsaved.execute("action.batch", &save_close(&dest)).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert!(r.get("warning").is_none(), "{r}"); + assert_eq!(file_names(&dest), ["Untitled_a.vectorcraft", "Untitled_b.vectorcraft"], "{r}"); + } + #[test] fn one_file_rule_covers_save_and_close_and_steps_left_in_place() { let saved = saved_with_two_data_sets(&tmp("one-file-rule").join("template.vectorcraft")); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index d982b6127c..65872508f2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own first) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/docs/mcp.md b/docs/mcp.md index deb110a535..312230a86c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3517,8 +3517,10 @@ an earlier version 1 set without that flag includes every step. The Actions pane destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. With a Data Sets source, `saveAndClose` saves the open document over its own file after each data set, so the file keeps only the last one, and a document that was never saved, was converted from an older version or was restored by Data Recovery is -refused before a data set is selected. The result carries `warning` when every data set saves over the same file: -with `saveAndClose`, or with a Save, Save a Copy, Save as Template or export step (PDF, EPS, DXF, Save for Web and +refused before a data set is selected. When `destinationFolder` is set and Override Save points a recorded Save or +Save As step into it, that step makes each data set's file the document's own, and `saveAndClose` saves each data +set to its own file. The result carries `warning` when every data set saves over the same file: +with `saveAndClose` without such a step, or with a Save, Save a Copy, Save as Template or export step (PDF, EPS, DXF, Save for Web and Save for Office Documents included) that writes a file and that the batch does not point into `destinationFolder`. The dialog shows the same warning. For a Data Sets source, `datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b932d6cf0b..cddb2ecb97 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -643,7 +643,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. + - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Without such a Save step, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. From 0d1a8b6ffa838cb46ce6d252f1882a604de63a82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:21:38 -0800 Subject: [PATCH 11/26] Actions: Batch Save and Close over data sets counts only saves that make the file the document's own A recorded save in the template format writes a copy and leaves the document's file as it was, so it no longer clears the warning or the refusals. A recorded Save or Save As with its own path gives a never-saved, converted or restored document its file before Save and Close, so the batch runs and warns that every data set saves over that one file. --- crates/engine/src/cmd/fileio/action_batch.rs | 43 +++++++++++++++++++- crates/engine/src/cmd/fileio/commands.rs | 2 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 45 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 942f58e773..ded4dcd5d7 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -161,7 +161,25 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { /// data set's own file in the destination folder (`redirected`). Such a step makes that file the /// document's own, so Save and Close then saves each data set to its own file. fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool { - redirected && steps.iter().any(|c| matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs"))) + redirected && steps.iter().any(|c| retargeting_save(c, true)) +} + +/// Whether step `c` is a Save, Save As or `document.save` that writes a file (its own `path`, or one +/// in the destination folder when `redirected`) and makes that file the document's own: a save in +/// the native template format writes a copy and leaves the document's file as it was. +fn retargeting_save(c: &Value, redirected: bool) -> bool { + if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) { + return false; + } + let params = c.get("params"); + let path = params.and_then(|p| p.get("path")).and_then(Value::as_str).filter(|p| !p.is_empty()); + let format_ok = match params.and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()) { + Some(f) => super::format(f).is_some_and(|f| f.id != "template"), + // Override Save gives the step a native file name; else its own path names the format. + None if redirected => true, + None => path.and_then(super::format_for_name).is_none_or(|f| f.id != "template"), + }; + format_ok && (redirected || path.is_some()) } #[cfg(not(target_arch = "wasm32"))] @@ -209,7 +227,9 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { if names.len() > MAX_BATCH_FILES { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } - if run.destination == "saveAndClose" && !saves_move_to_each_file(run.steps, run.override_save && run.dest_folder.is_some()) { + let redirected = run.override_save && run.dest_folder.is_some(); + // A recorded save with a file to write gives the document a file of its own before Save and Close. + if run.destination == "saveAndClose" && !run.steps.iter().any(|c| retargeting_save(c, redirected)) { if st.path.is_none() { return Err(bad(cmd, "the document has never been saved")); } @@ -1450,6 +1470,25 @@ mod tests { assert_eq!(r["failed"], 0, "{r}"); assert!(r.get("warning").is_none(), "{r}"); assert_eq!(file_names(&dest), ["Untitled_a.vectorcraft", "Untitled_b.vectorcraft"], "{r}"); + // A template save writes a copy: Save and Close still saves over the document's own file. + let mut template = save_close(&dest); + template["commands"] = json!([{"command": "document.save", "params": {"format": "template"}}]); + assert!(batch_overwrites_one_file(&s, &template), "{template}"); + let mut never = with_data_sets(&["a", "b"]); + let msg = never.execute("action.batch", &template).unwrap_err().to_string(); + assert!(msg.ends_with("the document has never been saved"), "{msg}"); + // A recorded Save As with its own path gives a never-saved document its file, the same one + // for every data set. + let one = tmp("save-as-then-close").join("one.vectorcraft"); + let p = json!({ + "source": "datasets", + "destination": "saveAndClose", + "commands": [{"command": "file.saveAs", "params": {"path": one.to_string_lossy()}}] + }); + let r = never.execute("action.batch", &p).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}"); + assert!(one.exists(), "{r}"); } #[test] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 65872508f2..b71ede0965 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own first) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/docs/mcp.md b/docs/mcp.md index 312230a86c..facbe02e4c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3517,7 +3517,8 @@ an earlier version 1 set without that flag includes every step. The Actions pane destination `none` | `saveAndClose` | `folder` and Override Open / Save / Export. With a Data Sets source, `saveAndClose` saves the open document over its own file after each data set, so the file keeps only the last one, and a document that was never saved, was converted from an older version or was restored by Data Recovery is -refused before a data set is selected. When `destinationFolder` is set and Override Save points a recorded Save or +refused before a data set is selected, unless a recorded Save or Save As step (not in the template format) writes a +file and makes it the document's own first. When `destinationFolder` is set and Override Save points a recorded Save or Save As step into it, that step makes each data set's file the document's own, and `saveAndClose` saves each data set to its own file. The result carries `warning` when every data set saves over the same file: with `saveAndClose` without such a step, or with a Save, Save a Copy, Save as Template or export step (PDF, EPS, DXF, Save for Web and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cddb2ecb97..794ab3fb84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -643,7 +643,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Without such a Save step, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. + - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Unless a recorded Save or Save As step writes a file and makes it the document's own first, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. From a33d6a6ec8eaa03a0d49628437b34d6c66b04cbc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:45:26 +0700 Subject: [PATCH 12/26] Canvas: a General option makes Cmd/Ctrl-wheel scroll the canvas sideways Squashed from #5023 onto main. --- crates/engine/src/cmd/prefscmds.rs | 1 + crates/engine/src/prefs.rs | 3 + crates/engine/src/tests/prefs.rs | 14 ++ crates/ui-egui/src/canvas/input.rs | 10 +- crates/ui-egui/src/canvas/tests.rs | 290 ++++++++++++++++++++++- crates/ui-egui/src/canvas/view.rs | 93 +++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/prefs_dialog.rs | 5 + crates/ui-egui/src/prefs_dialog/tests.rs | 35 +++ docs/control-protocol.md | 2 +- docs/mcp.md | 6 + docs/target-app-parity.md | 1 + 37 files changed, 472 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index a702f15802..ad52c808ab 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -150,6 +150,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("scaleCorners", "General", "Options", "Scale Corners", bool), p!("scaleStrokes", "General", "Options", "Scale Strokes & Effects", bool), p!("zoomWithMouseWheel", "General", "Options", "Zoom with Mouse Wheel", bool), + p!("ctrlWheelScrollsSideways", "General", "Options", "Scroll Sideways with Cmd/Ctrl + Wheel", bool), p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool), p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool), p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 82946ac29d..920ef3d1c5 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -54,6 +54,8 @@ pub struct Prefs { /// Scale Strokes & Effects. pub scale_strokes: bool, pub zoom_with_mouse_wheel: bool, + /// While Zoom with Mouse Wheel is off, Cmd/Ctrl-wheel scrolls sideways instead of zooming. + pub ctrl_wheel_scrolls_sideways: bool, /// A horizontal drag on a numeric field or its label steps its value (#400). pub scrub_numeric_fields: bool, /// A two-finger rotation on a Mac trackpad turns the view about the pointer once it reaches 5°. @@ -367,6 +369,7 @@ impl Default for Prefs { scale_corners: false, scale_strokes: false, zoom_with_mouse_wheel: false, + ctrl_wheel_scrolls_sideways: true, scrub_numeric_fields: true, trackpad_rotate_view: true, hold_tool_keys: true, diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 4377011364..7a17fe4139 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -2511,6 +2511,20 @@ fn a_straight_segment_dragged_by_direct_selection_lands_on_a_ruler_guide() { } } +/// General › Scroll Sideways with Cmd/Ctrl + Wheel starts on: in a new session, in a preferences +/// file saved before the option existed and after a reset. +#[test] +fn scroll_sideways_with_cmd_wheel_is_on_by_default() { + assert!(Prefs::default().ctrl_wheel_scrolls_sideways); + let old: Prefs = serde_json::from_value(json!({"zoomWithMouseWheel": false})).unwrap(); + assert!(old.ctrl_wheel_scrolls_sideways); + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "ctrlWheelScrollsSideways", "value": false})).unwrap(); + assert!(!s.prefs.ctrl_wheel_scrolls_sideways); + s.execute("prefs.reset", &json!({})).unwrap(); + assert!(s.prefs.ctrl_wheel_scrolls_sideways); +} + /// The Transform panel menu's choice starts as `default` (the panels follow General › Transform /// Pattern Tiles): in a new session, in a preferences file saved before the choice existed and /// after a reset; `prefs.set` takes it and the three menu choices, and nothing else. diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 49baf494b3..0094dc07d8 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -206,8 +206,14 @@ fn wheel_view( let turn_id = egui::Id::unique("canvas-wheel-turn"); let turn_before: WheelTurn = ui.data(|d| d.get_temp(turn_id)).unwrap_or_default(); let mut turn = turn_before; - let (pointer, m, space, (factor, scroll)) = - ui.input(|i| (i.pointer.clone(), i.modifiers, i.key_down(egui::Key::Space), wheel(i, wheel_zooms, animate, line, rect.height(), &mut turn))); + let (pointer, m, space, (factor, scroll)) = ui.input(|i| { + ( + i.pointer.clone(), + i.modifiers, + i.key_down(egui::Key::Space), + wheel(i, &app.session.prefs, wheel_zooms, animate, line, rect.height(), &mut turn), + ) + }); if turn != turn_before { ui.data_mut(|d| d.insert_temp(turn_id, turn)); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d9fa7f09c7..c37d6b8687 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4306,7 +4306,8 @@ fn show_hidden_characters_releases_the_text_nodes_of_a_closed_document() { } /// General › Zoom with Mouse Wheel (#394), through the control channel's `ui.wheel`: off, -/// the wheel scrolls and Cmd-wheel zooms; on, the wheel zooms about the pointer, Shift-wheel +/// the wheel scrolls and Cmd-wheel scrolls sideways (Scroll Sideways with Cmd/Ctrl + Wheel is on +/// by default); on, the wheel zooms about the pointer, Shift-wheel /// scrolls up and down and Cmd/Ctrl-wheel sideways. Alt-wheel (Option on the Mac) and a /// trackpad pinch zoom about the pointer either way. #[test] @@ -4348,7 +4349,9 @@ fn zoom_with_mouse_wheel_preference() { let zooms_in = |(zoom, _, moved): (f64, _, f64)| zoom > 1.01 && moved < 1e-6; let (zoom, scroll, _) = turn(&mut app, ""); assert!((zoom - 1.0).abs() < 1e-9 && scroll.x == 0.0 && scroll.y < -1.0, "off: the wheel scrolls up ({zoom}, {scroll:?})"); - assert!(zooms_in(turn(&mut app, "cmd")), "off: Cmd-wheel zooms in about the pointer"); + // General › Scroll Sideways with Cmd/Ctrl + Wheel is on by default. + let (zoom, scroll, _) = turn(&mut app, "cmd"); + assert!((zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, "off: Cmd-wheel scrolls sideways ({zoom}, {scroll:?})"); assert!(zooms_in(turn(&mut app, "alt")), "off: Alt-wheel zooms in about the pointer"); assert!(zooms_in(turn(&mut app, "pinch")), "off: a pinch zooms in about the pointer"); app.session.execute("prefs.set", &json!({"key": "zoomWithMouseWheel", "value": true})).unwrap(); @@ -4361,6 +4364,289 @@ fn zoom_with_mouse_wheel_preference() { assert!((zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, "on: Cmd-wheel scrolls sideways ({zoom}, {scroll:?})"); } +/// General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default), through the control channel's +/// `ui.wheel`: with Zoom with Mouse Wheel off, Cmd/Ctrl-wheel zooms about the pointer while the +/// option is off and scrolls sideways while it is on, and a trackpad pinch, two fingers spread on a touch +/// screen, Alt + Cmd/Ctrl-wheel and Alt-wheel still zoom. A Cmd/Ctrl-wheel notch with a plain +/// one right after it scrolls two notches in all, and a trackpad gesture during which Cmd/Ctrl +/// is pressed and released scrolls sideways until the gesture ends, while an Alt gesture that +/// pauses past egui's scroll timeout no longer holds Alt for the next move. With Zoom with +/// Mouse Wheel also on, Cmd/Ctrl-wheel scrolls sideways and the wheel zooms. +#[test] +fn cmd_wheel_scrolls_sideways_preference() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + // A canvas frame through the host's input hook (it feeds the control channel's input). + let run = |app: &mut VectorcraftApp| { + let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + run(&mut app); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() + vec2(60.0, 40.0); + // One notch up at `at` with `mods` held, or a pinch: → (zoom ratio, scroll in points, how + // far the point under `at` moved). + let turn = |app: &mut VectorcraftApp, mods: &str| { + let before = *app.view().unwrap(); + if mods == "pinch" { + app.synthetic.extend([egui::Event::PointerMoved(at), egui::Event::Zoom(1.25)]); + } else { + let mut p = json!({"x": at.x, "y": at.y, "dy": 1}); + for m in mods.split('+').filter(|m| !m.is_empty()) { + p[m] = json!(true); + } + crate::tests_synthetic::control(app, &ctx, "ui.wheel", p); + } + // egui spreads a notch over a few frames. + for _ in 0..40 { + run(app); + } + let after = *app.view().unwrap(); + let moved = Xf::new(rect, &after).to_doc(at).distance(Xf::new(rect, &before).to_doc(at)); + (after.zoom / before.zoom, (after.center - before.center) * after.zoom, moved) + }; + let zooms_in = |(zoom, _, moved): (f64, _, f64)| zoom > 1.01 && moved < 1e-6; + assert!(app.session.prefs.ctrl_wheel_scrolls_sideways, "the option is on by default"); + app.session.execute("prefs.set", &json!({"key": "ctrlWheelScrollsSideways", "value": false})).unwrap(); + assert!(zooms_in(turn(&mut app, "cmd")), "off: Cmd-wheel zooms in about the pointer"); + let (zoom, scroll, _) = turn(&mut app, "shift"); + assert!((zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, "off: Shift-wheel scrolls sideways ({zoom}, {scroll:?})"); + app.session.execute("prefs.set", &json!({"key": "ctrlWheelScrollsSideways", "value": true})).unwrap(); + // A notch scrolls one wheel line. + let line = f64::from(ctx.options(|o| o.input_options.line_scroll_speed)); + let (zoom, scroll, _) = turn(&mut app, "cmd"); + assert!( + (zoom - 1.0).abs() < 1e-9 && (scroll.x + line).abs() < 0.5 && scroll.y == 0.0, + "on: Cmd-wheel scrolls sideways by a notch ({zoom}, {scroll:?})" + ); + assert!(zooms_in(turn(&mut app, "pinch")), "on: a pinch right after it zooms in about the pointer"); + // Two fingers spread on a touch screen, with no wheel turn since the Cmd-wheel one. + let before = app.view().unwrap().zoom; + let touch = |n: u64, phase, pos| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(n), phase, pos, force: None }; + let fingers = |phase, d: f32| vec![touch(1, phase, at - vec2(40.0 + d, 0.0)), touch(2, phase, at + vec2(40.0 + d, 0.0))]; + frame(&mut app, &ctx, fingers(egui::TouchPhase::Start, 0.0)); + for k in 1..=3 { + frame(&mut app, &ctx, fingers(egui::TouchPhase::Move, 10.0 * k as f32)); + } + frame(&mut app, &ctx, fingers(egui::TouchPhase::End, 30.0)); + let zoom = app.view().unwrap().zoom / before; + assert!(zoom > 1.01, "on: fingers spread on a touch screen zoom in ({zoom})"); + assert!(zooms_in(turn(&mut app, "alt+cmd")), "on: Alt + Cmd-wheel zooms in about the pointer"); + assert!(zooms_in(turn(&mut app, "alt")), "on: so does Alt-wheel"); + let (zoom, scroll, _) = turn(&mut app, ""); + assert!((zoom - 1.0).abs() < 1e-9 && scroll.x == 0.0 && scroll.y < -1.0, "on: the wheel scrolls up ({zoom}, {scroll:?})"); + let (zoom, scroll, _) = turn(&mut app, "shift"); + assert!((zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, "on: Shift-wheel scrolls sideways ({zoom}, {scroll:?})"); + // A Cmd-wheel notch with a plain one right after it, before egui has spread the first: they + // scroll two notches in all, sideways and up. + let before = *app.view().unwrap(); + crate::tests_synthetic::control(&mut app, &ctx, "ui.wheel", json!({"x": at.x, "y": at.y, "dy": 1, "cmd": true})); + crate::tests_synthetic::control(&mut app, &ctx, "ui.wheel", json!({"x": at.x, "y": at.y, "dy": 1})); + for _ in 0..40 { + run(&mut app); + } + let after = *app.view().unwrap(); + let scroll = (after.center - before.center) * after.zoom; + assert!( + scroll.x < -1.0 && scroll.y < -1.0 && (scroll.x + scroll.y + 2.0 * line).abs() < 0.5, + "on: a Cmd-wheel notch and a plain one right after it scroll two notches in all ({scroll:?})" + ); + // A pinch while egui still spreads a Cmd-wheel notch zooms by the pinch alone, and the + // canvas scrolls sideways by one notch; the pinch magnifies the part scrolled before it. + let before = *app.view().unwrap(); + let p = Xf::new(rect, &before).to_doc(at); + crate::tests_synthetic::control(&mut app, &ctx, "ui.wheel", json!({"x": at.x, "y": at.y, "dy": 1, "cmd": true})); + app.synthetic.extend([egui::Event::PointerMoved(at), egui::Event::Zoom(1.25)]); + for _ in 0..40 { + run(&mut app); + } + let after = *app.view().unwrap(); + let (zoom, moved) = (after.zoom / before.zoom, Xf::new(rect, &after).to_screen(p) - at); + let notch = line as f32; + assert!( + (zoom - 1.25).abs() < 1e-6 && moved.x > notch - 0.5 && moved.x < 1.25 * notch + 0.5 && moved.y.abs() < 1e-3, + "on: a pinch during a Cmd-wheel notch zooms by the pinch, and the notch scrolls sideways ({zoom}, {moved:?})" + ); + // A trackpad gesture starts with no modifier, and Cmd is pressed and released during it: + // egui keeps Cmd in its wheel state until the gesture ends, and the canvas keeps scrolling + // sideways until then. + let before = *app.view().unwrap(); + let swipe = |phase, modifiers| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 6.0), + phase, + modifiers, + source: egui::MouseWheelSource::Unknown, + }; + app.synthetic.extend([ + egui::Event::PointerMoved(at), + swipe(egui::TouchPhase::Start, egui::Modifiers::NONE), + swipe(egui::TouchPhase::Move, egui::Modifiers::COMMAND), + swipe(egui::TouchPhase::Move, egui::Modifiers::NONE), + swipe(egui::TouchPhase::End, egui::Modifiers::NONE), + ]); + for _ in 0..40 { + run(&mut app); + } + let after = *app.view().unwrap(); + let scroll = (after.center - before.center) * after.zoom; + assert!( + (after.zoom / before.zoom - 1.0).abs() < 1e-9 && (scroll.x + 12.0).abs() < 0.01 && scroll.y == 0.0, + "on: a trackpad gesture scrolls sideways to its end after Cmd is let go ({}, {scroll:?})", + after.zoom / before.zoom + ); + // An Alt-wheel gesture pauses past egui's scroll timeout with no frame in between: egui + // ends it before the next event, so a move with Cmd alone scrolls sideways. + // Frames at the given times, with the events in the frame's own input (the host's input + // hook hands synthetic events out over several frames). + let run_at = |app: &mut VectorcraftApp, time: f64, events: Vec| { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), + time: Some(time), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + // The Alt part rests the fingers without moving, so only the Cmd move below acts. + let rest = |phase| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::ZERO, + phase, + modifiers: egui::Modifiers::ALT, + source: egui::MouseWheelSource::Unknown, + }; + let t = ctx.input(|i| i.time) + 1.0; + run_at(&mut app, t, vec![egui::Event::PointerMoved(at), rest(egui::TouchPhase::Start), rest(egui::TouchPhase::Move)]); + let before = *app.view().unwrap(); + run_at(&mut app, t + 2.0, vec![swipe(egui::TouchPhase::Move, egui::Modifiers::COMMAND)]); + for k in 1..=40 { + run_at(&mut app, t + 2.0 + f64::from(k) / 60.0, vec![]); + } + let after = *app.view().unwrap(); + let scroll = (after.center - before.center) * after.zoom; + assert!( + (after.zoom / before.zoom - 1.0).abs() < 1e-9 && (scroll.x + 6.0).abs() < 0.01 && scroll.y == 0.0, + "on: after egui's timeout, a Cmd move scrolls sideways ({}, {scroll:?})", + after.zoom / before.zoom + ); + app.session.execute("prefs.set", &json!({"key": "zoomWithMouseWheel", "value": true})).unwrap(); + let (zoom, scroll, _) = turn(&mut app, "cmd"); + assert!( + (zoom - 1.0).abs() < 1e-9 && scroll.x < -1.0 && scroll.y == 0.0, + "with Zoom with Mouse Wheel: Cmd-wheel scrolls sideways ({zoom}, {scroll:?})" + ); + assert!(zooms_in(turn(&mut app, "")), "with Zoom with Mouse Wheel: the wheel zooms in about the pointer"); +} + +/// With Scroll Sideways with Cmd/Ctrl + Wheel on and Animated Zoom off, Alt + Cmd-wheel zooms +/// about the pointer by egui's Cmd-wheel zoom, as Cmd-wheel does with the option off, and +/// Cmd-wheel alone scrolls sideways. +#[test] +fn cmd_wheel_sideways_alt_cmd_zooms_without_animated_zoom() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for (key, value) in [("ctrlWheelScrollsSideways", true), ("zoomWithMouseWheel", false), ("animatedZoom", false)] { + app.session.execute("prefs.set", &json!({"key": key, "value": value})).unwrap(); + } + let ctx = egui::Context::default(); + let run = |app: &mut VectorcraftApp| { + let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + run(&mut app); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() + vec2(60.0, 40.0); + let before = *app.view().unwrap(); + crate::tests_synthetic::control(&mut app, &ctx, "ui.wheel", json!({"x": at.x, "y": at.y, "dy": 1, "alt": true, "cmd": true})); + for _ in 0..40 { + run(&mut app); + } + let after = *app.view().unwrap(); + let expected = ctx.options(|o| f64::from(o.input_options.line_scroll_speed * o.input_options.scroll_zoom_speed).exp()); + let zoom = after.zoom / before.zoom; + assert!((zoom - expected).abs() < 1e-3, "Alt + Cmd-wheel zooms in by one notch ({zoom}, expected {expected})"); + assert!(Xf::new(rect, &after).to_doc(at).distance(Xf::new(rect, &before).to_doc(at)) < 1e-6, "Alt + Cmd-wheel zooms about the pointer"); + + let before = after; + crate::tests_synthetic::control(&mut app, &ctx, "ui.wheel", json!({"x": at.x, "y": at.y, "dy": 1, "cmd": true})); + for _ in 0..40 { + run(&mut app); + } + let after = *app.view().unwrap(); + let scroll = (after.center - before.center) * after.zoom; + let line = f64::from(ctx.options(|o| o.input_options.line_scroll_speed)); + assert!((after.zoom / before.zoom - 1.0).abs() < 1e-9, "Cmd-wheel does not zoom"); + assert!((scroll.x + line).abs() < 0.5 && scroll.y == 0.0, "Cmd-wheel scrolls sideways ({scroll:?})"); +} + +/// With Zoom with Mouse Wheel off, a trackpad gesture that starts with Alt keeps zooming about the +/// pointer until it ends, also after Alt is let go, as egui keeps a modifier held during a gesture, +/// with Animated Zoom on and off. A gesture that gains Alt partway zooms from then on. +#[test] +fn alt_wheel_gesture_keeps_zooming_after_alt_is_let_go() { + for animate in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for (key, value) in [("zoomWithMouseWheel", false), ("animatedZoom", animate)] { + app.session.execute("prefs.set", &json!({"key": key, "value": value})).unwrap(); + } + let ctx = egui::Context::default(); + let run = |app: &mut VectorcraftApp| { + let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + run(&mut app); + let rect = app.canvas_rect.unwrap(); + let at = rect.center() + vec2(60.0, 40.0); + let swipe = |phase, modifiers| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 6.0), + phase, + modifiers, + source: egui::MouseWheelSource::Unknown, + }; + // One gesture with the given modifiers on its Start and its two Moves → (zoom ratio, how far + // the point under `at` moved). + let gesture = |app: &mut VectorcraftApp, mods: [egui::Modifiers; 3]| { + let before = *app.view().unwrap(); + app.synthetic.extend([ + egui::Event::PointerMoved(at), + swipe(egui::TouchPhase::Start, mods[0]), + swipe(egui::TouchPhase::Move, mods[1]), + swipe(egui::TouchPhase::Move, mods[2]), + swipe(egui::TouchPhase::End, egui::Modifiers::NONE), + ]); + for _ in 0..40 { + run(app); + } + let after = *app.view().unwrap(); + (after.zoom / before.zoom, Xf::new(rect, &after).to_doc(at).distance(Xf::new(rect, &before).to_doc(at))) + }; + let alt = egui::Modifiers::ALT; + let (held, _) = gesture(&mut app, [alt, alt, alt]); + assert!(held > 1.01, "animate {animate}: an Alt gesture zooms in ({held})"); + let (zoom, moved) = gesture(&mut app, [alt, alt, egui::Modifiers::NONE]); + assert!( + (zoom - held).abs() < 1e-9 && moved < 1e-6, + "animate {animate}: a move without Alt keeps the gesture zooming about the pointer ({zoom}, expected {held}; moved {moved})" + ); + let (zoom, moved) = gesture(&mut app, [egui::Modifiers::NONE, alt, egui::Modifiers::NONE]); + assert!( + (zoom - held).abs() < 1e-9 && moved < 1e-6, + "animate {animate}: Alt pressed partway zooms the rest of the gesture about the pointer ({zoom}, expected {held}; moved {moved})" + ); + } +} + /// #888: with Zoom with Mouse Wheel, a wheel notch's zoom glides in over a few frames, as a /// scroll does, instead of jumping on the frame it arrives; it ends at the same zoom. #[test] diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index c0e2a4bc07..39bc805453 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -52,8 +52,19 @@ const WHEEL_GLIDE: f64 = 0.05; /// What the wheel did across frames ([`wheel`]). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct WheelTurn { - /// The last wheel turn was an Alt-wheel one. + /// The last wheel turn was an Alt-wheel one: `held` had Alt without Cmd/Ctrl at its last Start + /// or Move. alt: bool, + /// The modifiers egui's wheel state holds, followed while Zoom with Mouse Wheel is off: each + /// wheel event's own, or, through a trackpad gesture, all those held since it began; none + /// while the wheel is idle. + held: egui::Modifiers, + /// A trackpad gesture is under way: egui has seen its Start phase and has not yet seen its End + /// or Cancel phase. + gesture: bool, + /// When the last wheel event came (`InputState::time`), and whether a trackpad sent it. + last: f64, + trackpad: bool, /// The zoom (natural log) wheel notches still have to glide in. pub(super) glide: f64, } @@ -342,13 +353,22 @@ struct ThumbDrag { /// What the wheel, a pinch and a two-finger drag on a touch screen did over the canvas this frame: /// a zoom factor (about the pointer) and a scroll (screen points the content moves). The wheel scrolls, Cmd- and Alt-wheel (Option -/// on the Mac) zoom. With General › Zoom with Mouse Wheel (`wheel_zooms`) the wheel and Alt-wheel -/// zoom, Shift-wheel scrolls up and down and Cmd/Ctrl-wheel sideways. `line` and `page`: points +/// on the Mac) zoom; with General › Scroll Sideways with Cmd/Ctrl + Wheel, Cmd/Ctrl-wheel scrolls +/// sideways instead, and Alt + Cmd/Ctrl-wheel still zooms. With General › Zoom with Mouse Wheel the +/// wheel and Alt-wheel zoom, Shift-wheel scrolls up and down and Cmd/Ctrl-wheel sideways. `line` and `page`: points /// per wheel line and page. `turn`: kept by the caller across frames. With Performance › Animated /// Zoom (`animate`) a mouse wheel's notches zoom in a glide over a few frames, as scrolling does /// (#888); off, each notch zooms on the frame it arrives (#4283). A trackpad's fine steps zoom at /// once either way. -pub(super) fn wheel(i: &egui::InputState, wheel_zooms: bool, animate: bool, line: f32, page: f32, turn: &mut WheelTurn) -> (f64, egui::Vec2) { +pub(super) fn wheel( + i: &egui::InputState, + prefs: &vectorcraft_engine::Prefs, + wheel_zooms: bool, + animate: bool, + line: f32, + page: f32, + turn: &mut WheelTurn, +) -> (f64, egui::Vec2) { // Fingers on a touch screen pan the content with them (a trackpad sends scrolls instead). let pan = i.multi_touch().map_or(egui::Vec2::ZERO, |t| t.translation_delta); // A wheel event's motion in points. @@ -360,17 +380,72 @@ pub(super) fn wheel(i: &egui::InputState, wheel_zooms: bool, animate: bool, line if !wheel_zooms { // egui makes Cmd-wheel (and a pinch) its zoom and the rest a scroll it spreads over a few // frames: the rest of an Alt-wheel turn zooms too, however soon Alt is let go. - if let Some(m) = i.events.iter().rev().find_map(|e| if let egui::Event::MouseWheel { modifiers, .. } = e { Some(modifiers) } else { None }) { - turn.alt = m.alt && !m.command; + // Each wheel event changes `turn.held` and `turn.gesture` as `WheelState::on_wheel_event` + // changes egui's wheel modifiers and status. Both are cleared while egui's wheel is idle. + // `turn.alt` follows `turn.held` after each Start or Move, so a trackpad gesture that held + // Alt keeps zooming until it ends, also after Alt is let go. + for e in &i.events { + if let egui::Event::MouseWheel { phase, modifiers, source, .. } = e { + // A wheel event that comes after egui's scroll timeout ends the turn first, as + // `on_wheel_event` does (1 s for fingers resting on a trackpad mid-gesture, else + // 0.15 s), also when no frame ran in between. + let timeout = if turn.gesture && turn.trackpad { 1.0 } else { 0.150 }; + if i.time - turn.last > timeout { + turn.gesture = false; + turn.held = egui::Modifiers::NONE; + } + turn.last = i.time; + turn.trackpad = *source == egui::MouseWheelSource::Trackpad; + match phase { + egui::TouchPhase::Start => { + turn.gesture = true; + turn.held = *modifiers; + turn.alt = turn.held.alt && !turn.held.command; + } + egui::TouchPhase::Move => { + if turn.gesture { + turn.held |= *modifiers; + } else { + turn.held = *modifiers; + } + turn.alt = turn.held.alt && !turn.held.command; + } + egui::TouchPhase::End | egui::TouchPhase::Cancel => { + turn.gesture = false; + turn.held = egui::Modifiers::NONE; + } + } + } + } + if !i.is_scrolling() { + turn.gesture = false; + turn.held = egui::Modifiers::NONE; + } + let (mut zoom, mut scroll) = (f64::from(i.zoom_delta()), i.smooth_scroll_delta); + // Scroll Sideways with Cmd/Ctrl + Wheel: while egui's wheel state holds Cmd/Ctrl without + // Alt, egui's zoom, less the pinches', is `exp(points × scroll_zoom_speed)`, at egui's + // default speed, which the app keeps. The canvas scrolls sideways by those points instead. + // A trackpad or web pinch still zooms. With fingers on a touch screen, egui's zoom is the + // fingers' alone, and the canvas leaves it as it is. + if prefs.ctrl_wheel_scrolls_sideways && turn.held.command && !turn.held.alt && i.multi_touch().is_none() { + let pinch: f64 = i.events.iter().filter_map(|e| if let egui::Event::Zoom(f) = e { Some(f64::from(*f)) } else { None }).product(); + let wheel_zoom = zoom / pinch; + if wheel_zoom.is_finite() && wheel_zoom > 0.0 { + scroll.x += (wheel_zoom.ln() / f64::from(egui::InputOptions::default().scroll_zoom_speed)) as f32; + zoom = pinch; + } } - let (zoom, scroll) = (f64::from(i.zoom_delta()), i.smooth_scroll_delta); if turn.alt && !animate { // Without Animated Zoom, Alt-wheel zooms by the wheel events themselves, on the frame - // they arrive; the rest of egui's spread scroll is dropped. + // they arrive; the rest of egui's spread scroll is dropped. Only Move events count, as + // `on_wheel_event` moves egui's scroll by Move events alone. let d: f32 = i .events .iter() - .filter_map(|e| if let egui::Event::MouseWheel { unit, delta, .. } = e { Some(points(unit, *delta)) } else { None }) + .filter_map(|e| match e { + egui::Event::MouseWheel { unit, delta, phase: egui::TouchPhase::Move, .. } => Some(points(unit, *delta)), + _ => None, + }) .map(|d| d.x + d.y) .sum(); return (zoom * (f64::from(d) * WHEEL_ZOOM).exp(), pan); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d8ada61f0b..92e94aa1e6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3710,6 +3710,7 @@ digits Malayalam Малаялам Zoom to Selection Приближаване до селекцията Zoom Tool Инструмент „Мащаб“ Zoom with Mouse Wheel Мащабиране с колелцето на мишката + Scroll Sideways with Cmd/Ctrl + Wheel Хоризонтално превъртане с Cmd/Ctrl + колелцето Scrub Numeric Fields by Dragging Плъзгане на числени полета чрез влачене @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} файл в {folder} {note}. Показване на папката на пакета?|{n} файла в {folder} {note}. Показване на папката на пакета? @plural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index bcd4472804..2c365fa503 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3699,6 +3699,7 @@ theme Appearance Izgled Yards Jardi Zoom to Selection Zumiraj na odabir Zoom with Mouse Wheel Zumiraj točkićem miša + Scroll Sideways with Cmd/Ctrl + Wheel Pomjeraj vodoravno uz Cmd/Ctrl + točkić miša Scrub Numeric Fields by Dragging Mijenjaj numerička polja prevlačenjem Linux Display Server Linux server prikaza Print Preview Pregled štampanja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index bb3c3a35ae..f0c3542ad3 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3728,6 +3728,7 @@ digits Malayalam Malaiàlam Scribble… Garabateig… Script / Brush Cal·ligràfica / Pinzell Scripts Scripts + Scroll Sideways with Cmd/Ctrl + Wheel Desplaça horitzontalment amb Cmd/Ctrl + roda del ratolí Scrub Numeric Fields by Dragging Canvia els camps numèrics arrossegant Search Cerca Search All Cerca a tot diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9991617c3d..2332578971 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3744,6 +3744,7 @@ theme Appearance Motiv Yards Yardy Zoom to Selection Zvětšit na výběr Zoom with Mouse Wheel Zvětšovat kolečkem myši + Scroll Sideways with Cmd/Ctrl + Wheel Posouvat vodorovně kolečkem s Cmd/Ctrl Scrub Numeric Fields by Dragging Měnit číselné hodnoty tažením Linux Display Server Zobrazovací server Linuxu Print Preview Náhled tisku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 874d196f01..94516cb64e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3472,6 +3472,7 @@ theme Appearance Udseende Yards Yards Zoom to Selection Zoom til markering Zoom with Mouse Wheel Zoom med musehjul + Scroll Sideways with Cmd/Ctrl + Wheel Rul vandret med Cmd/Ctrl + musehjul Scrub Numeric Fields by Dragging Juster numeriske felter ved at trække Linux Display Server Linux-visningsserver Print Preview Udskriftsvisning diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 114657cc75..6dc11392ef 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3703,6 +3703,7 @@ effect Points Punkte Zoom to Selection Auf Auswahl zoomen Zoom Tool Zoom-Werkzeug Zoom with Mouse Wheel Mit Mausrad zoomen + Scroll Sideways with Cmd/Ctrl + Wheel Mit Cmd/Ctrl + Mausrad horizontal scrollen Scrub Numeric Fields by Dragging Zahlenfelder durch Ziehen ändern @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} Datei in {folder} {note}. Paketordner anzeigen?|{n} Dateien in {folder} {note}. Paketordner anzeigen? @plural {n} linked file not found|{n} linked files not found {n} verknüpfte Datei nicht gefunden|{n} verknüpfte Dateien nicht gefunden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 00dcc70442..267920a0f5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4036,6 +4036,7 @@ digits Malayalam Μαλαγιάλαμ Zig Zag… Ζιγκ-ζαγκ… Zoom to Selection Ζουμ στην επιλογή Zoom with Mouse Wheel Ζουμ με τον τροχό του ποντικιού + Scroll Sideways with Cmd/Ctrl + Wheel Οριζόντια κύλιση με Cmd/Ctrl + τροχό του ποντικιού Scrub Numeric Fields by Dragging Ρύθμιση αριθμητικών πεδίων με σύρσιμο @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} αρχείο στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας;|{n} αρχεία στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας; @plural {n} linked file not found|{n} linked files not found Δεν βρέθηκε {n} συνδεδεμένο αρχείο|Δεν βρέθηκαν {n} συνδεδεμένα αρχεία diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 1ae8b7fae0..105146217d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3793,6 +3793,7 @@ digits Malayalam Malayálam Zoom to Selection Zoom a la selección Zoom Tool Herramienta Zoom Zoom with Mouse Wheel Zoom con la rueda del mouse + Scroll Sideways with Cmd/Ctrl + Wheel Desplazar horizontalmente con Cmd/Ctrl + rueda del mouse Scrub Numeric Fields by Dragging Ajustar campos numéricos arrastrando @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} archivo en {folder} {note}. ¿Mostrar la carpeta del paquete?|{n} archivos en {folder} {note}. ¿Mostrar la carpeta del paquete? @plural {n} linked file not found|{n} linked files not found No se encontró {n} archivo vinculado|No se encontraron {n} archivos vinculados diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bf26c1cc36..821935c270 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3668,6 +3668,7 @@ theme Appearance Ulkoasu Yards Jaardit Zoom to Selection Zoomaa valintaan Zoom with Mouse Wheel Zoomaa hiiren rullalla + Scroll Sideways with Cmd/Ctrl + Wheel Vieritä vaakasuunnassa Cmd/Ctrl + hiiren rullalla Scrub Numeric Fields by Dragging Muuta numerokenttiä vetämällä Linux Display Server Linuxin näyttöpalvelin Print Preview Tulostuksen esikatselu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 455af6aa56..f7215a99b0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3785,6 +3785,7 @@ digits Malayalam Malayalam Zoom to Selection Zoom sur la sélection Zoom Tool Outil Zoom Zoom with Mouse Wheel Zoom avec la molette de la souris + Scroll Sideways with Cmd/Ctrl + Wheel Défilement horizontal avec Cmd/Ctrl + molette Scrub Numeric Fields by Dragging Modifier les champs numériques en faisant glisser @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? @plural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9574c304a9..9690969c5f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4526,6 +4526,7 @@ mark-style Japanese Japán Zoom to Selection Nagyítás a kijelölésre Zoom Tool Nagyító Zoom with Mouse Wheel Nagyítás egérgörgővel + Scroll Sideways with Cmd/Ctrl + Wheel Vízszintes görgetés Cmd/Ctrl + görgővel @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Fájlok: {n}, mappa: {folder} {note}. Megnyitod a csomag mappáját? @plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nem olvasható mappák vagy fájlok: {n} @plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Kihagyott mappák: {n} (például más alkalmazások, a rendszer és a rejtett mappák) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2b4ab48e84..12c1b4c851 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3472,6 +3472,7 @@ theme Appearance Tampilan Yards Yard Zoom to Selection Zum ke seleksi Zoom with Mouse Wheel Zum dengan roda mouse + Scroll Sideways with Cmd/Ctrl + Wheel Gulir horizontal dengan Cmd/Ctrl + roda mouse Scrub Numeric Fields by Dragging Atur nilai kolom numerik dengan menyeret Linux Display Server Server tampilan Linux Print Preview Pratinjau cetak diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1f6d0a139f..004d41e2c3 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3830,6 +3830,7 @@ digits Malayalam Malayalam Zoom to Selection Zoom sulla selezione Zoom Tool Strumento Zoom Zoom with Mouse Wheel Zoom con la rotellina del mouse + Scroll Sideways with Cmd/Ctrl + Wheel Scorrimento orizzontale con Cmd/Ctrl + rotellina Scrub Numeric Fields by Dragging Regola i campi numerici trascinando @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto?|{n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto? @plural {n} linked file not found|{n} linked files not found File collegati non trovati: {n}|File collegati non trovati: {n} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 17b2aa06f4..716de0b24f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3408,6 +3408,7 @@ mark-style Japanese 日本式 Zoom Tool ズームツール Zoom to Selection 選択範囲にズーム Zoom with Mouse Wheel マウスホイールでズーム + Scroll Sideways with Cmd/Ctrl + Wheel Cmd/Ctrl + ホイールで横スクロール Scrub Numeric Fields by Dragging ドラッグで数値フィールドを調整 [Default] is protected: New… starts an editable copy. [Default] は変更できません。「新規…」で編集できる複製を作ります。 [Unnamed] [名称未設定] diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f9545785b8..e5d0a28c08 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3288,6 +3288,7 @@ theme Appearance იერსახე Yards იარდები Zoom to Selection მონიშნულის მასშტაბირება Zoom with Mouse Wheel მაუსის ბორბლით მასშტაბირება + Scroll Sideways with Cmd/Ctrl + Wheel ჰორიზონტალური გადაადგილება Cmd/Ctrl + ბორბლით Scrub Numeric Fields by Dragging რიცხვითი ველების შეცვლა გადათრევით Linux Display Server Linux-ის ეკრანის სერვერი Print Preview ნახვა ამობეჭდვამდე diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index ae73d31acf..a8f2c0db48 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3397,6 +3397,7 @@ mark-style Japanese 일본식 Zoom Tool 확대/축소 도구 Zoom to Selection 선택 항목에 맞춰 확대/축소 Zoom with Mouse Wheel 마우스 휠로 확대/축소 + Scroll Sideways with Cmd/Ctrl + Wheel Cmd/Ctrl + 휠로 가로 스크롤 Scrub Numeric Fields by Dragging 드래그로 숫자 필드 조절 [Default] is protected: New… starts an editable copy. [Default]는 보호되어 있습니다. 새로 만들기…를 누르면 편집 가능한 복사본이 만들어집니다. [Unnamed] [이름 없음] diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c52207339a..e803314e09 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3486,6 +3486,7 @@ theme Appearance Vormgeving Yards Yards Zoom to Selection Inzoomen op selectie Zoom with Mouse Wheel Zoomen met muiswiel + Scroll Sideways with Cmd/Ctrl + Wheel Horizontaal scrollen met Cmd/Ctrl + muiswiel Scrub Numeric Fields by Dragging Numerieke velden aanpassen door te slepen Linux Display Server Linux-weergaveserver Print Preview Afdrukvoorbeeld diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f3538c540e..591790721f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3607,6 +3607,7 @@ theme Appearance Wygląd Yards Jardy Zoom to Selection Powiększaj do zaznaczenia Zoom with Mouse Wheel Powiększaj kółkiem myszy + Scroll Sideways with Cmd/Ctrl + Wheel Przewijaj w poziomie kółkiem z Cmd/Ctrl Scrub Numeric Fields by Dragging Zmieniaj pola liczbowe przeciąganiem Linux Display Server Serwer wyświetlania Linux Print Preview Podgląd wydruku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d1028010bf..cae6a2fd75 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3115,6 +3115,7 @@ digits Malayalam Malaiala Zoom Tool Ferramenta Zoom Zoom to Selection Ampliar para a Seleção Zoom with Mouse Wheel Zoom com a Roda do Mouse + Scroll Sideways with Cmd/Ctrl + Wheel Rolar na Horizontal com Cmd/Ctrl + Roda Scrub Numeric Fields by Dragging Ajustar Campos Numéricos Arrastando [Default] is protected: New… starts an editable copy. [Padrão] é protegido: Novo… inicia uma cópia editável. [Unnamed] [Sem Nome] diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f0a56b6132..3f1b8e702b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3825,6 +3825,7 @@ digits Malayalam Малаялам Zoom to Selection Масштаб по выделению Zoom Tool Инструмент «Масштаб» Zoom with Mouse Wheel Масштабировать колесом мыши + Scroll Sideways with Cmd/Ctrl + Wheel Прокручивать по горизонтали колесом с Cmd/Ctrl Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета? @plural {n} linked file not found|{n} linked files not found Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9e2a2ce013..3362155f01 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3715,6 +3715,7 @@ digits Malayalam Malayalam Zoom to Selection Zooma till markering Zoom Tool Zoomverktyg Zoom with Mouse Wheel Zooma med mushjulet + Scroll Sideways with Cmd/Ctrl + Wheel Rulla horisontellt med Cmd/Ctrl + mushjulet Scrub Numeric Fields by Dragging Ändra numeriska fält genom att dra @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fil i {folder} {note}. Visa paketmappen?|{n} filer i {folder} {note}. Visa paketmappen? @plural {n} linked file not found|{n} linked files not found {n} länkad fil hittades inte|{n} länkade filer hittades inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7cd9822fd6..9308d7ea61 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3602,6 +3602,7 @@ digits Malayalam Malayalam Zoom to Selection Seçimi Yakınlaştır Zoom Tool Yakınlaştırma Aracı Zoom with Mouse Wheel Fare Tekerleği ile Yakınlaştırma + Scroll Sideways with Cmd/Ctrl + Wheel Cmd/Ctrl + Tekerlek ile Yatay Kaydırma Scrub Numeric Fields by Dragging Sayısal Alanları Sürükleyerek Fırçalayın @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} içinde {n} dosya {note}. Paket klasörü gösterilsin mi? @plural {n} linked file not found|{n} linked files not found {n} bağlantılı dosya bulunamadı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2f50e09918..55edd38d50 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3823,6 +3823,7 @@ effect Points Точки Zoom to Selection Масштаб виділення Zoom Tool Інструмент «Масштаб» Zoom with Mouse Wheel Масштабувати колесом миші + Scroll Sideways with Cmd/Ctrl + Wheel Прокручувати по горизонталі колесом із Cmd/Ctrl Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета? @plural {n} linked file not found|{n} linked files not found не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d2dc9a4782..e8ea0991f4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4189,6 +4189,7 @@ mark-style Japanese Kiểu Nhật Zoom to Selection Thu phóng đến vùng chọn Zoom Tool Công cụ thu phóng Zoom with Mouse Wheel Thu phóng bằng con lăn chuột + Scroll Sideways with Cmd/Ctrl + Wheel Cuộn ngang bằng Cmd/Ctrl + con lăn @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} tệp trong {folder} {note}. Hiện thư mục gói? @plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} thư mục hoặc tệp không thể đọc được @plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Đã bỏ qua {n} thư mục, chẳng hạn thư mục của ứng dụng khác, thư mục hệ thống và thư mục ẩn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 100128f3c2..4cf9b672fc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3680,6 +3680,7 @@ digits Malayalam 马拉雅拉姆数字 Zoom to Selection 缩放到所选对象 Zoom Tool 缩放工具 Zoom with Mouse Wheel 使用鼠标滚轮缩放 + Scroll Sideways with Cmd/Ctrl + Wheel 使用 Cmd/Ctrl + 滚轮水平滚动 Scrub Numeric Fields by Dragging 拖动以调整数值字段 @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 个文件{note}。要显示打包文件夹吗? @plural {n} linked file not found|{n} linked files not found 找不到 {n} 个链接文件 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d0f9c079ee..4aee5622d4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4716,6 +4716,7 @@ digits Malayalam 馬來亞拉姆數字 Zoom to Selection 縮放至選取範圍 Zoom Tool 縮放工具 Zoom with Mouse Wheel 使用滑鼠滾輪縮放 + Scroll Sideways with Cmd/Ctrl + Wheel 使用 Cmd/Ctrl + 滾輪水平捲動 Scrub Numeric Fields by Dragging 拖曳以調整數值欄位 @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 個檔案{note}。要顯示封裝資料夾嗎? @plural {n} linked file not found|{n} linked files not found 找不到 {n} 個連結檔案 diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index c3532da834..8c3fa35d6b 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -456,6 +456,11 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, let v = d.fields.get(sp.key).cloned().unwrap_or(Value::Null); let mark = found_mark(ui, d, sp.key); match sp.kind { + // General › Scroll Sideways with Cmd/Ctrl + Wheel acts only while Zoom with Mouse Wheel + // is off: dimmed while it is on. + PrefKind::Bool if sp.key == "ctrlWheelScrollsSideways" => { + ui.add_enabled_ui(!d.bool("zoomWithMouseWheel"), |ui| bool_row(ui, d, sp.key, sp.label)); + } // Units › Numbers Without Units Are Points only tells points from picas: dimmed // unless a unit is Picas. PrefKind::Bool if sp.key == "numbersWithoutUnitsArePoints" => { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index a43ec66776..9e8ce28045 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -503,6 +503,41 @@ fn numbers_without_units_are_points_reaches_the_fields_and_dims_without_picas() assert!(picas_in_use(d), "enabled with a unit in picas"); } +/// General › Scroll Sideways with Cmd/Ctrl + Wheel: its checkbox is dimmed while Zoom with +/// Mouse Wheel is checked in the dialog, and a click on it then leaves the setting as it was. +#[test] +fn scroll_sideways_with_cmd_wheel_dims_with_zoom_with_mouse_wheel() { + fn label(s: &egui::Shape, text: &str) -> Option<(egui::Color32, egui::Rect)> { + match s { + egui::Shape::Text(t) if t.galley.text() == text => t.galley.job.sections.first().map(|s| (s.format.color, t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().find_map(|s| label(s, text)), + _ => None, + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut a = app(); + let mut frame = |d: &mut Dialog, events: Vec| { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 900.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| category_fields(ui, &mut a, d, "General")); + out.textures_delta.clear(); + out.shapes.iter().find_map(|c| label(&c.shape, "Scroll Sideways with Cmd/Ctrl + Wheel")) + }; + let t = Tokens::get(&ctx); + for (zoom, color, what) in [(false, t.text, "enabled while Zoom with Mouse Wheel is off"), (true, t.text_disabled, "dimmed while it is on")] { + let mut d = Dialog::new("preferences", json!({"zoomWithMouseWheel": zoom, "ctrlWheelScrollsSideways": true})); + let (shown, at) = frame(&mut d, vec![]).unwrap_or_else(|| panic!("no label ({what})")); + assert_eq!(shown, color, "{what}"); + let press = + |pressed| egui::Event::PointerButton { pos: at.center(), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut d, vec![egui::Event::PointerMoved(at.center()), press(true)]); + frame(&mut d, vec![press(false)]); + // A click turns it off while it is enabled, and leaves it on while it is dimmed. + assert_eq!(d.fields["ctrlWheelScrollsSideways"], json!(zoom), "after a click, {what}"); + } +} + /// 0.5.0 saved `powerSaving` for everyone (its default): it reads as Automatic, while the /// choices this version offers are kept (#502). #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4e8408cd5b..9357927f00 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -100,7 +100,7 @@ the two can still win that race. | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | -| `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls and Cmd- or Alt-wheel (Option on the Mac) zooms about the pointer; with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it | +| `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls, Cmd-wheel (Ctrl on Windows and Linux) scrolls sideways and Alt-wheel (Option on the Mac) zooms about the pointer (with the `ctrlWheelScrollsSideways` preference off, Cmd-wheel zooms too); with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it. Over the canvas, the wheel preferences in `docs/mcp.md` change what these keys do | | `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | | `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value}` or `{fields: [{field, value}…]}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`), `__` fields, `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | diff --git a/docs/mcp.md b/docs/mcp.md index facbe02e4c..8ad9232d89 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3693,6 +3693,12 @@ desktop app): in View › Pixel Preview, on softens placed and embedded bitmaps; `disableAutoAddDelete` (off by default): on, the Pen no longer adds or deletes an anchor when a click lands on a segment or an anchor of a selected path. +`ctrlWheelScrollsSideways` (on by default): on, Cmd/Ctrl-wheel scrolls the canvas sideways instead of zooming while +`zoomWithMouseWheel` is off; off, Cmd/Ctrl-wheel zooms about the pointer. Alt + Cmd/Ctrl-wheel and a pinch on a Mac +trackpad, on a touch screen or in the web build still zoom about the pointer. With `zoomWithMouseWheel` off, once a +trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. The control channel's +`ui.wheel` with `cmd: true` turns the wheel with Cmd/Ctrl held. + `gridlineEvery` (72 pt by default) and `gridSubdivisions` (8 by default) set the document grid that View › Show Grid draws, and View › Snap to Grid snaps to its subdivisions. Changing either sets the grid of every open document. `file.new` gives a new document that grid, and `document.open`, `file.newFromTemplate` and `file.revert` give it to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 794ab3fb84..42a9d7011b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -736,6 +736,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (on by default: pink behind OpenType substitutions on screen — ligatures, contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set`, #394). About 14 stored options still do nothing yet (the rest of #394: Open Documents As Tabs, Real-time Drawing and Editing, GPU Performance beyond Animated Zoom, hyphenation language, scratch disks, the legacy clipboard, Touch Workspace). - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Three stored options still do nothing yet (the audit below). + - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl-wheel scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - Units › East Asian Type (#394, `unitsAsianType`): Points by default; it offers every unit and Q and Ha, a quarter of a millimetre each (0.709 pt: the [Illustrator Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/); `q` and `h` are the field suffixes [InDesign's notation table](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html) lists), and only it lists them: rulers, Document Setup and the other Units preferences keep their ten. The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. The model stays in points; any length field reads `13q`/`13h`. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` (`crates/engine/src/tests/units.rs`). From 6cd4171fbdc95dc8279ad6f64689ecdf1af68a60 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:45:41 +0700 Subject: [PATCH 13/26] Paragraph: Reset Panel also resets the Mojikumi Set and tab stops Squashed from #5025 onto main. --- crates/ui-egui/src/panels/paragraph.rs | 22 ++- crates/ui-egui/src/panels/paragraph/tests.rs | 141 +++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 160 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 8cb29ef305..4c3241608a 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -828,11 +828,19 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { /// Reset Panel: the paragraphs the panel acts on ([`format`]) take Auto alignment, no list, no /// indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification -/// options, Auto direction, Bottom-to-Bottom Leading, Regular burasagari, the Hard kinsoku set, the -/// Every-line Composer, Roman Hanging Punctuation off and no kashidas. +/// options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi +/// Set, Regular burasagari, the Hard kinsoku set, the Every-line Composer, Roman Hanging +/// Punctuation off, no kashidas and no tab stops, as one undo step named Reset Panel (inside an +/// undo group that is already open, as part of its step). fn reset_panel(app: &mut VectorcraftApp) { let h = HyphenationOptions::default(); let j = vectorcraft_doc::JustificationOptions::default(); + // The Type tool's typing session stays an undo step of its own. + super::character::end_typing(app); + let open = app.session.active().is_some_and(|st| st.undo_group.is_some()); + if !open { + app.session.begin_named_undo_group(Some("Reset Panel".into())); + } para_cmd(app, "text.setStyle", json!({"justify": "auto"})); format( app, @@ -842,10 +850,16 @@ fn reset_panel(app: &mut VectorcraftApp) { "hyphenLimit": h.hyphen_limit, "hyphenationZone": h.zone, "hyphenateCapitalized": h.capitalized, "kashida": "none", "wordSpacing": j.word_spacing, "letterSpacing": j.letter_spacing, "glyphScaling": j.glyph_scaling, "autoLeading": j.auto_leading, "singleWordJustification": "fullJustify", - "direction": "auto", "leadingModel": "romanBaseline", "burasagari": "standard", "kinsoku": "hard", "composer": "everyLine", - "romanHangingPunctuation": false + "direction": "auto", "leadingModel": "romanBaseline", "mojikumi": "lineEndHalf", "burasagari": "standard", "kinsoku": "hard", + "composer": "everyLine", "romanHangingPunctuation": false }), ); + para_cmd(app, "text.tabs.clear", json!({})); + // Closes the active document's undo group only, so an undo group open in another document + // stays open. + if !open && let Some(st) = app.session.active_mut() { + st.undo_group = None; + } } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index a1df5a927d..5facaee19b 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -1,4 +1,5 @@ use super::*; +use vectorcraft_doc::Mojikumi; use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; @@ -691,3 +692,143 @@ fn the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right() assert!(seen.iter().all(|s| *s), "{case}: a wide bar shows every group: {seen:?}"); } } + +/// Reset Panel gives the paragraphs it acts on new type's Mojikumi Set (Line-end Punctuation +/// Half Width) and no tab stops, as one undo step named Reset Panel: while the Type tool edits, +/// the paragraph at its caret (the typing before it stays a step of its own), and then the +/// selected type's paragraphs. In an undo group that is already open, the reset is part of +/// that group's step. +#[test] +fn reset_panel_resets_the_mojikumi_set_and_tab_stops_in_one_step() { + let (mut app, id) = editing_text("First\nSecond"); + app.run("text.setFormat", json!({"id": id, "mojikumi": "none"})).unwrap(); + app.run("text.tabs.set", json!({"id": id, "stops": [{"position": 36}, {"position": 90, "align": "right"}]})).unwrap(); + let text = |app: &VectorcraftApp| { + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Text(text) = &node.kind else { panic!("text") }; + text.as_ref().clone() + }; + let paras = |app: &VectorcraftApp| { + let text = text(app); + [text.para_at(0), text.para_at(1)].map(|p| (p.mojikumi, p.tabs.len())) + }; + let custom = (Mojikumi::None, 2); + let reset = (Mojikumi::LineEndHalf, 0); + assert_eq!(paras(&app), [custom, custom]); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let last_step = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.last().map(|e| e.label.clone()); + // Type over the second paragraph's text: the typing session is still open. + select_range(&mut app, 6, 12); + let before = steps(&app); + let ctx = egui::Context::default(); + let raw = egui::RawInput { events: vec![egui::Event::Text("X".into())], ..Default::default() }; + ctx.run_ui(raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())).textures_delta.clear(); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + reset_panel(&mut app); + assert_eq!(paras(&app), [custom, reset], "only the paragraph at the caret"); + assert_eq!((steps(&app), last_step(&app)), (before + 2, Some("Reset Panel".to_string()))); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(paras(&app), [custom, custom]); + assert_eq!(text(&app).plain_text(), "First\nX", "the typing stays"); + app.run("edit.redo", json!({})).unwrap(); + app.session.set_tool_option("stopEditing", &json!(true)); + let doc = app.session.active().unwrap().doc.clone(); + let before = steps(&app); + reset_panel(&mut app); + assert_eq!(paras(&app), [reset, reset]); + assert_eq!((steps(&app), last_step(&app)), (before + 1, Some("Reset Panel".to_string()))); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, doc, "one Undo takes the whole reset back"); + // In an undo group that is already open (MCP `command_batch` with `atomic`), the reset is + // part of that group's step. + app.run("edit.undoGroup.begin", json!({"label": "Batch"})).unwrap(); + let before = steps(&app); + reset_panel(&mut app); + assert_eq!(paras(&app), [reset, reset]); + app.run("text.setFormat", json!({"id": id, "mojikumi": "none"})).unwrap(); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!((steps(&app), last_step(&app)), (before + 1, Some("Batch".to_string()))); +} + +/// Reset Panel gives paragraphs that start with different Mojikumi Sets and tab stops the same +/// Mojikumi Set and no tab stops, as one undo step, and one Undo gives each paragraph its own +/// values back: while the Type tool edits, the paragraphs the selection touches, and then the +/// paragraphs of every selected type object. +#[test] +fn reset_panel_resets_paragraphs_with_different_values_in_one_step() { + let (mut app, id) = editing_text("First\nSecond\nThird"); + app.run("text.setFormat", json!({"id": id, "start": 0, "end": 1, "mojikumi": "none"})).unwrap(); + app.run("text.setFormat", json!({"id": id, "start": 6, "end": 7, "mojikumi": "lineEndHalf"})).unwrap(); + app.run("text.setFormat", json!({"id": id, "start": 13, "end": 14, "mojikumi": "none"})).unwrap(); + app.run("text.tabs.set", json!({"id": id, "start": 0, "end": 1, "stops": [{"position": 36}, {"position": 90, "align": "right"}]})).unwrap(); + app.run("text.tabs.set", json!({"id": id, "start": 6, "end": 7, "stops": [{"position": 120, "align": "decimal", "leader": "."}]})).unwrap(); + let paras = |app: &VectorcraftApp, id: &Value| { + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Text(text) = &node.kind else { panic!("text") }; + text.paragraph_styles().into_iter().map(|p| (p.mojikumi, p.tabs.iter().map(|t| t.position).collect::>())).collect::>() + }; + let first = (Mojikumi::None, vec![36.0, 90.0]); + let second = (Mojikumi::LineEndHalf, vec![120.0]); + let third = (Mojikumi::None, vec![]); + let reset = (Mojikumi::LineEndHalf, vec![]); + assert_eq!(paras(&app, &id), [first.clone(), second.clone(), third.clone()]); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let last_step = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.last().map(|e| e.label.clone()); + // A selection from the first paragraph into the second. + select_range(&mut app, 2, 8); + let doc = app.session.active().unwrap().doc.clone(); + let before = steps(&app); + reset_panel(&mut app); + assert_eq!(paras(&app, &id), [reset.clone(), reset.clone(), third.clone()], "only the paragraphs the selection touches"); + assert_eq!((steps(&app), last_step(&app)), (before + 1, Some("Reset Panel".to_string()))); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, doc, "one Undo takes the whole reset back"); + assert_eq!(paras(&app, &id), [first.clone(), second.clone(), third.clone()]); + // Two selected type objects. + app.session.set_tool_option("stopEditing", &json!(true)); + let other = app.run("text.create", json!({"x": 40, "y": 120, "text": "Other"})).unwrap()["id"].clone(); + app.run("text.setFormat", json!({"id": other, "mojikumi": "none"})).unwrap(); + app.run("text.tabs.set", json!({"id": other, "stops": [{"position": 48, "align": "center"}]})).unwrap(); + let other_values = (Mojikumi::None, vec![48.0]); + app.run("select.set", json!({"ids": [id, other]})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let before = steps(&app); + reset_panel(&mut app); + assert_eq!(paras(&app, &id), [reset.clone(), reset.clone(), reset.clone()]); + assert_eq!(paras(&app, &other), [reset]); + assert_eq!((steps(&app), last_step(&app)), (before + 1, Some("Reset Panel".to_string()))); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, doc, "one Undo takes the whole reset back"); + assert_eq!(paras(&app, &id), [first, second, third]); + assert_eq!(paras(&app, &other), [other_values]); +} + +/// Reset Panel closes only the undo group it opens: an undo group open in another document +/// stays open, and that document's later edits stay part of its step. +#[test] +fn reset_panel_leaves_an_undo_group_open_in_another_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "A"})).unwrap()["id"].clone(); + // The second document is open before the group begins, so switching to it opens no group in it. + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + assert_eq!(app.session.active_index(), Some(1)); + app.run("text.create", json!({"x": 20, "y": 50, "text": "B"})).unwrap(); + app.session.set_active(0); + app.run("edit.undoGroup.begin", json!({"label": "Batch"})).unwrap(); + app.run("text.setFormat", json!({"id": a, "mojikumi": "none"})).unwrap(); + let steps = |st: &vectorcraft_engine::DocState| (st.history.undo.len(), st.history.undo.last().map(|e| e.label.clone())); + let a_steps = steps(&app.session.documents()[0]); + assert_eq!(a_steps.1, Some("Batch".to_string())); + app.session.set_active(1); + assert!(app.session.active().unwrap().undo_group.is_none()); + let b_steps = steps(app.session.active().unwrap()).0; + reset_panel(&mut app); + assert_eq!(steps(app.session.active().unwrap()), (b_steps + 1, Some("Reset Panel".to_string()))); + assert!(app.session.active().unwrap().undo_group.is_none()); + assert!(app.session.documents()[0].undo_group.is_some(), "the other document's undo group stays open"); + app.session.set_active(0); + app.run("text.setFormat", json!({"id": a, "mojikumi": "lineEndHalf"})).unwrap(); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(steps(app.session.active().unwrap()), a_steps, "the later edit is part of the Batch step"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 42a9d7011b..4d22add2fd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1037,6 +1037,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. Type › Optical Margin Alignment (`type.opticalMarginAlignment`) hangs the punctuation and letter edges at the ends of a type object's lines outside its margins: at the left of left-aligned lines, at the right of right-aligned lines, and at both ends of centered and justified lines, in point and area type of left-to-right paragraphs. Quotation marks, hyphens, full stops and commas hang wholly; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their width. It is off by default and saved with the type object. Justification's Glyph Scaling leaves the glyphs that hang at their width, so they hang exactly their share, and Standard burasagari counts what hangs at a line's start as room before hanging a comma; `crates/text/src/tests/hang.rs` checks whole paragraphs with both composers, ragged, centred and justified, with Line-end Punctuation Half Width and bidirectional lines. Optical Margin Alignment and Roman Hanging Punctuation hang right-to-left paragraphs of point and area type, and type on a path whose first paragraph runs right to left, too. Auto aligns a right-to-left line at its right, or at the end bracket of a path, so it hangs there. A right-to-left line is read from right to left: where it hangs at its left margin, `."` ending it hangs both glyphs. + The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, the Every-line Composer, Roman Hanging Punctuation off, no kashidas and no tab stops, as one undo step. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. PDF export with type as text writes the hyphen that ends a line broken inside a word as a hyphen character where the line draws it, and the file opens with the hyphen in the line's text; kashidas are drawn as paths. The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. From be391e541afb4e474b8b15953060f586050cceb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:45:50 +0700 Subject: [PATCH 14/26] Type: Type Orientation is a setting of the whole thread Squashed from #5027 onto main. --- crates/engine/src/cmd/fileio/load.rs | 6 +- crates/engine/src/cmd/threads.rs | 64 ++++++++- crates/engine/src/cmd/threads/tests.rs | 171 +++++++++++++++++++++++++ crates/engine/src/cmd/typecmd.rs | 18 ++- docs/mcp.md | 6 + docs/target-app-parity.md | 1 + docs/type-parity.md | 1 + 7 files changed, 258 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index a1ec671aae..ae63ba9186 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -475,11 +475,15 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } // Threaded type read from a file flows through its frames (the threaded type of a restored // document keeps its text as saved), and every frame of a thread takes its first frame's - // Optical Margin Alignment setting. + // Optical Margin Alignment setting and writing direction. When that changes the direction of a + // frame of a restored document, the story flows through that frame's thread again. Threaded + // frames keep their size: Auto Size is off for them. if !doc.text_threads.is_empty() && !restored { crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc); } else if !doc.text_threads.is_empty() { + crate::cmd::threads::keep_frame_sizes(&mut doc); crate::cmd::threads::share_optical_margin(&mut doc); + crate::cmd::threads::share_orientation(&mut doc); // A frame whose first paragraph continues from the frame before draws it without the // paragraph's first-line indent and list marker. crate::cmd::threads::mark_continued(&mut doc); diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 61a21e506d..61fc7f33ae 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -168,7 +168,17 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { } } let optical = if live.len() >= 2 { optical_margin(before, doc, &live) } else { None }; - let frames: Vec = live.iter().filter_map(|id| text_of(doc, *id).cloned()).collect(); + let vertical = if live.len() >= 2 { thread_setting(before, doc, &live, |t| t.vertical) } else { None }; + // The story is measured in each frame with the settings the frame takes. + let frames: Vec = live + .iter() + .filter_map(|id| text_of(doc, *id).cloned()) + .map(|mut t| { + t.optical_margin = optical.unwrap_or(t.optical_margin); + t.vertical = vertical.unwrap_or(t.vertical); + t + }) + .collect(); let refs: Vec<&TextObject> = frames.iter().collect(); let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s); for (id, part) in live.iter().zip(parts) { @@ -177,11 +187,13 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { next.runs = part.runs; next.set_paragraph_styles(part.paras); let optical = optical.unwrap_or(t.optical_margin); + let vertical = vertical.unwrap_or(t.vertical); let continues = part.continues; if next.runs != t.runs || next.para != t.para || next.paras != t.paras || optical != t.optical_margin + || vertical != t.vertical || part.list_count != t.list_count || continues != t.first_para_continues { @@ -189,6 +201,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { t.para = next.para; t.paras = next.paras; t.optical_margin = optical; + t.vertical = vertical; t.list_count = part.list_count; t.first_para_continues = continues; refresh_bounds(t); @@ -235,11 +248,37 @@ pub(crate) fn restart_unthreaded_counts(doc: &mut std::sync::Arc) { /// The Optical Margin Alignment setting that every frame of a thread with the frames `live` takes: /// that of the first frame whose setting changed between `before` and `doc`, else the first frame's. fn optical_margin(before: &Document, doc: &Document, live: &[NodeId]) -> Option { - let now = |id: &NodeId| text_of(doc, *id).map(|t| t.optical_margin); - let changed = live.iter().find(|id| text_of(before, **id).is_some_and(|t| Some(t.optical_margin) != now(id))); + thread_setting(before, doc, live, |t| t.optical_margin) +} + +/// The value of the frame setting `get` that every frame of a thread with the frames `live` takes: +/// that of the first frame whose value changed between `before` and `doc`, or the first frame's value +/// when none changed. +fn thread_setting(before: &Document, doc: &Document, live: &[NodeId], get: impl Fn(&TextObject) -> T) -> Option { + let now = |id: &NodeId| text_of(doc, *id).map(&get); + let changed = live.iter().find(|id| text_of(before, **id).is_some_and(|t| Some(get(t)) != now(id))); changed.or(live.first()).and_then(now) } +/// Turn Auto Size off for the frames of each thread of two or more frames, as [`reflow`] does, +/// without re-flowing the story: for a document restored from a file as it was saved, so a later +/// change to a frame's settings keeps the frame's size. +pub(crate) fn keep_frame_sizes(doc: &mut Document) { + for thread in doc.text_threads.clone() { + let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); + if live.len() < 2 { + continue; + } + for id in live { + if text_of(doc, id).is_some_and(|t| t.area.fit == vectorcraft_doc::AreaFit::AutoHeight) + && let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) + { + t.area.fit = vectorcraft_doc::AreaFit::None; + } + } + } +} + /// Give every frame of each thread the first frame's Optical Margin Alignment setting, without /// re-flowing the story: for a document restored from a file as it was saved. pub(crate) fn share_optical_margin(doc: &mut Document) { @@ -257,6 +296,25 @@ pub(crate) fn share_optical_margin(doc: &mut Document) { } } +/// Give every frame of each thread the first frame's writing direction, and re-flow each thread in +/// which that changes a frame: for a document restored from a file as it was saved. +pub(crate) fn share_orientation(doc: &mut Document) { + let before = doc.clone(); + for thread in doc.text_threads.clone() { + let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); + let Some(vertical) = thread_setting(doc, doc, &live, |t| t.vertical) else { continue }; + // Only the frames whose direction changes are copied, so only their threads re-flow. + let turn: Vec = live.into_iter().filter(|id| text_of(doc, *id).is_some_and(|t| t.vertical != vertical)).collect(); + for id in turn { + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.vertical = vertical; + refresh_bounds(t); + } + } + } + reflow(&before, doc); +} + /// Mark the frames of each thread whose first paragraph continues from the frame before /// ([`TextObject::first_para_continues`]), without re-flowing the story: for a document restored /// from a file as it was saved. diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 71d175b3ac..1ead2e823c 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -1090,6 +1090,177 @@ fn a_thread_saved_with_differing_frames_opens_with_the_first_frames_setting() { } } +/// The writing direction of each of the frames `ids` (true: vertical). +fn vertical(s: &Session, ids: [u64; N]) -> [bool; N] { + ids.map(|id| { + let Some(t) = text_of(&s.doc().unwrap().doc, NodeId(id)) else { panic!("not area type") }; + t.vertical + }) +} + +/// Whether each frame of the thread `ids` holds the part of the story that its layout, in its +/// writing direction, has room for: the parts that [`vectorcraft_text::thread::distribute`] +/// gives the frames as they are now. +fn flows_as_laid_out(s: &Session, ids: &[u64]) -> bool { + let d = &s.doc().unwrap().doc; + let frames: Vec<&TextObject> = ids.iter().map(|id| text_of(d, NodeId(*id)).unwrap()).collect(); + let story = vectorcraft_text::thread::story(&frames); + let paras = vectorcraft_text::thread::story_paras(&frames, &[]); + let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &frames, &story, ¶s); + let texts = |runs: &[TextRun]| runs.iter().map(|r| r.text.as_str()).collect::(); + parts.iter().zip(&frames).all(|(part, f)| texts(&part.runs) == f.plain_text()) +} + +/// Type Orientation is a setting of the whole thread: Type › Type Orientation in any frame sets +/// it in every frame of the thread, in one undo step, and the story flows through the frames in +/// that direction. Typing keeps it, and frames taken out of the thread keep it. +#[test] +fn type_orientation_is_set_for_every_frame_of_a_thread() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let r = s.execute("type.orientation.vertical", &json!({})).unwrap(); + assert_eq!(r, json!({"vertical": true, "ids": [a, b]})); + assert_eq!(vertical(&s, [a, b]), [true, true], "the second frame is vertical too"); + assert!(flows_as_laid_out(&s, &[a, b])); + assert_eq!(format!("{}{}", text(&s, a), text(&s, b)), TEXT.repeat(4)); + // Set back from the second frame, both are horizontal, and one undo makes both vertical. + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + assert_eq!(s.execute("type.orientation.horizontal", &json!({})).unwrap()["ids"], json!([b, a])); + assert_eq!(vertical(&s, [a, b]), [false, false]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(vertical(&s, [a, b]), [true, true]); + // Typing in the first frame re-flows the story and keeps the direction. + s.execute("text.editRange", &json!({"id": a, "start": 0, "end": 0, "insert": "NEW "})).unwrap(); + assert_eq!(vertical(&s, [a, b]), [true, true]); + assert!(flows_as_laid_out(&s, &[a, b])); + // Any edit that sets one frame sets the thread. + s.edit("Set", |d, _| { + let Some(NodeKind::Text(t)) = d.node_mut(NodeId(b)).map(|n| &mut n.kind) else { panic!("not text") }; + t.vertical = false; + refresh_bounds(t); + Ok(()) + }) + .unwrap(); + assert_eq!(vertical(&s, [a, b]), [false, false]); + assert!(flows_as_laid_out(&s, &[a, b])); + s.execute("edit.undo", &json!({})).unwrap(); + // Released or unthreaded, each frame keeps it. + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("text.thread.releaseSelection", &json!({})).unwrap(); + assert_eq!(vertical(&s, [a, b]), [true, true]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("text.thread.remove", &json!({})).unwrap(); + assert!(threads(&s).is_empty()); + assert_eq!(vertical(&s, [a, b]), [true, true]); +} + +/// Threading type gives the joined thread the writing direction of its first frame, and the +/// story flows through every frame in that direction. +#[test] +fn a_thread_takes_its_first_frames_type_orientation() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let area = json!({"width": 150, "height": 60}); + let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": TEXT.repeat(4), "area": area, "vertical": true})).unwrap()); + let b = new_id(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 60, "height": 200})).unwrap()); + let c = new_id(s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 150, "height": 200})).unwrap()); + s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + assert_eq!(vertical(&s, [a, b, c]), [true; 3]); + assert!(!text(&s, b).is_empty() && !text(&s, c).is_empty()); + assert!(flows_as_laid_out(&s, &[a, b, c]), "the middle frame holds what fits it as vertical type"); + // From `c`'s out port into horizontal area type `d`: `d` joins the thread and becomes vertical. + let d = new_id(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Own text.", "area": {"width": 150, "height": 190}})).unwrap()); + s.execute("text.thread.add", &json!({"from": c, "to": d})).unwrap(); + assert_eq!(threads(&s), [[a, b, c, d]]); + assert_eq!(vertical(&s, [a, b, c, d]), [true; 4]); + assert!(flows_as_laid_out(&s, &[a, b, c, d])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(vertical(&s, [d]), [false], "undo gives `d` its own direction back"); +} + +/// A file saved with the frames of one thread in different writing directions opens with the +/// first frame's direction in every frame, and the story flows through them in it: a native +/// file, and an EPS file restored from the document it carries. +#[test] +fn a_thread_saved_with_differing_orientations_opens_with_the_first_frames() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + for (first, name) in [(true, "old.vectorcraft"), (false, "old.vectorcraft"), (true, "old.eps"), (false, "old.eps")] { + for (id, on) in [(a, first), (b, !first)] { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) else { panic!("not text") }; + t.vertical = on; + refresh_bounds(t); + } + let bytes = if name.ends_with(".eps") { + let r = s.execute("document.exportEps", &json!({})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() + } else { + vectorcraft_format::save(&s.doc().unwrap().doc, false) + }; + let r = s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert_eq!(r["restored"], name.ends_with(".eps"), "{r}"); + assert_eq!(threads(&s), [[a, b]], "{name}"); + assert_eq!(vertical(&s, [a, b]), [first, first], "{name}, first frame vertical: {first}"); + assert!(flows_as_laid_out(&s, &[a, b]), "{name}, first frame vertical: {first}"); + assert_eq!(format!("{}{}", text(&s, a), text(&s, b)), TEXT.repeat(4), "{name}"); + } +} + +/// A thread restored from an EPS file whose frames share one writing direction keeps its text +/// in its frames as saved. +#[test] +fn a_restored_thread_in_one_direction_keeps_its_text_as_saved() { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + let story = TEXT.repeat(4); + for (id, part) in [(a, &story[..10]), (b, &story[10..])] { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) else { panic!("not text") }; + t.runs = vec![TextRun::new(part.to_string(), t.runs[0].style.clone())]; + refresh_bounds(t); + } + let r = s.execute("document.exportEps", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let r = s.execute("document.open", &json!({"name": "saved.eps", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert_eq!(r["restored"], true, "{r}"); + assert_eq!((text(&s, a), text(&s, b)), (story[..10].to_string(), story[10..].to_string())); +} + +/// A threaded frame restored from a file with Auto Size on keeps its size when it turns from +/// vertical to horizontal: as the file opens, when the first frame is horizontal, and with Type +/// Orientation, when the whole thread is vertical. +#[test] +fn a_restored_threaded_frame_with_auto_size_keeps_its_size_when_it_turns_horizontal() { + for first_vertical in [false, true] { + let (mut s, a, b) = setup(); + s.execute("text.thread.create", &json!({})).unwrap(); + for (id, on) in [(a, first_vertical), (b, true)] { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) else { panic!("not text") }; + t.vertical = on; + if id == b { + t.area.fit = vectorcraft_doc::AreaFit::AutoHeight; + } + refresh_bounds(t); + } + let saved = frame_box(&s, b); + let r = s.execute("document.exportEps", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let r = s.execute("document.open", &json!({"name": "saved.eps", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert_eq!(r["restored"], true, "{r}"); + if first_vertical { + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + s.execute("type.orientation.horizontal", &json!({})).unwrap(); + } + assert_eq!(vertical(&s, [a, b]), [false, false], "first frame vertical: {first_vertical}"); + assert_eq!(frame_box(&s, b), saved, "first frame vertical: {first_vertical}"); + assert!(flows_as_laid_out(&s, &[a, b]), "first frame vertical: {first_vertical}"); + } +} + /// One count runs through a thread: the second frame's numbered paragraphs go on from the /// first frame's, also after an edit, a save and a reopen. A pasted or duplicated copy of a /// frame, a frame converted to point type, the frames of a thread that Remove Threading breaks diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 4ad5776517..b349ef894e 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -16,15 +16,21 @@ use super::{ pub fn specs() -> Vec { vec![ - cmd!("type.orientation.vertical", "Vertical", ["Type", "Orientation"], None, "{ids?|id?} set vertical writing", has_selection, |s, p| { - orientation(s, p, true) - }), + cmd!( + "type.orientation.vertical", + "Vertical", + ["Type", "Orientation"], + None, + "{ids?|id?} set vertical writing for the selected type and every frame of its threads → {vertical, ids}", + has_selection, + |s, p| orientation(s, p, true) + ), cmd!( "type.orientation.horizontal", "Horizontal", ["Type", "Orientation"], None, - "{ids?|id?} set horizontal writing", + "{ids?|id?} set horizontal writing for the selected type and every frame of its threads → {vertical, ids}", has_selection, |s, p| orientation(s, p, false) ), @@ -139,8 +145,10 @@ pub fn specs() -> Vec { ] } +/// Type › Type Orientation: set vertical or horizontal writing on every selected text object and +/// every frame of their threads, in one undo step. fn orientation(s: &mut Session, p: &Value, vertical: bool) -> Result { - let ids = text_targets(s, p, "Text Orientation")?; + let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Text Orientation")?); s.edit("Text Orientation", |d, _| { for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { diff --git a/docs/mcp.md b/docs/mcp.md index 8ad9232d89..f7b5d261ef 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -481,6 +481,12 @@ for horizontal writing. This is the same option as `text.create` / `text.createI on the OpenType `vert` feature, so a font's vertical glyph alternates are used; it does not change the engine's CJK composition. +`type.orientation.vertical` and `type.orientation.horizontal` (Type › Type Orientation) switch existing type objects +(the selection, or `ids`) and reply `{vertical, ids}`. The writing direction is a setting of the whole thread: the +commands set every frame of a selected frame's thread, and `ids` lists them all. Threading frames gives the thread its +first frame's direction, frames taken out of a thread keep theirs, and a file whose frames of one thread differ opens +with the first frame's direction in all of them. + For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options: {"advanced": {"outlineText": true}}`; its default is false (live text). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4d22add2fd..7ec7277d26 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1035,6 +1035,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. + The frames of threaded text share one writing direction: Type › Type Orientation (`type.orientation.vertical`, `type.orientation.horizontal`) in one frame sets every frame, threading frames gives the thread its first frame's direction, frames taken out of a thread keep theirs, and the story flows through every frame in the thread's direction. Type › Optical Margin Alignment (`type.opticalMarginAlignment`) hangs the punctuation and letter edges at the ends of a type object's lines outside its margins: at the left of left-aligned lines, at the right of right-aligned lines, and at both ends of centered and justified lines, in point and area type of left-to-right paragraphs. Quotation marks, hyphens, full stops and commas hang wholly; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their width. It is off by default and saved with the type object. Justification's Glyph Scaling leaves the glyphs that hang at their width, so they hang exactly their share, and Standard burasagari counts what hangs at a line's start as room before hanging a comma; `crates/text/src/tests/hang.rs` checks whole paragraphs with both composers, ragged, centred and justified, with Line-end Punctuation Half Width and bidirectional lines. Optical Margin Alignment and Roman Hanging Punctuation hang right-to-left paragraphs of point and area type, and type on a path whose first paragraph runs right to left, too. Auto aligns a right-to-left line at its right, or at the end bracket of a path, so it hangs there. A right-to-left line is read from right to left: where it hangs at its left margin, `."` ending it hangs both glyphs. The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, the Every-line Composer, Roman Hanging Punctuation off, no kashidas and no tab stops, as one undo step. diff --git a/docs/type-parity.md b/docs/type-parity.md index 010c74aa59..69ea7c3736 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -21,6 +21,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Mouse wheel over the closed font-family field | done | #5253: Character, Properties and Control step selected text through the family list using saved font filters (excluding search text), one undo step per notch; the style is matched and the list stops at either end. Escape and leaving the field keep the change. Order, bounds and Undo grouping are VectorCraft's choices; scores unchanged. | | Soft return (forced line break, Shift+Enter) | done | Shift+Enter inserts a soft return (U+2028), breaking the line without starting a new paragraph; paragraph spacing (space before/after) and first-line indents apply only at paragraph ends; continuation lines in lists do not repeat the marker; soft return lines in justified text do not spread (#2754) | | Native font-family labels | partial | With Show Font Names in English off, localized legacy names are used when typographic names contain no native label (#2208); loaded-font and catalog-only regressions. Choosing among multiple native languages is unchanged. | +| Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802); `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands; Type › Type Orientation sets every frame of a thread, and a thread's frames share one writing direction | | Point, area and type-on-a-path type; vertical variants | done / partial | vertical point, area and path type have initial support; fullwidth `!` / `?` keep the nominal glyph upright when no vertical alternate exists (Unicode Tu); in a non-rectangular area a word too wide for the top lines moves down to the first line that holds it (#1615); Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802), and Cmd+Enter (Ctrl+Enter on Windows and Linux) does the same unless a command is bound to it; `text.create` and `text.createInPath` take `justify` (#1752); MCP `add_text` forwards `vertical` to both commands; the Type and Vertical Type tools make area type when a closed path's outline is clicked and type on a path when an open one is, with pointers that say which, as the public help describes ([Create text](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html), [Create type on a path](https://web.archive.org/web/20220127090635/https://helpx.adobe.com/illustrator/using/creating-type-path.html)) | | Area Type Options (rows, columns, inset, first baseline, Text Flow by rows or by columns, Auto Size, Shrink Text to Fit) | done | Text Flow fills the cells down each column first (By Columns, the default, as files from before it open) or across each row first (By Rows), in the dialog and `text.areaOptions {flow}` (#4978); the commands that make or restyle type say when it does not fit its frame; MCP `add_text` takes Auto Size and Shrink Text to Fit (#1471) | | Threaded text, Fit Headline, Text Wrap | done | Fit Headline sees wrapping in a frame one line tall (#1444); a thread holds area type and type on a path in any mix, as Illustrator links type in an area or along a path ([help](https://helpx.adobe.com/illustrator/using/manage-text-area.html)) | From 3f4d1a251236bcd048d30197f245ab3bcc75bd22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:46:20 +0700 Subject: [PATCH 15/26] Render: the decoded-image cache can grow to a quarter of installed memory on every desktop OS Squashed from #5034 onto main. --- crates/render/src/images.rs | 267 ++++++++++++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 255 insertions(+), 13 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index dbdbf00669..93adbf245f 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -21,8 +21,9 @@ use vello_cpu::color::PremulRgba8; use crate::ink::Ink; -/// Largest default budget of the shared image store, in bytes; less on machines with under 8 GiB -/// of memory (an eighth of it). [`set_image_cache_budget`] changes it. +/// Default budget of the shared image store, in bytes, where the installed memory can't be read. +/// Elsewhere the default is a quarter of the installed memory, and on the web it is 256 MiB. +/// [`set_image_cache_budget`] changes it. pub const IMAGE_CACHE_MAX: usize = 1 << 30; /// The default budget on the web (a tab's memory is tight). @@ -33,14 +34,21 @@ fn default_budget() -> usize { #[cfg(not(target_arch = "wasm32"))] fn default_budget() -> usize { - physical_memory().map_or(IMAGE_CACHE_MAX, budget_for) + budget_for_reading(physical_memory()) } -/// The default budget on a machine with `memory` bytes installed: an eighth of it, at most -/// [`IMAGE_CACHE_MAX`]. +/// The default budget for a reading of the installed memory: [`IMAGE_CACHE_MAX`] when `memory` is +/// `None` or 0, otherwise [`budget_for`] it. +#[cfg(not(target_arch = "wasm32"))] +fn budget_for_reading(memory: Option) -> usize { + memory.filter(|&m| m > 0).map_or(IMAGE_CACHE_MAX, budget_for) +} + +/// The default budget on a machine with `memory` bytes installed: a quarter of it, and at most a +/// quarter of the address space (on 32-bit builds). #[cfg(not(target_arch = "wasm32"))] fn budget_for(memory: u64) -> usize { - usize::try_from(memory / 8).unwrap_or(usize::MAX).min(IMAGE_CACHE_MAX) + usize::try_from(memory / 4).unwrap_or(usize::MAX).min(usize::MAX / 4) } /// Installed memory in bytes, `None` where it isn't known (the web, other systems). Other crates @@ -52,13 +60,116 @@ pub fn installed_memory() -> Option { physical_memory() } -/// Installed memory in bytes (`MemTotal` in `/proc/meminfo`). +/// Installed memory in bytes (`MemTotal` in `/proc/meminfo`), or the memory limit of the process's +/// cgroups where that is lower. #[cfg(target_os = "linux")] fn physical_memory() -> Option { let info = std::fs::read_to_string("/proc/meminfo").ok()?; let line = info.lines().find(|l| l.starts_with("MemTotal:"))?; let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; - kib.checked_mul(1024) + let total = kib.checked_mul(1024)?; + let cgroups = std::fs::read_to_string("/proc/self/cgroup").unwrap_or_default(); + let mounts = std::fs::read_to_string("/proc/self/mountinfo").unwrap_or_default(); + Some(cgroup_limit(&cgroups, &mounts, |path| std::fs::read_to_string(path).ok()).map_or(total, |limit| limit.min(total))) +} + +/// The lowest memory limit of the cgroups listed in `/proc/self/cgroup` (`cgroups`) and of their +/// ancestors within the mounted cgroup hierarchy: `memory.max` under cgroup v2 and +/// `memory.limit_in_bytes` under cgroup v1. Each cgroup is looked up under the mount in +/// `/proc/self/mountinfo` (`mounts`) whose root holds it, or under `/sys/fs/cgroup` (v2) or +/// `/sys/fs/cgroup/memory` (v1) when `mounts` lists no mount of its hierarchy; a cgroup that no +/// listed mount holds sets no limit. A mount whose root lies above the cgroup namespace's root +/// (`/..`) gives the limit of its mount point alone. `read` reads a file; a file that can't be read, or that holds +/// `max`, sets no limit. +#[cfg(any(target_os = "linux", test))] +fn cgroup_limit(cgroups: &str, mounts: &str, read: impl Fn(&str) -> Option) -> Option { + let mut lowest: Option = None; + for line in cgroups.lines() { + let mut fields = line.splitn(3, ':'); + let (Some(_), Some(controllers), Some(path)) = (fields.next(), fields.next(), fields.next()) else { + continue; + }; + let v2 = controllers.is_empty(); + if !v2 && !controllers.split(',').any(|c| c == "memory") { + continue; + } + let file = if v2 { "memory.max" } else { "memory.limit_in_bytes" }; + let mounted = cgroup_mounts(mounts, v2); + // Every mount that holds the cgroup shows the same hierarchy; each may show more ancestors. + let holding: Vec<(String, String)> = if mounted.is_empty() { + vec![(path.to_owned(), (if v2 { "/sys/fs/cgroup" } else { "/sys/fs/cgroup/memory" }).to_owned())] + } else { + mounted + .into_iter() + .filter_map(|(root, point)| { + let root = root.trim_end_matches('/'); + // A root of `..` steps is an ancestor of the cgroup namespace's root, so of every + // cgroup listed: only the mount point's own limit can be read. + if !root.is_empty() && root.split('/').skip(1).all(|step| step == "..") { + return Some((String::new(), point)); + } + let rest = path.strip_prefix(root).filter(|rest| rest.is_empty() || rest.starts_with('/'))?; + Some((rest.to_owned(), point)) + }) + .collect() + }; + for (relative, mount_point) in &holding { + let root = mount_point.trim_end_matches('/'); + let mut dir = relative.trim_end_matches('/'); + loop { + if let Some(limit) = read(&format!("{root}{dir}/{file}")).and_then(|s| s.trim().parse::().ok()) { + lowest = Some(lowest.map_or(limit, |l| l.min(limit))); + } + match dir.rsplit_once('/') { + Some((parent, _)) => dir = parent, + None => break, + } + } + } + } + lowest +} + +/// The root and the mount point of each cgroup v2 mount (`v2`) or cgroup v1 mount with the +/// `memory` controller in `/proc/self/mountinfo` (`mounts`), with their octal escapes decoded. +#[cfg(any(target_os = "linux", test))] +fn cgroup_mounts(mounts: &str, v2: bool) -> Vec<(String, String)> { + mounts + .lines() + .filter_map(|line| { + let (before, after) = line.split_once(" - ")?; + let mut fields = before.split_whitespace().skip(3); + let (root, point) = (fields.next()?, fields.next()?); + let mut after = after.split_whitespace(); + let (fs, _, options) = (after.next()?, after.next()?, after.next().unwrap_or("")); + let found = if v2 { fs == "cgroup2" } else { fs == "cgroup" && options.split(',').any(|o| o == "memory") }; + found.then(|| (mountinfo_unescape(root), mountinfo_unescape(point))) + }) + .collect() +} + +/// A path field of `/proc/self/mountinfo` with its octal escapes (`\040` for a space) decoded. +#[cfg(any(target_os = "linux", test))] +fn mountinfo_unescape(field: &str) -> String { + let mut bytes = Vec::with_capacity(field.len()); + let mut rest = field.as_bytes(); + while let Some((&b, tail)) = rest.split_first() { + let code = match tail { + [a @ b'0'..=b'3', c @ b'0'..=b'7', d @ b'0'..=b'7', ..] if b == b'\\' => Some(((a - b'0') << 6) | ((c - b'0') << 3) | (d - b'0')), + _ => None, + }; + match code { + Some(code) => { + bytes.push(code); + rest = tail.get(3..).unwrap_or_default(); + } + None => { + bytes.push(b); + rest = tail; + } + } + } + String::from_utf8_lossy(&bytes).into_owned() } /// Installed memory in bytes (`GlobalMemoryStatusEx`). @@ -524,18 +635,148 @@ mod tests { drop(held); } + #[test] + #[cfg(target_pointer_width = "64")] + fn default_budget_is_a_quarter_of_installed_memory() { + assert_eq!(budget_for(16 << 30), 4 << 30); + assert_eq!(budget_for(64 << 30), 16 << 30, "no fixed ceiling"); + assert_eq!(budget_for(2 << 30), 512 << 20); + } + + #[test] + #[cfg(target_pointer_width = "64")] + fn budget_follows_the_memory_reading() { + assert_eq!(budget_for_reading(Some(2 << 30)), 512 << 20); + assert_eq!(budget_for_reading(Some(8 << 30)), 2 << 30); + assert_eq!(budget_for_reading(Some(64 << 30)), 16 << 30); + assert_eq!(budget_for_reading(None), IMAGE_CACHE_MAX, "memory that can't be read"); + assert_eq!(budget_for_reading(Some(0)), IMAGE_CACHE_MAX, "memory that reads as 0"); + } + #[test] #[cfg(not(target_arch = "wasm32"))] - fn default_budget_is_an_eighth_of_installed_memory_at_most_1_gib() { - assert_eq!(budget_for(4 << 30), 512 << 20); - assert_eq!(budget_for(8 << 30), IMAGE_CACHE_MAX); - assert_eq!(budget_for(64 << 30), IMAGE_CACHE_MAX); + fn images_past_the_budget_drop_the_least_recently_used() { + // 16 MiB installed (16 GiB scaled down): a 4 MiB budget, room for four 512 × 512 images. + let mut s = ImageStore::new(budget_for_reading(Some(16 << 20))); + for k in ["a", "b", "c", "d"] { + drop(s.insert(key(k), Arc::new(Pixmap::new(512, 512)))); + } + assert_eq!(s.bytes(), 4 << 20, "four images fill the budget exactly"); + assert!(["a", "b", "c", "d"].iter().all(|k| s.peek(&key(k)).is_some())); + drop(s.insert(key("e"), Arc::new(Pixmap::new(512, 512)))); + assert_eq!(s.bytes(), 4 << 20); + assert!(s.peek(&key("a")).is_none(), "the oldest image is dropped"); + assert!(["b", "c", "d", "e"].iter().all(|k| s.peek(&key(k)).is_some())); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn an_image_larger_than_the_budget_is_kept_only_while_drawn() { + // 16 MiB installed: a 4 MiB budget. A 1,100 × 1,000 image takes 4.2 MiB. + let budget = budget_for_reading(Some(16 << 20)); + let mut s = ImageStore::new(budget); + assert!(!s.keep(key("big"), Arc::new(Pixmap::new(1100, 1000))), "not kept for a later frame"); + assert_eq!(s.bytes(), 0); + drop(s.insert(key("small"), Arc::new(Pixmap::new(512, 512)))); + let drawn = s.insert(key("big"), Arc::new(Pixmap::new(1100, 1000))); + assert!(s.peek(&key("big")).is_some(), "kept while drawn"); + assert!(s.peek(&key("small")).is_none(), "the other image is dropped to make room"); + drop(drawn); + s.set_budget(budget); + assert!(s.peek(&key("big")).is_none(), "dropped once nothing draws it"); + assert_eq!(s.bytes(), 0); } #[test] #[cfg(any(target_os = "linux", windows, target_os = "macos", target_os = "freebsd"))] fn installed_memory_is_read() { - assert!(physical_memory().is_some_and(|m| m >= 256 << 20), "{:?}", physical_memory()); + // A cgroup's limit can be far below the installed memory. + assert!(physical_memory().is_some_and(|m| m > 0), "{:?}", physical_memory()); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn two_images_of_a_tenth_of_memory_each_stay_cached() { + // 16 MiB installed (16 GiB scaled down): two images of 1,600 KiB (640 × 640 pixels) take + // about a fifth of it. + let mut s = ImageStore::new(budget_for(16 << 20)); + drop(s.insert(key("a"), Arc::new(Pixmap::new(640, 640)))); + drop(s.insert(key("b"), Arc::new(Pixmap::new(640, 640)))); + assert!(s.peek(&key("a")).is_some() && s.peek(&key("b")).is_some(), "neither image is decoded again"); + assert_eq!(s.bytes(), 2 * 640 * 640 * 4); + } + + #[test] + fn cgroup_limit_is_the_lowest_limit_of_the_cgroups_and_their_ancestors() { + let files = |list: &'static [(&'static str, &'static str)]| { + move |path: &str| list.iter().find(|(p, _)| *p == path).map(|(_, text)| (*text).to_owned()) + }; + let v2 = files(&[("/sys/fs/cgroup/user.slice/memory.max", "2147483648\n"), ("/sys/fs/cgroup/user.slice/app.scope/memory.max", "max\n")]); + assert_eq!(cgroup_limit("0::/user.slice/app.scope\n", "", v2), Some(2 << 30), "the parent's limit applies"); + let v1 = files(&[("/sys/fs/cgroup/memory/memory.limit_in_bytes", "1073741824\n")]); + let v1_mounts = "30 25 0:26 / /sys/fs/cgroup/cpu rw - cgroup cgroup rw,cpu,cpuacct\n\ + 31 25 0:27 /docker/1 /sys/fs/cgroup/memory rw,nosuid master:9 - cgroup cgroup rw,memory\n"; + let cgroups = "4:cpu,cpuacct:/docker/1\n5:memory:/docker/1\n"; + assert_eq!(cgroup_limit(cgroups, v1_mounts, v1), Some(1 << 30), "a container's own mount"); + assert_eq!(cgroup_limit("0::/\n", "", files(&[("/sys/fs/cgroup/memory.max", "max\n")])), None, "no limit"); + assert_eq!(cgroup_limit("", "", files(&[])), None); + } + + #[test] + fn cgroup_limit_reads_a_subtree_mount_relative_to_its_root() { + let mounts = "25 1 0:22 / /proc rw - proc proc rw\n\ + 40 25 0:30 /docker/id /sys/fs/cgroup rw,nosuid - cgroup2 cgroup2 rw,nsdelegate\n"; + let files = [("/sys/fs/cgroup/worker/memory.max", "536870912\n"), ("/sys/fs/cgroup/memory.max", "4294967296\n")]; + let read = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, text)| (*text).to_owned()); + assert_eq!(cgroup_limit("0::/docker/id/worker\n", mounts, read), Some(512 << 20), "the worker's own limit"); + assert_eq!(cgroup_limit("0::/elsewhere\n", mounts, read), None, "no mount holds the cgroup"); + } + + #[test] + fn cgroup_limit_reads_the_mount_that_holds_the_cgroup() { + let mounts = "40 25 0:30 /other /mnt/other rw - cgroup2 cgroup2 rw\n\ + 41 25 0:30 /docker/id /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n"; + let files = [("/mnt/other/memory.max", "1048576\n"), ("/sys/fs/cgroup/memory.max", "268435456\n")]; + let read = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, text)| (*text).to_owned()); + assert_eq!(cgroup_limit("0::/docker/id\n", mounts, read), Some(256 << 20), "the unrelated subtree's limit is not read"); + let both = "40 25 0:30 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n\ + 41 25 0:30 /parent/child /mnt/child rw - cgroup2 cgroup2 rw\n"; + let files = [("/mnt/child/memory.max", "max\n"), ("/sys/fs/cgroup/parent/memory.max", "1073741824\n")]; + let read = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, text)| (*text).to_owned()); + assert_eq!(cgroup_limit("0::/parent/child\n", both, read), Some(1 << 30), "the ancestor that only the full mount shows"); + } + + #[test] + fn cgroup_limit_reads_a_mount_above_the_namespace_root() { + let mounts = "40 25 0:30 /.. /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n"; + let files = [("/sys/fs/cgroup/memory.max", "1073741824\n"), ("/sys/fs/cgroup/worker/memory.max", "4096\n")]; + let read = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, text)| (*text).to_owned()); + assert_eq!(cgroup_limit("0::/\n", mounts, read), Some(1 << 30), "the namespace root's ancestor"); + assert_eq!(cgroup_limit("0::/worker\n", mounts, read), Some(1 << 30), "the cgroup's directory is hidden"); + let v1 = "31 25 0:27 /../.. /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n"; + let files = [("/sys/fs/cgroup/memory/memory.limit_in_bytes", "536870912\n")]; + let read = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, text)| (*text).to_owned()); + assert_eq!(cgroup_limit("5:memory:/\n", v1, read), Some(512 << 20)); + let sibling = "40 25 0:30 /../other /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n"; + let files = [("/sys/fs/cgroup/memory.max", "1048576\n")]; + let read = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, text)| (*text).to_owned()); + assert_eq!(cgroup_limit("0::/\n", sibling, read), None, "a sibling of the namespace root is not an ancestor"); + } + + #[test] + fn cgroup_mounts_lists_the_hierarchy_of_the_memory_limit() { + let mounts = "30 25 0:26 / /sys/fs/cgroup/cpu rw - cgroup cgroup rw,cpu\n\ + 31 25 0:27 /a\\040b /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n\ + 32 25 0:28 / /sys/fs/cgroup/unified rw - cgroup2 cgroup2 rw\n"; + assert_eq!(cgroup_mounts(mounts, false), [("/a b".to_owned(), "/sys/fs/cgroup/memory".to_owned())]); + assert_eq!(cgroup_mounts(mounts, true), [("/".to_owned(), "/sys/fs/cgroup/unified".to_owned())]); + assert!(cgroup_mounts("", true).is_empty()); + } + + #[test] + fn mountinfo_paths_have_their_escapes_decoded() { + assert_eq!(mountinfo_unescape(r"/a\040b\011c\012d\134e"), "/a b\tc\nd\\e"); + assert_eq!(mountinfo_unescape(r"/plain\9x\04"), r"/plain\9x\04", "not an escape"); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7ec7277d26..051d300098 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1382,6 +1382,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Hard-edge rendering, including the internal hard-edge frame of Art Optimized supersampled raster exports, draws a knockout element with one opaque solid fill once instead of erasing and adding it through separate layers. Analytical antialiasing keeps the existing compositor and rounding. Synthetic path/compound-hole tests compare exact pixels against the general knockout path across precision, supersampling, translucent parent groups and backdrop blending; translucent fills retain their knockout behavior. An image whose pixels can't be decoded, such as a PNG cut short or an image over the 2 GB decoding allowance as RGBA that can't be drawn at reduced size, is tried once: the renderer notes it and does not try to decode it again on later frames. An image refused only because the images being drawn leave no room for it is tried again on the next render. On the canvas such an image draws as a light gray box crossed from corner to corner, and the status bar says once for each image that it couldn't be decoded; exports leave it out and report it as before. A PNG, JPEG, GIF or WebP image that takes more than 2 GiB as RGBA (512 MiB in the web app) draws in the canvas and in raster exports at the largest size within that allowance, instead of as that crossed box on the canvas and not at all in exports. Each pixel of the result is the mean of the image's pixels it covers, and the document keeps the whole file. A PNG that isn't interlaced is read a row at a time, and other images are read whole when their decoded samples fit in the allowance. A 16-bit PNG that isn't interlaced, whose decoded samples take more than the allowance and whose RGBA fits in it, draws at its own size, read a row at a time. An image of more pixels than the allowance has bytes (on the desktop, 46,341 × 46,341 is more) still draws as the crossed box, and so does one whose decoded samples take more than the allowance, other than a PNG that isn't interlaced. Open, Place and the Links panel say "an image of W × H pixels is shown at reduced size", and say "too large to draw" of an image that is not drawn at reduced size. + The renderers keep the decoded images they share within a quarter of the installed memory on Windows, macOS, Linux and FreeBSD (on Linux, of the process's cgroup memory limit where that is lower, and in a 32-bit build at most a quarter of the address space), within 1 GiB where the installed memory can't be read, and within 256 MiB in the web build; while the decoded images add up to less than that budget, they are not decoded again when the view changes. With `--deep`, each memory row of `vectorcraft-cli perf` also gives the peak so far: the peak working set on Windows and the peak resident memory (`VmHWM`) on Linux. A new last row gives the memory after the SVG export and the save → open → save at the end of the run. The renderer composes the two ink planes of a CMYK document that shows transparency into screen colors on up to as many threads as it rasterizes with, instead of on one. At 2880 × 1800 on 8 threads, a page of 300 shapes at 20% to 90% opacity takes 30 ms a frame instead of 55 ms, and 50,000 paths with one at 99% opacity take 258 ms instead of 361 ms (`vectorcraft-cli bench`), with the same pixels. With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. From c1164f271fc3fce6271c217e8dda7dc2987fad86 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 27 Oct 2026 19:38:51 -0700 Subject: [PATCH 16/26] Type: Start Lists From Typed Markers turns typed list detection off Preferences > Type gets Start Lists From Typed Markers (`typedLists`, on by default). With it off, a list marker and a space typed with the Type tool at the start of a paragraph (`1. `, `1) `, `A. `, `A) `, `* `, `# `, `> `, `+ `) stay as text and start no list. `text.startList`, `text.setFormat {list}` and the Bullets and Numbered List buttons work as before. The preference reaches the Type tool through `ToolContext::typed_lists`. The label has a row in every catalog. --- crates/engine/src/cmd/prefscmds.rs | 1 + crates/engine/src/prefs.rs | 4 +++ crates/engine/src/tests/textedit.rs | 45 +++++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/context.rs | 3 ++ crates/tools/src/lib.rs | 1 + crates/tools/src/text.rs | 4 +++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 6 +++- 32 files changed, 88 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index ad52c808ab..de1b657557 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -208,6 +208,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("highlightAlternateGlyphs", "Type", "Options", "Highlight Alternate Glyphs", bool), p!("highlightSubstitutedFonts", "Type", "Options", "Highlight Substituted Fonts", bool), p!("placeholderText", "Type", "Options", "Fill New Type Objects With Placeholder Text", bool), + p!("typedLists", "Type", "Options", "Start Lists From Typed Markers", bool), p!("fontsFolder", "Type", "Options", "Additional Fonts Folder", text), // Units p!("unitsGeneral", "Units", "", "General", choice(UNITS)), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 920ef3d1c5..1e51475828 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -97,6 +97,9 @@ pub struct Prefs { /// font is highlighted, in every document (on by default). pub highlight_substituted_fonts: bool, pub placeholder_text: bool, + /// Type › Start Lists From Typed Markers: a list marker and a space typed at the start of a + /// paragraph start a list (on by default). Off, they stay as typed text. + pub typed_lists: bool, // Units pub units_general: String, pub units_stroke: String, @@ -402,6 +405,7 @@ impl Default for Prefs { highlight_alternate_glyphs: false, highlight_substituted_fonts: true, placeholder_text: true, + typed_lists: true, units_general: s("points"), units_stroke: s("points"), units_type: s("points"), diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index ed3e2eac39..bb1ac80a08 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1132,6 +1132,51 @@ fn the_caret_follows_undo_and_redo_of_a_typed_list() { } } +/// Type › Start Lists From Typed Markers off: a list marker and a space typed at the start of a +/// paragraph stay as text and start no list; `text.startList` still starts one. +#[test] +fn typed_lists_off_leaves_typed_markers_as_text() { + let v = ViewInfo::default(); + for typed in ["1.", "1)", "A.", "A)", "*", "#", ">", "+"] { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "typedLists", "value": false})).unwrap(); + s.select_tool("type", v).unwrap(); + click(&mut s, 200.0, 200.0); + let id = s.doc().unwrap().selection.objects[0]; + for c in typed.chars().chain(" a".chars()) { + s.tool_text(&c.to_string(), v).unwrap(); + } + let t = obj(&s, id); + assert_eq!((t.plain_text(), t.para_at(0).list), (format!("{typed} a"), None), "{typed}"); + assert!(!undo_labels(&s).iter().any(|l| l == "Bullets and Numbering"), "{typed}"); + } + let mut s = session(); + s.execute("prefs.set", &json!({"key": "typedLists", "value": false})).unwrap(); + let id = text(&mut s, "1. a"); + let r = s.execute("text.startList", &json!({"id": id.0, "at": 3})).unwrap(); + assert_eq!(r["started"], true); + assert_eq!(obj(&s, id).plain_text(), "a"); + assert!(obj(&s, id).para_at(0).list.is_some()); +} + +/// `typedLists` is a Type preference, on by default: `prefs.list` lists it as a bool, and +/// `prefs.reset` of the Type category turns it back on. +#[test] +fn typed_lists_is_a_type_preference_on_by_default() { + let mut s = Session::new(); + assert!(s.prefs.typed_lists); + let l = s.execute("prefs.list", &json!({})).unwrap(); + let row = l.as_array().unwrap().iter().find(|e| e["key"] == "typedLists").unwrap().clone(); + assert_eq!( + (&row["category"], &row["kind"], &row["label"], &row["value"]), + (&json!("Type"), &json!("bool"), &json!("Start Lists From Typed Markers"), &json!(true)) + ); + s.execute("prefs.set", &json!({"key": "typedLists", "value": false})).unwrap(); + assert!(!s.prefs.typed_lists); + s.execute("prefs.reset", &json!({"category": "Type"})).unwrap(); + assert!(s.prefs.typed_lists); +} + /// The same characters later in a paragraph, without the space, typed in one piece with the space /// (a paste), or at the start of a paragraph that is already in a list start nothing. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 1871722c30..23edf6b568 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -332,6 +332,7 @@ impl Session { pen_rubber_band: self.prefs.pen_rubber_band, curvature_rubber_band: self.prefs.curvature_rubber_band, placeholder_text: self.prefs.placeholder_text, + typed_lists: self.prefs.typed_lists, smart_guide_color: rgb(&self.prefs.smart_guide_color, vectorcraft_tools::guides::MAGENTA), alignment_guides: self.prefs.alignment_guides, anchor_path_labels: self.prefs.anchor_path_labels, diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 835303b449..074756d847 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -223,6 +223,9 @@ pub struct ToolContext<'a> { /// Type → Fill New Type Objects With Placeholder Text: type the Type tools place starts with /// placeholder text, selected. pub placeholder_text: bool, + /// Type → Start Lists From Typed Markers: a list marker and a space typed at the start of a + /// paragraph start a list ([`crate::text::TypeTool`]). + pub typed_lists: bool, /// Smart Guides → Color: the smart guides' lines and labels (RGB). pub smart_guide_color: [u8; 3], /// Smart Guides → Alignment Guides: the lines along the edges and centres the art lines up diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index f77ba9dbfe..2893c06abd 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -525,6 +525,7 @@ pub(crate) mod testutil { pen_rubber_band: true, curvature_rubber_band: true, placeholder_text: false, + typed_lists: true, smart_guide_color: guides::MAGENTA, alignment_guides: true, anchor_path_labels: true, diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index c7a5a1ad4a..9cca37e679 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -521,7 +521,11 @@ impl TypeTool { /// from the start of the caret's paragraph up to it start a list ([`TextObject::typed_list_at`]), /// the typing session ends as one undo step with those characters, and `text.startList` /// removes them and makes the paragraph a list as the next one, so one Undo puts them back. + /// With Type › Start Lists From Typed Markers off, the characters stay as typed. fn start_typed_list(&mut self, cx: &ToolContext) -> Vec { + if !cx.typed_lists { + return vec![]; + } let (Some(id), Some(ty)) = (self.editing, &self.typing) else { return vec![] }; let Some(mut t) = Self::text(cx, id).cloned() else { return vec![] }; // The document does not have the space yet (its preview is applied after this input). diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 92e94aa1e6..3ae7712f6e 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1130,6 +1130,7 @@ font-technology Variable Променливи Live curve fitting Напасване на кривата в реално време Fill Color Цвят на запълване Fill New Type Objects With Placeholder Text Запълване на нови текстови обекти с примесен текст + Start Lists From Typed Markers Започване на списъци от въведени маркери Fill Rule Правило за запълване Fill with Placeholder Text Запълване с примесен текст Fill: Запълване: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2332578971..5fa8b5bd05 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3620,6 +3620,7 @@ theme Appearance Motiv Feet Stopy Files Soubory Fill New Type Objects With Placeholder Text Vyplňovat nové textové objekty zástupným textem + Start Lists From Typed Markers Začínat seznamy z napsaných značek Folder Složka Font Preview Size Velikost náhledu písma Get Preferences Získat předvolby diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 94516cb64e..382df11e60 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3362,6 +3362,7 @@ theme Appearance Udseende Feet Fod Files Filer Fill New Type Objects With Placeholder Text Udfyld nye tekstobjekter med pladsholdertekst + Start Lists From Typed Markers Start lister fra indtastede markører Folder Mappe Font Preview Size Størrelse på skrifttypeforhåndsvisning Get Preferences Hent indstillinger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6dc11392ef..dfa4a3a330 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1145,6 +1145,7 @@ font-technology Variable Variabel Stroke When Editable Kontur, wenn bearbeitbar Fill Color Flächenfarbe Fill New Type Objects With Placeholder Text Neue Textobjekte mit Platzhaltertext füllen + Start Lists From Typed Markers Listen aus getippten Aufzählungszeichen beginnen Fill Rule Füllregel Fill with Placeholder Text Mit Platzhaltertext füllen Fill: Fläche: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 267920a0f5..2aa0a151f8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1103,6 +1103,7 @@ font-technology Variable Μεταβλητές Live curve fitting Προσαρμογή καμπύλης σε πραγματικό χρόνο Fill Color Χρώμα γεμίσματος Fill New Type Objects With Placeholder Text Συμπλήρωση νέων αντικειμένων κειμένου με κείμενο υπόδειξης + Start Lists From Typed Markers Έναρξη λιστών από πληκτρολογημένα σύμβολα Fill Rule Κανόνας γεμίσματος Fill with Placeholder Text Γέμισμα με κείμενο υπόδειξης Fill: Γέμισμα: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 105146217d..1db3e9aabf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1173,6 +1173,7 @@ font-technology Variable Variables Stroke When Editable Trazo si es editable Fill Color Color de relleno Fill New Type Objects With Placeholder Text Rellenar nuevos objetos de texto con texto de muestra + Start Lists From Typed Markers Iniciar listas a partir de marcadores escritos Fill Rule Regla de relleno Fill with Placeholder Text Rellenar con texto de muestra Insert Inline Symbol Insertar símbolo en el texto diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 821935c270..0752a3fbb4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3558,6 +3558,7 @@ theme Appearance Ulkoasu Feet Jalat Files Tiedostot Fill New Type Objects With Placeholder Text Täytä uudet tekstiobjektit paikkamerkkitekstillä + Start Lists From Typed Markers Aloita luettelot kirjoitetuista merkeistä Folder Kansio Font Preview Size Fontin esikatselukoko Get Preferences Hae asetukset diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f7215a99b0..755beef3eb 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1168,6 +1168,7 @@ font-technology Variable Variables Stroke When Editable Contour quand il est modifiable Fill Color Couleur de fond Fill New Type Objects With Placeholder Text Remplir les nouveaux objets texte avec un texte de substitution + Start Lists From Typed Markers Commencer des listes à partir des marqueurs saisis Fill Rule Règle de remplissage Fill with Placeholder Text Remplir avec un texte de substitution Fill: Fond : diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9690969c5f..eae9829b9b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1467,6 +1467,7 @@ digits Malayalam Malajálam Highlight: Kiemelés: Stroke When Editable Körvonal, ha szerkeszthető Fill New Type Objects With Placeholder Text Új szövegobjektumok kitöltése helykitöltő szöveggel + Start Lists From Typed Markers Listák indítása begépelt jelölőkből Fill Rule Kitöltési szabály Fill with Placeholder Text Kitöltés helykitöltő szöveggel Fill: Kitöltés: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 12c1b4c851..433380d539 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3362,6 +3362,7 @@ theme Appearance Tampilan Feet Kaki Files File Fill New Type Objects With Placeholder Text Isi objek teks baru dengan teks placeholder + Start Lists From Typed Markers Mulai daftar dari penanda yang diketik Folder Folder Font Preview Size Ukuran pratinjau font Get Preferences Dapatkan preferensi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 004d41e2c3..46c0bc7e58 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1175,6 +1175,7 @@ font-technology Variable Variabili Stroke When Editable Traccia se modificabile Fill Color Colore riempimento Fill New Type Objects With Placeholder Text Riempi i nuovi oggetti di testo con testo segnaposto + Start Lists From Typed Markers Avvia elenchi dai marcatori digitati Fill Rule Regola di riempimento Fill with Placeholder Text Riempi con testo segnaposto Fill: Riempimento: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 716de0b24f..6df9879ea4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1635,6 +1635,7 @@ digits Malayalam マラヤーラム数字 Files of this standard tag their colours with ICC profiles. この規格のファイルでは、カラーに ICC プロファイルが付けられます。 Fill 塗り Fill New Type Objects With Placeholder Text 新規テキストオブジェクトをダミーテキストで埋める + Start Lists From Typed Markers 入力した記号からリストを開始 Fill Rule 塗りのルール Fill and Stroke 塗りと線 Fill new strokes 新しいストロークに塗りを適用 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e5d0a28c08..b23ea6b0c6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3178,6 +3178,7 @@ theme Appearance იერსახე Feet ფუტები Files ფაილები Fill New Type Objects With Placeholder Text ახალი ტექსტური ობიექტების ჩანაცვლების ტექსტით შევსება + Start Lists From Typed Markers სიების დაწყება აკრეფილი მარკერებიდან Folder საქაღალდე Font Preview Size შრიფტის ნიმუშის ზომა Get Preferences პარამეტრების მიღება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a8f2c0db48..4a026cd0de 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1625,6 +1625,7 @@ digits Malayalam 말라얄람어 Files of this standard tag their colours with ICC profiles. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. Fill 칠 Fill New Type Objects With Placeholder Text 새 문자 개체를 대체 텍스트로 채우기 + Start Lists From Typed Markers 입력한 기호로 목록 시작 Fill Rule 칠 규칙 Fill and Stroke 칠과 선 Fill new strokes 새 선 칠하기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e803314e09..3a0ffaf16f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3376,6 +3376,7 @@ theme Appearance Vormgeving Feet Voet Files Bestanden Fill New Type Objects With Placeholder Text Nieuwe tekstobjecten met plaatshoudertekst vullen + Start Lists From Typed Markers Lijsten starten met getypte opsommingstekens Folder Map Font Preview Size Grootte van lettertypevoorbeelden Get Preferences Voorkeuren ophalen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 591790721f..d858f80817 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3497,6 +3497,7 @@ theme Appearance Wygląd Feet Stopy Files Pliki Fill New Type Objects With Placeholder Text Wypełniaj nowe obiekty tekstowe tekstem zastępczym + Start Lists From Typed Markers Rozpoczynaj listy od wpisanych znaczników Folder Folder Font Preview Size Rozmiar podglądu czcionki Get Preferences Pobierz preferencje diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index cae6a2fd75..49a4edc7c6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1045,6 +1045,7 @@ Fill & Stroke Preenchimento e Traçado Fill Color Cor de Preenchimento Fill New Type Objects With Placeholder Text Preencher Novos Objetos de Texto com Texto de Placeholder + Start Lists From Typed Markers Iniciar Listas a Partir de Marcadores Digitados Fill Rule Regra de Preenchimento Fill and Stroke Preenchimento e Traçado Fill new strokes Preencher novos traçados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3f1b8e702b..e37f1db9db 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1172,6 +1172,7 @@ font-technology Variable Вариативные Stroke When Editable Редактируемая обводка Fill Color Цвет заливки Fill New Type Objects With Placeholder Text Заполнять новые текстовые объекты текстом-заполнителем + Start Lists From Typed Markers Начинать списки с введённых маркеров Fill Rule Правило заливки Fill with Placeholder Text Заполнить текстом-заполнителем Fill: Заливка: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 3362155f01..f0cb484b2f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1138,6 +1138,7 @@ font-technology Variable Variabla Live curve fitting Kurvanpassning medan du ritar Fill Color Fyllnadsfärg Fill New Type Objects With Placeholder Text Fyll nya textobjekt med platshållartext + Start Lists From Typed Markers Starta listor från inskrivna punkttecken Fill Rule Fyllningsregel Fill with Placeholder Text Fyll med platshållartext Fill: Fyllning: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9308d7ea61..73ba123e07 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1127,6 +1127,7 @@ font-technology Variable Değişken Merge only with selection Yalnızca seçimle birleştir Fill Color Dolgu Rengi Fill New Type Objects With Placeholder Text Yeni Yazım Nesnelerini Yer Tutucu Metinle Doldurun + Start Lists From Typed Markers Yazılan İşaretlerden Liste Başlat Fill Rule Doldurma Kuralı Fill with Placeholder Text Yer Tutucu Metinle Doldur Fill: Doldurun: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 55edd38d50..fe0edb479f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1169,6 +1169,7 @@ font-technology Variable Варіативні Stroke When Editable Обведення, яке можна редагувати Fill Color Колір заливки Fill New Type Objects With Placeholder Text Заповнювати нові текстові об’єкти текстом-заповнювачем + Start Lists From Typed Markers Починати списки з введених маркерів Fill Rule Правило заливки Fill with Placeholder Text Заповнити текстом-заповнювачем Fill: Заливка: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e8ea0991f4..a567d484a3 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1345,6 +1345,7 @@ digits Malayalam Malayalam Highlight: Làm nổi bật: Stroke When Editable Nét khi có thể chỉnh sửa Fill New Type Objects With Placeholder Text Tô đối tượng chữ mới bằng văn bản giữ chỗ + Start Lists From Typed Markers Bắt đầu danh sách từ ký hiệu đã gõ Fill Rule Quy tắc tô Fill with Placeholder Text Tô bằng văn bản giữ chỗ Fill: Tô: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4cf9b672fc..be6b5fd2bb 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1114,6 +1114,7 @@ Stroke When Editable 可编辑时的描边 Fill Color 填色 Fill New Type Objects With Placeholder Text 用占位文本填充新文字对象 + Start Lists From Typed Markers 从键入的标记开始列表 Fill Rule 填充规则 Fill with Placeholder Text 用占位文本填充 Insert Inline Symbol 插入行内符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4aee5622d4..fd5d3df2b4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1139,6 +1139,7 @@ font-technology Variable 可變 Highlight: 強調顯示: Stroke When Editable 可編輯時的筆畫 Fill New Type Objects With Placeholder Text 以預留位置文字填滿新文字物件 + Start Lists From Typed Markers 從輸入的標記開始清單 Fill Rule 填色規則 Fill with Placeholder Text 以預留位置文字填滿 Insert Inline Symbol 插入行內符號 diff --git a/docs/mcp.md b/docs/mcp.md index f7b5d261ef..49d1fcef2d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3799,6 +3799,9 @@ Pen's second anchor at (150, 431), in line with the square's centre. - `placeholderText` (on by default): type the Type tools place (`pointer_gesture` with `type`, `areaType`…) starts with placeholder text, selected, so `type_text` replaces it; `text.create` and `text.createInPath` take `placeholder: true`. +- `typedLists` (on by default; Type › Start Lists From Typed Markers): a list marker and a space typed with the Type tool + at the start of a paragraph start a list (see `text.startList`). Off, the Type tool leaves them as typed text; + `text.startList`, `text.setFormat {list}` and the Bullets and Numbered List buttons work as before. - `typeSizeIncrement`, `trackingIncrement`, `baselineShiftIncrement`: what `type.step {attribute: "size" | "leading" | "tracking" | "kerning" | "baselineShift", by?}` steps by, on the text range given, the type objects in `ids`, the Type tool's selected text or the selected type objects. `type.size.increase` / `type.size.decrease` (Cmd+Shift+. and @@ -5757,7 +5760,8 @@ whose left and first-line indents are both 0 gets 18 pt and -18 pt. The tool run the byte after the space, as an undo step of its own after the typing: one Undo puts the characters back as text with no list, and typing goes on after them; Redo removes them again, and typing goes on before the paragraph's text. The same characters later in a paragraph start nothing, and so do list characters that arrive in one piece with the space: a -paste, an IME commit, or `type_text` of a longer string. From a script, `text.startList {id, at?}` (`at` defaults to the end of the text) does +paste, an IME commit, or `type_text` of a longer string. With the `typedLists` preference off (Preferences › Type › +Start Lists From Typed Markers), the Type tool starts no list from typed characters. From a script, `text.startList {id, at?}` (`at` defaults to the end of the text) does the same with the text before `at` and returns `started` and `caret`. When the list starts, `caret` is the byte where the paragraph's text now starts; when the text before `at` starts no list, nothing changes, `started` is false and `caret` is `at`. From 8f833f6a1ef0e561a6d934c760d8a2cb10ca40e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 23:36:30 -0700 Subject: [PATCH 17/26] Tests: Start Lists From Typed Markers on again, and its preferences checkbox - typed_lists_off_leaves_typed_markers_as_text turns the preference back on for each marker and checks that typing it in a new paragraph starts a list with a Bullets and Numbering undo step. - start_lists_from_typed_markers_is_a_saved_type_preference: the Type page shows the checkbox, checked by default; unchecking it turns the preference off in the session and in the saved preferences, and every bundled language translates its label. --- crates/engine/src/tests/textedit.rs | 9 +++++++++ crates/ui-egui/src/prefs_dialog/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index bb1ac80a08..7738e45a4a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1149,6 +1149,15 @@ fn typed_lists_off_leaves_typed_markers_as_text() { let t = obj(&s, id); assert_eq!((t.plain_text(), t.para_at(0).list), (format!("{typed} a"), None), "{typed}"); assert!(!undo_labels(&s).iter().any(|l| l == "Bullets and Numbering"), "{typed}"); + // Turned back on, the same typing in a new paragraph starts a list. + s.execute("prefs.set", &json!({"key": "typedLists", "value": true})).unwrap(); + key(&mut s, ToolKey::Enter, Mods::default()); + for c in typed.chars().chain(" ".chars()) { + s.tool_text(&c.to_string(), v).unwrap(); + } + let t = obj(&s, id); + assert_eq!((t.plain_text(), t.para_at(0).list, t.para_at(1).list.is_some()), (format!("{typed} a\n"), None, true), "on: {typed}"); + assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Bullets and Numbering"), "on: {typed}"); } let mut s = session(); s.execute("prefs.set", &json!({"key": "typedLists", "value": false})).unwrap(); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 9e8ce28045..da1814b35e 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -16,6 +16,27 @@ fn geometric_snapping_is_a_saved_smart_guides_preference() { assert!(a.run("view.snapping", json!({})).is_err()); } +/// Type › Start Lists From Typed Markers is a checkbox in the Type panel, on by default; turning +/// it off is saved, and every bundled language translates its label. +#[test] +fn start_lists_from_typed_markers_is_a_saved_type_preference() { + const LABEL: &str = "Start Lists From Typed Markers"; + let mut a = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert!(a.session.prefs.typed_lists); + open(&mut a, Some("Type")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains(LABEL), "{text}"); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields.get("typedLists"), Some(&json!(true))); + a.ui.dialog.as_mut().unwrap().fields.insert("typedLists".into(), json!(false)); + confirm(&mut a).unwrap(); + assert!(!a.session.prefs.typed_lists); + let saved: Prefs = serde_json::from_value(a.ui.engine_prefs.clone()).unwrap(); + assert!(!saved.typed_lists); + for lang in crate::i18n::Lang::all().filter(|l| l.code() != crate::i18n::Lang::EN.code()) { + assert!(crate::i18n::has(lang, LABEL), "{}", lang.code()); + } +} + /// A resting checkbox must have a visible outline in both states and every brightness. #[test] fn preference_checkboxes_draw_outlines_without_hover() { From 455eb807a63817d0f227cbb35303d460ffeb1591 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 01:37:23 -0700 Subject: [PATCH 18/26] i18n: Bosnian and Catalan rows for Start Lists From Typed Markers main added bs and ca as bundled languages, and the preference test checks that every bundled language translates the checkbox label. --- crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + 2 files changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2c365fa503..aba170ea49 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3577,6 +3577,7 @@ theme Appearance Izgled Feet Stope Files Datoteke Fill New Type Objects With Placeholder Text Ispuni nove tekstualne objekte tekstom čuvara mjesta + Start Lists From Typed Markers Započni liste iz otkucanih oznaka Folder Folder Font Preview Size Veličina pregleda fonta Get Preferences Preuzmi postavke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f0c3542ad3..370d9b6773 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1555,6 +1555,7 @@ digits Malayalam Malaiàlam Fill Line Línia de farciment Fill new strokes Omple els traços nous Fill New Type Objects With Placeholder Text Omple els objectes de text nous amb text de mostra + Start Lists From Typed Markers Comença llistes a partir dels marcadors escrits Fill Rule Regla de farciment Fill with Placeholder Text Omple amb text de mostra Fill: Farciment: From 1e6c67a374edd9a84f77af1485c92a07ccf51a9c Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 8 Nov 2026 23:31:53 +0700 Subject: [PATCH 19/26] i18n: Hindi has the typed-list-markers preference label --- crates/ui-egui/src/i18n/hi.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0f212f4fde..b7cb6fccea 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7960,3 +7960,4 @@ swatch White, Black सफ़ेद, काला swatch Yellow पीला swatch Yellow Green पीला हरा theme Appearance अपीयरेंस + Start Lists From Typed Markers टाइप किए गए चिह्नों से सूचियाँ शुरू करें From 246b8ed8cd4b846e1abb756a30f742e7e3738dfb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 23:28:09 -0700 Subject: [PATCH 20/26] Type: typed `+`, `#` and `>` start lists with a hollow circle, square and dash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typed list detection gave every bulleted trigger the filled dot. Now `*` and a space start a list with the filled dot (•), `+` with the hollow circle (◦), `#` with the filled square (▪) and `>` with the dash (–), each one of the existing Bullets presets. `1.`, `1)`, `A.` and `A)` start the same numbered lists as before. Only the list a typed trigger starts changes. Lists already in a document keep their bullets, pasted triggers start no list, and Undo and Redo of a typed list work as before. Docs: docs/mcp.md (typed list paragraph), docs/target-app-parity.md. --- crates/doc/src/text/tabs_lists.rs | 9 ++++--- crates/doc/src/text/tests.rs | 13 ++++----- crates/engine/src/tests/textedit.rs | 42 ++++++++++++++++++++--------- docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 5 files changed, 45 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index b66795e890..7f6382b2fe 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -233,13 +233,16 @@ impl ParaList { /// The list that the Type tool starts when `typed` and a space are typed at the start of a /// paragraph: "1." or "1)" starts a numbered list in 1, 2, 3, "A." or "A)" starts one in A, B, - /// C, and "*", "#", ">" or "+" starts a bulleted list with the filled dot. Any other text starts - /// none. + /// C, and "*" starts a bulleted list with the filled dot, "+" one with the hollow circle, "#" + /// one with the filled square and ">" one with the dash. Any other text starts none. pub fn typed(typed: &str) -> Option { match typed { "1." | "1)" => Some(Self::numbered(NumberStyle::Arabic)), "A." | "A)" => Some(Self::numbered(NumberStyle::UpperLetters)), - "*" | "#" | ">" | "+" => Some(Self::bulleted(Bullet::Dot)), + "*" => Some(Self::bulleted(Bullet::Dot)), + "+" => Some(Self::bulleted(Bullet::Circle)), + "#" => Some(Self::bulleted(Bullet::Square)), + ">" => Some(Self::bulleted(Bullet::Dash)), _ => None, } } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 2a47ee453e..ad45a6477e 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -212,22 +212,23 @@ fn number_styles_write_their_numbers_and_roll_over() { } /// Typed list detection: "1.", "1)", "A." and "A)" and a space at the start of a paragraph -/// start a numbered list, and "*", "#", ">" and "+" and a space start a bulleted list with the -/// filled dot. Other text, the same characters later in a paragraph or without the space, and -/// a paragraph already in a list start nothing. +/// start a numbered list, and "*", "+", "#" and ">" and a space start a bulleted list with the +/// filled dot, the hollow circle, the filled square and the dash. Other text, the same characters +/// later in a paragraph or without the space, and a paragraph already in a list start nothing. #[test] fn typed_list_starts_are_found_at_a_paragraphs_start() { let (arabic, letters, dot) = (ParaList::numbered(NumberStyle::Arabic), ParaList::numbered(NumberStyle::UpperLetters), ParaList::bulleted(Bullet::Dot)); - let typed = ["1.", "1)", "A.", "A)", "*", "#", ">", "+"].map(ParaList::typed); - assert_eq!(typed, [arabic, arabic, letters, letters, dot, dot, dot, dot].map(Some)); + let (circle, square, dash) = (ParaList::bulleted(Bullet::Circle), ParaList::bulleted(Bullet::Square), ParaList::bulleted(Bullet::Dash)); + let typed = ["1.", "1)", "A.", "A)", "*", "+", "#", ">"].map(ParaList::typed); + assert_eq!(typed, [arabic, arabic, letters, letters, dot, circle, square, dash].map(Some)); for other in ["", "2.", "a.", "a)", "I.", "1", "A", "1:", "-", "•", "1.)", " 1.", "*1", "1."] { assert_eq!(ParaList::typed(other), None, "{other:?}"); } let mut t = TextObject::point(Point::ZERO, "Fruit\n1. Apples\nA) x * y\n+ ", CharStyle::default()); assert_eq!(t.typed_list_at(9), Some((6, arabic))); assert_eq!(t.typed_list_at(19), Some((16, letters))); - assert_eq!(t.typed_list_at(27), Some((25, dot))); + assert_eq!(t.typed_list_at(27), Some((25, circle))); // Not at the paragraph's start, not right after the space, or past the end. for at in [0, 5, 8, 10, 15, 23, 25, 26, 99] { assert_eq!(t.typed_list_at(at), None, "{at}"); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 7738e45a4a..4d0ade073a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1047,18 +1047,20 @@ fn list_markers(s: &Session, id: NodeId) -> Vec { } /// Typed list detection: at the start of a paragraph, "1.", "1)", "A." or "A)" and a space start -/// a numbered list, and "*", "#", ">" or "+" and a space start a bulleted list with the filled dot. -/// The typed characters go, the paragraph takes the hanging indent, and the text typed next is the -/// list item's. One Undo puts the typed characters back with no list, and typing goes on after -/// them, also after a Backspace that deleted nothing. +/// a numbered list, and "*", "+", "#" or ">" and a space start a bulleted list with the filled dot, +/// the hollow circle, the filled square or the dash. The typed characters go, the paragraph takes +/// the hanging indent, and the text typed next is the list item's. One Undo puts the typed +/// characters back with no list, and typing goes on after them, also after a Backspace that +/// deleted nothing. #[test] fn typing_a_list_start_and_a_space_starts_a_list() { use vectorcraft_doc::text::{Bullet, NumberStyle, ParaList}; let v = ViewInfo::default(); - let (arabic, letters, dot) = - (ParaList::numbered(NumberStyle::Arabic), ParaList::numbered(NumberStyle::UpperLetters), ParaList::bulleted(Bullet::Dot)); + let (arabic, letters) = (ParaList::numbered(NumberStyle::Arabic), ParaList::numbered(NumberStyle::UpperLetters)); let cases = [("1.", arabic, "1."), ("1)", arabic, "1."), ("A.", letters, "A."), ("A)", letters, "A.")]; - let bullets = ["*", "#", ">", "+"].map(|b| (b, dot, "\u{2022}")); + let bullets = + [("*", Bullet::Dot, "\u{2022}"), ("+", Bullet::Circle, "\u{25E6}"), ("#", Bullet::Square, "\u{25AA}"), (">", Bullet::Dash, "\u{2013}")] + .map(|(b, bullet, marker)| (b, ParaList::bulleted(bullet), marker)); for (typed, list, marker) in cases.into_iter().chain(bullets) { let mut s = session(); s.select_tool("type", v).unwrap(); @@ -1190,7 +1192,7 @@ fn typed_lists_is_a_type_preference_on_by_default() { /// (a paste), or at the start of a paragraph that is already in a list start nothing. #[test] fn list_starts_typed_elsewhere_or_pasted_start_no_list() { - use vectorcraft_doc::text::{NumberStyle, ParaList}; + use vectorcraft_doc::text::{Bullet, NumberStyle, ParaList}; let v = ViewInfo::default(); let mut s = session(); s.select_tool("type", v).unwrap(); @@ -1205,12 +1207,26 @@ fn list_starts_typed_elsewhere_or_pasted_start_no_list() { for c in "1.Pears".chars() { s.tool_text(&c.to_string(), v).unwrap(); } - key(&mut s, ToolKey::Enter, Mods::default()); - s.tool_text("* ", v).unwrap(); + for pasted in ["* ", "+ ", "# ", "> "] { + key(&mut s, ToolKey::Enter, Mods::default()); + s.tool_text(pasted, v).unwrap(); + } let t = obj(&s, id); - assert_eq!(t.plain_text(), "Fruit 1. * A) x\n1. Apples\n1.Pears\n* "); - assert_eq!((0..4).map(|i| t.para_at(i).list).collect::>(), [None, None, None, None]); + assert_eq!(t.plain_text(), "Fruit 1. * A) x\n1. Apples\n1.Pears\n* \n+ \n# \n> "); + assert!((0..7).all(|i| t.para_at(i).list.is_none())); assert!(!undo_labels(&s).iter().any(|l| l == "Bullets and Numbering")); + // A paragraph in a bulleted list keeps its bullet when another list start is typed before it. + let id = text(&mut s, "Item"); + s.execute("text.setFormat", &json!({"ids": [id.0], "list": "bullet", "bullet": "dot"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + click(&mut s, 101.0, 95.0); + s.set_tool_option("select", &json!({"start": 0, "end": 0})); + for c in "+ ".chars() { + s.tool_text(&c.to_string(), v).unwrap(); + } + let t = obj(&s, id); + assert_eq!((t.plain_text().as_str(), t.para_at(0).list), ("+ Item", Some(ParaList::bulleted(Bullet::Dot)))); + assert_eq!(list_markers(&s, id), ["\u{2022}"]); // A paragraph in a list keeps its list, and the typed characters stay as text. let id = text(&mut s, "Item"); s.execute("text.setFormat", &json!({"ids": [id.0], "list": "number"})).unwrap(); @@ -1245,7 +1261,7 @@ fn start_list_command_removes_the_typed_characters_and_starts_the_list() { let id = text(&mut s, "x\n# "); let r = s.execute("text.startList", &json!({"id": id.0})).unwrap(); assert_eq!((r["started"].clone(), obj(&s, id).plain_text()), (json!(true), "x\n".to_string())); - assert_eq!(obj(&s, id).para_at(1).list, Some(ParaList::bulleted(Bullet::Dot))); + assert_eq!(obj(&s, id).para_at(1).list, Some(ParaList::bulleted(Bullet::Square))); let steps = undo_labels(&s).len(); let id = text(&mut s, "1.x"); assert_eq!(s.execute("text.startList", &json!({"id": id.0, "at": 3})).unwrap()["started"], json!(false)); diff --git a/docs/mcp.md b/docs/mcp.md index 49d1fcef2d..2074f47f0e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5755,7 +5755,8 @@ next to the same character, and that frame becomes the selection when it was not Typing starts a list too. When the Type tool types a space on its own (one key press, or `type_text {text: " "}`) right after `1.` or `1)`, `A.` or `A)`, or one of `*`, `#`, `>` and `+` at the start of a paragraph that is in no list, the typed characters and the space are removed and the paragraph becomes a numbered list in 1, 2, 3 or A, B, C, or a -bulleted list with the filled dot. A list started with `1)` or `A)` also writes its numbers with a period. A paragraph +bulleted list: `*` gives the filled dot (•), `+` the hollow circle (◦), `#` the filled square (▪) and `>` the dash +(–). A list started with `1)` or `A)` also writes its numbers with a period. A paragraph whose left and first-line indents are both 0 gets 18 pt and -18 pt. The tool runs `text.startList {id, at}`, with `at` the byte after the space, as an undo step of its own after the typing: one Undo puts the characters back as text with no list, and typing goes on after them; Redo removes them again, and typing goes on before the paragraph's text. The same diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 051d300098..037b7d4c2c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1048,7 +1048,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. Type › Bullets and Numbering › Convert to Text (`type.convertListToText`, `text.convertListToText`) makes the bullets and numbers of the list paragraphs editable characters of their text ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [December 2022 release notes](https://web.archive.org/web/20260203094741/https://helpx.adobe.com/illustrator/using/whats-new/2023-1.html)): each marker becomes its characters and a tab at the start of its paragraph, in the marker's font, size and color, the list is turned off, and a left tab stop at the left indent keeps the text after the tab where it started; threaded type keeps the numbers its story counted. While no type is being edited, a press with Shift held makes new type with the horizontal or vertical counterpart of the Type, Area Type or Type on a Path tool chosen, and a press with Alt (Option) held makes it with Type on a Path in place of Area Type or the reverse, in the chosen tool's writing direction; with both keys held, both switch ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). The pointer shows the tool the press acts as, and the tool chosen stays selected. - The Type tool starts a list from the characters [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html) names (`text.startList`): a space typed on its own after `1.`, `1)`, `A.` or `A)` at the start of a paragraph in no list makes the paragraph a numbered list in 1, 2, 3 or A, B, C, and a space typed after `*`, `#`, `>` or `+` makes it a bulleted list with the filled dot. The typed characters are removed, and one Undo puts them back as text with no list. The same characters later in a paragraph, and pasted list characters, start nothing. + The Type tool starts a list from the characters [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html) names (`text.startList`): a space typed on its own after `1.`, `1)`, `A.` or `A)` at the start of a paragraph in no list makes the paragraph a numbered list in 1, 2, 3 or A, B, C, and a space typed after `*`, `+`, `#` or `>` makes it a bulleted list with the filled dot, the hollow circle, the filled square or the dash (a VectorCraft choice: the page does not say which bullet each character gives). The typed characters are removed, and one Undo puts them back as text with no list. The same characters later in a paragraph, and pasted list characters, start nothing. PDF export writes bullets and numbers as text, in the glyphs and at the places the canvas draws them, in area type, type on a path, right-to-left paragraphs and threaded frames, and a PDF viewer selects, copies and finds them; a marker glyph that stands for no character is drawn as a path. The Character panel menu's Character Direction (with the Indic options; `text.setFormat {charDirection}`, `text.setRangeStyle {charDirection}`) sets the selected characters left to right or right to left inside their paragraph, as a Unicode bidi embedding: a date set Left to Right keeps its order in right-to-left text, and a word set Right to Left keeps the punctuation after it on its left. Default (the default) leaves the characters to the bidi algorithm; character styles and the native file keep the setting. In vertical type, the Tabs panel names its alignment buttons Top-Justified Tab, Center-Justified Tab, Bottom-Justified Tab and Decimal-Justified Tab, in their tool tips and for screen readers, and labels the position field Y. In horizontal type the buttons keep the names Left-Justified Tab and Right-Justified Tab, and the field keeps the label X. From 6fce6d18841ba2851667d5c04e84c0b21e84cb55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 01:27:20 -0700 Subject: [PATCH 21/26] Type: text.startList names the bullet each typed trigger starts The command catalog said "* ", "# ", "> " and "+ " all start a list with the filled dot. It now names the filled dot, hollow circle, filled square and dash. The text.startList test checks each of the four triggers and the marker the layout draws. --- crates/engine/src/cmd/textedit.rs | 2 +- crates/engine/src/tests/textedit.rs | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 29d1de28ff..d8514ef562 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Bullets and Numbering", [], None, - "{id, at?: byte (default: the end of the text)} start a list from typed characters, what the Type tool runs when a space is typed on its own: when the text from the start of the paragraph that `at` is in up to `at` is \"1. \" or \"1) \" (a numbered list in 1, 2, 3), \"A. \" or \"A) \" (a numbered list in A, B, C), or \"* \", \"# \", \"> \" or \"+ \" (a bulleted list with the filled dot), and the paragraph is in no list, those characters are removed and the paragraph joins that list as one undo step (left and first-line indents of 0 become 18 and -18, as text.setFormat sets them); otherwise nothing changes → {id, started: bool, caret: byte (the paragraph's start when started, else `at`)}", + "{id, at?: byte (default: the end of the text)} start a list from typed characters, what the Type tool runs when a space is typed on its own: when the text from the start of the paragraph that `at` is in up to `at` is \"1. \" or \"1) \" (a numbered list in 1, 2, 3), \"A. \" or \"A) \" (a numbered list in A, B, C), \"* \" (a bulleted list with the filled dot), \"+ \" (the hollow circle), \"# \" (the filled square) or \"> \" (the dash), and the paragraph is in no list, those characters are removed and the paragraph joins that list as one undo step (left and first-line indents of 0 become 18 and -18, as text.setFormat sets them); otherwise nothing changes → {id, started: bool, caret: byte (the paragraph's start when started, else `at`)}", has_doc, start_list ), diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 4d0ade073a..a895655b99 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1258,10 +1258,16 @@ fn start_list_command_removes_the_typed_characters_and_starts_the_list() { assert_eq!(list_markers(&s, id), ["1."]); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!((obj(&s, id).plain_text().as_str(), obj(&s, id).para_at(1).list), ("Fruit\n1) Apples", None)); - let id = text(&mut s, "x\n# "); - let r = s.execute("text.startList", &json!({"id": id.0})).unwrap(); - assert_eq!((r["started"].clone(), obj(&s, id).plain_text()), (json!(true), "x\n".to_string())); - assert_eq!(obj(&s, id).para_at(1).list, Some(ParaList::bulleted(Bullet::Square))); + for (typed, bullet, marker) in + [("* ", Bullet::Dot, "\u{2022}"), ("+ ", Bullet::Circle, "\u{25E6}"), ("# ", Bullet::Square, "\u{25AA}"), ("> ", Bullet::Dash, "\u{2013}")] + { + let id = text(&mut s, &format!("x\n{typed}")); + let r = s.execute("text.startList", &json!({"id": id.0})).unwrap(); + assert_eq!((r["started"].clone(), obj(&s, id).plain_text()), (json!(true), "x\n".to_string()), "{typed:?}"); + assert_eq!(obj(&s, id).para_at(1).list, Some(ParaList::bulleted(bullet)), "{typed:?}"); + s.execute("text.editRange", &json!({"id": id.0, "start": 2, "end": 2, "insert": "Item"})).unwrap(); + assert_eq!(list_markers(&s, id), [marker], "{typed:?}"); + } let steps = undo_labels(&s).len(); let id = text(&mut s, "1.x"); assert_eq!(s.execute("text.startList", &json!({"id": id.0, "at": 3})).unwrap()["started"], json!(false)); From 2464ac02be6abfbe9d31ffae3fd2c3a678f4a62d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 8 Nov 2026 22:59:02 +0700 Subject: [PATCH 22/26] Type: a continued paragraph's list test types `*`, since `#` now starts a square bullet --- crates/doc/src/text/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index ad45a6477e..a3f4ab4d22 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -246,7 +246,7 @@ fn typed_list_starts_are_found_at_a_paragraphs_start() { #[test] fn typed_list_starts_skip_a_continued_paragraph() { let dot = ParaList::bulleted(Bullet::Dot); - let mut t = TextObject::point(Point::ZERO, "* Pears\n# ", CharStyle::default()); + let mut t = TextObject::point(Point::ZERO, "* Pears\n* ", CharStyle::default()); assert_eq!(t.typed_list_at(2), Some((0, dot))); t.first_para_continues = true; assert_eq!(t.typed_list_at(2), None, "a continued paragraph starts no list"); From eaa42374a3d88af0154a5de10e6b45977b78f672 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:47:10 +0700 Subject: [PATCH 23/26] Shortcuts: F2, F3 and F4 also cut, copy and paste on Windows and Linux Squashed from #5041 onto main. --- crates/ui-egui/src/dialogs/shortcut_import.rs | 2 +- .../src/dialogs/tests_shortcut_import.rs | 19 ++ crates/ui-egui/src/keymap.rs | 91 +++++++++- crates/ui-egui/src/shortcut_editor.rs | 163 ++++++++++++++++-- crates/ui-egui/src/shortcuts/tests.rs | 47 +++++ docs/target-app-parity.md | 2 + 6 files changed, 306 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index c65b4e6022..00ae1abe7b 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -508,7 +508,7 @@ pub fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { shortcut_editor::open(app); } if let Some(k) = app.ui.dialog.as_mut() { - k.fields.insert("overrides".into(), crate::keymap::stored::to_value(km.overrides())); + k.fields.insert("overrides".into(), crate::keymap::stored::to_value(&shortcut_editor::saved_overrides(km.overrides(), &ov))); k.fields.insert("set".into(), json!(set)); k.fields.insert("__message".into(), json!(tl!("Imported. Press OK to keep the imported set."))); } diff --git a/crates/ui-egui/src/dialogs/tests_shortcut_import.rs b/crates/ui-egui/src/dialogs/tests_shortcut_import.rs index 61bbc18e8c..77842ec8d0 100644 --- a/crates/ui-egui/src/dialogs/tests_shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/tests_shortcut_import.rs @@ -500,6 +500,25 @@ fn apply_rows(app: &mut VectorcraftApp, start: &str, rows: &[(&str, &str, &str, (out, dialog(app).fields["overrides"].clone()) } +#[test] +fn resetting_an_imported_function_key_restores_its_edit_default() { + if crate::keymap::platform().is_mac() { + return; + } + for (alias, edit) in [("F2", "edit.cut"), ("F3", "edit.copy"), ("F4", "edit.paste")] { + let mut app = app(); + let (out, value) = apply_rows(&mut app, "defaults", &[("Acme Duplicate", "Menus", "edit.duplicate", alias)]); + assert_eq!(out["applied"], 1); + let mut saved = crate::keymap::stored::from_value(value); + assert!(!crate::keymap::has_override(&saved, edit), "{alias} saved edit override"); + shortcut_editor::reset_one(&mut saved, "edit.duplicate"); + assert_eq!( + crate::keymap::lookup(&crate::keymap::keymap_with(&saved), &crate::keymap::vc_chord(alias).unwrap()), + Some(crate::keymap::command_of(edit)), + ); + } +} + /// Cmd and Ctrl are one key off the Mac: the review lets both rows through, and the later one takes /// the shortcut. #[test] diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 572c6b175d..d481ba389c 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -132,7 +132,7 @@ fn vc_binding(text: &str) -> Option { /// Every listed entry as the crate sees it, in dispatch priority: commands (engine, then UI), /// panels, tools. Each tool is its own group: tools never cycle. -fn catalogue() -> Vec { +fn catalogue(p: Platform) -> Vec { let rank = |e: &Entry| { if e.is_tool { 2 @@ -159,7 +159,7 @@ fn catalogue() -> Vec { if let Some(d) = shortcut_editor::default_of(&e.key).and_then(vc_binding) { b = b.with_default(d); } - for alias in default_aliases(&e.key) { + for alias in default_aliases(&e.key, p) { if let Some(d) = vc_binding(alias) { b = b.with_default(d); } @@ -170,14 +170,22 @@ fn catalogue() -> Vec { } /// Additional defaults for commands whose primary shortcut remains in their command spec. -fn default_aliases(key: &str) -> &'static [&'static str] { +fn default_aliases(key: &str, p: Platform) -> &'static [&'static str] { match key { + "edit.cut" if !p.is_mac() => &["F2"], + "edit.copy" if !p.is_mac() => &["F3"], + "edit.paste" if !p.is_mac() => &["F4"], "paint.lastColor" => &["Shift+,"], "paint.lastGradient" => &["Shift+."], _ => &[], } } +/// Cut, Copy and Paste with their primary shortcut and the function key [`default_aliases`] adds +/// outside macOS. +pub(crate) const EDIT_FUNCTION_KEYS: [(&str, &str, &str); 3] = + [("edit.cut", "Cmd+X", "F2"), ("edit.copy", "Cmd+C", "F3"), ("edit.paste", "Cmd+V", "F4")]; + /// On the web, the browser's operating system once egui reports it ([`note_os`]). static WEB_PLATFORM: RwLock> = RwLock::new(None); @@ -220,13 +228,38 @@ pub fn template() -> &'static Keymap { } /// The default keymap of `p`. The chords the operating system takes can't be assigned. -fn keymap_for(p: Platform) -> Keymap { - Keymap::new(catalogue(), Scopes::new(), p).with_reserved(craft_keymap::reserved::system(p)) +pub(crate) fn keymap_for(p: Platform) -> Keymap { + Keymap::new(catalogue(p), Scopes::new(), p).with_reserved(craft_keymap::reserved::system(p)) } /// The keymap with `overrides` applied. pub fn keymap_with(overrides: &Overrides) -> Keymap { - template().clone().with_overrides(overrides.clone()) + let defaults = template(); + defaults.clone().with_overrides(edit_alias_overrides(overrides, defaults.platform())) +} + +/// When a saved override assigns F2, F3 or F4 elsewhere without changing its edit command, +/// keep only that edit command's primary shortcut so the saved assignment runs. +pub(crate) fn edit_alias_overrides(overrides: &Overrides, p: Platform) -> Overrides { + let mut resolved = overrides.clone(); + if p.is_mac() { + return resolved; + } + for (key, primary, alias) in EDIT_FUNCTION_KEYS { + if overrides.get(key).is_some() { + continue; + } + let Some(binding) = vc_binding(alias) else { continue }; + let assigned_elsewhere = overrides.iter().any(|(other, texts)| { + other != key + && shortcut_editor::entry(&entry_of_stored(other)).is_some() + && texts.iter().any(|text| Binding::parse(text).is_ok_and(|b| b == binding)) + }); + if assigned_elsewhere { + let _ = resolved.insert(key, vec![vc_to_crate(primary)]); + } + } + resolved } /// The command a chord runs, the first for tools sharing it. @@ -424,7 +457,7 @@ mod tests { .filter_map(|e| shortcut_editor::default_of(&e.key).map(|d| (e.key.as_str(), d))) .filter(|(key, d)| { let mut expected: Vec = vc_binding(d).into_iter().collect(); - expected.extend(default_aliases(key).iter().filter_map(|alias| vc_binding(alias))); + expected.extend(default_aliases(key, platform()).iter().filter_map(|alias| vc_binding(alias))); expected != template().default_bindings(&command_of(key)) }) .collect(); @@ -451,6 +484,50 @@ mod tests { assert!(template().conflicts().is_empty()); } + #[test] + fn edit_function_keys_follow_platform_and_reset_restores_both_bindings() { + for p in [Platform::Windows, Platform::Linux, Platform::Mac] { + let km = keymap_for(p); + for (key, primary, alternate) in [("edit.cut", "Cmd+X", "F2"), ("edit.copy", "Cmd+C", "F3"), ("edit.paste", "Cmd+V", "F4")] { + let command = command_of(key); + let mut expected = vec![vc_binding(primary).unwrap()]; + if !p.is_mac() { + expected.push(vc_binding(alternate).unwrap()); + } + assert_eq!(km.default_bindings(&command), expected, "{p:?} {key}"); + assert_eq!(lookup(&km, &vc_chord(primary).unwrap()), Some(command.clone()), "{p:?} {primary}"); + assert_eq!(lookup(&km, &vc_chord(alternate).unwrap()), (!p.is_mac()).then_some(command.clone()), "{p:?} {alternate}"); + assert_eq!(effective_with(&km, key).as_deref(), Some(primary)); + let mut changed = km.clone(); + shortcut_editor::assign_in(&mut changed, key, Some("Ctrl+Alt+Shift+F12"), true).unwrap(); + assert_eq!(changed.bindings(&command), vec![vc_binding("Ctrl+Alt+Shift+F12").unwrap()]); + changed.reset(&command); + assert_eq!(changed.bindings(&command), expected, "{p:?} {key} reset"); + let mut overrides = Overrides::new(); + set_override(&mut overrides, key, "Ctrl+Alt+Shift+F12"); + shortcut_editor::reset_one(&mut overrides, key); + assert_eq!(km.clone().with_overrides(overrides).bindings(&command), expected, "{p:?} {key} use default"); + } + assert!(km.conflicts().is_empty(), "{p:?}"); + assert!(km.problems().is_empty(), "{p:?}"); + + for (alias, edit, primary) in [("F2", "edit.cut", "Cmd+X"), ("F3", "edit.copy", "Cmd+C"), ("F4", "edit.paste", "Cmd+V")] { + let mut saved = Overrides::new(); + set_override(&mut saved, "tool:pen", alias); + let assigned = keymap_for(p).with_overrides(edit_alias_overrides(&saved, p)); + assert_eq!(lookup(&assigned, &vc_chord(alias).unwrap()), Some(command_of("tool:pen")), "{p:?} saved {alias} assignment"); + assert_eq!(lookup(&assigned, &vc_chord(primary).unwrap()), Some(command_of(edit)), "{p:?} primary {edit} binding"); + shortcut_editor::reset_one(&mut saved, "tool:pen"); + let reset = keymap_for(p).with_overrides(edit_alias_overrides(&saved, p)); + assert_eq!(lookup(&reset, &vc_chord(alias).unwrap()), (!p.is_mac()).then_some(command_of(edit)), "{p:?} reset saved {alias}"); + } + let mut unknown = Overrides::new(); + set_override(&mut unknown, "missing.command", "F2"); + let km = keymap_for(p).with_overrides(edit_alias_overrides(&unknown, p)); + assert_eq!(lookup(&km, &vc_chord("F2").unwrap()), (!p.is_mac()).then_some(command_of("edit.cut")), "{p:?} unknown saved entry"); + } + } + /// The chords the operating system takes are refused, and no default uses one. #[test] fn system_shortcuts_are_refused() { diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index d5ed1ade2c..01deb3be8c 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -65,14 +65,14 @@ pub(crate) use ui_mirror; /// The keymap with the user's overrides, and the effective text of every entry they change. pub(crate) struct Mirror { pub keymap: Keymap, + source_overrides: Overrides, text: HashMap>, } impl Mirror { fn new(overrides: Overrides) -> Mirror { - let keymap = crate::keymap::template().clone().with_overrides(overrides); - let text = keymap - .overrides() + let keymap = crate::keymap::keymap_with(&overrides); + let text = overrides .iter() .map(|(k, _)| { let key = entry_of_stored(k); @@ -80,7 +80,7 @@ impl Mirror { (key, t) }) .collect(); - Mirror { keymap, text } + Mirror { keymap, source_overrides: overrides, text } } } @@ -113,7 +113,7 @@ pub fn sync(ui: &UiState) { let same = store() .read() .map(|m| match &*m { - Some(m) => *m.keymap.overrides() == ui.shortcut_overrides && m.keymap.platform() == crate::keymap::platform(), + Some(m) => m.source_overrides == ui.shortcut_overrides && m.keymap.platform() == crate::keymap::platform(), None => ui.shortcut_overrides.is_empty(), }) .unwrap_or(false); @@ -612,10 +612,32 @@ pub fn conflicts_in(km: &Keymap) -> Vec<(String, Vec)> { pub fn assign(overrides: &mut Overrides, key: &str, chord: Option<&str>, force: bool) -> Result, String> { let mut km = keymap_with(overrides); let removed = assign_in(&mut km, key, chord, force)?; - *overrides = km.overrides().clone(); + *overrides = saved_overrides(km.overrides(), overrides); Ok(removed) } +/// The overrides to save from a working keymap's `current` overrides. An entry for Cut, Copy or +/// Paste that `source`, the set before the change, did not hold is left out when it is the entry +/// [`crate::keymap::keymap_with`] makes from the other entries of `source` or of `current`. +pub(crate) fn saved_overrides(current: &Overrides, source: &Overrides) -> Overrides { + let mut saved = current.clone(); + for (key, _, _) in crate::keymap::EDIT_FUNCTION_KEYS { + let Some(now) = current.get(key) else { continue }; + if source.get(key).is_some() { + continue; + } + let made = |from: &Overrides| { + let mut rest = from.clone(); + rest.remove(key); + crate::keymap::edit_alias_overrides(&rest, crate::keymap::platform()).get(key).is_some_and(|t| t == now) + }; + if made(current) || made(source) { + saved.remove(key); + } + } + saved +} + /// [`assign`] on a keymap. pub fn assign_in(km: &mut Keymap, key: &str, chord: Option<&str>, force: bool) -> Result, String> { let command = command_of(key); @@ -789,7 +811,7 @@ pub fn run_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option return Some(Err(e)), }; let km = keymap_with(&app.ui.shortcut_overrides); - let ov = km.overrides(); + let ov = &app.ui.shortcut_overrides; Ok(Value::Array( entries() .iter() @@ -943,7 +965,7 @@ impl DialogView { let backtick = backtick_text(); let texts = entries().iter().map(|e| dialog_shortcuts_with(&keymap, &e.key, backtick.as_deref())).collect(); let conflicts = conflicts_in(&keymap).len(); - DialogView { source: stored::to_value(keymap.overrides()), backtick, keymap, texts, conflicts } + DialogView { source: stored::to_value(&overrides), backtick, keymap, texts, conflicts } } /// The view of `d`'s working set, from the cache unless the set or the backtick key's @@ -972,6 +994,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut ok = false; let mut cancel = false; drop_hidden(&mut d, km.overrides()); + let saved = dialog_overrides(&d); let recording = d.str("__recording"); // Record a chord (before widgets see the keys). Modifiers held down are part of the next key's // chord, not a chord of their own. @@ -1089,7 +1112,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { d.fields.insert("__selected".into(), json!(e.key)); } let label = if rec == e.key { tl!("Press keys…").to_string() } else { sc.unwrap_or_else(|| "—".into()) }; - let changed = crate::keymap::has_override(km.overrides(), &e.key); + let changed = crate::keymap::has_override(&saved, &e.key); let txt = egui::RichText::new(label).color(if changed { t.accent } else { t.text }); let b = ui .add_sized([150.0, 20.0], egui::Button::new(txt).selected(rec == e.key)) @@ -1161,7 +1184,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); }); if let Cow::Owned(km) = &km { - d.fields.insert("overrides".into(), stored::to_value(km.overrides())); + d.fields.insert("overrides".into(), stored::to_value(&saved_overrides(km.overrides(), &saved))); } let import = d.fields.remove("__import").is_some(); let export = d.fields.remove("__export").is_some(); @@ -1667,6 +1690,126 @@ mod tests { assert_eq!(view.conflicts, 0); } + #[test] + fn edit_dialog_rows_show_primary_and_function_keys() { + for p in [craft_keymap::Platform::Windows, craft_keymap::Platform::Linux, craft_keymap::Platform::Mac] { + let km = crate::keymap::keymap_for(p); + for (key, primary, alternate) in [("edit.cut", "Cmd+X", "F2"), ("edit.copy", "Cmd+C", "F3"), ("edit.paste", "Cmd+V", "F4")] { + let shown = dialog_shortcuts_with(&km, key, None).unwrap(); + let primary = menus::pretty_shortcut(primary); + assert!(shown.contains(&primary), "{p:?} {key}: {shown}"); + assert_eq!(shown.contains(alternate), !p.is_mac(), "{p:?} {key}: {shown}"); + } + } + for (key, primary) in [("edit.cut", "Cmd+X"), ("edit.copy", "Cmd+C"), ("edit.paste", "Cmd+V")] { + let shown = menus::item_shortcut(key, &Value::Null).map(menus::pretty_shortcut); + assert_eq!(shown, Some(menus::pretty_shortcut(primary)), "{key} menu shortcut"); + } + } + + #[test] + fn saved_function_key_assignment_does_not_change_cut_in_the_editor() { + if crate::keymap::platform().is_mac() { + return; + } + let mut saved = Overrides::new(); + crate::keymap::set_override(&mut saved, "tool:pen", "F2"); + let mirror = Mirror::new(saved.clone()); + assert!(!mirror.text.contains_key("edit.cut")); + assert!(conflicts_in(&mirror.keymap).is_empty()); + + let view = DialogView::new(saved.clone()); + assert_eq!(view.source, stored::to_value(&saved)); + assert_eq!(view.conflicts, 0); + assert_eq!(dialog_shortcuts_with(&view.keymap, "edit.cut", None), Some(menus::pretty_shortcut("Cmd+X"))); + + let mut other = saved.clone(); + assign(&mut other, "edit.preferences", Some("Cmd+Alt+Shift+F12"), false).unwrap(); + assert!(!crate::keymap::has_override(&other, "edit.cut")); + let (set, imported) = import_json(&export_json("Mine", &other)).unwrap(); + assert_eq!(set, "Mine"); + assert_eq!(imported, other); + assert!(!crate::keymap::has_override(&imported, "edit.cut")); + + let mut km = view.keymap.clone(); + assign_in(&mut km, "edit.preferences", Some("Cmd+Alt+Shift+F12"), false).unwrap(); + assert_eq!(saved_overrides(km.overrides(), &saved), other); + } + + #[test] + fn reset_stolen_edit_function_keys_restores_their_defaults() { + if crate::keymap::platform().is_mac() { + return; + } + for (alias, edit) in [("F2", "edit.cut"), ("F3", "edit.copy"), ("F4", "edit.paste")] { + let mut saved = Overrides::new(); + assert_eq!(assign(&mut saved, "tool:pen", Some(alias), true).unwrap(), vec![edit]); + assert!(!crate::keymap::has_override(&saved, edit), "{alias} saved edit override"); + reset_one(&mut saved, "tool:pen"); + assert_eq!(crate::keymap::lookup(&keymap_with(&saved), &crate::keymap::vc_chord(alias).unwrap()), Some(command_of(edit))); + + let mut d = Dialog::new("shortcuts", json!({"overrides": {}})); + let source = dialog_overrides(&d); + let mut km = keymap_with(&source); + record(&mut d, &mut km, "tool:pen", alias); + d.fields.insert("overrides".into(), stored::to_value(&saved_overrides(km.overrides(), &source))); + let mut dialog_saved = dialog_overrides(&d); + assert!(!crate::keymap::has_override(&dialog_saved, edit), "{alias} dialog edit override"); + reset_one(&mut dialog_saved, "tool:pen"); + assert_eq!(crate::keymap::lookup(&keymap_with(&dialog_saved), &crate::keymap::vc_chord(alias).unwrap()), Some(command_of(edit))); + + let mut changed = Overrides::new(); + crate::keymap::set_override(&mut changed, edit, "Ctrl+Alt+Shift+F12"); + assign(&mut changed, "tool:pen", Some(alias), true).unwrap(); + assert_eq!(crate::keymap::override_text(&changed, edit).as_deref(), Some("Ctrl+Alt+Shift+F12")); + } + } + + #[test] + fn reassigning_a_saved_function_key_gives_it_back_to_its_edit_command() { + if crate::keymap::platform().is_mac() { + return; + } + for (alias, edit) in [("F2", "edit.cut"), ("F3", "edit.copy"), ("F4", "edit.paste")] { + let mut saved = Overrides::new(); + crate::keymap::set_override(&mut saved, "edit.preferences", alias); + assign(&mut saved, "edit.preferences", Some("Cmd+Alt+Shift+F12"), false).unwrap(); + assert!(!crate::keymap::has_override(&saved, edit), "{alias} saved edit override"); + assert_eq!(crate::keymap::lookup(&keymap_with(&saved), &crate::keymap::vc_chord(alias).unwrap()), Some(command_of(edit))); + + let mut source = Overrides::new(); + crate::keymap::set_override(&mut source, "edit.preferences", alias); + let mut d = Dialog::new("shortcuts", json!({"overrides": stored::to_value(&source)})); + let mut km = keymap_with(&source); + record(&mut d, &mut km, "edit.preferences", "Cmd+Alt+Shift+F12"); + let dialog_saved = saved_overrides(km.overrides(), &source); + assert!(!crate::keymap::has_override(&dialog_saved, edit), "{alias} dialog edit override"); + assert_eq!(crate::keymap::lookup(&keymap_with(&dialog_saved), &crate::keymap::vc_chord(alias).unwrap()), Some(command_of(edit))); + } + } + + #[test] + fn assigning_an_edit_function_key_elsewhere_reports_the_conflict() { + if crate::keymap::platform().is_mac() { + return; + } + for (alias, edit) in [("F2", "edit.cut"), ("F3", "edit.copy"), ("F4", "edit.paste")] { + let label = entry(edit).map(|e| e.label.clone()).unwrap(); + assert_eq!(conflicts_with(&Overrides::new(), alias, "tool:pen"), vec![edit.to_string()], "{alias}"); + let mut ov = Overrides::new(); + let err = assign(&mut ov, "tool:pen", Some(alias), false).unwrap_err(); + assert!(err.ends_with(&format!("is already used by {label}")), "{alias}: {err}"); + assert!(!crate::keymap::has_override(&ov, "tool:pen"), "{alias}: a refused assignment saves nothing"); + + let mut d = Dialog::new("shortcuts", json!({"overrides": {}})); + let mut km = keymap_with(&Overrides::new()); + record(&mut d, &mut km, "tool:pen", alias); + assert_eq!(d.str("__conflict"), edit, "{alias}"); + assert!(d.str("__message").contains(&label), "{alias}: {}", d.str("__message")); + assert_eq!(crate::keymap::lookup(&km, &crate::keymap::vc_chord(alias).unwrap()), Some(command_of("tool:pen")), "{alias}"); + } + } + #[test] fn entries_cover_tools_and_menu_commands() { assert!(entries().iter().any(|e| e.key == "tool:selection")); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index b64dd4f7ae..3d40a54279 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -28,6 +28,53 @@ fn named_panel_default_chords_toggle_their_panels() { } } +#[test] +fn edit_function_keys_dispatch_outside_text_editing_only() { + if crate::keymap::platform().is_mac() { + return; + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let shape = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [shape]})).unwrap(); + crate::shortcut_editor::sync(&app.ui); + frame(&mut app, press(Key::F3, Modifiers::NONE)); + assert_eq!(app.session.clipboard.nodes.len(), 1, "F3 copies the selection"); + frame(&mut app, press(Key::F2, Modifiers::NONE)); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "F2 cuts the selection"); + frame(&mut app, press(Key::F4, Modifiers::NONE)); + assert_eq!(app.session.active().unwrap().selection.objects.len(), 1, "F4 pastes the copied object"); + + let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + assert!(app.session.tool_wants_text()); + for key in [Key::F2, Key::F3, Key::F4] { + frame(&mut app, press(key, Modifiers::NONE)); + assert_eq!(text_and_layers(&mut app, id).0, "Hi", "{key:?} leaves edited text alone"); + assert!(app.session.tool_wants_text(), "{key:?} keeps editing"); + } + + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + let mut field = String::from("Field text"); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let response = ui.text_edit_singleline(&mut field); + ui.ctx().memory_mut(|m| m.request_focus(response.id)); + }); + out.textures_delta.clear(); + for key in [Key::F2, Key::F3, Key::F4] { + let mut out = ctx.run_ui(egui::RawInput { events: press(key, Modifiers::NONE), ..Default::default() }, |ui| { + handle(&mut app, ui.ctx()); + ui.text_edit_singleline(&mut field); + }); + out.textures_delta.clear(); + assert_eq!(field, "Field text", "{key:?} leaves focused text alone"); + assert_eq!(app.session.active().unwrap().selection.objects.len(), 1, "{key:?} leaves the canvas selection alone"); + } +} + #[test] fn other_panel_shortcuts_keep_plain_panel_params() { for panel in ["character", "swatches"] { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 037b7d4c2c..ce03481a2d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -760,6 +760,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. - The function key shortcuts for Brushes, Color, Layers, Info, Gradient, Stroke, Attributes, Graphic Styles, Appearance, Align, Transform, Pathfinder, Transparency, and Symbols activate a background tab on the first press, hide its expanded dock or floating group when that tab is in front, and restore the group with all its tabs together on the next press; in an icon column they open and close the flyout while keeping the icons. A reassigned chord keeps that behavior, and Window > a hidden sibling restores the group. + - On Windows and Linux, F2, F3 and F4 run Cut, Copy and Paste alongside Ctrl+X, Ctrl+C and Ctrl+V, and in the web build they do so everywhere except macOS. The Edit menu keeps the Ctrl shortcuts, and Keyboard Shortcuts lists both keys of each row. On macOS only Cmd+X, Cmd+C and Cmd+V are the defaults. F2, F3 and F4 do not run these commands in a focused text field or while the Type tool edits text. A saved shortcut set that assigns one of these keys to another command keeps that assignment. Public reference: [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). + - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`). - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`, `panels::tabs::tests::indent_markers_after_select_all_keep_each_story_paragraphs_indents`, `dialogs::justification::tests::justification_dialog_follows_the_story_thread_at_ok`). From def24714546cb5769099467ce2f506488d959687 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sun, 8 Nov 2026 23:32:22 +0700 Subject: [PATCH 24/26] Layers: the rename test allows F2's Cut alternate --- crates/ui-egui/src/panels/layers/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 0bd0efdde6..cad2530e5f 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -494,14 +494,14 @@ fn rename_opens_the_name_field_of_the_selected_object() { assert_eq!(name(&app), before, "one undo step"); } -/// Rename (`ui.rename`) has no default key, F2 being free: it is listed in Keyboard Shortcuts, +/// Rename (`ui.rename`) has no default key (F2 is Cut's alternate on Windows and Linux): it is listed in Keyboard Shortcuts, /// where a key can be assigned to it. #[test] fn rename_has_no_default_key() { use crate::shortcut_editor::{command_for_key, default_command_shortcut}; crate::shortcut_editor::sync(&crate::state::UiState::default()); assert_eq!(default_command_shortcut("ui.rename"), None); - assert_eq!(command_for_key("F2"), None); + assert_ne!(command_for_key("F2"), Some("ui.rename")); let (mut app, _, _) = two_rects(); let listed = app.run("shortcuts.list", json!({"query": "ui.rename"})).unwrap(); let rows: Vec<_> = listed.as_array().expect("rows").iter().map(|r| r["label"].clone()).collect(); From 023ee9065724389107d8bdd1cd4a3884b1a7f7f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 17:22:32 -0800 Subject: [PATCH 25/26] Perspective grid: Snap to Grid moves objects at every depth by one plane offset With Snap to Grid on, a move of objects on one perspective plane at different depths applied the snap correction only to the objects at the first object's depth, and every other object moved by the pointer's offset read at its own depth. Those objects left the grid and lost their spacing. Every object on the first object's plane now moves by that object's plane offset plus the correction, so the edge of the joint bounds nearer a gridline lands on it and the objects keep their spacing. A selection at one depth snaps as before, and objects on other planes keep their own offset. --- crates/engine/src/cmd/distortcmds.rs | 2 +- .../engine/src/cmd/distortcmds/perspective.rs | 25 +++++++++----- crates/engine/src/cmd/perspgrid.rs | 2 +- crates/engine/src/tests/persp_select.rs | 34 +++++++++++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 1 + 6 files changed, 55 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 9e0841de66..d54238925f 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Move in Perspective", [], None, - "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: bool (default false; constrain each in-plane move to its plane's nearest axis or 45° diagonal)} slide objects within their own planes (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the first plane's joint bounds toward a gridline within a quarter cell while preserving the constrained direction; Transform Again repeats it", + "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: bool (default false; constrain each in-plane move to its plane's nearest axis or 45° diagonal)} slide objects within their own planes (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the first plane's joint bounds toward a gridline within a quarter cell while preserving the constrained direction, and moves every object on that plane, at any depth, by the same plane offset; Transform Again repeats it", has_doc, persp_move ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 786d0d9568..a561e50998 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -285,7 +285,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { let constrain = switch_or(p, "constrain", false, C)?; // `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false. check_switches(p, &["snap"], C)?; - // Snap to Grid: a correction for the objects on the first one's plane and depth. + // Shift: the constrained end point, read on the first object's plane and depth. let snap_to = if constrain && !perp { let doc = &s.doc()?.doc; let g = grid_of(doc); @@ -300,11 +300,20 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { } else { to }; - let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, snap_to)) }; - let snapped = move |pl: Plane, depth: f64, raw: vectorcraft_geom::Vec2| { + // With Snap to Grid, every object on the first one's plane, at any depth, moves by the first + // one's plane-space offset and its correction, so the objects keep their spacing on the plane. + let fix = if perp { + None + } else { + let doc = &s.doc()?.doc; + crate::cmd::perspgrid::snap_fix(doc, &ids, p, (from, snap_to)) + .and_then(|(plane, depth, correction)| Some((plane, grid_of(doc).plane_delta(plane, depth, from, to)?, correction))) + }; + let snapped = move |pl: Plane, raw: vectorcraft_geom::Vec2| { + let raw = fix.filter(|f| f.0 == pl).map_or(raw, |f| f.1); let (direction, dv) = if constrain { vectorcraft_tools::distort::perspective::constrain_move_delta(raw) } else { (vectorcraft_geom::Vec2::ZERO, raw) }; - dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| { + dv + fix.filter(|f| f.0 == pl).map_or(vectorcraft_geom::Vec2::ZERO, |f| { if !constrain { return f.2; } @@ -325,7 +334,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { let to_depth = g.depth_at(pl, depth, from, to).ok_or_else(beyond_horizon)?; Ok((g.transform_map(pl, depth, Affine::IDENTITY, to_depth - depth).ok_or_else(beyond_horizon)?, to_depth)) } else { - let dv = snapped(pl, depth, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?); + let dv = snapped(pl, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?); Ok((g.transform_map(pl, depth, Affine::translate(dv), 0.0).ok_or_else(beyond_horizon)?, depth)) } }; @@ -336,7 +345,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { if perp { g.depth_at(pl, depth, from, to).is_some_and(|d| (d - depth).abs() <= 1e-9) } else { - g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, depth, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9) + g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9) } }; let first_still = if copy { None } else { unmoved(s, &ids, still)? }; @@ -350,9 +359,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { let again = match perp { _ if first_still.is_some() => Some(json!({"matrix": matrix_json(Affine::IDENTITY), "copy": copy})), true => g.depth_at(pl, depth, from, to).map(|d| json!({"matrix": matrix_json(Affine::IDENTITY), "depth": d - depth, "copy": copy})), - false => { - g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, depth, dv))), "copy": copy})) - } + false => g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, dv))), "copy": copy})), }; if let Some(a) = again { record_again(s, a)?; diff --git a/crates/engine/src/cmd/perspgrid.rs b/crates/engine/src/cmd/perspgrid.rs index 822d88aad7..d13e7d8c52 100644 --- a/crates/engine/src/cmd/perspgrid.rs +++ b/crates/engine/src/cmd/perspgrid.rs @@ -428,7 +428,7 @@ fn rulers(s: &mut Session, p: &Value) -> Result { /// Snap to Grid for a move of `ids` from page point `from` to `to` (unless `p` says `snap: false`): /// the plane and depth of the first one and the plane-space correction that lands the edge of the -/// joint bounds of the objects there nearer a gridline on it. +/// joint bounds of the objects on that plane, each measured at its own depth, nearer a gridline on it. pub(crate) fn snap_fix(doc: &Document, ids: &[NodeId], p: &Value, (from, to): (Point, Point)) -> Option<(Plane, f64, Vec2)> { let g = grid_of(doc); if !bool_or(p, "snap", g.snap) { diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index 4ca4b46faf..6a6022fdb3 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -228,6 +228,40 @@ fn diagonal_shift_snap_lands_an_edge_on_a_gridline() { assert!(edge.iter().any(|y| ((y / g.cell).round() * g.cell - y).abs() < 1e-6), "{edge:?}, correction {correction:?}"); } +#[test] +fn snap_moves_objects_at_different_depths_by_one_plane_offset() { + let (mut s, _) = persp_session(); + let rect = |s: &mut Session, x: f64| { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 380, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()) + }; + let near = rect(&mut s, 240.0); + s.execute("perspective.attach", &json!({"ids": [near.0], "plane": "left"})).unwrap(); + s.execute("perspective.plane.move", &json!({"plane": "left", "offset": 50})).unwrap(); + let far = rect(&mut s, 150.0); + s.execute("perspective.attach", &json!({"ids": [far.0], "plane": "left"})).unwrap(); + s.execute("perspective.plane.move", &json!({"plane": "left", "offset": 0})).unwrap(); + assert_eq!(attached(&s, near), Some((Plane::Left, 0.0))); + assert_eq!(attached(&s, far), Some((Plane::Left, 50.0))); + s.execute("perspective.grid.snap", &json!({"on": true})).unwrap(); + let g = grid(&s); + let (near_before, far_before) = (plane_pts(&s, near, Plane::Left, 0.0), plane_pts(&s, far, Plane::Left, 50.0)); + let b = bounds_of(&near_before).union(bounds_of(&far_before)); + // A move that ends 0.3 pt past a gridline crossing on the near object's plane. + let past = |v: f64| (v / g.cell).ceil() * g.cell + 0.3 - v; + let start = bounds_of(&near_before).center(); + let h = g.homography_at(Plane::Left, 0.0).unwrap(); + let from = h.apply(start).unwrap(); + let to = h.apply(start + Vec2::new(past(b.x0), past(b.y0))).unwrap(); + s.execute("perspective.move", &json!({"ids": [near.0, far.0], "from": [from.x, from.y], "to": [to.x, to.y]})).unwrap(); + let near_delta = plane_pts(&s, near, Plane::Left, 0.0)[0] - near_before[0]; + let far_delta = plane_pts(&s, far, Plane::Left, 50.0)[0] - far_before[0]; + assert!((near_delta - far_delta).hypot() < 1e-6, "near {near_delta:?}, far {far_delta:?}"); + let on_line = |v: f64| ((v / g.cell).round() * g.cell - v).abs() < 1e-6; + let moved = b + near_delta; + assert!(on_line(moved.x0) || on_line(moved.x1), "{moved:?}"); + assert!(on_line(moved.y0) || on_line(moved.y1), "{moved:?}"); +} + #[test] fn constrained_move_uses_each_objects_plane() { let (mut s, right) = persp_session(); diff --git a/docs/mcp.md b/docs/mcp.md index 2074f47f0e..6b9de2d5ee 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6528,7 +6528,8 @@ bounding-box handles scale it in plane space (`perspective.transform`; Shift kee centre), and `press_key` `5` during a drag switches the move to perpendicular to the plane (press again to switch back). Holding Shift during an in-plane move constrains each object's displacement to an axis or 45° diagonal of its own plane. `perspective.move` accepts `constrain: true` (default false) and adjusts Snap to Grid along the constrained -direction on the first object's plane and depth. +direction on the first object's plane and depth. With Snap to Grid, every object on the first object's plane moves +by the same plane offset, whatever its depth, and the edge of their joint bounds nearer a gridline lands on it. `press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, Alt copies). Object › Transform › Transform Again repeats the last perspective move or scale in plane space. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ce03481a2d..3955c28c4a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1413,6 +1413,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. With the Perspective Selection tool, holding Shift while moving or copying constrains each object's displacement to the nearest axis or 45° diagonal of its own plane; releasing Shift resumes the raw pointer position, and 5 still moves perpendicular to the plane. Snap to Grid follows the constrained line on the first object's plane and depth. + With Snap to Grid on, a move of objects on one perspective plane at different depths moves them all by the same offset on the plane, so they keep their spacing, and the edge of their joint bounds nearer a gridline lands on it. Regression: `snap_moves_objects_at_different_depths_by_one_plane_offset` in `crates/engine/src/tests/persp_select.rs`. When the desktop app opens a document on a thread of its own (#1245), that thread also reads the document's linked files and lays out its type, and the UI thread only adds the finished document: in release builds, the step left on the UI thread takes 0.02 ms instead of 1.04 s for a document with 12 linked 3000 × 2000 TIFFs, and it takes 0.1 ms instead of 0.85 s for one with 300 Auto Size area type objects, every second one in three columns. Laying out type keeps each font face's shaping plans, at most 32 per face, so type objects of the same font, script, direction, language and features share one plan: the layouts of a document of 5,000 short point type objects take 59 ms instead of 73 ms in a release build, and the glyphs, bounds and baselines do not change. Laying out type looks up the font face of each style run once and uses it for the run's glyphs and for the line metrics of a paragraph that starts in that run: the layouts of a document of 5,000 short point type objects take a median of 215 million CPU cycles instead of 236 million in a release build (11 alternating runs of each build on Windows 11, measured while other builds were running), and the glyphs, bounds and baselines do not change. From 2049082ce71fbba15b9fca39a74a9e83ab7b5697 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 13:48:10 +0700 Subject: [PATCH 26/26] Drawing tools: Escape on an arc, spiral or grid drag puts back the options it changed Squashed from #5202 onto main. --- crates/engine/src/tests/toolsettings.rs | 19 +++ crates/engine/src/tooling.rs | 5 + crates/tools/src/draw2/family.rs | 187 +++++++++++++++++++++++- docs/target-app-parity.md | 1 + 4 files changed, 210 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 3e522a5529..6b4ad87065 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -91,6 +91,25 @@ fn a_gesture_keeps_what_it_changed_and_a_document_switch_keeps_options() { assert_eq!(s.tool_options()["segments"], json!(14)); } +/// Escape on a grid drag puts back the dividers its arrows changed, in the saved options too, +/// while an option set during the drag stays. +#[test] +fn escape_on_a_drag_saves_the_options_it_put_back() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + select(&mut s, "rectangularGrid"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + // Saves every option, the rows the arrow changed included. + s.set_tool_option("columns", &json!(8)); + assert_eq!(s.prefs.tool_settings["rectangularGrid"]["rows"], json!(6)); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + let saved = &s.prefs.tool_settings["rectangularGrid"]; + assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(8))); +} + /// A dropped press (a long touch, a canceled touch, a second finger) keeps nothing it began: the /// tool ends at rest with the options it had before the press, and the options the drag changed /// are not stored. A release stores them. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 23edf6b568..12d5952630 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -578,6 +578,11 @@ impl Session { } let acts = self.with_tool_cx(view, |t, cx| t.key(cx, key, mods)); self.take_tool_panic()?; + // A key that cancels a gesture may put back options the gesture changed (Escape on an + // arc, spiral or grid drag): keep them. + if acts.contains(&Action::Cancel) { + self.keep_tool_settings(); + } self.apply_actions(acts) } diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 0bbdcf79b8..ed1ab47b03 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -12,6 +12,7 @@ //! On a grid, F and V lower and raise //! the skew of the horizontal (rectangular) or radial (polar) dividers, and X and C lower and raise //! that of the vertical or concentric ones. +//! Escape cancels the drag and puts back the options its keys and modifiers changed. use serde_json::{Value, json}; use vectorcraft_geom::Point; @@ -63,6 +64,22 @@ pub struct FamilyTool { /// its own). The Reference Point is `reference`. pub grid_size: (f64, f64), snap: DrawSnap, + /// The options a drag's keys and modifiers change, as they were when the drag began: Escape + /// puts them back. + before_drag: Option, +} + +/// The options that keys and modifiers change while a shape is dragged out. +#[derive(Clone, Copy)] +struct DragOptions { + slope: f64, + closed: bool, + base_along: &'static str, + decay: f64, + segments: u32, + rows: u32, + columns: u32, + skew: [f64; 2], } impl FamilyTool { @@ -99,9 +116,35 @@ impl FamilyTool { fill: false, grid_size: (100.0, 100.0), snap: DrawSnap::default(), + before_drag: None, } } + fn drag_options(&self) -> DragOptions { + DragOptions { + slope: self.slope, + closed: self.closed, + base_along: self.base_along, + decay: self.decay, + segments: self.segments, + rows: self.rows, + columns: self.columns, + skew: self.skew, + } + } + + /// Put back the options a canceled drag changed. + fn restore_drag_options(&mut self, o: DragOptions) { + self.slope = o.slope; + self.closed = o.closed; + self.base_along = o.base_along; + self.decay = o.decay; + self.segments = o.segments; + self.rows = o.rows; + self.columns = o.columns; + self.skew = o.skew; + } + fn label(&self) -> &'static str { match self.id { "spiral" => "Spiral", @@ -264,6 +307,7 @@ impl Tool for FamilyTool { self.began = false; self.spiral_end = None; self.spiral_alt_base = None; + self.before_drag = None; vec![] } PointerKind::Drag => { @@ -279,6 +323,7 @@ impl Tool for FamilyTool { return out; } self.began = true; + self.before_drag = Some(self.drag_options()); out.push(Action::Begin(self.label().into())); } if self.id == "spiral" { @@ -293,6 +338,7 @@ impl Tool for FamilyTool { self.snap.clear(); self.spiral_end = None; self.spiral_alt_base = None; + self.before_drag = None; if std::mem::take(&mut self.began) { vec![Action::Commit] } else { vec![Action::Dialog(self.id.into(), json!({"x": s.x, "y": s.y}))] } } _ => vec![], @@ -364,6 +410,9 @@ impl Tool for FamilyTool { self.began = false; self.spiral_end = None; self.spiral_alt_base = None; + if let Some(o) = self.before_drag.take() { + self.restore_drag_options(o); + } self.snap.clear(); vec![Action::Cancel] } else { @@ -442,6 +491,23 @@ impl Tool for FamilyTool { "height" => self.grid_size.1 = grid_length(v, self.grid_size.1), _ => {} } + // An option set while a shape is dragged out stays when Escape cancels the drag; a value + // the match above ignores leaves the drag's starting value as it was. + if let Some(b) = self.before_drag.as_mut() { + let finite = v.as_f64().is_some_and(f64::is_finite); + match key { + "slope" if finite => b.slope = self.slope, + "closed" if v.is_boolean() => b.closed = self.closed, + "baseAlong" if v.is_string() => b.base_along = self.base_along, + "decay" if v.as_f64().is_some() => b.decay = self.decay, + "segments" => b.segments = self.segments, + "rows" | "concentric" => b.rows = self.rows, + "columns" | "radial" => b.columns = self.columns, + "rowSkew" | "concentricSkew" if finite => b.skew[0] = self.skew[0], + "columnSkew" | "radialSkew" if finite => b.skew[1] = self.skew[1], + _ => {} + } + } } } @@ -672,7 +738,8 @@ mod tests { } /// Switching between Alt and Ctrl/Cmd keeps the held inner end and uses the current segment - /// count when Alt resumes. Escape clears the held end before the next drag. + /// count when Alt resumes. Escape clears the held end and puts back the segments and decay + /// from before the drag. #[test] fn spiral_drag_switches_between_alt_and_ctrl_and_escape_lets_go_of_the_inner_end() { let (d, _) = doc_with_rect(); @@ -699,9 +766,125 @@ mod tests { t.key(&cx, ToolKey::Escape, alt); assert_eq!(t.spiral_end, None); assert_eq!(t.spiral_alt_base, None); + assert_eq!((t.segments, t.decay), (10, 80.0), "the options from before the drag"); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 100.0).with_mods(alt)); - assert_eq!(t.segments, 18, "a new drag holds a new inner end"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 100.0).with_mods(alt)); + assert_eq!(t.segments, 14, "a new drag holds a new inner end"); + } + + /// Escape during a drag puts back every option the drag's keys changed, for the next drag and + /// the tool's options; a drag that is let go keeps them. + #[test] + fn escape_puts_back_the_options_a_drag_changed() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let keys = |id: &str| -> Vec { + match id { + "arc" => vec![ToolKey::Up, ToolKey::Letter('c'), ToolKey::Letter('f')], + "spiral" => vec![ToolKey::Up], + _ => vec![ToolKey::Up, ToolKey::Right, ToolKey::Letter('v'), ToolKey::Letter('c')], + } + }; + let arc_and_spiral = ["slope", "closed", "baseAlong", "segments", "decay"]; + let grids = ["rows", "columns", "concentric", "radial", "rowSkew", "columnSkew", "concentricSkew", "radialSkew"]; + let pick = |v: &Value| arc_and_spiral.iter().chain(&grids).filter_map(|f| v.get(*f).map(|x| (*f, x.clone()))).collect::>(); + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let mut t = FamilyTool::new(id); + let preview = |a: Vec| match a.last() { + Some(Action::Preview(_, v)) => v.clone(), + _ => panic!("{id}: {a:?}"), + }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let before = pick(&preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)))); + let options = t.options(); + let mut changed = before.clone(); + for k in keys(id) { + changed = pick(&preview(t.key(&cx, k, Mods::default()))); + } + assert_ne!(changed, before, "{id}: the keys change the options"); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{id}"); + assert_eq!(t.options(), options, "{id}: the tool's options"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let next = pick(&preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)))); + assert_eq!(next, before, "{id}: the next drag"); + // A drag that is let go keeps what its keys changed. + for k in keys(id) { + t.key(&cx, k, Mods::default()); + } + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 60.0, 40.0)), vec![Action::Commit]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let kept = pick(&preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)))); + assert_eq!(kept, changed, "{id}: a finished drag keeps them"); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert_eq!(pick(&t.options()), changed, "{id}: Escape puts back only what this drag changed"); + } + } + + /// Alt and Ctrl/Cmd change a spiral's segments and decay as it is dragged out; Escape puts + /// both back. + #[test] + fn escape_puts_back_the_spiral_decay_and_segments_alt_and_ctrl_changed() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let alt = Mods { alt: true, ..Mods::default() }; + let ctrl = Mods { cmd: true, ..Mods::default() }; + let mut t = FamilyTool::new("spiral"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 100.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 100.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 100.0).with_mods(ctrl)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 100.0).with_mods(ctrl)); + assert!(t.segments != 10 && t.decay != 80.0, "{} {}", t.segments, t.decay); + t.key(&cx, ToolKey::Escape, ctrl); + assert_eq!((t.segments, t.decay), (10, 80.0)); + } + + /// An option set while a shape is dragged out (`tool.setOption`) stays when Escape cancels + /// the drag; the options only the drag's keys changed go back. + #[test] + fn escape_keeps_an_option_set_during_the_drag() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let mut t = FamilyTool::new("rectangularGrid"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)); + t.key(&cx, ToolKey::Up, Mods::default()); + t.key(&cx, ToolKey::Right, Mods::default()); + t.set_option("columns", &json!(9)); + t.set_option("rowSkew", &json!(30.0)); + t.key(&cx, ToolKey::Escape, Mods::default()); + let o = t.options(); + assert_eq!((o["rows"].clone(), o["columns"].clone(), o["rowSkew"].clone()), (json!(5), json!(9), json!(30.0))); + let mut t = FamilyTool::new("arc"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)); + t.key(&cx, ToolKey::Letter('c'), Mods::default()); + t.set_option("slope", &json!(-20.0)); + t.key(&cx, ToolKey::Escape, Mods::default()); + let o = t.options(); + assert_eq!((o["closed"].clone(), o["slope"].clone()), (json!(false), json!(-20.0))); + // A value the option ignores leaves the starting value for Escape. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)); + t.key(&cx, ToolKey::Up, Mods::default()); + t.key(&cx, ToolKey::Letter('c'), Mods::default()); + t.key(&cx, ToolKey::Letter('f'), Mods::default()); + for (k, v) in [("slope", json!("steep")), ("closed", json!(1)), ("baseAlong", json!(null))] { + t.set_option(k, &v); + } + t.key(&cx, ToolKey::Escape, Mods::default()); + let o = t.options(); + assert_eq!((o["slope"].clone(), o["closed"].clone(), o["baseAlong"].clone()), (json!(-20.0), json!(false), json!("x"))); } /// Alt adjusts the segment count in whole winds while keeping it within 2 to 1000. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3955c28c4a..58cac25d7f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -839,6 +839,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While a grid is dragged out, F lowers `rowSkew` (rectangular) or `radialSkew` (polar) by 10 percentage points and V raises it by 10; X lowers `columnSkew` (rectangular) or `concentricSkew` (polar) by 10 and C raises it by 10. Plain and Shift presses work; with Alt, Ctrl or Cmd held they do not, as for the other letters a tool takes while dragging. Each press changes the skew once and updates the preview; values stay within ±500% and remain in the tool options after release. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list the four drag keys and a 10% change. The signs (positive values follow VectorCraft's existing skew convention, so F and X lower the stored value) and one change per press with key repeat ignored are our own rules. While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules. While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. + Escape while an arc, spiral or grid is dragged out cancels it and puts back the options its keys, Alt and Ctrl/Cmd changed (slope, open or closed, base axis, segments, decay, dividers and skews), so the next drag and the tool's options start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle.