From 7dc66d660a369afe94bce3d3862a88863bc0d1a3 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:24:08 +0530 Subject: [PATCH 001/105] Fix #5526: select images by link status Selection Tools add-on: addon.select.byLinkStatus selects the image objects and placed documents whose link is linked, embedded, missing or modified (one status or several), as links.list reports it. Optional ids limit the search, add adds to the selection, and zoom runs the existing Zoom to Selection in the desktop app. Objects that are hidden, locked, on a template layer or outside the isolated group are left out and returned with the reason. Only the selection changes. Select Linked / Embedded / Missing / Modified are in Object > Plug-ins > Selection Tools and the Links panel menu. Each is off when no image has that status, and Shift adds to the selection. Select by Link Status... lists the images with name, status and format, with a name search, a status filter, checkboxes with All / None and Zoom to Selection. The status bar says what was selected and how many were left out, with plural rows in every catalog. Tests: engine (statuses, ids, add, zoom, skip reasons, bad params), command sweep, and UI (message, list filtering, menu items, Links panel menu, headless dialog frame). Docs: mcp, target-app-parity, ui-parity, roadmap. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/addons/select.rs | 156 +++++++++- crates/engine/src/cmd/addons/select/tests.rs | 176 +++++++++++ crates/engine/src/cmd/links.rs | 2 +- crates/engine/tests/command_sweep.rs | 4 + crates/ui-egui/src/addons/select.rs | 9 +- .../ui-egui/src/addons/select/link_status.rs | 286 ++++++++++++++++++ .../src/addons/select/link_status/tests.rs | 199 ++++++++++++ crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 19 ++ crates/ui-egui/src/i18n/bs.tsv | 19 ++ crates/ui-egui/src/i18n/ca.tsv | 19 ++ crates/ui-egui/src/i18n/cs.tsv | 19 ++ crates/ui-egui/src/i18n/da.tsv | 19 ++ crates/ui-egui/src/i18n/de.tsv | 19 ++ crates/ui-egui/src/i18n/el.tsv | 19 ++ crates/ui-egui/src/i18n/es.tsv | 19 ++ crates/ui-egui/src/i18n/fi.tsv | 19 ++ crates/ui-egui/src/i18n/fr.tsv | 19 ++ crates/ui-egui/src/i18n/hu.tsv | 19 ++ crates/ui-egui/src/i18n/id.tsv | 19 ++ crates/ui-egui/src/i18n/it.tsv | 19 ++ crates/ui-egui/src/i18n/ja.tsv | 19 ++ crates/ui-egui/src/i18n/ka.tsv | 19 ++ crates/ui-egui/src/i18n/ko.tsv | 19 ++ crates/ui-egui/src/i18n/nl.tsv | 19 ++ crates/ui-egui/src/i18n/pl.tsv | 19 ++ crates/ui-egui/src/i18n/pt-br.tsv | 19 ++ crates/ui-egui/src/i18n/ru.tsv | 19 ++ crates/ui-egui/src/i18n/sv.tsv | 19 ++ crates/ui-egui/src/i18n/tr.tsv | 19 ++ crates/ui-egui/src/i18n/uk.tsv | 19 ++ crates/ui-egui/src/i18n/vi.tsv | 19 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 19 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 19 ++ crates/ui-egui/src/menus.rs | 2 + crates/ui-egui/src/menus/invoke.rs | 7 +- crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/panels/links.rs | 14 +- crates/ui-egui/src/state.rs | 6 + docs/mcp.md | 24 ++ docs/roadmap.md | 3 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 45 files changed, 1370 insertions(+), 25 deletions(-) create mode 100644 crates/ui-egui/src/addons/select/link_status.rs create mode 100644 crates/ui-egui/src/addons/select/link_status/tests.rs diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index ce2869abca..4d71895c01 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -1,31 +1,51 @@ //! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects -//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu -//! (Object › Plug-ins › Selection Tools) and dialog are the UI's. +//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by +//! Link Status selects the images and placed documents whose file is linked, embedded, missing or +//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins +//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. #[cfg(test)] mod tests; +use std::collections::BTreeSet; + use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_geom::Point; -use super::super::select::{on_artboard, selectable}; -use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param}; -use crate::{Result, Session}; +use super::super::links::{Status, statuses}; +use super::super::select::{is_selectable, on_artboard, selectable}; +use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param}; +use crate::{DocState, Result, Session}; /// How Select by Artboards relates an object to the chosen artboards (`relation`). pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"]; +/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept +/// in the document, a file not found, a file changed since it was read. +pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"]; + pub fn specs() -> Vec { - vec![cmd!( - "addon.select.byArtboards", - "Select by Artboards", - ["Object", "Plug-ins", "Selection Tools"], - None, - "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", - has_doc, - by_artboards - )] + vec![ + cmd!( + "addon.select.byArtboards", + "Select by Artboards", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + has_doc, + by_artboards + ), + cmd!( + "addon.select.byLinkStatus", + "Select by Link Status", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}", + has_doc, + by_link_status + ), + ] } fn by_artboards(s: &mut Session, p: &Value) -> Result { @@ -61,3 +81,109 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result { s.select(|_, sel| sel.set(ids))?; Ok(json!({ "count": s.doc()?.selection.objects.len() })) } + +/// The link statuses `p` asks for (`status`: one, or a list of them), each once. +fn link_statuses(p: &Value, cmd: &str) -> Result> { + let given: Vec<&Value> = match p.get("status") { + None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")), + Some(Value::Array(v)) => v.iter().collect(), + Some(v) => vec![v], + }; + let mut out = vec![]; + for v in given { + let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?; + let known = + LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?; + if !out.contains(known) { + out.push(*known); + } + } + if out.is_empty() { + return Err(bad(cmd, "choose at least one status")); + } + Ok(out) +} + +/// The link status of every image object and placed document in the layers of `st`, as +/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is +/// looked at once. +pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> { + let linked = statuses(st); + let mut out = vec![]; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { + let status = match linked.get(&n.id).map(|(s, ..)| *s) { + Some(Status::Ok) => "linked", + Some(Status::Modified) => "modified", + Some(Status::Missing) => "missing", + None => "embedded", + }; + out.push((n.id, status)); + } + }); + out +} + +/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated +/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside +/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's +/// [`vectorcraft_doc::Document::locked_artboards`]. +fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> { + let d = &st.doc; + if is_selectable(d, st.isolation, locks, id) { + return None; + } + let ancestry = d.ancestry(id).unwrap_or_default(); + // Outside the isolated container, or the isolated container itself (its art is what's taken). + if let Some(c) = st.isolation.and_then(|i| d.node(i)) + && ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container()) + { + return Some("isolation"); + } + let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect(); + Some(if held.iter().any(|n| n.is_template()) { + "template" + } else if held.iter().any(|n| !n.visible) { + "hidden" + } else { + // A locked object, group or layer, or the locked artboard that holds it. + "locked" + }) +} + +fn by_link_status(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.byLinkStatus"; + let wanted = link_statuses(p, C)?; + let add = switch_or(p, "add", false, C)?; + let zoom = switch_or(p, "zoom", false, C)?; + let only: Option> = match p.get("ids") { + None | Some(Value::Null) => None, + Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()), + }; + let st = s.doc()?; + let locks = st.doc.locked_artboards(); + let (mut picked, mut skipped) = (vec![], vec![]); + for (id, status) in link_status_of_objects(st) { + if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) { + continue; + } + match skip_reason(st, &locks, id) { + None => picked.push(id), + Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })), + } + } + s.select(|_, sel| { + if add { + for id in &picked { + sel.add(*id); + } + } else { + sel.set(picked.iter().copied()); + } + })?; + let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::>(), "skipped": skipped }); + if zoom { + out["zoom"] = json!(true); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index bea05ff9e2..ca59565261 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -126,3 +126,179 @@ fn a_symbol_instance_is_measured_by_its_art() { assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]); assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]); } + +/// Select by Link Status. +mod by_link_status { + use serde_json::{Value, json}; + use vectorcraft_doc::{Document, NodeId}; + + use crate::Session; + use crate::tests_links::{BLUE, Folder, RED, place, png, session, write}; + + const C: &str = "addon.select.byLinkStatus"; + + /// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`), + /// one whose file goes (`missing`), an embedded one, and a placed document whose file goes + /// (missing too), bottom to top. + struct Links { + s: Session, + ok: NodeId, + modified: NodeId, + missing: NodeId, + embedded: NodeId, + document: NodeId, + _dir: Folder, + } + + fn links(name: &str) -> Links { + let dir = Folder::new(name); + let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft")); + write(&a, &png(10, 10, RED)); + write(&b, &png(12, 10, RED)); + write(&c, &png(14, 10, BLUE)); + write(&e, &png(16, 10, BLUE)); + write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0))); + let mut s = session(); + let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c)); + let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap()); + let document = place(&mut s, &d); + write(&b, &png(13, 10, BLUE)); + std::fs::remove_file(&c).unwrap(); + std::fs::remove_file(&d).unwrap(); + Links { s, ok, modified, missing, embedded, document, _dir: dir } + } + + fn run(s: &mut Session, p: Value) -> Value { + s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}")) + } + + fn sorted(mut v: Vec) -> Vec { + v.sort(); + v + } + + fn selection(s: &Session) -> Vec { + sorted(s.doc().unwrap().selection.objects.clone()) + } + + fn ids(v: &Value) -> Vec { + sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()) + } + + #[test] + fn each_status_selects_its_images_and_placed_documents() { + let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status"); + // As the Links panel lists them. + let listed = s.execute("links.list", &json!({})).unwrap(); + let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone(); + assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s))); + let undo = s.doc().unwrap().history.undo.len(); + for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])] + { + s.execute("select.none", &json!({})).unwrap(); + let r = run(&mut s, json!({"status": status})); + assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}"); + assert_eq!(selection(&s), sorted(want), "{status}"); + assert_eq!(r["skipped"], json!([])); + assert!(r.get("zoom").is_none()); + } + // Several at once, in stacking order (bottom first); a status listed twice counts once. + let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]})); + assert_eq!(r["selected"], json!([ok.0, missing.0, document.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn ids_add_and_zoom() { + let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options"); + // Only among the ids given; other objects among them (a rectangle) are passed over. + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap(); + let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]})); + assert_eq!(r["selected"], json!([document.0])); + assert_eq!(selection(&s), vec![document]); + // Added to the selection. + let r = run(&mut s, json!({"status": "embedded", "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0]))); + assert_eq!(selection(&s), sorted(vec![document, embedded])); + // Replacing it by default. + run(&mut s, json!({"status": "modified"})); + assert_eq!(selection(&s), vec![modified]); + // Nothing to select: added, the selection stays; replacing, it empties. + let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([]))); + assert_eq!(selection(&s), vec![modified]); + run(&mut s, json!({"status": "linked", "ids": [embedded.0]})); + assert_eq!(selection(&s), vec![]); + // Zoom is reported for the caller (the desktop app zooms). + assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true); + assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none()); + } + + #[test] + fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() { + let dir = Folder::new("select-skipped"); + let files: Vec = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect(); + for (i, f) in files.iter().enumerate() { + write(f, &png(10 + i as u32, 10, RED)); + } + let mut s = session(); + let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i])); + s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap(); + // Inside a locked group. + s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + // On a template layer. + let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap(); + let on_template = place(&mut s, &files[5]); + s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}"); + let mut reasons: Vec<(u64, String)> = + r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect(); + reasons.sort(); + let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")] + .into_iter() + .map(|(id, why)| (id.0, why.to_string())) + .collect(); + want.sort(); + assert_eq!(reasons, want, "{r}"); + assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str()))); + // In isolation mode, those outside the isolated group are left out. + s.execute("select.set", &json!({"ids": [mate.0]})).unwrap(); + let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": iso})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(r["selected"], json!([mate.0]), "{r}"); + let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone()); + assert_eq!(why(free), Some(json!("isolation"))); + assert_eq!(why(hidden), Some(json!("isolation"))); + } + + #[test] + fn bad_params_are_errors_and_leave_the_selection() { + let Links { mut s, ok, _dir, .. } = links("select-bad"); + for p in [ + json!({}), + json!({"status": null}), + json!({"status": []}), + json!({"status": "lost"}), + json!({"status": ["linked", "lost"]}), + json!({"status": 3}), + json!({"status": [true]}), + json!({"status": "linked", "add": "yes"}), + json!({"status": "linked", "zoom": 1}), + json!({"status": "linked", "ids": "1"}), + json!({"status": "linked", "ids": [999_999]}), + json!({"status": "linked", "ids": [-1]}), + json!({"status": "linked", "stauts": "missing"}), + ] { + s.execute("select.set", &json!({"ids": [ok.0]})).unwrap(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}"); + } + // Without a document it is off, not a crash. + assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); + } +} diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 441249b05b..842d78b56c 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1110,7 +1110,7 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { /// Per linked image in the layers of `st`: its file's status, where it was found when away from /// its path, and whether the image shows its preview (each file probed once). -fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { +pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { let mut out = BTreeMap::new(); for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) { let (status, found) = probe(g, st.path.as_deref()); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b8b360b804..42970aa160 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -239,6 +239,10 @@ fn structured_junk() { ("addon.select.byArtboards", json!({"artboards": [0, u64::MAX, -1, "x", null, 1.5], "relation": "inside"})), ("addon.select.byArtboards", json!({"artboards": [1e308], "relation": [1]})), ("addon.select.byArtboards", json!({"artboards": {"a": 1}, "relation": "outside"})), + ("addon.select.byLinkStatus", json!({"status": ["linked", "missing", null, 7, {"a": 1}], "ids": [2, u64::MAX, -1, "x", 1.5]})), + ("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})), + ("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})), + ("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})), ("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})), ("object.transform", json!({"matrix": [1e308, 1e308, 1e308, 1e308, 1e308, 1e308]})), ("object.transform", json!({"matrix": [1, 2, 3]})), diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 8f6b258269..c61eb0537d 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -1,7 +1,8 @@ //! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the //! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, //! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK -//! runs `addon.select.byArtboards` with the relation chosen. +//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status +//! ([`link_status`], #5526). use egui::{Sense, Ui, vec2}; use serde_json::{Value, json}; @@ -13,6 +14,8 @@ use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; +pub mod link_status; + /// Select by Artboards, and its dialog's kind. pub const COMMAND: &str = "addon.select.byArtboards"; pub const KIND: &str = "selectByArtboards"; @@ -25,7 +28,9 @@ const LIST_H: f32 = 220.0; /// Object › Plug-ins › Selection Tools. pub fn menu() -> Vec { - vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null)] + let mut v = vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null), Item::Sep]; + v.extend(link_status::menu()); + v } /// The dialog's fields to start with: the active artboard chosen, Overlapping. diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs new file mode 100644 index 0000000000..7b7203276c --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -0,0 +1,286 @@ +//! Select by Link Status in the interface (#5526): Select Linked, Embedded, Missing and Modified +//! (in Object › Plug-ins › Selection Tools and the Links panel's menu; Shift adds to the +//! selection), the Select by Link Status dialog, and the status bar's line saying what was +//! selected and what was left out. Everything goes through `addon.select.byLinkStatus`; the dialog +//! lists what `links.list` reports. + +use egui::{Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets; + +/// Select by Link Status, and its dialog's kind. +pub const COMMAND: &str = "addon.select.byLinkStatus"; +pub const KIND: &str = "selectByLinkStatus"; +/// The statuses, as the command names them, with their menu items' and the dialog's labels. +pub const STATUSES: [(&str, &str, &str); 4] = [ + ("linked", "Select Linked", "Linked"), + ("embedded", "Select Embedded", "Embedded"), + ("missing", "Select Missing", "Missing"), + ("modified", "Select Modified", "Modified"), +]; +/// The dialog's Show choices: (value, label). +const SHOW: [(&str, &str); 5] = [("all", "All"), ("linked", "Linked"), ("embedded", "Embedded"), ("missing", "Missing"), ("modified", "Modified")]; +/// How often the statuses are looked at again while the document stays as it is (s): files +/// change on disk without the document knowing. +const RECHECK: f64 = 2.0; +/// The least time between two looks while the document keeps changing (s). +const SETTLE: f64 = 0.5; +const ROW_H: f32 = 22.0; +const LIST_H: f32 = 240.0; +const STATUS_W: f32 = 80.0; +const FORMAT_W: f32 = 70.0; + +/// The menu items: one per status, then the dialog. +pub fn menu() -> Vec { + let mut v: Vec = STATUSES.iter().map(|&(status, label, _)| Item::Cmd(label, COMMAND, json!({ "status": status }))).collect(); + v.push(Item::Cmd("Select by Link Status…", COMMAND, Value::Null)); + v +} + +/// Which statuses ([`STATUSES`] order) the active document's images and placed documents have, +/// for the document and revision it was read for and when. +#[derive(Clone, Debug, Default)] +pub struct Present { + key: Option<(u64, u64)>, + at: f64, + pub has: [bool; 4], +} + +/// The statuses the `links.list` result `list` holds, in [`STATUSES`] order. +pub(crate) fn statuses_in(list: &Value) -> [bool; 4] { + let rows = list["links"].as_array().map_or(&[][..], Vec::as_slice); + STATUSES.map(|(status, ..)| rows.iter().any(|r| command_status(r) == status)) +} + +/// The status of a `links.list` row as the command names it (`ok` is `linked`). +fn command_status(row: &Value) -> &str { + match row["status"].as_str().unwrap_or_default() { + "ok" => "linked", + s => s, + } +} + +/// Keep [`Present`] up to date: at once when another document comes to the front, at most every +/// [`SETTLE`] seconds while its revision changes (a drag changes it every frame, and each look +/// asks the file system about every linked file), and every [`RECHECK`] seconds while it has +/// linked files. +pub fn refresh(app: &mut VectorcraftApp, now: f64) { + let key = app.session.active().map(|st| (st.uid, st.revision)); + let p = &app.ui.link_statuses; + let linked = p.has.iter().zip(STATUSES).any(|(on, (status, ..))| *on && status != "embedded"); + let other_document = p.key.map(|k| k.0) != key.map(|k| k.0); + let due = if p.key == key { linked && now - p.at >= RECHECK } else { other_document || now - p.at >= SETTLE }; + if !due { + return; + } + let has = if key.is_some() { app.session.execute("links.list", &json!({})).map(|l| statuses_in(&l)).unwrap_or_default() } else { [false; 4] }; + app.ui.link_statuses = Present { key, at: now, has }; +} + +/// Is menu item `status` (a [`STATUSES`] value) on: does an image or placed document have it? +pub(crate) fn enabled(app: &VectorcraftApp, p: &Value) -> bool { + let Some(status) = p.get("status").and_then(Value::as_str) else { return true }; + STATUSES.iter().position(|(s, ..)| *s == status).and_then(|i| app.ui.link_statuses.has.get(i).copied()).unwrap_or(false) +} + +/// A menu item's params with Shift held: add to the selection. +pub(crate) fn with_shift(mut p: Value) -> Value { + if let Some(o) = p.as_object_mut() + && o.contains_key("status") + { + o.insert("add".into(), json!(true)); + } + p +} + +/// Run the command; with `zoom` and something selected, Zoom to Selection; the status bar says +/// what was selected and what was left out. Without params (the menu's "Select by Link Status…") +/// it opens the dialog instead. +pub(crate) fn run(app: &mut VectorcraftApp, p: &Value) -> Result { + if p.as_object().is_none_or(serde_json::Map::is_empty) { + if app.session.active().is_none() { + return Err("no document".into()); + } + let fields = fields(app); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + return Ok(json!({ "dialog": KIND })); + } + let r = app.session.execute(COMMAND, p).map_err(|e| e.to_string())?; + let count = r["count"].as_u64().unwrap_or(0); + if r["zoom"] == true && count > 0 { + crate::addons::arrange::zoom(app)?; + } + let statuses: Vec<&str> = match &p["status"] { + Value::Array(v) => v.iter().filter_map(Value::as_str).collect(), + v => v.as_str().into_iter().collect(), + }; + let reasons: Vec<&str> = r["skipped"].as_array().map_or(vec![], |v| v.iter().filter_map(|k| k["reason"].as_str()).collect()); + app.status(message(&statuses, count, &reasons)); + Ok(r) +} + +/// The status bar's line: `count` objects of `statuses` selected, and the `reasons` the others +/// were left out for (e.g. "Selected 9 missing images; 3 more are hidden or locked"). +pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String { + let n = count; + let selected = match statuses { + ["linked"] => crate::i18n::msg_n(n, "Selected {n} linked image", "Selected {n} linked images", &[]), + ["embedded"] => crate::i18n::msg_n(n, "Selected {n} embedded image", "Selected {n} embedded images", &[]), + ["missing"] => crate::i18n::msg_n(n, "Selected {n} missing image", "Selected {n} missing images", &[]), + ["modified"] => crate::i18n::msg_n(n, "Selected {n} modified image", "Selected {n} modified images", &[]), + _ => crate::i18n::msg_n(n, "Selected {n} image", "Selected {n} images", &[]), + }; + let Some(first) = reasons.first() else { return selected }; + // Hidden and locked go together; a template layer, or the isolated group, alone. + fn kind(r: &str) -> &str { + match r { + "hidden" | "locked" => "locked", + r => r, + } + } + let (one, other) = match kind(first) { + k if reasons.iter().any(|r| kind(r) != k) => ("{selected}; {n} more can't be selected now", "{selected}; {n} more can't be selected now"), + "template" => ("{selected}; {n} more is on a template layer", "{selected}; {n} more are on template layers"), + "isolation" => ("{selected}; {n} more is outside the isolated group", "{selected}; {n} more are outside the isolated group"), + _ => ("{selected}; {n} more is hidden or locked", "{selected}; {n} more are hidden or locked"), + }; + crate::i18n::msg_n(reasons.len() as u64, one, other, &[("selected", &selected)]) +} + +/// The dialog's fields to start with: every image and placed document (`__rows`, as `links.list` +/// lists them, read once), those selected chosen, All shown, Zoom to Selection on. +pub(crate) fn fields(app: &mut VectorcraftApp) -> Value { + let list = app.session.execute("links.list", &json!({})).unwrap_or_default(); + let rows: Vec = list["links"].as_array().cloned().unwrap_or_default(); + let selected: Vec = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); + let chosen: Vec = rows.iter().filter_map(|r| r["id"].as_u64()).filter(|id| selected.contains(id)).collect(); + json!({ "__rows": rows, "ids": chosen, "show": "all", "zoom": true }) +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Select by Link Status").to_string(), + body, + confirm, + ok: Some("Select"), + min_width: 420.0, + max_width: Some(480.0), + ok_enabled: Some(|_, d| !chosen(d).is_empty()), + ..DialogSpec::FORM +}; + +/// The ids chosen in dialog `d`. +pub(crate) fn chosen(d: &Dialog) -> Vec { + d.fields.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect() +} + +/// The rows of `rows` the name search `query` (ignoring case) and the Show choice `show` let through. +pub(crate) fn shown<'a>(rows: &'a [Value], query: &str, show: &str) -> Vec<&'a Value> { + let q = query.trim().to_lowercase(); + rows.iter() + .filter(|r| show == "all" || command_status(r) == show) + .filter(|r| q.is_empty() || r["name"].as_str().unwrap_or_default().to_lowercase().contains(&q)) + .collect() +} + +/// All (`on`) or None: choose every row `shown`, or none of them; rows the search or Show hides +/// keep their state. +pub(crate) fn choose_shown(chosen: &mut Vec, shown: &[u64], on: bool) { + if on { + for id in shown { + if !chosen.contains(id) { + chosen.push(*id); + } + } + } else { + chosen.retain(|id| !shown.contains(id)); + } +} + +/// Tick or untick row `id`. +pub(crate) fn toggle(chosen: &mut Vec, id: u64) { + match chosen.iter().position(|c| *c == id) { + Some(i) => { + chosen.remove(i); + } + None => chosen.push(id), + } +} + +/// A status's label in the list. +fn status_label(status: &str) -> &'static str { + STATUSES.iter().find(|(s, ..)| *s == status).map_or("", |&(.., label)| tl!(label)) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let rows: Vec = d.fields.get("__rows").and_then(Value::as_array).cloned().unwrap_or_default(); + let query = widgets::search_field(ui, ui.scope_id().with("select-by-link-status-search"), tl!("Search images")); + d.fields.insert("__search".into(), json!(query)); + ui.add_space(4.0); + form::choice(ui, d, "show", tl!("Show:"), (60.0, 140.0), &SHOW); + let show = d.str("show"); + let visible = shown(&rows, &query, &show); + let mut picked = chosen(d); + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(LIST_H).auto_shrink([false, true]).show(ui, |ui| { + if visible.is_empty() { + ui.label(egui::RichText::new(tl!("No images match.")).color(t.text_dim)); + } + for r in &visible { + let Some(id) = r["id"].as_u64() else { continue }; + let name = r["name"].as_str().unwrap_or_default(); + let status = status_label(command_status(r)); + let format = r["format"].as_str().unwrap_or_default(); + ui.horizontal(|ui| { + ui.set_min_height(ROW_H); + let on = picked.contains(&id); + let name_w = (ui.available_width() - STATUS_W - FORMAT_W - 40.0).max(60.0); + let check = ui.scope(|ui| { + ui.set_width(name_w + 24.0); + widgets::check_name(ui, name, on) + }); + if check.inner { + toggle(&mut picked, id); + } + ui.add_sized(vec2(STATUS_W, ROW_H), egui::Label::new(egui::RichText::new(status).color(t.text_dim)).truncate()); + ui.add_sized(vec2(FORMAT_W, ROW_H), egui::Label::new(egui::RichText::new(format).color(t.text_dim)).truncate()); + }); + } + }); + ui.add_space(4.0); + let ids: Vec = visible.iter().filter_map(|r| r["id"].as_u64()).collect(); + ui.horizontal(|ui| { + if widgets::flat_button_fit(ui, "All", 50.0).clicked() { + choose_shown(&mut picked, &ids, true); + } + if widgets::flat_button_fit(ui, "None", 50.0).clicked() { + choose_shown(&mut picked, &ids, false); + } + let count = crate::i18n::fmt(tl!("Chosen: {n} of {total}"), &[("n", &picked.len().to_string()), ("total", &rows.len().to_string())]); + ui.label(egui::RichText::new(count).color(t.text_dim)); + }); + d.fields.insert("ids".into(), json!(picked)); + ui.add_space(6.0); + form::check(ui, d, "zoom", tl!("Zoom to Selection")); + false +} + +/// The command's params for dialog `d`: the rows chosen, whatever their status. +pub(crate) fn params(d: &Dialog) -> Value { + json!({ "status": STATUSES.map(|(s, ..)| s), "ids": chosen(d), "zoom": d.bool("zoom") }) +} + +/// Select: select the rows chosen (and zoom to them) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + app.run(COMMAND, params(d)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs new file mode 100644 index 0000000000..22b07ccace --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -0,0 +1,199 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{COMMAND, KIND, choose_shown, message, refresh, shown, toggle}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// A fresh folder for one test (removed when dropped). +struct Folder(std::path::PathBuf); + +impl Folder { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-select-links-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + fn file(&self, name: &str, bytes: &[u8]) -> String { + let p = self.0.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn png(w: u32, h: u32) -> Vec { + let mut out = vec![]; + image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + out +} + +/// A document with `river.png` linked, `harbour.png` linked and then deleted (missing), and +/// `stamp.png` embedded → (app, river, harbour, stamp). +fn app(dir: &Folder) -> (VectorcraftApp, u64, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let place = |app: &mut VectorcraftApp, path: &str, at: [u32; 2], link: bool| { + app.run("file.place", json!({"path": path, "at": at, "link": link})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (a, b, c) = (dir.file("river.png", &png(40, 30)), dir.file("harbour.png", &png(30, 20)), dir.file("stamp.png", &png(20, 20))); + let river = place(&mut app, &a, [100, 100], true); + let harbour = place(&mut app, &b, [300, 100], true); + let stamp = place(&mut app, &c, [200, 220], false); + std::fs::remove_file(&b).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, river, harbour, stamp) +} + +fn selected(app: &VectorcraftApp) -> Vec { + let mut ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +#[test] +fn the_message_says_what_was_selected_and_what_was_left_out() { + assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images"); + assert_eq!(message(&["linked"], 1, &[]), "Selected 1 linked image"); + assert_eq!(message(&["embedded", "modified"], 2, &[]), "Selected 2 images"); + assert_eq!(message(&["missing"], 9, &["hidden", "locked", "hidden"]), "Selected 9 missing images; 3 more are hidden or locked"); + assert_eq!(message(&["modified"], 0, &["template"]), "Selected 0 modified images; 1 more is on a template layer"); + assert_eq!(message(&["embedded"], 2, &["isolation", "isolation"]), "Selected 2 embedded images; 2 more are outside the isolated group"); + assert_eq!(message(&["linked"], 1, &["isolation", "locked"]), "Selected 1 linked image; 2 more can't be selected now"); +} + +#[test] +fn the_list_filters_by_name_and_status_and_all_and_none_act_on_the_rows_shown() { + let rows = vec![ + json!({"id": 1, "name": "River.png", "status": "ok"}), + json!({"id": 2, "name": "harbour.png", "status": "missing"}), + json!({"id": 3, "name": "Stamp.png", "status": "embedded"}), + json!({"id": 4, "name": "river-2.tif", "status": "modified"}), + ]; + let ids = |v: Vec<&Value>| v.iter().map(|r| r["id"].as_u64().unwrap()).collect::>(); + assert_eq!(ids(shown(&rows, "", "all")), vec![1, 2, 3, 4]); + assert_eq!(ids(shown(&rows, " RIVER ", "all")), vec![1, 4]); + assert_eq!(ids(shown(&rows, "river", "linked")), vec![1], "ok is Linked"); + assert_eq!(ids(shown(&rows, "", "missing")), vec![2]); + assert_eq!(ids(shown(&rows, "zzz", "all")), Vec::::new()); + // Row 3 is chosen but hidden: neither All nor None touches it. + let mut c = vec![3]; + choose_shown(&mut c, &[1, 4], true); + assert_eq!(c, vec![3, 1, 4]); + choose_shown(&mut c, &[1, 4], false); + assert_eq!(c, vec![3]); + toggle(&mut c, 2); + toggle(&mut c, 3); + assert_eq!(c, vec![2]); +} + +#[test] +fn menu_items_are_on_for_the_statuses_present_and_shift_adds() { + let dir = Folder::new("menu"); + let (mut app, river, harbour, stamp) = app(&dir); + refresh(&mut app, 0.0); + let entries = menus::menu_entries(&app); + let item = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap(); + for (label, on) in + [("Select Linked", true), ("Select Embedded", true), ("Select Missing", true), ("Select Modified", false), ("Select by Link Status…", true)] + { + assert_eq!(item(label).enabled, on, "{label}"); + } + let run = |app: &mut VectorcraftApp, label: &str, shift: bool| { + let e = item(label); + let target = menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE }; + let (cmd, p) = menus::with_held_keys(target, held); + menus::invoke(app, &cmd, p); + }; + run(&mut app, "Select Missing", false); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.ui.status, "Selected 1 missing image"); + run(&mut app, "Select Embedded", true); + assert_eq!(selected(&app), vec![harbour, stamp], "Shift adds"); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), vec![river], "without Shift it replaces"); + // A hidden image is left out, and the status bar says so. + app.run("object.setProps", json!({"ids": [river], "visible": false})).unwrap(); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), Vec::::new()); + assert_eq!(app.ui.status, "Selected 0 linked images; 1 more is hidden or locked"); + // The document changes: the items follow on the next refresh. + app.run("select.set", json!({"ids": [harbour]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + refresh(&mut app, 1.0); + let entries = menus::menu_entries(&app); + let on = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap().enabled; + assert!(!on("Select Missing")); + assert!(on("Select Embedded")); +} + +#[test] +fn the_links_panel_menu_lists_the_select_items() { + let dir = Folder::new("flyout"); + let (mut app, ..) = app(&dir); + refresh(&mut app, 0.0); + let shown = painted_text(&mut app, crate::panels::links::menu); + for s in ["Select Linked", "Select Embedded", "Select Missing", "Select Modified"] { + assert!(shown.contains(s), "{s} in {shown}"); + } +} + +#[test] +fn the_dialog_lists_filters_and_selects_with_zoom() { + let dir = Folder::new("dialog"); + let (mut app, river, harbour, stamp) = app(&dir); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(560.0, 460.0))); + let zoom_before = app.view().unwrap().zoom; + menus::invoke(&mut app, COMMAND, Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["zoom"], &d.fields["show"]), (KIND, &json!(true), &json!("all"))); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in [ + "Select by Link Status", + "river.png", + "harbour.png", + "stamp.png", + "Linked", + "Missing", + "Embedded", + "PNG", + "Zoom to Selection", + "Chosen: 0 of 3", + "All", + "None", + "Select", + ] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert!(!(super::SPEC.ok_enabled.unwrap())(&app, app.ui.dialog.as_ref().unwrap()), "Select is off with nothing chosen"); + // Show: Missing lists only the missing image. + app.ui.dialog.as_mut().unwrap().fields.insert("show".into(), json!("missing")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("harbour.png") && !shown.contains("river.png") && !shown.contains("stamp.png"), "{shown}"); + // Choose two and Select: they are selected and the view zooms to them. + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([river, stamp])); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(selected(&app), vec![river, stamp]); + assert_eq!(app.ui.status, "Selected 2 images"); + assert_ne!(app.view().unwrap().zoom, zoom_before, "zoomed to the selection"); + // Without Zoom to Selection the view stays. + menus::invoke(&mut app, COMMAND, Value::Null); + let zoom = app.view().unwrap().zoom; + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([harbour])); + d.fields.insert("zoom".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.view().unwrap().zoom, zoom); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index eb9c3526e1..7a8e99409f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -314,6 +314,7 @@ impl VectorcraftApp { placing::poll(self); #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); + crate::addons::select::link_status::refresh(self, now); if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() || !self.plugin_runs.running.is_empty() diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2a90425c1f..c0f900f67c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -422,6 +422,7 @@ registry! { SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, SelectByArtboards: [crate::addons::select::KIND] => crate::addons::select::SPEC, + SelectByLinkStatus: [crate::addons::select::link_status::KIND] => crate::addons::select::link_status::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 07c4f90d9f..5c297aeb28 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6215,6 +6215,25 @@ breakText Glyphs Глифи Minimum angle Минимален ъгъл Maximum angle Максимален ъгъл +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Избиране на свързаните + Select Embedded Избиране на вградените + Select Missing Избиране на липсващите + Select Modified Избиране на модифицираните + Select by Link Status Избиране по състояние на връзката + Select by Link Status… Избиране по състояние на връзката… + Search images Търсене на изображения + No images match. Няма съвпадащи изображения. +@msgplural Selected {n} linked image|Selected {n} linked images Избрано е {n} свързано изображение|Избрани са {n} свързани изображения +@msgplural Selected {n} embedded image|Selected {n} embedded images Избрано е {n} вградено изображение|Избрани са {n} вградени изображения +@msgplural Selected {n} missing image|Selected {n} missing images Избрано е {n} липсващо изображение|Избрани са {n} липсващи изображения +@msgplural Selected {n} modified image|Selected {n} modified images Избрано е {n} модифицирано изображение|Избрани са {n} модифицирани изображения +@msgplural Selected {n} image|Selected {n} images Избрано е {n} изображение|Избрани са {n} изображения +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; още {n} е скрито или заключено|{selected}; още {n} са скрити или заключени +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; още {n} е в шаблонен слой|{selected}; още {n} са в шаблонни слоеве +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; още {n} е извън изолираната група|{selected}; още {n} са извън изолираната група +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; още {n} не може да бъде избрано сега|{selected}; още {n} не могат да бъдат избрани сега + # Compound Shapes add-on Compound Shapes Съставни фигури Shape Mode Buttons Make Compound Shapes Бутоните за режими на фигури създават съставни фигури diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d007b68291..12b748971d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6250,6 +6250,25 @@ shape Open Otvoren Minimum angle Najmanji ugao Maximum angle Najveći ugao +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Odaberi povezane + Select Embedded Odaberi ugrađene + Select Missing Odaberi nedostajuće + Select Modified Odaberi izmijenjene + Select by Link Status Odabir po statusu veze + Select by Link Status… Odabir po statusu veze… + Search images Pretraži slike + No images match. Nijedna slika ne odgovara. +@msgplural Selected {n} linked image|Selected {n} linked images Odabrana je {n} povezana slika|Odabrane su {n} povezane slike|Odabrano je {n} povezanih slika +@msgplural Selected {n} embedded image|Selected {n} embedded images Odabrana je {n} ugrađena slika|Odabrane su {n} ugrađene slike|Odabrano je {n} ugrađenih slika +@msgplural Selected {n} missing image|Selected {n} missing images Odabrana je {n} nedostajuća slika|Odabrane su {n} nedostajuće slike|Odabrano je {n} nedostajućih slika +@msgplural Selected {n} modified image|Selected {n} modified images Odabrana je {n} izmijenjena slika|Odabrane su {n} izmijenjene slike|Odabrano je {n} izmijenjenih slika +@msgplural Selected {n} image|Selected {n} images Odabrana je {n} slika|Odabrane su {n} slike|Odabrano je {n} slika +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; još {n} je skrivena ili zaključana|{selected}; još {n} su skrivene ili zaključane|{selected}; još {n} je skriveno ili zaključano +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; još {n} je na sloju predloška|{selected}; još {n} su na slojevima predloška|{selected}; još {n} je na slojevima predloška +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; još {n} je izvan izolirane grupe|{selected}; još {n} su izvan izolirane grupe|{selected}; još {n} je izvan izolirane grupe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; još {n} se sada ne može odabrati|{selected}; još {n} se sada ne mogu odabrati|{selected}; još {n} se sada ne može odabrati + # Compound Shapes add-on Compound Shapes Složeni oblici Shape Mode Buttons Make Compound Shapes Tasteri načina oblika prave složene oblike diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 34988b565f..d68f2a5bce 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6351,6 +6351,25 @@ breakText Glyphs Glifs Minimum angle Angle mínim Maximum angle Angle màxim +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecciona les enllaçades + Select Embedded Selecciona les incrustades + Select Missing Selecciona les que falten + Select Modified Selecciona les modificades + Select by Link Status Selecciona per estat de l’enllaç + Select by Link Status… Selecciona per estat de l’enllaç… + Search images Cerca imatges + No images match. Cap imatge no coincideix. +@msgplural Selected {n} linked image|Selected {n} linked images S’ha seleccionat {n} imatge enllaçada|S’han seleccionat {n} imatges enllaçades +@msgplural Selected {n} embedded image|Selected {n} embedded images S’ha seleccionat {n} imatge incrustada|S’han seleccionat {n} imatges incrustades +@msgplural Selected {n} missing image|Selected {n} missing images S’ha seleccionat {n} imatge que falta|S’han seleccionat {n} imatges que falten +@msgplural Selected {n} modified image|Selected {n} modified images S’ha seleccionat {n} imatge modificada|S’han seleccionat {n} imatges modificades +@msgplural Selected {n} image|Selected {n} images S’ha seleccionat {n} imatge|S’han seleccionat {n} imatges +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} més està oculta o bloquejada|{selected}; {n} més estan ocultes o bloquejades +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} més és en una capa de plantilla|{selected}; {n} més són en capes de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} més és fora del grup aïllat|{selected}; {n} més són fora del grup aïllat +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} més no es pot seleccionar ara|{selected}; {n} més no es poden seleccionar ara + # Compound Shapes add-on Compound Shapes Formes compostes Shape Mode Buttons Make Compound Shapes Els botons de mode de forma creen formes compostes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 57c3092b0d..10a96a0e8e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6365,6 +6365,25 @@ breakText Glyphs Glyfy Minimum angle Minimální úhel Maximum angle Maximální úhel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Vybrat propojené + Select Embedded Vybrat vložené + Select Missing Vybrat chybějící + Select Modified Vybrat upravené + Select by Link Status Vybrat podle stavu propojení + Select by Link Status… Vybrat podle stavu propojení… + Search images Hledat obrazy + No images match. Žádný obraz neodpovídá. +@msgplural Selected {n} linked image|Selected {n} linked images Vybrán {n} propojený obraz|Vybrány {n} propojené obrazy|Vybráno {n} propojených obrazů +@msgplural Selected {n} embedded image|Selected {n} embedded images Vybrán {n} vložený obraz|Vybrány {n} vložené obrazy|Vybráno {n} vložených obrazů +@msgplural Selected {n} missing image|Selected {n} missing images Vybrán {n} chybějící obraz|Vybrány {n} chybějící obrazy|Vybráno {n} chybějících obrazů +@msgplural Selected {n} modified image|Selected {n} modified images Vybrán {n} upravený obraz|Vybrány {n} upravené obrazy|Vybráno {n} upravených obrazů +@msgplural Selected {n} image|Selected {n} images Vybrán {n} obraz|Vybrány {n} obrazy|Vybráno {n} obrazů +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; další {n} je skrytý nebo zamčený|{selected}; další {n} jsou skryté nebo zamčené|{selected}; dalších {n} je skrytých nebo zamčených +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; další {n} je na vrstvě šablony|{selected}; další {n} jsou na vrstvách šablony|{selected}; dalších {n} je na vrstvách šablony +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; další {n} je mimo izolovanou skupinu|{selected}; další {n} jsou mimo izolovanou skupinu|{selected}; dalších {n} je mimo izolovanou skupinu +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; další {n} teď nelze vybrat|{selected}; další {n} teď nelze vybrat|{selected}; dalších {n} teď nelze vybrat + # Compound Shapes add-on Compound Shapes Složené tvary Shape Mode Buttons Make Compound Shapes Tlačítka režimů tvarů vytvářejí složené tvary diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b5980d5727..ae8069ffa0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6231,6 +6231,25 @@ breakText Glyphs Glyffer Minimum angle Mindste vinkel Maximum angle Største vinkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markér linkede + Select Embedded Markér integrerede + Select Missing Markér manglende + Select Modified Markér ændrede + Select by Link Status Markér efter linkstatus + Select by Link Status… Markér efter linkstatus… + Search images Søg i billeder + No images match. Ingen billeder passer. +@msgplural Selected {n} linked image|Selected {n} linked images Markerede {n} linket billede|Markerede {n} linkede billeder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerede {n} integreret billede|Markerede {n} integrerede billeder +@msgplural Selected {n} missing image|Selected {n} missing images Markerede {n} manglende billede|Markerede {n} manglende billeder +@msgplural Selected {n} modified image|Selected {n} modified images Markerede {n} ændret billede|Markerede {n} ændrede billeder +@msgplural Selected {n} image|Selected {n} images Markerede {n} billede|Markerede {n} billeder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} mere er skjult eller låst|{selected}; {n} mere er skjult eller låst +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} mere er på et skabelonlag|{selected}; {n} mere er på skabelonlag +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} mere er uden for den isolerede gruppe|{selected}; {n} mere er uden for den isolerede gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} mere kan ikke markeres nu|{selected}; {n} mere kan ikke markeres nu + # Compound Shapes add-on Compound Shapes Sammensatte figurer Shape Mode Buttons Make Compound Shapes Knapper til formtilstande opretter sammensatte figurer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5e38f90f52..436940908e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5951,6 +5951,25 @@ breakText Glyphs Glyphen Minimum angle Minimaler Winkel Maximum angle Maximaler Winkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Verknüpfte auswählen + Select Embedded Eingebettete auswählen + Select Missing Fehlende auswählen + Select Modified Geänderte auswählen + Select by Link Status Nach Verknüpfungsstatus auswählen + Select by Link Status… Nach Verknüpfungsstatus auswählen… + Search images Bilder suchen + No images match. Kein Bild passt. +@msgplural Selected {n} linked image|Selected {n} linked images {n} verknüpftes Bild ausgewählt|{n} verknüpfte Bilder ausgewählt +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} eingebettetes Bild ausgewählt|{n} eingebettete Bilder ausgewählt +@msgplural Selected {n} missing image|Selected {n} missing images {n} fehlendes Bild ausgewählt|{n} fehlende Bilder ausgewählt +@msgplural Selected {n} modified image|Selected {n} modified images {n} geändertes Bild ausgewählt|{n} geänderte Bilder ausgewählt +@msgplural Selected {n} image|Selected {n} images {n} Bild ausgewählt|{n} Bilder ausgewählt +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} weiteres ist ausgeblendet oder gesperrt|{selected}; {n} weitere sind ausgeblendet oder gesperrt +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} weiteres liegt auf einer Vorlagenebene|{selected}; {n} weitere liegen auf Vorlagenebenen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} weiteres liegt außerhalb der isolierten Gruppe|{selected}; {n} weitere liegen außerhalb der isolierten Gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} weiteres kann gerade nicht ausgewählt werden|{selected}; {n} weitere können gerade nicht ausgewählt werden + # Compound Shapes add-on Compound Shapes Zusammengesetzte Formen Shape Mode Buttons Make Compound Shapes Formmodus-Schaltflächen erstellen zusammengesetzte Formen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 84232bda24..9dd19335de 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6317,6 +6317,25 @@ breakText Glyphs Γλύφοι Minimum angle Ελάχιστη γωνία Maximum angle Μέγιστη γωνία +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Επιλογή συνδεδεμένων + Select Embedded Επιλογή ενσωματωμένων + Select Missing Επιλογή όσων λείπουν + Select Modified Επιλογή τροποποιημένων + Select by Link Status Επιλογή κατά κατάσταση σύνδεσης + Select by Link Status… Επιλογή κατά κατάσταση σύνδεσης… + Search images Αναζήτηση εικόνων + No images match. Καμία εικόνα δεν ταιριάζει. +@msgplural Selected {n} linked image|Selected {n} linked images Επιλέχθηκε {n} συνδεδεμένη εικόνα|Επιλέχθηκαν {n} συνδεδεμένες εικόνες +@msgplural Selected {n} embedded image|Selected {n} embedded images Επιλέχθηκε {n} ενσωματωμένη εικόνα|Επιλέχθηκαν {n} ενσωματωμένες εικόνες +@msgplural Selected {n} missing image|Selected {n} missing images Επιλέχθηκε {n} εικόνα που λείπει|Επιλέχθηκαν {n} εικόνες που λείπουν +@msgplural Selected {n} modified image|Selected {n} modified images Επιλέχθηκε {n} τροποποιημένη εικόνα|Επιλέχθηκαν {n} τροποποιημένες εικόνες +@msgplural Selected {n} image|Selected {n} images Επιλέχθηκε {n} εικόνα|Επιλέχθηκαν {n} εικόνες +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}· {n} ακόμη είναι κρυφή ή κλειδωμένη|{selected}· {n} ακόμη είναι κρυφές ή κλειδωμένες +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}· {n} ακόμη είναι σε επίπεδο προτύπου|{selected}· {n} ακόμη είναι σε επίπεδα προτύπου +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας|{selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}· {n} ακόμη δεν μπορεί να επιλεγεί τώρα|{selected}· {n} ακόμη δεν μπορούν να επιλεγούν τώρα + # Compound Shapes add-on Compound Shapes Σύνθετα σχήματα Shape Mode Buttons Make Compound Shapes Τα κουμπιά λειτουργιών σχημάτων δημιουργούν σύνθετα σχήματα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c09b51167c..46ed40b7db 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6307,6 +6307,25 @@ breakText Glyphs Glifos Minimum angle Ángulo mínimo Maximum angle Ángulo máximo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleccionar vinculadas + Select Embedded Seleccionar incrustadas + Select Missing Seleccionar ausentes + Select Modified Seleccionar modificadas + Select by Link Status Seleccionar por estado de vínculo + Select by Link Status… Seleccionar por estado de vínculo… + Search images Buscar imágenes + No images match. Ninguna imagen coincide. +@msgplural Selected {n} linked image|Selected {n} linked images Se seleccionó {n} imagen vinculada|Se seleccionaron {n} imágenes vinculadas +@msgplural Selected {n} embedded image|Selected {n} embedded images Se seleccionó {n} imagen incrustada|Se seleccionaron {n} imágenes incrustadas +@msgplural Selected {n} missing image|Selected {n} missing images Se seleccionó {n} imagen ausente|Se seleccionaron {n} imágenes ausentes +@msgplural Selected {n} modified image|Selected {n} modified images Se seleccionó {n} imagen modificada|Se seleccionaron {n} imágenes modificadas +@msgplural Selected {n} image|Selected {n} images Se seleccionó {n} imagen|Se seleccionaron {n} imágenes +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} más está oculta o bloqueada|{selected}; {n} más están ocultas o bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} más está en una capa de plantilla|{selected}; {n} más están en capas de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} más está fuera del grupo aislado|{selected}; {n} más están fuera del grupo aislado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} más no se puede seleccionar ahora|{selected}; {n} más no se pueden seleccionar ahora + # Compound Shapes add-on Compound Shapes Formas compuestas Shape Mode Buttons Make Compound Shapes Los botones de modo de forma crean formas compuestas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 909240b3d2..16860a45f9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6400,6 +6400,25 @@ breakText Glyphs Merkit Minimum angle Pienin kulma Maximum angle Suurin kulma +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Valitse linkitetyt + Select Embedded Valitse upotetut + Select Missing Valitse puuttuvat + Select Modified Valitse muokatut + Select by Link Status Valitse linkin tilan mukaan + Select by Link Status… Valitse linkin tilan mukaan… + Search images Hae kuvia + No images match. Mikään kuva ei vastaa hakua. +@msgplural Selected {n} linked image|Selected {n} linked images Valittiin {n} linkitetty kuva|Valittiin {n} linkitettyä kuvaa +@msgplural Selected {n} embedded image|Selected {n} embedded images Valittiin {n} upotettu kuva|Valittiin {n} upotettua kuvaa +@msgplural Selected {n} missing image|Selected {n} missing images Valittiin {n} puuttuva kuva|Valittiin {n} puuttuvaa kuvaa +@msgplural Selected {n} modified image|Selected {n} modified images Valittiin {n} muokattu kuva|Valittiin {n} muokattua kuvaa +@msgplural Selected {n} image|Selected {n} images Valittiin {n} kuva|Valittiin {n} kuvaa +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} muu on piilotettu tai lukittu|{selected}; {n} muuta on piilotettu tai lukittu +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} muu on mallitasolla|{selected}; {n} muuta on mallitasoilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} muu on eristetyn ryhmän ulkopuolella|{selected}; {n} muuta on eristetyn ryhmän ulkopuolella +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} muuta ei voi valita nyt|{selected}; {n} muuta ei voi valita nyt + # Compound Shapes add-on Compound Shapes Yhdistelmämuodot Shape Mode Buttons Make Compound Shapes Muototilapainikkeet luovat yhdistelmämuotoja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6738ec8df3..c028d24c8e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6360,6 +6360,25 @@ breakText Glyphs Glyphes Minimum angle Angle minimal Maximum angle Angle maximal +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Sélectionner les images liées + Select Embedded Sélectionner les images incorporées + Select Missing Sélectionner les images manquantes + Select Modified Sélectionner les images modifiées + Select by Link Status Sélectionner par état de lien + Select by Link Status… Sélectionner par état de lien… + Search images Rechercher des images + No images match. Aucune image ne correspond. +@msgplural Selected {n} linked image|Selected {n} linked images {n} image liée sélectionnée|{n} images liées sélectionnées +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} image incorporée sélectionnée|{n} images incorporées sélectionnées +@msgplural Selected {n} missing image|Selected {n} missing images {n} image manquante sélectionnée|{n} images manquantes sélectionnées +@msgplural Selected {n} modified image|Selected {n} modified images {n} image modifiée sélectionnée|{n} images modifiées sélectionnées +@msgplural Selected {n} image|Selected {n} images {n} image sélectionnée|{n} images sélectionnées +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected} ; {n} autre est masquée ou verrouillée|{selected} ; {n} autres sont masquées ou verrouillées +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected} ; {n} autre est sur un calque modèle|{selected} ; {n} autres sont sur des calques modèles +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected} ; {n} autre est hors du groupe isolé|{selected} ; {n} autres sont hors du groupe isolé +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected} ; {n} autre ne peut pas être sélectionnée pour l’instant|{selected} ; {n} autres ne peuvent pas être sélectionnées pour l’instant + # Compound Shapes add-on Compound Shapes Formes composées Shape Mode Buttons Make Compound Shapes Les boutons de mode de forme créent des formes composées diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 491c89fae0..3eb35419ce 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6349,6 +6349,25 @@ breakText Glyphs Glifák Minimum angle Legkisebb szög Maximum angle Legnagyobb szög +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Csatoltak kijelölése + Select Embedded Beágyazottak kijelölése + Select Missing Hiányzók kijelölése + Select Modified Módosítottak kijelölése + Select by Link Status Kijelölés csatolási állapot szerint + Select by Link Status… Kijelölés csatolási állapot szerint… + Search images Képek keresése + No images match. Nincs egyező kép. +@msgplural Selected {n} linked image|Selected {n} linked images Kijelölt csatolt képek: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images Kijelölt beágyazott képek: {n} +@msgplural Selected {n} missing image|Selected {n} missing images Kijelölt hiányzó képek: {n} +@msgplural Selected {n} modified image|Selected {n} modified images Kijelölt módosított képek: {n} +@msgplural Selected {n} image|Selected {n} images Kijelölt képek: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; további rejtett vagy zárolt: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; további sablonrétegen: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; további az elkülönített csoporton kívül: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; további most nem jelölhető ki: {n} + # Compound Shapes add-on Compound Shapes Összetett alakzatok Shape Mode Buttons Make Compound Shapes Az alakzatmód-gombok összetett alakzatokat hoznak létre diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ffb0cbf56f..33c3296008 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6231,6 +6231,25 @@ breakText Glyphs Glif Minimum angle Sudut minimum Maximum angle Sudut maksimum +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Pilih yang Tertaut + Select Embedded Pilih yang Tersemat + Select Missing Pilih yang Hilang + Select Modified Pilih yang Diubah + Select by Link Status Pilih menurut Status Tautan + Select by Link Status… Pilih menurut Status Tautan… + Search images Cari gambar + No images match. Tidak ada gambar yang cocok. +@msgplural Selected {n} linked image|Selected {n} linked images Telah memilih {n} gambar tertaut +@msgplural Selected {n} embedded image|Selected {n} embedded images Telah memilih {n} gambar tersemat +@msgplural Selected {n} missing image|Selected {n} missing images Telah memilih {n} gambar yang hilang +@msgplural Selected {n} modified image|Selected {n} modified images Telah memilih {n} gambar yang diubah +@msgplural Selected {n} image|Selected {n} images Telah memilih {n} gambar +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} lainnya tersembunyi atau terkunci +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} lainnya berada di layer templat +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} lainnya berada di luar grup yang diisolasi +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} lainnya tidak dapat dipilih sekarang + # Compound Shapes add-on Compound Shapes Bentuk majemuk Shape Mode Buttons Make Compound Shapes Tombol mode bentuk membuat bentuk majemuk diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cfd99e62b3..e59c310d82 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5985,6 +5985,25 @@ breakText Glyphs Glifi Minimum angle Angolo minimo Maximum angle Angolo massimo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleziona collegate + Select Embedded Seleziona incorporate + Select Missing Seleziona mancanti + Select Modified Seleziona modificate + Select by Link Status Seleziona per stato del collegamento + Select by Link Status… Seleziona per stato del collegamento… + Search images Cerca immagini + No images match. Nessuna immagine corrisponde. +@msgplural Selected {n} linked image|Selected {n} linked images Selezionata {n} immagine collegata|Selezionate {n} immagini collegate +@msgplural Selected {n} embedded image|Selected {n} embedded images Selezionata {n} immagine incorporata|Selezionate {n} immagini incorporate +@msgplural Selected {n} missing image|Selected {n} missing images Selezionata {n} immagine mancante|Selezionate {n} immagini mancanti +@msgplural Selected {n} modified image|Selected {n} modified images Selezionata {n} immagine modificata|Selezionate {n} immagini modificate +@msgplural Selected {n} image|Selected {n} images Selezionata {n} immagine|Selezionate {n} immagini +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; altra {n} è nascosta o bloccata|{selected}; altre {n} sono nascoste o bloccate +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; altra {n} è su un livello modello|{selected}; altre {n} sono su livelli modello +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; altra {n} è fuori dal gruppo isolato|{selected}; altre {n} sono fuori dal gruppo isolato +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; altra {n} non può essere selezionata ora|{selected}; altre {n} non possono essere selezionate ora + # Compound Shapes add-on Compound Shapes Forme composte Shape Mode Buttons Make Compound Shapes I pulsanti dei metodi forma creano forme composte diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5da2097f26..c0f05308cd 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6050,6 +6050,25 @@ breakText Glyphs 字形 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked リンク済みを選択 + Select Embedded 埋め込みを選択 + Select Missing 見つからない画像を選択 + Select Modified 変更された画像を選択 + Select by Link Status リンクの状態で選択 + Select by Link Status… リンクの状態で選択… + Search images 画像を検索 + No images match. 一致する画像はありません。 +@msgplural Selected {n} linked image|Selected {n} linked images リンク済みの画像を {n} 個選択しました +@msgplural Selected {n} embedded image|Selected {n} embedded images 埋め込み画像を {n} 個選択しました +@msgplural Selected {n} missing image|Selected {n} missing images 見つからない画像を {n} 個選択しました +@msgplural Selected {n} modified image|Selected {n} modified images 変更された画像を {n} 個選択しました +@msgplural Selected {n} image|Selected {n} images 画像を {n} 個選択しました +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}。ほかに {n} 個が非表示またはロックされています +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}。ほかに {n} 個がテンプレートレイヤー上にあります +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}。ほかに {n} 個が分離したグループの外にあります +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}。ほかに {n} 個は今は選択できません + # Compound Shapes add-on Compound Shapes 複合シェイプ Shape Mode Buttons Make Compound Shapes シェイプモードボタンで複合シェイプを作成 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b9f4a70a09..82127af216 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6376,6 +6376,25 @@ font-script Japanese იაპონური Minimum angle მინიმალური კუთხე Maximum angle მაქსიმალური კუთხე +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked დაკავშირებულების არჩევა + Select Embedded ჩაშენებულების არჩევა + Select Missing დაკარგულების არჩევა + Select Modified შეცვლილების არჩევა + Select by Link Status კავშირის მდგომარეობით არჩევა + Select by Link Status… კავშირის მდგომარეობით არჩევა… + Search images გამოსახულებების ძებნა + No images match. შესაბამისი გამოსახულება არ არის. +@msgplural Selected {n} linked image|Selected {n} linked images არჩეულია დაკავშირებული გამოსახულებები: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images არჩეულია ჩაშენებული გამოსახულებები: {n} +@msgplural Selected {n} missing image|Selected {n} missing images არჩეულია დაკარგული გამოსახულებები: {n} +@msgplural Selected {n} modified image|Selected {n} modified images არჩეულია შეცვლილი გამოსახულებები: {n} +@msgplural Selected {n} image|Selected {n} images არჩეულია გამოსახულებები: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; დამალული ან ჩაკეტილია კიდევ: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; შაბლონის ფენაზეა კიდევ: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; იზოლირებული ჯგუფის გარეთაა კიდევ: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ახლა ვერ აირჩევა კიდევ: {n} + # Compound Shapes add-on Compound Shapes შედგენილი ფიგურები Shape Mode Buttons Make Compound Shapes ფიგურის რეჟიმის ღილაკები ქმნის შედგენილ ფიგურებს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index ac5d1193a7..adbf827100 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5946,6 +5946,25 @@ breakText Glyphs 글리프 Minimum angle 최소 각도 Maximum angle 최대 각도 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 연결됨 선택 + Select Embedded 포함됨 선택 + Select Missing 없는 이미지 선택 + Select Modified 수정된 이미지 선택 + Select by Link Status 링크 상태로 선택 + Select by Link Status… 링크 상태로 선택… + Search images 이미지 검색 + No images match. 일치하는 이미지가 없습니다. +@msgplural Selected {n} linked image|Selected {n} linked images 연결된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} embedded image|Selected {n} embedded images 포함된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} missing image|Selected {n} missing images 없는 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} modified image|Selected {n} modified images 수정된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} image|Selected {n} images 이미지 {n}개를 선택했습니다 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}. {n}개는 숨겨졌거나 잠겨 있습니다 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}. {n}개는 템플릿 레이어에 있습니다 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}. {n}개는 격리된 그룹 밖에 있습니다 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}. {n}개는 지금 선택할 수 없습니다 + # Compound Shapes add-on Compound Shapes 컴파운드 모양 Shape Mode Buttons Make Compound Shapes 모양 모드 버튼으로 컴파운드 모양 만들기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 62385d6c98..5c00ac9f49 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6275,6 +6275,25 @@ breakText Glyphs Glyphs Minimum angle Minimale hoek Maximum angle Maximale hoek +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Gekoppelde selecteren + Select Embedded Ingesloten selecteren + Select Missing Ontbrekende selecteren + Select Modified Gewijzigde selecteren + Select by Link Status Selecteren op koppelingsstatus + Select by Link Status… Selecteren op koppelingsstatus… + Search images Afbeeldingen zoeken + No images match. Geen afbeelding komt overeen. +@msgplural Selected {n} linked image|Selected {n} linked images {n} gekoppelde afbeelding geselecteerd|{n} gekoppelde afbeeldingen geselecteerd +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} ingesloten afbeelding geselecteerd|{n} ingesloten afbeeldingen geselecteerd +@msgplural Selected {n} missing image|Selected {n} missing images {n} ontbrekende afbeelding geselecteerd|{n} ontbrekende afbeeldingen geselecteerd +@msgplural Selected {n} modified image|Selected {n} modified images {n} gewijzigde afbeelding geselecteerd|{n} gewijzigde afbeeldingen geselecteerd +@msgplural Selected {n} image|Selected {n} images {n} afbeelding geselecteerd|{n} afbeeldingen geselecteerd +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; nog {n} is verborgen of vergrendeld|{selected}; nog {n} zijn verborgen of vergrendeld +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; nog {n} staat op een sjabloonlaag|{selected}; nog {n} staan op sjabloonlagen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; nog {n} staat buiten de geïsoleerde groep|{selected}; nog {n} staan buiten de geïsoleerde groep +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; nog {n} kan nu niet worden geselecteerd|{selected}; nog {n} kunnen nu niet worden geselecteerd + # Compound Shapes add-on Compound Shapes Samengestelde vormen Shape Mode Buttons Make Compound Shapes Vormmodus-knoppen maken samengestelde vormen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 908f36c948..0754590d46 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6220,6 +6220,25 @@ breakText Glyphs Glify Minimum angle Kąt minimalny Maximum angle Kąt maksymalny +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Zaznacz połączone + Select Embedded Zaznacz osadzone + Select Missing Zaznacz brakujące + Select Modified Zaznacz zmodyfikowane + Select by Link Status Zaznacz według stanu połączenia + Select by Link Status… Zaznacz według stanu połączenia… + Search images Szukaj obrazów + No images match. Żaden obraz nie pasuje. +@msgplural Selected {n} linked image|Selected {n} linked images Zaznaczono {n} połączony obraz|Zaznaczono {n} połączone obrazy|Zaznaczono {n} połączonych obrazów +@msgplural Selected {n} embedded image|Selected {n} embedded images Zaznaczono {n} osadzony obraz|Zaznaczono {n} osadzone obrazy|Zaznaczono {n} osadzonych obrazów +@msgplural Selected {n} missing image|Selected {n} missing images Zaznaczono {n} brakujący obraz|Zaznaczono {n} brakujące obrazy|Zaznaczono {n} brakujących obrazów +@msgplural Selected {n} modified image|Selected {n} modified images Zaznaczono {n} zmodyfikowany obraz|Zaznaczono {n} zmodyfikowane obrazy|Zaznaczono {n} zmodyfikowanych obrazów +@msgplural Selected {n} image|Selected {n} images Zaznaczono {n} obraz|Zaznaczono {n} obrazy|Zaznaczono {n} obrazów +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; jeszcze {n} jest ukryty lub zablokowany|{selected}; jeszcze {n} są ukryte lub zablokowane|{selected}; jeszcze {n} jest ukrytych lub zablokowanych +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; jeszcze {n} jest na warstwie szablonu|{selected}; jeszcze {n} są na warstwach szablonu|{selected}; jeszcze {n} jest na warstwach szablonu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; jeszcze {n} jest poza izolowaną grupą|{selected}; jeszcze {n} są poza izolowaną grupą|{selected}; jeszcze {n} jest poza izolowaną grupą +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć + # Compound Shapes add-on Compound Shapes Kształty złożone Shape Mode Buttons Make Compound Shapes Przyciski trybów kształtu tworzą kształty złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index eb376906ca..6ba1f7ff38 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6438,6 +6438,25 @@ swatch Yellow Green Verde-amarelado Minimum angle Ângulo Mínimo Maximum angle Ângulo Máximo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecionar vinculadas + Select Embedded Selecionar incorporadas + Select Missing Selecionar ausentes + Select Modified Selecionar modificadas + Select by Link Status Selecionar por status do vínculo + Select by Link Status… Selecionar por status do vínculo… + Search images Pesquisar imagens + No images match. Nenhuma imagem corresponde. +@msgplural Selected {n} linked image|Selected {n} linked images {n} imagem vinculada selecionada|{n} imagens vinculadas selecionadas +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} imagem incorporada selecionada|{n} imagens incorporadas selecionadas +@msgplural Selected {n} missing image|Selected {n} missing images {n} imagem ausente selecionada|{n} imagens ausentes selecionadas +@msgplural Selected {n} modified image|Selected {n} modified images {n} imagem modificada selecionada|{n} imagens modificadas selecionadas +@msgplural Selected {n} image|Selected {n} images {n} imagem selecionada|{n} imagens selecionadas +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; mais {n} está oculta ou bloqueada|{selected}; mais {n} estão ocultas ou bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; mais {n} está em uma camada de modelo|{selected}; mais {n} estão em camadas de modelo +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; mais {n} está fora do grupo isolado|{selected}; mais {n} estão fora do grupo isolado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; mais {n} não pode ser selecionada agora|{selected}; mais {n} não podem ser selecionadas agora + # Compound Shapes add-on Compound Shapes Formas Compostas Shape Mode Buttons Make Compound Shapes Os Botões de Modo de Forma Criam Formas Compostas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d700736c6c..7be753b6f7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6454,6 +6454,25 @@ shape Open Открытый Minimum angle Минимальный угол Maximum angle Максимальный угол +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Выделить связанные + Select Embedded Выделить внедрённые + Select Missing Выделить отсутствующие + Select Modified Выделить изменённые + Select by Link Status Выделить по состоянию связи + Select by Link Status… Выделить по состоянию связи… + Search images Поиск изображений + No images match. Нет подходящих изображений. +@msgplural Selected {n} linked image|Selected {n} linked images Выделено {n} связанное изображение|Выделено {n} связанных изображения|Выделено {n} связанных изображений +@msgplural Selected {n} embedded image|Selected {n} embedded images Выделено {n} внедрённое изображение|Выделено {n} внедрённых изображения|Выделено {n} внедрённых изображений +@msgplural Selected {n} missing image|Selected {n} missing images Выделено {n} отсутствующее изображение|Выделено {n} отсутствующих изображения|Выделено {n} отсутствующих изображений +@msgplural Selected {n} modified image|Selected {n} modified images Выделено {n} изменённое изображение|Выделено {n} изменённых изображения|Выделено {n} изменённых изображений +@msgplural Selected {n} image|Selected {n} images Выделено {n} изображение|Выделено {n} изображения|Выделено {n} изображений +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ещё {n} скрыто или заблокировано|{selected}; ещё {n} скрыты или заблокированы|{selected}; ещё {n} скрыты или заблокированы +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ещё {n} на слое-шаблоне|{selected}; ещё {n} на слоях-шаблонах|{selected}; ещё {n} на слоях-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить + # Compound Shapes add-on Compound Shapes Составные фигуры Shape Mode Buttons Make Compound Shapes Кнопки режимов фигур создают составные фигуры diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 85f4812d15..68eee36052 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6421,6 +6421,25 @@ digits Hindi Hindi Minimum angle Minsta vinkel Maximum angle Största vinkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markera länkade + Select Embedded Markera inbäddade + Select Missing Markera saknade + Select Modified Markera ändrade + Select by Link Status Markera efter länkstatus + Select by Link Status… Markera efter länkstatus… + Search images Sök bilder + No images match. Ingen bild matchar. +@msgplural Selected {n} linked image|Selected {n} linked images Markerade {n} länkad bild|Markerade {n} länkade bilder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerade {n} inbäddad bild|Markerade {n} inbäddade bilder +@msgplural Selected {n} missing image|Selected {n} missing images Markerade {n} saknad bild|Markerade {n} saknade bilder +@msgplural Selected {n} modified image|Selected {n} modified images Markerade {n} ändrad bild|Markerade {n} ändrade bilder +@msgplural Selected {n} image|Selected {n} images Markerade {n} bild|Markerade {n} bilder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} till är dold eller låst|{selected}; {n} till är dolda eller låsta +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} till ligger på ett mallager|{selected}; {n} till ligger på mallager +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} till ligger utanför den isolerade gruppen|{selected}; {n} till ligger utanför den isolerade gruppen +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} till kan inte markeras nu|{selected}; {n} till kan inte markeras nu + # Compound Shapes add-on Compound Shapes Sammansatta former Shape Mode Buttons Make Compound Shapes Formlägesknapparna skapar sammansatta former diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5c6446de73..184bd0b46d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6322,6 +6322,25 @@ breakText Glyphs Glifler Minimum angle En Küçük Açı Maximum angle En Büyük Açı +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Bağlantılıları Seç + Select Embedded Gömülüleri Seç + Select Missing Eksikleri Seç + Select Modified Değiştirilenleri Seç + Select by Link Status Bağlantı Durumuna Göre Seç + Select by Link Status… Bağlantı Durumuna Göre Seç… + Search images Görüntülerde ara + No images match. Eşleşen görüntü yok. +@msgplural Selected {n} linked image|Selected {n} linked images {n} bağlantılı görüntü seçildi +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} gömülü görüntü seçildi +@msgplural Selected {n} missing image|Selected {n} missing images {n} eksik görüntü seçildi +@msgplural Selected {n} modified image|Selected {n} modified images {n} değiştirilmiş görüntü seçildi +@msgplural Selected {n} image|Selected {n} images {n} görüntü seçildi +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} tane daha gizli veya kilitli +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} tane daha şablon katmanında +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} tane daha izole grubun dışında +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} tane daha şu anda seçilemiyor + # Compound Shapes add-on Compound Shapes Bileşik Şekiller Shape Mode Buttons Make Compound Shapes Şekil Modu Düğmeleri Bileşik Şekiller Yapar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4bb7083401..f89aa17e9a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5965,6 +5965,25 @@ breakText Glyphs Гліфи Minimum angle Мінімальний кут Maximum angle Максимальний кут +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Виділити пов’язані + Select Embedded Виділити вбудовані + Select Missing Виділити відсутні + Select Modified Виділити змінені + Select by Link Status Виділити за станом зв’язку + Select by Link Status… Виділити за станом зв’язку… + Search images Пошук зображень + No images match. Немає відповідних зображень. +@msgplural Selected {n} linked image|Selected {n} linked images Виділено {n} пов’язане зображення|Виділено {n} пов’язані зображення|Виділено {n} пов’язаних зображень +@msgplural Selected {n} embedded image|Selected {n} embedded images Виділено {n} вбудоване зображення|Виділено {n} вбудовані зображення|Виділено {n} вбудованих зображень +@msgplural Selected {n} missing image|Selected {n} missing images Виділено {n} відсутнє зображення|Виділено {n} відсутні зображення|Виділено {n} відсутніх зображень +@msgplural Selected {n} modified image|Selected {n} modified images Виділено {n} змінене зображення|Виділено {n} змінені зображення|Виділено {n} змінених зображень +@msgplural Selected {n} image|Selected {n} images Виділено {n} зображення|Виділено {n} зображення|Виділено {n} зображень +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ще {n} приховане або заблоковане|{selected}; ще {n} приховані або заблоковані|{selected}; ще {n} приховані або заблоковані +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ще {n} на шарі-шаблоні|{selected}; ще {n} на шарах-шаблонах|{selected}; ще {n} на шарах-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити + # Compound Shapes add-on Compound Shapes Складені фігури Shape Mode Buttons Make Compound Shapes Кнопки режимів фігур створюють складені фігури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 330792405e..a76ec9ebec 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5966,6 +5966,25 @@ breakText Glyphs Glyph Minimum angle Góc tối thiểu Maximum angle Góc tối đa +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Chọn ảnh đã liên kết + Select Embedded Chọn ảnh đã nhúng + Select Missing Chọn ảnh bị thiếu + Select Modified Chọn ảnh đã sửa đổi + Select by Link Status Chọn theo trạng thái liên kết + Select by Link Status… Chọn theo trạng thái liên kết… + Search images Tìm ảnh + No images match. Không có ảnh nào khớp. +@msgplural Selected {n} linked image|Selected {n} linked images Đã chọn {n} ảnh đã liên kết +@msgplural Selected {n} embedded image|Selected {n} embedded images Đã chọn {n} ảnh đã nhúng +@msgplural Selected {n} missing image|Selected {n} missing images Đã chọn {n} ảnh bị thiếu +@msgplural Selected {n} modified image|Selected {n} modified images Đã chọn {n} ảnh đã sửa đổi +@msgplural Selected {n} image|Selected {n} images Đã chọn {n} ảnh +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; thêm {n} ảnh bị ẩn hoặc khóa +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; thêm {n} ảnh nằm trên lớp mẫu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; thêm {n} ảnh nằm ngoài nhóm đã tách biệt +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; thêm {n} ảnh hiện không thể chọn + # Compound Shapes add-on Compound Shapes Hình phức hợp Shape Mode Buttons Make Compound Shapes Nút chế độ hình dạng tạo hình phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 48f040a9cb..c1945d7266 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6206,6 +6206,25 @@ breakText Glyphs 字形 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 选择已链接 + Select Embedded 选择嵌入 + Select Missing 选择缺失 + Select Modified 选择已修改 + Select by Link Status 按链接状态选择 + Select by Link Status… 按链接状态选择… + Search images 搜索图像 + No images match. 没有匹配的图像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已选择 {n} 个已链接的图像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已选择 {n} 个嵌入的图像 +@msgplural Selected {n} missing image|Selected {n} missing images 已选择 {n} 个缺失的图像 +@msgplural Selected {n} modified image|Selected {n} modified images 已选择 {n} 个已修改的图像 +@msgplural Selected {n} image|Selected {n} images 已选择 {n} 个图像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 个已隐藏或锁定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 个位于模板图层上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 个位于隔离的编组之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 个现在无法选择 + # Compound Shapes add-on Compound Shapes 复合形状 Shape Mode Buttons Make Compound Shapes 形状模式按钮创建复合形状 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f0c659b50a..d7347d1745 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6003,6 +6003,25 @@ breakText Glyphs 字符 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 選取已連結 + Select Embedded 選取已內嵌 + Select Missing 選取遺失 + Select Modified 選取已修改 + Select by Link Status 依連結狀態選取 + Select by Link Status… 依連結狀態選取… + Search images 搜尋影像 + No images match. 沒有符合的影像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已選取 {n} 個已連結的影像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已選取 {n} 個已內嵌的影像 +@msgplural Selected {n} missing image|Selected {n} missing images 已選取 {n} 個遺失的影像 +@msgplural Selected {n} modified image|Selected {n} modified images 已選取 {n} 個已修改的影像 +@msgplural Selected {n} image|Selected {n} images 已選取 {n} 個影像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 個已隱藏或鎖定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 個位於範本圖層上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 個位於隔離的群組之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 個現在無法選取 + # Compound Shapes add-on Compound Shapes 複合形狀 Shape Mode Buttons Make Compound Shapes 形狀模式按鈕製作複合形狀 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a419204162..ab50fe76dd 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -64,6 +64,8 @@ use bar::{menu_body, pointer_reaches_title}; pub use context::{context_items, context_menu_body, ruler_menu_body, ruler_unit_items}; pub use entries::{MenuEntry, Row, context_entries, entry, menu_entries, pretty_shortcut, shown_shortcut}; pub(crate) use invoke::graph_dialog; +#[cfg(test)] +pub(crate) use invoke::with_held_keys; pub use invoke::{click_target, invoke, invoke_from_system_menu}; #[cfg(test)] pub(crate) use labels::lists_plugin; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 963eab802f..5b0d0f3c40 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -15,10 +15,13 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { /// What an in-window menu click on `target` (a [`click_target`]) runs with `held` held: Object › /// Unlock All and Object › Show All chosen with Shift+Alt (Shift+Option) act only inside the groups -/// that hold the selected objects (`scope: "group"`). -pub(super) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { +/// that hold the selected objects (`scope: "group"`); Select Linked, Embedded, Missing and Modified +/// chosen with Shift add to the selection (`add: true`). +pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { match target.0.as_str() { "object.unlockAll" | "object.showAll" if held.shift && held.alt => (target.0, json!({"scope": "group"})), + // Select Linked, Embedded, Missing and Modified with Shift add to the selection. + crate::addons::select::link_status::COMMAND if held.shift => (target.0, crate::addons::select::link_status::with_shift(target.1)), _ => target, } } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e9776e78f4..1bb536f76e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -578,6 +578,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), + crate::addons::select::link_status::COMMAND => crate::addons::select::link_status::run(app, p), crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), crate::addons::document::EXPORT_ALL => crate::addons::document::export_all(app, p), crate::addons::document::BATCH_TRACE => crate::addons::document::batch_trace(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 673ceb81fd..78553cc7bd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -135,7 +135,7 @@ fn swapped_out(app: &VectorcraftApp, id: &str) -> bool { /// or off), or `None` while they leave it out: an empty slot ([`hidden_when_disabled`]) or an item /// another stands in for ([`swapped_out`]). pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { - let en = enabled(app, id); + let en = enabled(app, id) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)); if (!en && hidden_when_disabled(id)) || swapped_out(app, id) { return None; } diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index d924d06f3f..d27603424a 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -4,7 +4,8 @@ //! from the last row clicked without Shift to it (with Ctrl/Cmd, adds them); the buttons Relink, //! Go To, Update and Edit Original act on the selected rows; Link Info shows the details of the //! first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: -//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Show filters, Sort, thumbnail size +//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / +//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, thumbnail size //! and Show in Folder. //! //! Everything runs through the `links.*` commands (`links.editOriginal` and `links.reveal` are UI @@ -597,6 +598,17 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, "links.reveal", json!({})); } ui.separator(); + // Select Linked, Embedded, Missing and Modified: every such image in the document, not only + // the rows shown; with Shift, added to the selection. + use crate::addons::select::link_status; + for (i, (status, label, _)) in link_status::STATUSES.iter().enumerate() { + if menu_item(ui, tl!(label), app.ui.link_statuses.has.get(i).copied().unwrap_or(false), false) { + let p = json!({ "status": status }); + let p = if ui.input(|i| i.modifiers.shift) { link_status::with_shift(p) } else { p }; + crate::menus::invoke(app, link_status::COMMAND, p); + } + } + ui.separator(); for (id, label) in SHOW { if menu_item(ui, tl!(label), true, o.show == id) { set_options(ui.ctx(), |o| o.show = id); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2baf6f6ee7..044f3e66bc 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -382,6 +382,11 @@ pub struct UiState { /// is open. Not saved. #[serde(skip)] pub context_intertwine: Option<(u64, vectorcraft_doc::NodeId, vectorcraft_geom::Point, vectorcraft_doc::NodeId)>, + /// Which link statuses the active document's images and placed documents have, for Select › + /// Linked, Embedded, Missing and Modified to be on only when some do (refreshed by + /// [`crate::addons::select::link_status::refresh`]). Not saved. + #[serde(skip)] + pub link_statuses: crate::addons::select::link_status::Present, /// Last tool shown in each toolbar slot (keyed by the slot's first tool id). #[serde(default)] pub slot_tool: std::collections::BTreeMap, @@ -942,6 +947,7 @@ impl Default for UiState { shape_modes_compound: false, context_locked: None, context_intertwine: None, + link_statuses: Default::default(), slot_tool: Default::default(), floating_flyouts: vec![], toolbar_edits: ToolbarEdits::default(), diff --git a/docs/mcp.md b/docs/mcp.md index 1e6fbc2042..fcbb492fdc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6864,6 +6864,30 @@ The dialog lists every artboard with its number, name and size in the document's name; a click chooses one artboard, Shift-click adds a range and Cmd/Ctrl-click toggles one, and Select All / None act on the rows shown (rows hidden by the search stay chosen). It opens with the active artboard chosen and Overlapping. +`addon.select.byLinkStatus {status, ids?, add?, zoom?}` (Select Linked / Embedded / Missing / Modified and Select by +Link Status…, #5526) selects the image objects and placed documents whose link has a status, as `links.list` reports +it: `linked` (its file found unchanged; `links.list` says `ok`), `embedded`, `missing` or `modified` (its file changed +since it was read). `status` is one of them or a list of them (at least one; one listed twice counts once). `ids` picks +only among those objects (other objects among them are passed over); `add: true` adds them to the selection instead of +replacing it; `zoom: true` asks for Zoom to Selection afterwards, which the desktop app runs (`addon.arrange.zoomSelection`) +when something was selected, and which other callers get back as `zoom: true`. Objects that are hidden or locked, inside +a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the +isolated group or layer are left out and listed with the reason. Only the selection changes, so there is nothing to +undo. It returns `{count, selected: [ids] (bottom first), skipped: [{id, reason: hidden|locked|template|isolation}]}`. +A missing or unknown status, an id naming no object, or a value of the wrong type is an error, and the selection is left +as it was. + +```json +{"name":"run_command","arguments":{"command":"addon.select.byLinkStatus","params":{"status":["missing","modified"],"zoom":true}}} +``` + +In the desktop app, Object › Plug-ins › Selection Tools and the Links panel menu have Select Linked, Select Embedded, +Select Missing and Select Modified, each off when no image has that status; with Shift held they add to the selection. +The status bar says what was selected and what was left out, e.g. "Selected 9 missing images; 3 more are hidden or +locked". Select by Link Status… lists every image and placed document with its name, status and format, searches by +name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select +selects the rows chosen, zooming to them when Zoom to Selection is on (the default). + ### Vector Halftone (live) `addon.color.halftone` (Effect › Color Effects › Vector Halftone…, also in Object › Plug-ins › Color Effects) draws its diff --git a/docs/roadmap.md b/docs/roadmap.md index 6831863a9a..0db3a84355 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Select by Artboards add-on selects by overlap, inside or outside several artboards; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Selection Tools add-on: Select by Link Status selects images and placed documents that are linked, embedded, missing or modified, #5526; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -28,6 +28,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-04 | minor | M7: Find Font's Replace With Font lists family and style rows with a search, and the list and the document's font list scroll on their own (#4972); scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen preset; Recent and Saved cards keep the units their document or preset was made in, and the built-in tabs still follow the chosen units (#2078). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 004188166e..27b63a9215 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; Optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Selection Tools add-on: Select by Link Status selects images and placed documents that are linked, embedded, missing or modified, #5526; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -23,6 +23,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-05 | minor | Type Tools add-on: Release Type on a Path (a VectorCraft addition, #5532): evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `minAngle`/`maxAngle` round only the corners whose angle is in a range (#5545); evidence added; scores unchanged. | @@ -736,6 +737,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. While an opacity mask or a pattern is edited, a Shaper double-click on a Shaper Group in the mask or pattern art selects the original shape under the pointer without entering Construction mode, the Shaper Group's mode widget does not show, and a Shaper scribble, Release and Expand keep the editing layer isolated. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fca5458f04..560fc3edb0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; Select by Artboards add-on selects by overlap, inside or outside several artboards; Cmd+Space keeps the active drawing cursor during its drag; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Selection Tools add-on: Select by Link Status selects images and placed documents that are linked, embedded, missing or modified, #5526; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -30,6 +30,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-05 | minor | Gradient panel: Delete Stop sits at the right end of the ramp, so it shows whenever the ramp does instead of under the stop fields, where a short panel hid it (#5403); scores and estimates unchanged | | 2026-11-04 | minor | Artboards panel: a Shift- or Ctrl/Cmd-click on a row selects several artboards with any tool, switching to the Artboard tool first, so a preset, orientation, size or Fill set in Properties or the Control bar goes to every selected artboard; Fill used to set the active artboard only (#5698); scores and estimates unchanged | @@ -395,6 +396,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | | Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | | Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | +| Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | ## Look and feel From 96505d3a77c79e65ecdfe9635ecb8ae02f75072e Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:37:16 +0530 Subject: [PATCH 002/105] Fix #5526: document the functions the link-status selection touches Doc comments for the Select add-on commands, the Select by Link Status dialog body, the Links panel menu and the test helpers (review: docstring coverage). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/addons/select.rs | 6 ++++++ crates/engine/src/cmd/addons/select/tests.rs | 6 ++++++ crates/ui-egui/src/addons/select/link_status.rs | 3 +++ crates/ui-egui/src/addons/select/link_status/tests.rs | 2 ++ crates/ui-egui/src/panels/links.rs | 2 ++ 5 files changed, 19 insertions(+) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index 4d71895c01..b2ab59d851 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -25,6 +25,7 @@ pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"]; /// in the document, a file not found, a file changed since it was read. pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"]; +/// The add-on's commands: Select by Artboards and Select by Link Status. pub fn specs() -> Vec { vec![ cmd!( @@ -48,6 +49,8 @@ pub fn specs() -> Vec { ] } +/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie +/// outside the chosen artboards. fn by_artboards(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.byArtboards"; let relation = text_param(p, "relation", C)?.unwrap_or("overlap"); @@ -151,6 +154,9 @@ fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'s }) } +/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the +/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list +/// those left out with the reason ([`skip_reason`]). fn by_link_status(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.byLinkStatus"; let wanted = link_statuses(p, C)?; diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index ca59565261..c97b278258 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -150,6 +150,8 @@ mod by_link_status { _dir: Folder, } + /// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two + /// removed. fn links(name: &str) -> Links { let dir = Folder::new(name); let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft")); @@ -168,19 +170,23 @@ mod by_link_status { Links { s, ok, modified, missing, embedded, document, _dir: dir } } + /// Run the command with `p`, which must succeed. fn run(s: &mut Session, p: Value) -> Value { s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}")) } + /// `v` sorted. fn sorted(mut v: Vec) -> Vec { v.sort(); v } + /// The selected objects, sorted. fn selection(s: &Session) -> Vec { sorted(s.doc().unwrap().selection.objects.clone()) } + /// The ids of a JSON list, sorted. fn ids(v: &Value) -> Vec { sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()) } diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs index 7b7203276c..0b367a7ba0 100644 --- a/crates/ui-egui/src/addons/select/link_status.rs +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -138,6 +138,7 @@ pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String }; let Some(first) = reasons.first() else { return selected }; // Hidden and locked go together; a template layer, or the isolated group, alone. + /// The group reason `r` is told in: hidden and locked are one. fn kind(r: &str) -> &str { match r { "hidden" | "locked" => "locked", @@ -217,6 +218,8 @@ fn status_label(status: &str) -> &'static str { STATUSES.iter().find(|(s, ..)| *s == status).map_or("", |&(.., label)| tl!(label)) } +/// The dialog: the search, the Show filter, a checkbox row per image shown (name, status, format), +/// All / None with the count chosen, and Zoom to Selection. Returns false: nothing to preview. fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let rows: Vec = d.fields.get("__rows").and_then(Value::as_array).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs index 22b07ccace..8ad61f6e5a 100644 --- a/crates/ui-egui/src/addons/select/link_status/tests.rs +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -28,6 +28,7 @@ impl Drop for Folder { } } +/// A `w` × `h` red PNG. fn png(w: u32, h: u32) -> Vec { let mut out = vec![]; image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) @@ -53,6 +54,7 @@ fn app(dir: &Folder) -> (VectorcraftApp, u64, u64, u64) { (app, river, harbour, stamp) } +/// The selected objects' ids, sorted. fn selected(app: &VectorcraftApp) -> Vec { let mut ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); ids.sort_unstable(); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index d27603424a..a7fe30185f 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -535,6 +535,8 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { row(ui, tl!("Status"), status.into()); } +/// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / +/// Missing / Modified for the whole document, and the Show, Sort and thumbnail options. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). From 50128e6025fd7c07494b8ad0873c01549e2600fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 19:47:11 -0800 Subject: [PATCH 003/105] Render: adding or deleting an anchor of a long path splices the kept path When anchors of a kept path (a path or compound path of 1,024 anchors or more) are added or deleted, or a subpath is closed or opened, the next frame writes again only the path elements from the first anchor that changed to the last, and the closing segment and ClosePath when an end anchor changed or the subpath was closed or opened. The elements after the change move with it. Before, such an edit made the whole path again and measured it whole. - The runs of segments now carry their own ends. The runs that held the segments written become one run, split into runs of 128 when it grows past 256, and only those runs are measured again, with the miter tips of the run of the segment with length before each span. When a subpath is closed or opened and the stroke reaches farther from one than from the other, all of that subpath's tips are measured again. - On a subpath that is open before and after the edit, the handle before the first anchor and the one after the last are not compared, so Delete Anchor Point, which clears them, writes again only the segments around the anchor deleted. - A subpath that has fewer than two anchors before or after the edit is written again whole. A compound path member that gains or loses subpaths is made again. When members are added or removed, those members and every member between the first and the last of them are made again, and the members before and after them stay. - An edit that adds or deletes anchors in, closes or opens more than 16 subpaths makes the whole path again, as before. - An edit that leaves every anchor as it was, such as a new stroke, leaves the kept path as it is. The pixels and the cull bounds are the same as with a path made again. Docs: docs/target-app-parity.md. --- crates/render/src/kept_paths.rs | 487 ++++++++++++++++++++++------ crates/render/src/tests/keptpath.rs | 202 +++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 579 insertions(+), 111 deletions(-) diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index 4525a0f1c3..dc48d3cafb 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -1,25 +1,39 @@ //! The paths of long paths and compound paths kept by object id, with the boxes of their segments //! and of their miter tips by runs of segments. When an object's anchors move, the renderer changes -//! only the path elements, boxes and tips of the segments that start or end at a moved anchor, -//! instead of making its path again and measuring it whole. +//! only the path elements, boxes and tips of the segments that start or end at a moved anchor. +//! When anchors are added or deleted, or a subpath is closed or opened, it replaces only the path +//! elements of the segments between the first and the last anchor that changed, and measures again +//! only the runs that hold them. When a compound path gains or loses members, or a member gains or +//! loses subpaths, it makes the path of those members again. In each case it does not make the +//! object's path again or measure it whole. use std::sync::Arc; use vectorcraft_doc::{LineJoin, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::bez::has_length; use vectorcraft_geom::path::segment_bounds; -use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Rect, SubPath}; +use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Point, Rect, SubPath}; /// Paths and compound paths with at least this many anchors are kept ([`KeptPath`]). pub(crate) const KEPT_ANCHORS: usize = 1024; -/// Segments measured together into one box. -const RUN: usize = 128; +/// Segments measured together into one box in a subpath measured whole. A run that anchors were +/// added to or deleted from holds more or fewer, and one that grows past twice this is split. +pub(crate) const RUN: usize = 128; + +/// The most subpaths one edit may add anchors to, delete anchors from, close or open: past this, +/// the kept path is made again whole. +const SPLICES: usize = 16; /// The boxes and the miter tips' boxes of a subpath's runs ([`KeptPath::runs`]). #[cfg(test)] pub(crate) type RunBoxes = (Vec>, Vec>); +/// A subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each of its +/// runs ([`KeptPath::layout`]). +#[cfg(test)] +pub(crate) type Layout = ((usize, usize, usize, bool), Vec); + /// A subpath of a kept path. struct Sub { /// Where its MoveTo is in the path's elements. @@ -28,7 +42,9 @@ struct Sub { segs: usize, anchors: usize, closed: bool, - /// The box of each run of [`RUN`] segments ([`segment_bounds`]). + /// The segment after the last of each run of segments. + ends: Vec, + /// The box of each run of segments ([`segment_bounds`]). boxes: Vec>, /// The box of the miter tips of `tips_of` at the joints whose first segment is in each run. tips: Vec>, @@ -72,8 +88,14 @@ pub(crate) fn kept(n: &Node) -> bool { /// Whether anchors `a` and `b` have the same points, bit for bit. fn same(a: &Anchor, b: &Anchor) -> bool { - let bits = |a: &Anchor| [a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits); - bits(a) == bits(b) + same_drawn(a, b, true, true) +} + +/// Whether anchors `a` and `b` have the same point, bit for bit, and the same incoming handle when +/// `h_in` and outgoing handle when `h_out`. +fn same_drawn(a: &Anchor, b: &Anchor, h_in: bool, h_out: bool) -> bool { + let bits = |p: Point| [p.x, p.y].map(f64::to_bits); + bits(a.p) == bits(b.p) && (!h_in || bits(a.h_in) == bits(b.h_in)) && (!h_out || bits(a.h_out) == bits(b.h_out)) } /// The path element of segment `i` of `sp`, as [`SubPath::to_bezpath_into`] writes it. @@ -82,15 +104,62 @@ fn element(sp: &SubPath, i: usize) -> PathEl { if sp.segment_is_line(i) { PathEl::LineTo(c.p3) } else { PathEl::CurveTo(c.p1, c.p2, c.p3) } } +/// Element `o` of the elements [`SubPath::to_bezpath_into`] writes for `sp`, a subpath with +/// anchors: its MoveTo, then its segments, then its ClosePath. +fn element_at(sp: &SubPath, o: usize) -> PathEl { + match o { + 0 => PathEl::MoveTo(sp.anchors.first().map_or(Point::ORIGIN, |a| a.p)), + o if o <= sp.segment_count() => element(sp, o - 1), + _ => PathEl::ClosePath, + } +} + /// The point a path element ends at (`None` for a ClosePath). -fn end(el: &PathEl) -> Option { +fn end(el: &PathEl) -> Option { match *el { PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), PathEl::ClosePath => None, } } +/// The ends of the runs of a subpath of `segs` segments measured whole: [`RUN`] segments each. +fn whole_runs(segs: usize) -> Vec { + (1..=segs.div_ceil(RUN)).map(|r| (r * RUN).min(segs)).collect() +} + +/// The paths `ps` written over the `len` elements at `at` in `els`, and their subpaths measured +/// whole with the tips of `st`. `at` moves past them. +fn made_again(ps: &[&PathData], len: usize, els: &mut Vec, at: &mut usize, st: Option<&StrokeLayer>) -> Vec> { + let mut bp = BezPath::new(); + ps.iter().flat_map(|p| &p.subpaths).for_each(|sp| sp.to_bezpath_into(&mut bp)); + let to = (*at + len).min(els.len()); + els.splice((*at).min(to)..to, bp.into_elements()); + let mut measure = |sp: &SubPath| { + let sub = Sub::measured(sp, *at, els, st); + *at += sub.len(); + sub + }; + ps.iter().map(|p| p.subpaths.iter().map(&mut measure).collect()).collect() +} + impl Sub { + /// Subpath `sp`, its MoveTo at `start` in `els`, measured whole, with the tips of `st`. + fn measured(sp: &SubPath, start: usize, els: &[PathEl], st: Option<&StrokeLayer>) -> Self { + let segs = sp.segment_count(); + let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, ends: whole_runs(segs), boxes: vec![], tips: vec![] }; + sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); + if let Some(st) = st { + sub.tips = (0..sub.runs()).map(|r| sub.run_tips(els, r, st)).collect(); + } + sub + } + + /// Its elements in the path: none without anchors, otherwise its MoveTo, its segments and + /// its ClosePath when closed. + fn len(&self) -> usize { + if self.anchors == 0 { 0 } else { 1 + self.segs + usize::from(self.closed) } + } + /// Segment `i`, as kurbo's `segments` makes it from the path's elements. fn seg(&self, els: &[PathEl], i: usize) -> Option { let p0 = end(els.get(self.start + i)?)?; @@ -103,12 +172,23 @@ impl Sub { } fn runs(&self) -> usize { - self.segs.div_ceil(RUN) + self.ends.len() + } + + /// The segments of run `r`. + fn range(&self, r: usize) -> std::ops::Range { + let from = r.checked_sub(1).and_then(|p| self.ends.get(p)).copied().unwrap_or(0); + from..self.ends.get(r).copied().unwrap_or(from) + } + + /// The run that holds segment `i` (the last run for a segment past the end). + fn run_of(&self, i: usize) -> usize { + self.ends.partition_point(|&e| e <= i).min(self.runs().saturating_sub(1)) } /// The box of the segments of run `r`. fn run_box(&self, els: &[PathEl], r: usize) -> Option { - (r * RUN..((r + 1) * RUN).min(self.segs)).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) + self.range(r).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) } /// The segment with length that follows segment `i` (round to the start when closed), or @@ -140,7 +220,7 @@ impl Sub { /// ([`StrokeLayer::miter_tip`]). fn run_tips(&self, els: &[PathEl], r: usize, st: &StrokeLayer) -> Option { let mut out: Option = None; - for i in r * RUN..((r + 1) * RUN).min(self.segs) { + for i in self.range(r) { let Some(a) = self.seg(els, i).filter(has_length) else { continue }; let Some(b) = self.next_drawn(els, i) else { continue }; if let Some(tip) = st.miter_tip(self.closed, &a, &b) { @@ -149,6 +229,200 @@ impl Sub { } out } + + /// Bring the subpath, its MoveTo now at `at` in `els`, up to date from `was` to `now`, with the + /// tips of `st`. + fn update(&mut self, was: &SubPath, now: &SubPath, at: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + self.start = at; + if was.anchors.len() == now.anchors.len() && was.closed == now.closed { + self.moved(was, now, els, st); + } else if was.anchors.len() < 2 || now.anchors.len() < 2 { + let to = (at + self.len()).min(els.len()); + let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; + els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); + *self = Sub::measured(now, at, els, st); + } else { + self.spliced(was, now, els, st); + } + } + + /// [`Self::update`] for a subpath with the same anchor count and closed state: the elements of + /// the segments that start or end at an anchor that moved are made again, with the boxes of + /// their runs and the tips of those runs and of the runs of the segments with length before + /// them. + fn moved(&mut self, was: &SubPath, now: &SubPath, els: &mut [PathEl], st: Option<&StrokeLayer>) { + let (mut first, mut segs) = (false, vec![]); + for (k, (a, b)) in was.anchors.iter().zip(&now.anchors).enumerate() { + if same(a, b) { + continue; + } + if k >= 1 && k - 1 < self.segs { + segs.push(k - 1); + } + if k == 0 { + first = true; + if self.closed && self.segs > 0 { + segs.push(self.segs - 1); + } + } + if k < self.segs { + segs.push(k); + } + } + if !first && segs.is_empty() { + return; + } + segs.sort_unstable(); + segs.dedup(); + if first && let (Some(a), Some(el)) = (now.anchors.first(), els.get_mut(self.start)) { + *el = PathEl::MoveTo(a.p); + } + for &i in &segs { + if let Some(el) = els.get_mut(self.start + 1 + i) { + *el = element(now, i); + } + } + let els: &[PathEl] = els; + // Many moved: the subpath is measured again whole. + let all = segs.len() * 4 > self.segs; + let mut boxes: Vec = if all { (0..self.runs()).collect() } else { segs.iter().map(|&i| self.run_of(i)).collect() }; + boxes.dedup(); + for r in boxes { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return }; + // A joint's tip changes with its segments and with which segment with length comes next: + // the runs of the moved segments and of the segments with length before them. + let mut runs = vec![]; + let mut whole = all; + for &i in &segs { + runs.push(self.run_of(i)); + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + } + + /// [`Self::update`] for a subpath of at least two anchors before and after that gained or lost + /// anchors or was closed or opened. Its elements from the first anchor that changed to the + /// last are written again, and the closing segment and the ClosePath when the first or last + /// anchor changed or it was closed or opened; the elements before and after stay. The runs + /// that held the segments written are measured again, with the tips of the runs of the + /// segments with length before them. + fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>) { + let (n0, n1) = (was.anchors.len(), now.anchors.len()); + let least = n0.min(n1); + // On a subpath open before and after, the handle before the first anchor and the one after + // the last draw nothing. + let open = !was.closed && !now.closed; + let a = was.anchors.iter().zip(&now.anchors).enumerate().take_while(|(i, (x, y))| same_drawn(x, y, !open || *i > 0, true)).count().min(least); + let b = was + .anchors + .iter() + .rev() + .zip(now.anchors.iter().rev()) + .take(least - a) + .enumerate() + .take_while(|(i, (x, y))| same_drawn(x, y, true, !open || *i > 0)) + .count(); + let (s0, s1) = (self.segs, now.segment_count()); + let (c0, c1) = (self.closed, now.closed); + let (len0, len1) = (1 + s0 + usize::from(c0), 1 + s1 + usize::from(c1)); + // Elements `a..mid` change: the MoveTo when the first anchor changed and the segments up + // to the first of those between the last `b` anchors. + let (mid0, mid1) = ((1 + n0 - b).min(1 + s0), (1 + n1 - b).min(1 + s1)); + // Elements `tail..len` follow the segments between the last `b` anchors: the closing + // segment and the ClosePath. They stay when the anchors either side of the closing segment + // stayed and the subpath was neither closed nor opened. + let (tail0, tail1) = if b >= 1 { (n0, n1) } else { (mid0, mid1) }; + let keep_tail = c0 == c1 && (!c1 || b == 0 || a >= 1); + let at = self.start; + let mut stale = vec![false; self.runs()]; + let tips = st.is_some(); + if !keep_tail { + let to = (at + len0).min(els.len()); + els.splice((at + tail0).min(to)..to, (tail1..len1).map(|o| element_at(now, o))); + let (lo, old, new) = (tail0 - 1, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1)); + self.resize(lo, old, new, &mut stale, tips); + } + let to = (at + mid0).min(els.len()); + els.splice((at + a).min(to)..to, (a..mid1).map(|o| element_at(now, o))); + let lo = a.max(1) - 1; + self.resize(lo, mid0 - 1 - lo, mid1 - 1 - lo, &mut stale, tips); + self.anchors = n1; + self.closed = c1; + let els: &[PathEl] = els; + for (r, _) in stale.iter().enumerate().filter(|(_, s)| **s) { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return }; + let mut runs: Vec = stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r).collect(); + // Closed or opened: the tips of every joint change when the stroke reaches farther from one + // than from the other. + let mut whole = c0 != c1 && st.side_reach(c0).to_bits() != st.side_reach(c1).to_bits(); + for i in [lo].into_iter().chain((!keep_tail).then_some(tail1 - 1)) { + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + } + + /// Replace the `old` segments from segment `lo` with `new` segments in the runs: the runs that + /// held them become one run, split into runs of [`RUN`] segments when longer than twice that, + /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. + fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) { + if old == 0 && new == 0 { + return; + } + let (r0, r1, first, last) = match self.runs() { + 0 => (0, 0, 0, new), + _ => { + let r0 = self.run_of(lo); + let r1 = if old == 0 { r0 } else { self.run_of(lo + old - 1) }; + let last = self.ends.get(r1).copied().unwrap_or(lo + old) + new - old; + (r0, r1 + 1, self.range(r0).start, last) + } + }; + let len = last - first; + let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; + for e in self.ends.iter_mut().skip(r1) { + *e = *e + new - old; + } + self.ends.splice(r0..r1, (1..=count).map(|j| if j == count { last } else { first + j * RUN })); + self.boxes.splice(r0..r1, std::iter::repeat_n(None, count)); + if tips { + self.tips.splice(r0.min(self.tips.len())..r1.min(self.tips.len()), std::iter::repeat_n(None, count)); + } + stale.splice(r0..r1, std::iter::repeat_n(true, count)); + self.segs = self.segs + new - old; + } + + /// Measure again the tips of `st` in `runs`, or in every run when `whole`. + fn measure_tips(&mut self, els: &[PathEl], mut runs: Vec, whole: bool, st: &StrokeLayer) { + if whole { + runs = (0..self.runs()).collect(); + } + runs.sort_unstable(); + runs.dedup(); + for r in runs { + let t = self.run_tips(els, r, st); + if let Some(slot) = self.tips.get_mut(r) { + *slot = t; + } + } + } } /// What [`KeptPath::tips`] measures `st`'s tips by: its reach from an open and a closed path and @@ -157,6 +431,24 @@ fn tips_key(st: &StrokeLayer) -> [u64; 3] { [st.side_reach(false).to_bits(), st.side_reach(true).to_bits(), st.miter_limit.to_bits()] } +/// Whether the subpaths of `was` and `now` differ: in number, in anchors or in being closed. +fn differs(was: &PathData, now: &PathData) -> bool { + !std::ptr::eq(was, now) + && (was.subpaths.len() != now.subpaths.len() + || was.subpaths.iter().zip(&now.subpaths).any(|(w, p)| { + w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.iter().zip(&p.anchors).any(|(a, b)| !same(a, b)) + })) +} + +/// The subpaths of `was` and `now`, paths with as many subpaths, whose anchors were added or +/// deleted or that were closed or opened. +fn splices(was: &PathData, now: &PathData) -> usize { + if std::ptr::eq(was, now) || was.subpaths.len() != now.subpaths.len() { + return 0; + } + was.subpaths.iter().zip(&now.subpaths).filter(|(w, p)| w.anchors.len() != p.anchors.len() || w.closed != p.closed).count() +} + impl KeptPath { /// The kept path of `n`, or `None` when it has none ([`kept`]). pub(crate) fn new(n: &Arc, stamp: u64) -> Option { @@ -170,12 +462,8 @@ impl KeptPath { for pd in paths(n)? { let mut subs = vec![]; for sp in &pd.subpaths { - let segs = sp.segment_count(); - let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, boxes: vec![], tips: vec![] }; - sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); - if !sp.anchors.is_empty() { - start += 1 + segs + usize::from(sp.closed); - } + let sub = Sub::measured(sp, start, els, None); + start += sub.len(); subs.push(sub); } parts.push(subs); @@ -183,106 +471,79 @@ impl KeptPath { (start == els.len()).then(|| Self { node: n.clone(), path: Arc::new(path), parts, tips_of: None, stamp }) } - /// Bring the path up to date with `n`, a path with the same subpaths and anchor counts as the - /// object it was made from: the elements of the segments that start or end at an anchor that - /// moved are made again, with the boxes of their runs and the tips of those runs and of the - /// runs of the segments with length before them. False, and nothing changed, when `n` has - /// other subpaths, other anchor counts or no kept path. + /// Bring the path up to date with `n`, a later version of the object it was made from. The + /// subpaths whose anchors moved change as [`Sub::moved`] says, and those whose anchors were + /// added or deleted or that were closed or opened as [`Sub::spliced`] says. A member of a + /// compound path that gained or lost subpaths is made again, and so are the members added + /// between the first and the last member that the edit left as they were, when the edit added + /// or removed members. False, and nothing changed, when `n` has no kept path, or when the edit + /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths. False as well + /// when the path written does not end where the subpaths measured end. The renderer makes the + /// path again whole after a false. pub(crate) fn update(&mut self, n: &Arc) -> bool { let old = self.node.clone(); let (Some(was), Some(now)) = (paths(&old), paths(n)) else { return false }; - let shape = - |ps: &[&PathData]| ps.iter().map(|p| p.subpaths.iter().map(|s| (s.anchors.len(), s.closed)).collect::>()).collect::>(); - if !kept(n) || shape(&was) != shape(&now) { + if !kept(n) || self.parts.len() != was.len() || self.parts.iter().zip(&was).any(|(s, p)| s.len() != p.subpaths.len()) { return false; } - // Per subpath whose anchors moved: (member, subpath, whether its first anchor moved, the - // segments that start or end at a moved anchor). - let mut moved: Vec<(usize, usize, bool, Vec)> = vec![]; - for (pi, (w, p)) in was.iter().zip(&now).enumerate() { - if std::ptr::eq(*w, *p) { - continue; - } - for (si, (ws, ps)) in w.subpaths.iter().zip(&p.subpaths).enumerate() { - let Some(sub) = self.parts.get(pi).and_then(|s| s.get(si)) else { return false }; - let (mut first, mut segs) = (false, vec![]); - for (k, (a, b)) in ws.anchors.iter().zip(&ps.anchors).enumerate() { - if same(a, b) { - continue; - } - if k >= 1 && k - 1 < sub.segs { - segs.push(k - 1); - } - if k == 0 { - first = true; - if sub.closed && sub.segs > 0 { - segs.push(sub.segs - 1); - } - } - if k < sub.segs { - segs.push(k); - } - } - if first || !segs.is_empty() { - segs.sort_unstable(); - segs.dedup(); - moved.push((pi, si, first, segs)); - } - } + // The members paired with one of `was`: all when there are as many, otherwise those + // before the first and after the last that is not the same. The others are made again. + let (head, tail) = if was.len() == now.len() { + (was.len(), 0) + } else { + let head = was.iter().zip(&now).take_while(|(w, p)| std::ptr::eq(**w, **p)).count(); + let rest = (was.len() - head).min(now.len() - head); + (head, was.iter().rev().zip(now.iter().rev()).take(rest).take_while(|(w, p)| std::ptr::eq(**w, **p)).count()) + }; + let paired = |i: usize| if i < head { Some(i) } else { (now.len() - i <= tail).then(|| was.len() - (now.len() - i)) }; + let spliced: usize = (0..now.len()).filter_map(|i| paired(i).map(|w| splices(was[w], now[i]))).sum(); + if spliced > SPLICES { + return false; } self.node = n.clone(); - if moved.is_empty() { + // Nothing to change: the path is left as it is, shared or not. + if was.len() == now.len() && was.iter().zip(&now).all(|(w, p)| !differs(w, p)) { return true; } + let st = self.tips_of.clone(); + let st = st.as_ref(); let path = Arc::make_mut(&mut self.path); - let els = path.elements_mut(); - for (pi, si, first, segs) in &moved { - let (Some(sub), Some(sp)) = (self.parts.get(*pi).and_then(|s| s.get(*si)), now.get(*pi).and_then(|p| p.subpaths.get(*si))) else { + let mut els = std::mem::take(path).into_elements(); + let mut old_parts: Vec>> = std::mem::take(&mut self.parts).into_iter().map(Some).collect(); + let mut at = 0; + let mut parts = Vec::with_capacity(now.len()); + for (i, p) in now.iter().enumerate() { + if i == head { + // The members of `was` that are not paired give way to those of `now`. + let gone: usize = old_parts[head..was.len() - tail].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(&now[head..now.len() - tail], gone, &mut els, &mut at, st)); + } + let Some(w) = paired(i) else { continue }; + let Some(mut subs) = old_parts.get_mut(w).and_then(Option::take) else { continue }; + if was[w].subpaths.len() != p.subpaths.len() { + let len = subs.iter().map(Sub::len).sum(); + parts.extend(made_again(&[*p], len, &mut els, &mut at, st)); continue; - }; - if *first && let (Some(a), Some(el)) = (sp.anchors.first(), els.get_mut(sub.start)) { - *el = PathEl::MoveTo(a.p); } - for &i in segs { - if let Some(el) = els.get_mut(sub.start + 1 + i) { - *el = element(sp, i); + let moved = !std::ptr::eq(was[w], *p); + for (sub, (ws, ps)) in subs.iter_mut().zip(was[w].subpaths.iter().zip(&p.subpaths)) { + if moved { + sub.update(ws, ps, at, &mut els, st); } + sub.start = at; + at += sub.len(); } + parts.push(subs); } - let els = path.elements(); - for (pi, si, _, segs) in moved { - let tips_of = self.tips_of.as_ref(); - let Some(sub) = self.parts.get_mut(pi).and_then(|s| s.get_mut(si)) else { continue }; - // Many moved: the subpath is measured again whole. - let all = segs.len() * 4 > sub.segs; - let mut boxes: Vec = if all { (0..sub.runs()).collect() } else { segs.iter().map(|i| i / RUN).collect() }; - boxes.dedup(); - for r in boxes { - sub.boxes[r] = sub.run_box(els, r); - } - let Some(st) = tips_of else { continue }; - // A joint's tip changes with its segments and with which segment with length comes - // next: the runs of the moved segments and of the segments with length before them. - let mut runs = vec![]; - let mut whole = all; - for &i in &segs { - runs.push(i / RUN); - match sub.prev_drawn(els, i) { - Ok(Some(j)) => runs.push(j / RUN), - Ok(None) => {} - Err(()) => whole = true, - } - } - if whole { - runs = (0..sub.runs()).collect(); - } - runs.sort_unstable(); - runs.dedup(); - for r in runs { - sub.tips[r] = sub.run_tips(els, r, st); - } + if head == now.len() && head < was.len() { + // Members were removed from the end. + let gone: usize = old_parts[head..].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(&[], gone, &mut els, &mut at, st)); } - true + let made = at == els.len(); + *path = BezPath::from_vec(els); + self.parts = parts; + made } /// The object's geometric bounds ([`Node::geometric_bounds`]): each path's as @@ -318,9 +579,25 @@ impl KeptPath { self.parts.iter().flatten().flat_map(|s| s.tips.iter().flatten()).copied().reduce(|a, b| a.union(b)) } - /// The boxes and tips kept per run of each subpath, and the stroke the tips were measured for. + /// Each subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each + /// of its runs. #[cfg(test)] - pub(crate) fn runs(&self) -> (Vec, Option) { - (self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(), self.tips_of.clone()) + pub(crate) fn layout(&self) -> Vec { + let runs = |s: &Sub| (0..s.runs()).map(|r| s.range(r).len()).collect(); + self.parts.iter().flatten().map(|s| ((s.start, s.segs, s.anchors, s.closed), runs(s))).collect() + } + + /// The boxes and tips kept per run of each subpath, the same measured again from the path + /// over the same runs, and the stroke the tips were measured for. + #[cfg(test)] + pub(crate) fn runs(&self) -> (Vec, Vec, Option) { + let els = self.path.elements(); + let kept = self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(); + let again = self.parts.iter().flatten().map(|s| { + let boxes = (0..s.runs()).map(|r| s.run_box(els, r)).collect(); + let tips = self.tips_of.as_ref().map_or(vec![], |st| (0..s.runs()).map(|r| s.run_tips(els, r, st)).collect()); + (boxes, tips) + }); + (kept, again.collect(), self.tips_of.clone()) } } diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index 94c5621b97..3ec7fee229 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -71,19 +71,43 @@ fn check(r: &mut Renderer, d: &Document, id: NodeId, what: &str) { } let k = r.kept.get(&id).unwrap_or_else(|| panic!("{what}: its path kept")); assert!(std::ptr::eq(Arc::as_ptr(&k.node), n), "{what}: its path kept"); - // The boxes and miter tips kept, run by run, are those of the path measured whole. - let (runs, tips_of) = k.runs(); - let mut whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); - if let Some(st) = &tips_of { - whole.tips(st); + // The subpaths kept are those of the path measured whole, each run holds from one segment to + // twice the segments of a run, and the boxes and miter tips kept, run by run, are those + // measured again from the path. + let whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); + let (layout, fresh) = (k.layout(), whole.layout()); + assert!(layout.iter().map(|l| l.0).eq(fresh.iter().map(|l| l.0)), "{what}: the same subpaths as the path measured whole"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&fresh) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); +} + +/// Check `d` as [`check`] does, then the document before the edit (undone) and `d` again (redone). +fn check_undo(r: &mut Renderer, before: &Document, d: &Document, id: NodeId, what: &str) { + check(r, d, id, what); + check(r, before, id, &format!("{what}, undone")); + check(r, d, id, &format!("{what}, redone")); +} + +/// The members of compound path `id` of `d`. +fn members(d: &mut Document, id: NodeId) -> &mut Vec> { + match d.node_mut(id).map(|n| &mut n.kind) { + Some(NodeKind::Compound { children, .. }) => children, + _ => panic!("a compound path"), } - assert!(runs == whole.runs().0, "{what}: the same boxes and tips as the path measured whole"); } fn path_of(d: &mut Document, id: NodeId) -> &mut PathData { d.node_mut(id).and_then(|n| n.path_data_mut()).unwrap() } +fn corner(x: f64, y: f64) -> Anchor { + Anchor::corner(Point::new(x, y)) +} + fn moved(a: &mut Anchor, by: Vec2) { *a = a.transform(Affine::translate(by)); } @@ -194,6 +218,172 @@ fn edits_in_runs_of_segments_without_length_measure_as_when_the_path_is_made_aga } } +#[test] +fn a_long_path_draws_and_culls_after_anchors_are_added_or_deleted_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let path = PathData::new(vec![ + zigzag(3000, 0.0), + ring(1200, Point::new(12_000.0, 15.0), 45.0), + SubPath::new(vec![Anchor::corner(Point::new(11_990.0, 20.0))], false), + SubPath::new(vec![], false), + SubPath::new(vec![Anchor::corner(Point::new(11_995.0, 0.0)), Anchor::corner(Point::new(12_005.0, 30.0))], false), + ]); + let n = Node::path(d.alloc_id(), path, look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt), stroke(14.0, LineJoin::Round, LineCap::Round)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 28] = [ + // Anchor 1,152, a corner at (9,032, 30), ends the segments of the first nine runs: the + // joint there is in the run before. + ("an anchor added where a run of segments starts", |p| p.subpaths[0].anchors.insert(1153, corner(9_036.0, -30.0))), + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1520, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1521)), + ("an anchor added at the start", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 30.0))), + ("an anchor added at the end", |p| p.subpaths[0].anchors.push(corner(24_100.0, 0.0))), + ("the first anchor deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("an anchor added onto the one before it", |p| { + let a = p.subpaths[0].anchors[1499]; + p.subpaths[0].anchors.insert(1500, Anchor::corner(a.p)); + }), + ("300 anchors deleted", |p| _ = p.subpaths[0].anchors.drain(1100..1400)), + ("400 anchors added", |p| { + let at: Vec = (0..400).map(|i| corner(8_800.0 + f64::from(i) * 0.5, if i % 2 == 0 { -20.0 } else { 50.0 })).collect(); + p.subpaths[0].anchors.splice(1100..1100, at); + }), + ("anchors moved and others deleted", |p| { + p.subpaths[0].anchors[10] = corner(80.0, -40.0); + p.subpaths[0].anchors.drain(2000..2010); + }), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ("an anchor added at the start of the closed subpath", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 60.0))), + ("an anchor added after the first of the closed subpath", |p| p.subpaths[0].anchors.insert(1, corner(-20.0, -30.0))), + ("an anchor added at the end of the closed subpath", |p| p.subpaths[0].anchors.push(corner(24_000.0, 60.0))), + ("the first anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("the subpath opened", |p| p.subpaths[0].closed = false), + ("an anchor of the ring added in the view", |p| p.subpaths[1].anchors.insert(300, corner(12_010.0, 10.0))), + ("an anchor of the ring deleted", |p| _ = p.subpaths[1].anchors.remove(600)), + ("the ring opened", |p| p.subpaths[1].closed = false), + ("the ring closed", |p| p.subpaths[1].closed = true), + ("the one-anchor subpath given a second anchor", |p| p.subpaths[2].anchors.push(corner(12_000.0, 40.0))), + ("the second anchor deleted again", |p| _ = p.subpaths[2].anchors.pop()), + ("the one-anchor subpath emptied", |p| p.subpaths[2].anchors.clear()), + ("the empty subpath given an anchor", |p| p.subpaths[3].anchors.push(corner(12_015.0, 5.0))), + ("the two-anchor subpath closed", |p| p.subpaths[4].closed = true), + ("an anchor deleted from the two-anchor subpath", |p| _ = p.subpaths[4].anchors.remove(0)), + ]; + for (what, edit) in edits { + let before = d.clone(); + edit(path_of(&mut d, id)); + check_undo(&mut r, &before, &d, id, what); + } +} + +#[test] +fn a_long_compound_path_draws_and_culls_after_members_are_added_or_removed_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let none = Appearance::default(); + let member = |d: &mut Document, p: PathData| Arc::new(Node::path(d.alloc_id(), p, none.clone())); + let children = vec![ + member(&mut d, PathData::single(zigzag(1500, 6000.0))), + member(&mut d, PathData::single(ring(1500, Point::new(12_000.0, 15.0), 45.0))), + member(&mut d, PathData::single(SubPath::new(vec![Anchor::corner(Point::new(11_980.0, 0.0))], false))), + ]; + let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![stroke(4.0, LineJoin::Miter, LineCap::Square)]).into(); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + let edits: [(&str, PathData, usize); 4] = [ + ("a member added at the end", PathData::single(ring(40, Point::new(12_010.0, 20.0), 8.0)), 3), + ("a member added at the start", PathData::single(zigzag(30, 11_950.0)), 0), + ("a member added between", PathData::new(vec![]), 2), + ("a member of two subpaths added between", PathData::new(vec![ring(5, Point::new(11_990.0, 25.0), 4.0), zigzag(3, 11_970.0)]), 1), + ]; + for (what, p, at) in edits { + let before = d.clone(); + let m = member(&mut d, p); + members(&mut d, id).insert(at, m); + check_undo(&mut r, &before, &d, id, what); + } + // Seven members: the first, the last, then the third removed. + for (what, at) in [("the first member removed", 0), ("the last member removed", 5), ("a member removed between", 2)] { + let before = d.clone(); + members(&mut d, id).remove(at); + check_undo(&mut r, &before, &d, id, what); + } + // Left: the member of two subpaths, the zigzag, the ring and the one-anchor member. + let ids: Vec = members(&mut d, id).iter().map(|m| m.id).collect(); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths.push(SubPath::new(vec![corner(12_020.0, 30.0)], false)); + check_undo(&mut r, &before, &d, id, "a subpath added to a member"); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths[0].anchors.insert(10, corner(12_000.0, 60.0)); + path_of(&mut d, ids[2]).subpaths[0].anchors.remove(700); + check_undo(&mut r, &before, &d, id, "anchors added and deleted in two members"); +} + +#[test] +fn adding_and_deleting_anchors_of_a_long_path_changes_its_kept_path_in_place() { + let mut d = Document::new(1000.0, 1000.0); + let n = Node::path(d.alloc_id(), PathData::single(zigzag(3000, 0.0)), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let kept = |r: &Renderer| r.kept.get(&id).map(|k| Arc::as_ptr(&k.path) as usize); + let before = kept(&r); + assert!(before.is_some(), "the path is kept"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 3] = [ + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1500, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1700)), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ]; + for (what, edit) in edits { + edit(path_of(&mut d, id)); + check(&mut r, &d, id, what); + assert_eq!(kept(&r), before, "{what}: the kept path changed in place"); + } + // An edit that leaves the anchors as they were leaves the kept path as it is, also while + // something else holds it. + let held = r.kept.get(&id).map(|k| k.path.clone()).unwrap(); + d.node_mut(id).unwrap().appearance = look(vec![stroke(8.0, LineJoin::Miter, LineCap::Butt)]).into(); + check(&mut r, &d, id, "the stroke changed"); + assert!(Arc::ptr_eq(&held, &r.kept.get(&id).unwrap().path), "the stroke changed: the kept path left as it is"); +} + +#[test] +fn deleting_an_anchor_of_an_open_path_and_clearing_the_handles_past_its_ends_measures_one_run_again() { + let mut d = Document::new(1000.0, 1000.0); + let mut sp = zigzag(3000, 0.0); + if let Some(a) = sp.anchors.last_mut() { + a.h_out = a.p + Vec2::new(3.0, 4.0); + } + assert!(sp.anchors[0].has_in(), "the first anchor has a handle before it"); + let n = Node::path(d.alloc_id(), PathData::single(sp), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let runs = |r: &Renderer| r.kept.get(&id).map(|k| k.layout()[0].1.clone()).unwrap(); + let before = runs(&r); + // Anchor 1,500 deleted, and the handles before the first anchor and after the last cleared: + // they draw nothing on an open subpath. + let p = &mut path_of(&mut d, id).subpaths[0]; + p.anchors.remove(1500); + if let Some(a) = p.anchors.first_mut() { + a.h_in = a.p; + } + if let Some(a) = p.anchors.last_mut() { + a.h_out = a.p; + } + check(&mut r, &d, id, "an anchor deleted and the end handles cleared"); + let after = runs(&r); + let changed: Vec = (0..before.len().max(after.len())).filter(|&i| before.get(i) != after.get(i)).collect(); + assert_eq!(changed, vec![1499 / crate::kept_paths::RUN], "only the run that held the anchor changed: {before:?} -> {after:?}"); +} + #[test] fn moving_one_anchor_of_a_long_path_changes_its_kept_path_in_place() { let mut d = Document::new(1000.0, 1000.0); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 27b63a9215..3051202252 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1280,6 +1280,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With more than 10,000 type on a path objects selected, the Selection and Direct Selection tools neither draw nor hit-test the objects' brackets. The renderer outlines the stroke of a path object with more than 1,024 path elements, without dashes or a width profile, only in and around the view, with a margin of the view's size on each side, and outlines it again when the view moves past that margin. The pixels are the same. At 1600 × 1200, the frame after one anchor of an open path of 200,000 anchors moves takes 28 to 30 ms instead of 103 ms, and with a closed path of 50,000 anchors 10 ms instead of 30 ms (`cargo run --release -p vectorcraft-engine --example anchor_bench`). The renderer outlines a dashed stroke of such a path the same way, without a width profile, and draws its dashes and dots in the same places as when the whole path is dashed, so the pixels are the same. A pattern too fine to draw is drawn solid, as before, and its stroke is outlined near the view too. At 1600 × 1200, the frame after one anchor moves takes 14 ms instead of 102 ms with a filled closed path of 50,000 anchors and a stroke of 6 pt dashes and 4 pt gaps (`cargo run --release -p vectorcraft-engine --example anchor_bench`, which now includes that document). + When anchors of a path or compound path of 1,024 anchors or more are added or deleted, or a subpath is closed or opened, the next frame writes again only the path elements from the first anchor that changed to the last, and the closing segment when an end anchor changed or the subpath was closed or opened. It measures again only the runs of segments that held them; a run grows or shrinks with the segments added or deleted, and one that grows past 256 segments is split. When a member gains or loses subpaths, the renderer makes the path of that member again. When a compound path gains or loses members, it makes the path of those members and of every member between the first and the last of them again. An edit that adds or deletes anchors in, closes or opens more than 16 subpaths makes the whole path again. The pixels and the cull bounds are the same. The renderer keeps the path of a path or compound path of 1,024 anchors or more by object, with the bounds of its segments and of its miter spikes in runs of 128 segments. When anchors move and the subpaths and anchor counts stay the same, the next frame changes only the segments that start or end at a moved anchor and measures again only the runs that hold them or the segments with length before them, instead of making the whole path again and measuring it whole for culling. The pixels and the cull bounds are the same. On Windows at 1600 × 1200, the frame after one anchor moves takes 8.2 ms instead of 30.1 ms with an open path of 200,000 anchors, 4.3 ms instead of 10.4 ms with a closed path of 50,000 anchors, and 6.6 ms instead of 11.9 ms with the filled closed path of 50,000 anchors and a dashed stroke (medians of five runs of `anchor_bench`). When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 123 ms instead of 403 ms with an open path of 200,000 anchors in view (103 ms with nothing changed), and 13 ms instead of 26 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. When a path object moves without changing shape, the renderer draws its stroke from the outline it made before the move, moved by the same offset. It outlines the stroke again when the path is scaled, rotated or edited, when the stroke changes, and when the move takes the view past the part of a long path it outlined. The pixels are the same. At 1600 × 1200, the frame after a 1 pt nudge takes 128 ms instead of 405 ms with an open path of 200,000 anchors in view (104 ms with nothing changed), and 14 ms instead of 28 ms with a closed path of 50,000 anchors whose stroke is dashed and has a width profile. From e3d30a704798a5cbde6575834137f919b1cfab6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:55:03 -0800 Subject: [PATCH 004/105] Render: kept-path splices check their arithmetic and make the subpath again on a mismatch The index arithmetic in `Sub::spliced`, `Sub::resize` and `KeptPath::update` uses `checked_sub` and `checked_add` instead of plain subtraction. When the segments or runs kept for a subpath do not fit its anchors before the edit, `resize` returns `None` without changing anything, and `update` writes the subpath's elements again from the new anchors and measures it whole, as it does for a subpath of fewer than two anchors. A compound path whose kept members do not pair with the new ones returns false, and the renderer makes the path again whole. --- crates/render/src/kept_paths.rs | 104 ++++++++++++++++++++++---------- 1 file changed, 72 insertions(+), 32 deletions(-) diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index dc48d3cafb..293e824664 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -237,15 +237,24 @@ impl Sub { if was.anchors.len() == now.anchors.len() && was.closed == now.closed { self.moved(was, now, els, st); } else if was.anchors.len() < 2 || now.anchors.len() < 2 { - let to = (at + self.len()).min(els.len()); - let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; - els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); - *self = Sub::measured(now, at, els, st); + self.remade(now, at, self.len(), els, st); } else { - self.spliced(was, now, els, st); + let mut span = self.len(); + if self.spliced(was, now, els, st, &mut span).is_none() { + self.remade(now, at, span, els, st); + } } } + /// Write the elements of `now` over the `span` elements at `at` in `els` that the subpath holds, + /// and measure it whole with the tips of `st`. + fn remade(&mut self, now: &SubPath, at: usize, span: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + let to = at.saturating_add(span).min(els.len()); + let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; + els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); + *self = Sub::measured(now, at, els, st); + } + /// [`Self::update`] for a subpath with the same anchor count and closed state: the elements of /// the segments that start or end at an anchor that moved are made again, with the boxes of /// their runs and the tips of those runs and of the runs of the segments with length before @@ -314,8 +323,10 @@ impl Sub { /// last are written again, and the closing segment and the ClosePath when the first or last /// anchor changed or it was closed or opened; the elements before and after stay. The runs /// that held the segments written are measured again, with the tips of the runs of the - /// segments with length before them. - fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>) { + /// segments with length before them. `span` is the count of elements the subpath holds in + /// `els`, kept up to date as they are written. `None` when the segments and runs kept do not + /// fit `was`: the caller then makes the subpath again from those `span` elements. + fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>, span: &mut usize) -> Option<()> { let (n0, n1) = (was.anchors.len(), now.anchors.len()); let least = n0.min(n1); // On a subpath open before and after, the handle before the first anchor and the one after @@ -336,25 +347,36 @@ impl Sub { let (len0, len1) = (1 + s0 + usize::from(c0), 1 + s1 + usize::from(c1)); // Elements `a..mid` change: the MoveTo when the first anchor changed and the segments up // to the first of those between the last `b` anchors. - let (mid0, mid1) = ((1 + n0 - b).min(1 + s0), (1 + n1 - b).min(1 + s1)); + let (mid0, mid1) = ((1 + n0.checked_sub(b)?).min(1 + s0), (1 + n1.checked_sub(b)?).min(1 + s1)); // Elements `tail..len` follow the segments between the last `b` anchors: the closing // segment and the ClosePath. They stay when the anchors either side of the closing segment // stayed and the subpath was neither closed nor opened. let (tail0, tail1) = if b >= 1 { (n0, n1) } else { (mid0, mid1) }; let keep_tail = c0 == c1 && (!c1 || b == 0 || a >= 1); + // The `old` segments from segment `lo` become `new` segments, and when the tail is written, + // the segments from the one before it do too. + let lo = a.saturating_sub(1); + let (old, new) = (mid0.checked_sub(1)?.checked_sub(lo)?, mid1.checked_sub(1)?.checked_sub(lo)?); + let tail = match keep_tail { + true => None, + false => Some((tail0.checked_sub(1)?, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1), tail1.checked_sub(1)?)), + }; let at = self.start; let mut stale = vec![false; self.runs()]; let tips = st.is_some(); - if !keep_tail { - let to = (at + len0).min(els.len()); - els.splice((at + tail0).min(to)..to, (tail1..len1).map(|o| element_at(now, o))); - let (lo, old, new) = (tail0 - 1, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1)); - self.resize(lo, old, new, &mut stale, tips); + // Writes elements `e0..e1` of `now` over elements `o0..o1` of the subpath and updates `span`. + let mut write = |els: &mut Vec, (o0, o1): (usize, usize), (e0, e1): (usize, usize)| { + let to = at.saturating_add(o1).min(els.len()); + let from = at.saturating_add(o0).min(to); + els.splice(from..to, (e0..e1).map(|o| element_at(now, o))); + *span = from.saturating_sub(at) + e1.saturating_sub(e0) + at.saturating_add(*span).saturating_sub(to); + }; + if let Some((lo, old, new, _)) = tail { + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (tail0, len0), (tail1, len1)); } - let to = (at + mid0).min(els.len()); - els.splice((at + a).min(to)..to, (a..mid1).map(|o| element_at(now, o))); - let lo = a.max(1) - 1; - self.resize(lo, mid0 - 1 - lo, mid1 - 1 - lo, &mut stale, tips); + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (a, mid0), (a, mid1)); self.anchors = n1; self.closed = c1; let els: &[PathEl] = els; @@ -364,12 +386,12 @@ impl Sub { *slot = b; } } - let Some(st) = st else { return }; + let Some(st) = st else { return Some(()) }; let mut runs: Vec = stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r).collect(); // Closed or opened: the tips of every joint change when the stroke reaches farther from one // than from the other. let mut whole = c0 != c1 && st.side_reach(c0).to_bits() != st.side_reach(c1).to_bits(); - for i in [lo].into_iter().chain((!keep_tail).then_some(tail1 - 1)) { + for i in [lo].into_iter().chain(tail.map(|(.., last)| last)) { match self.prev_drawn(els, i) { Ok(Some(j)) => runs.push(self.run_of(j)), Ok(None) => {} @@ -377,36 +399,43 @@ impl Sub { } } self.measure_tips(els, runs, whole, st); + Some(()) } /// Replace the `old` segments from segment `lo` with `new` segments in the runs: the runs that /// held them become one run, split into runs of [`RUN`] segments when longer than twice that, - /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. - fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) { + /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. `None`, and + /// nothing changed, when the runs kept do not hold those `old` segments. + fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) -> Option<()> { if old == 0 && new == 0 { - return; + return Some(()); } let (r0, r1, first, last) = match self.runs() { 0 => (0, 0, 0, new), _ => { let r0 = self.run_of(lo); let r1 = if old == 0 { r0 } else { self.run_of(lo + old - 1) }; - let last = self.ends.get(r1).copied().unwrap_or(lo + old) + new - old; + let last = self.ends.get(r1).copied().unwrap_or(lo + old).checked_add(new)?.checked_sub(old)?; (r0, r1 + 1, self.range(r0).start, last) } }; - let len = last - first; - let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; - for e in self.ends.iter_mut().skip(r1) { - *e = *e + new - old; + let len = last.checked_sub(first)?; + let segs = self.segs.checked_add(new)?.checked_sub(old)?; + let after: Vec = self.ends.get(r1..)?.iter().map(|&e| e.checked_add(new)?.checked_sub(old)).collect::>()?; + if r1 > self.boxes.len() || r1 > stale.len() { + return None; } + let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; + self.ends.truncate(r1); + self.ends.extend(after); self.ends.splice(r0..r1, (1..=count).map(|j| if j == count { last } else { first + j * RUN })); self.boxes.splice(r0..r1, std::iter::repeat_n(None, count)); if tips { self.tips.splice(r0.min(self.tips.len())..r1.min(self.tips.len()), std::iter::repeat_n(None, count)); } stale.splice(r0..r1, std::iter::repeat_n(true, count)); - self.segs = self.segs + new - old; + self.segs = segs; + Some(()) } /// Measure again the tips of `st` in `runs`, or in every run when `whole`. @@ -477,7 +506,9 @@ impl KeptPath { /// compound path that gained or lost subpaths is made again, and so are the members added /// between the first and the last member that the edit left as they were, when the edit added /// or removed members. False, and nothing changed, when `n` has no kept path, or when the edit - /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths. False as well + /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths, or when the + /// members kept do not pair with those of `n`. A subpath whose segments or runs kept do not fit + /// its anchors before the edit is made again whole ([`Sub::spliced`]). False as well /// when the path written does not end where the subpaths measured end. The renderer makes the /// path again whole after a false. pub(crate) fn update(&mut self, n: &Arc) -> bool { @@ -495,7 +526,15 @@ impl KeptPath { let rest = (was.len() - head).min(now.len() - head); (head, was.iter().rev().zip(now.iter().rev()).take(rest).take_while(|(w, p)| std::ptr::eq(**w, **p)).count()) }; - let paired = |i: usize| if i < head { Some(i) } else { (now.len() - i <= tail).then(|| was.len() - (now.len() - i)) }; + // Where the members that are not paired end in `was` and in `now`. + let (Some(was_end), Some(now_end)) = (was.len().checked_sub(tail), now.len().checked_sub(tail)) else { return false }; + if head > was_end || head > now_end { + return false; + } + let paired = |i: usize| match i < head { + true => Some(i), + false => now.len().checked_sub(i).filter(|&back| back <= tail).and_then(|back| was.len().checked_sub(back)), + }; let spliced: usize = (0..now.len()).filter_map(|i| paired(i).map(|w| splices(was[w], now[i]))).sum(); if spliced > SPLICES { return false; @@ -515,8 +554,9 @@ impl KeptPath { for (i, p) in now.iter().enumerate() { if i == head { // The members of `was` that are not paired give way to those of `now`. - let gone: usize = old_parts[head..was.len() - tail].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); - parts.extend(made_again(&now[head..now.len() - tail], gone, &mut els, &mut at, st)); + let gone: usize = + old_parts.get_mut(head..was_end).into_iter().flatten().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(now.get(head..now_end).unwrap_or_default(), gone, &mut els, &mut at, st)); } let Some(w) = paired(i) else { continue }; let Some(mut subs) = old_parts.get_mut(w).and_then(Option::take) else { continue }; From 924ec6f0d6f4bd7c50c2967651a672a7eb26a078 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:55:04 -0800 Subject: [PATCH 005/105] Tests: random edits of long paths keep what making the path again makes Two seeded tests run 300 random edits each on a long path and a long compound path: anchors added and deleted at the start, middle and end of a subpath and where a run of segments ends, subpaths closed and opened, anchors and handles moved, and in the compound path members added and removed and subpaths added to a member. The subpaths range from 2 anchors to 3,000, open and closed. After each edit the kept path's elements, subpaths, bounds and miter tips equal those of a new `KeptPath`, its runs hold each subpath's segments, and each run's box and tips equal those measured again. --- crates/render/src/tests/keptpath.rs | 180 ++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index 3ec7fee229..a2f8b3ad85 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -384,6 +384,186 @@ fn deleting_an_anchor_of_an_open_path_and_clearing_the_handles_past_its_ends_mea assert_eq!(changed, vec![1499 / crate::kept_paths::RUN], "only the run that held the anchor changed: {before:?} -> {after:?}"); } +/// Numbers from a fixed seed (a linear congruential generator). +struct Seeded(u64); + +impl Seeded { + /// A number below `m` (0 when `m` is 0). + fn below(&mut self, m: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) as usize % m.max(1) + } + + /// A whole number of points from -`r` to `r`. + fn offset(&mut self, r: usize) -> f64 { + self.below(2 * r + 1) as f64 - r as f64 + } + + /// Where in a subpath of `n` anchors to edit: at the start, at the end, where a run of segments + /// ends, or anywhere. + fn at(&mut self, n: usize) -> usize { + match self.below(4) { + 0 => self.below(3).min(n), + 1 => n.saturating_sub(self.below(3)), + 2 => (crate::kept_paths::RUN * (1 + self.below(24)) + self.below(3)).min(n), + _ => self.below(n + 1), + } + } +} + +/// An anchor to add after `before`: on it (a segment without length), a corner near it, or a +/// smooth anchor near it. +fn anchor_after(g: &mut Seeded, before: Point) -> Anchor { + let p = before + Vec2::new(g.offset(20), g.offset(40)); + match g.below(5) { + 0 => Anchor::corner(before), + 1 => Anchor::smooth(p, p + Vec2::new(g.offset(6), g.offset(6))), + _ => Anchor::corner(p), + } +} + +/// Edit `p` at random: anchors added or deleted at the start, middle or end of a subpath, a +/// subpath closed or opened, an anchor or a handle moved, or many anchors moved. Says what it did. +fn random_edit(g: &mut Seeded, p: &mut PathData) -> String { + let s = g.below(p.subpaths.len()); + let Some(sp) = p.subpaths.get_mut(s) else { return "nothing".into() }; + let n = sp.anchors.len(); + match g.below(6) { + 0 | 1 => { + let (at, k) = (g.at(n), 1 + g.below(3)); + for j in 0..k { + let before = sp.anchors.get((at + j).saturating_sub(1)).map_or(Point::new(12_000.0, 15.0), |a| a.p); + let a = anchor_after(g, before); + sp.anchors.insert(at + j, a); + } + format!("{k} anchors added at {at} of subpath {s} of {n}") + } + 2 | 3 if n > 0 => { + let at = g.at(n - 1); + let k = (1 + g.below(3)).min(n - at); + sp.anchors.drain(at..at + k); + format!("{k} anchors deleted at {at} of subpath {s} of {n}") + } + 4 => { + sp.closed = !sp.closed; + format!("subpath {s} of {n} closed: {}", sp.closed) + } + _ if n > 0 => { + let at = g.below(n); + match g.below(3) { + 0 => moved(&mut sp.anchors[at], Vec2::new(g.offset(30), g.offset(30))), + 1 => sp.anchors[at].h_out = sp.anchors[at].p + Vec2::new(g.offset(10), g.offset(10)), + _ => sp.anchors[at..].iter_mut().take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))), + } + format!("anchors moved at {at} of subpath {s} of {n}") + } + _ => "nothing".into(), + } +} + +/// Bring `k` up to date with `n` and check that it holds what [`KeptPath::new`] makes from `n`: +/// the same path elements and subpaths, runs that hold each subpath's segments, the boxes and miter +/// tips of `st` measured again over its runs, and the same bounds and tips in all. +fn same_as_made_again(k: &mut crate::kept_paths::KeptPath, n: &Arc, st: &StrokeLayer, what: &str) { + assert!(k.update(n), "{what}: brought up to date"); + let mut fresh = crate::kept_paths::KeptPath::new(n, 0).unwrap_or_else(|| panic!("{what}: kept")); + assert!(*k.path == *fresh.path, "{what}: the same path elements"); + let (layout, whole) = (k.layout(), fresh.layout()); + assert!(layout.iter().map(|l| l.0).eq(whole.iter().map(|l| l.0)), "{what}: the same subpaths: {layout:?}"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&whole) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); + assert_eq!(k.geometric(), fresh.geometric(), "{what}: the same bounds"); + assert_eq!(k.tips(st), fresh.tips(st), "{what}: the same miter tips"); +} + +#[test] +fn random_edits_of_a_long_path_keep_what_making_its_path_again_makes() { + let st = stroke(6.0, LineJoin::Miter, LineCap::Butt); + let mut g = Seeded(5744); + let closed = |sp: SubPath| SubPath::new(sp.anchors, true); + let path = PathData::new(vec![ + zigzag(2, 11_990.0), + closed(zigzag(3, 12_000.0)), + zigzag(7, 11_960.0), + closed(zigzag(40, 11_800.0)), + ring(300, Point::new(12_000.0, 15.0), 60.0), + zigzag(3000, 0.0), + closed(zigzag(2000, 4000.0)), + ]); + let mut n = Arc::new(Node::path(NodeId(1), path, look(vec![st.clone()]))); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let what = random_edit(&mut g, next.path_data_mut().unwrap()); + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + +#[test] +fn random_edits_of_a_long_compound_path_keep_what_making_its_path_again_makes() { + let st = stroke(4.0, LineJoin::Miter, LineCap::Square); + let mut g = Seeded(1050); + let ids = std::cell::Cell::new(10); + let member = |p: PathData| { + ids.set(ids.get() + 1); + Arc::new(Node::path(NodeId(ids.get()), p, Appearance::default())) + }; + let children = vec![ + member(PathData::new(vec![SubPath::new(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])), + member(PathData::single(zigzag(3000, 0.0))), + member(PathData::single(ring(40, Point::new(12_000.0, 15.0), 30.0))), + member(PathData::single(zigzag(2, 12_020.0))), + ]; + let mut n = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![st.clone()]).into(); + let mut n = Arc::new(n); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let NodeKind::Compound { children, .. } = &mut next.kind else { panic!("a compound path") }; + let what = match g.below(8) { + 0 => { + let at = [0, children.len(), g.below(children.len() + 1)][g.below(3)]; + let size = [1, 2, 4, 30, 200][g.below(5)]; + let mut sp = zigzag(size, 11_900.0 + g.offset(100)); + sp.closed = g.below(2) == 0; + children.insert(at, member(PathData::single(sp))); + format!("a member of {size} anchors added at {at}") + } + // The member of 3,000 anchors stays, so that the path stays kept. + 1 if children.len() > 2 => { + let at = [0, children.len() - 1, g.below(children.len())][g.below(3)]; + if children[at].path_data().is_some_and(|p| p.subpaths.iter().map(|s| s.anchors.len()).sum::() > 1000) { + "nothing".into() + } else { + children.remove(at); + format!("member {at} removed") + } + } + 2 => { + let at = g.below(children.len()); + let m = Arc::make_mut(&mut children[at]).path_data_mut().unwrap(); + m.subpaths.push(zigzag(1 + g.below(4), 12_030.0)); + format!("a subpath added to member {at}") + } + _ => { + let at = g.below(children.len()); + let what = random_edit(&mut g, Arc::make_mut(&mut children[at]).path_data_mut().unwrap()); + format!("member {at}: {what}") + } + }; + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + #[test] fn moving_one_anchor_of_a_long_path_changes_its_kept_path_in_place() { let mut d = Document::new(1000.0, 1000.0); From 19d9843971589ed4ddc966e236efb358f9b3f788 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 23:03:08 -0800 Subject: [PATCH 006/105] Shape Builder: a merge or erase takes the stretch of every coincident line Where two open paths lie along the same stretch, the planar map gave that stretch to one of them only, so a merge or an erase across it left the other path in place there. Every other open path along an edge now has its own piece in `lines_under`, under a closed path's outline or along a line in front. `lines`, `edges` and Live Paint's edges stay one per stretch, and an Alt-click there still takes the piece in front. --- crates/engine/src/tests/build.rs | 33 +++++++++++ crates/pathops/src/planar/map.rs | 66 ++++++++++++---------- crates/pathops/src/planar/shape_builder.rs | 5 +- crates/pathops/src/planar/tests.rs | 25 ++++++++ crates/tools/src/builder/map.rs | 5 +- crates/tools/src/builder/tests.rs | 24 ++++++++ 6 files changed, 123 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c6bd07ecff..b4be82c2ec 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -830,6 +830,39 @@ fn shape_builder_drag_from_a_merged_shape_over_a_line_under_its_edge_makes_one_r assert!(left_half_gone(&s, h)); } +#[test] +fn shape_builder_removes_the_stretch_of_every_line_under_a_merged_edge() { + // Two lines along the same stretch, under the bottom edge of the merged top row: merging the + // row with the cell below takes the stretch between them from both lines. + for erase in [false, true] { + let mut s = session(); + let h1 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let h2 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let v = line(&mut s, (200.0, 100.0), (200.0, 300.0)); + let sq = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + s.edit("t", |d, _| { + for id in [h1, h2, v, sq] { + d.node_mut(id).unwrap().appearance.set_fill(Paint::None); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [h1.0, h2.0, v.0, sq.0]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[150, 150], [250, 150]]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[250, 150], [150, 250]], "erase": erase})).unwrap(); + let d = &s.doc().unwrap().doc; + let left: Vec = d + .children(d.default_layer()) + .into_iter() + .flatten() + .filter(|n| !outline(n).0.is_closed()) + .filter_map(|n| n.geometric_bounds()) + .filter(|b| b.height() < 1e-6 && (b.y0 - 200.0).abs() < 1e-6 && b.x0 < 199.0) + .collect(); + assert!(left.is_empty(), "erase {erase}: {left:?}"); + } +} + #[test] fn shape_builder_alt_deletes_a_region_or_a_line_piece() { let mut s = session(); diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index 3abf7cfeaa..aa853b2469 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -423,8 +423,8 @@ impl Map { } /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) -/// that lie under the outline of a closed path in front of them, whose edges are that closed -/// path's. +/// that lie under another path in front of them, whose edges are that path's: under a closed +/// path's outline, or along an open path in front. pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { let m = map_with(shapes, false, precision)?; let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; @@ -461,61 +461,65 @@ pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Ve }) .collect() }; - let edge_shapes = to_shapes(chains_by(edges, around, |e| Some(e.source))); let is_line = |i: usize| shapes.get(i).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed)); - let under = to_shapes(chains_by(edges, around, |e| if is_line(e.source) { None } else { e.sources.iter().rev().copied().find(|&i| is_line(i)) })); + // An edge is the front-most input's. Every other open path along it has a piece there too. + let edge_shapes = to_shapes(chains_by(edges, around, |e| vec![e.source])); + let under = to_shapes(chains_by(edges, around, |e| e.sources.iter().rev().copied().filter(|&i| i != e.source && is_line(i)).collect())); Some((regions, edge_shapes, under)) } -/// The edges that `key` gives an input, joined into chains through the vertices where only two -/// edges of the same input meet, each with that input. A chain is closed when it comes back round -/// to where it started. -fn chains_by(edges: &[Edge], around: &[Vec], key: impl Fn(&Edge) -> Option) -> Vec<(Vec, bool, usize)> { - let keys: Vec> = edges.iter().map(&key).collect(); - let key_of = |h: usize| keys.get(h / 2).copied().flatten(); - let passes = |v: usize| -> Option<(usize, usize)> { +/// The edges that `keys` gives each input, joined into chains through the vertices where only two +/// edges of the same input meet, each with that input. An edge that several inputs share is in a +/// chain for each of them. A chain is closed when it comes back round to where it started. +fn chains_by(edges: &[Edge], around: &[Vec], keys: impl Fn(&Edge) -> Vec) -> Vec<(Vec, bool, usize)> { + let keys: Vec> = edges.iter().map(&keys).collect(); + // Where input `k` is among the inputs half-edge `h` gives. + let slot = |h: usize, k: usize| keys.get(h / 2).and_then(|ks| ks.iter().position(|&x| x == k)); + let passes = |v: usize, k: usize| -> Option<(usize, usize)> { let list = around.get(v)?; let (&a, &b) = (list.first()?, list.get(1)?); - (list.len() == 2 && key_of(a).is_some() && key_of(a) == key_of(b)).then_some((a, b)) + (list.len() == 2 && slot(a, k).is_some() && slot(b, k).is_some()).then_some((a, b)) }; - // Edges with no input to give are never walked. - let mut used: Vec = keys.iter().map(Option::is_none).collect(); + // Each edge's inputs, and whether its chain for each has been walked. + let mut used: Vec> = keys.iter().map(|ks| vec![false; ks.len()]).collect(); let mut chains: Vec<(Vec, bool, usize)> = Vec::new(); - // A chain from half-edge `h0` up to the next vertex where it doesn't pass straight through. - let walk = |h0: usize, used: &mut Vec| -> Option<(Vec, bool, usize)> { - let source = key_of(h0)?; + // A chain of input `k` from half-edge `h0` up to the next vertex where it doesn't pass straight through. + let walk = |h0: usize, k: usize, used: &mut Vec>| -> Option<(Vec, bool, usize)> { let mut segs = Vec::new(); let mut h = h0; loop { - let u = used.get_mut(h / 2)?; + let u = used.get_mut(h / 2)?.get_mut(slot(h, k)?)?; if *u { - return Some((segs, true, source)); + return Some((segs, true, k)); } *u = true; segs.extend(half_segs(edges, h)); let v = origin(edges, twin(h))?; - let Some((a, b)) = passes(v) else { return Some((segs, origin(edges, h0) == Some(v), source)) }; + let Some((a, b)) = passes(v, k) else { return Some((segs, origin(edges, h0) == Some(v), k)) }; h = if a == twin(h) { b } else { a }; } }; + let unwalked = |used: &[Vec], h: usize, k: usize| slot(h, k).is_some_and(|s| used.get(h / 2).and_then(|u| u.get(s)) == Some(&false)); for v in 0..around.len() { - if passes(v).is_some() { - continue; - } for &h in around.get(v).map(Vec::as_slice).unwrap_or_default() { - if !used.get(h / 2).copied().unwrap_or(true) - && let Some(c) = walk(h, &mut used) - { - chains.push(c); + for &k in keys.get(h / 2).map(Vec::as_slice).unwrap_or_default() { + if passes(v, k).is_none() + && unwalked(&used, h, k) + && let Some(c) = walk(h, k, &mut used) + { + chains.push(c); + } } } } // What's left are closed loops with no junction on them. for e in 0..edges.len() { - if !used.get(e).copied().unwrap_or(true) - && let Some(c) = walk(2 * e, &mut used) - { - chains.push(c); + for &k in keys.get(e).map(Vec::as_slice).unwrap_or_default() { + if unwalked(&used, 2 * e, k) + && let Some(c) = walk(2 * e, k, &mut used) + { + chains.push(c); + } } } chains diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index 290bc270d4..fde156f9b3 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -19,8 +19,9 @@ pub struct BuilderArrangement { /// share one); only when asked for. pub edges: Vec, /// The pieces of the paths with no closed subpath that lie under the outline of a closed path - /// in front of them, keyed by input index. No piece of `lines` covers them; there the edge is - /// the closed path's (in `edges`, when asked for). + /// in front of them, or along another such path in front of them, keyed by input index. No + /// piece of theirs is in `lines`; there the edge is the path's in front (in `edges` when it is + /// a closed path's and they were asked for, else in `lines`). pub lines_under: Vec, } diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index 654d7d5cb7..3cee370df8 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -444,6 +444,31 @@ fn shape_builder_keeps_the_pieces_of_a_line_under_an_outline_in_front() { assert!(shape_builder(&s, true).lines_under.is_empty()); } +#[test] +fn shape_builder_gives_each_coincident_line_its_pieces() { + // Two lines along the same stretch, whose left half lies under the bottom edge of a rectangle + // in front of them: each has its own pieces, under the edge and beyond it. Beyond the edge the + // front line's piece is the edge, and the back line's lies under it. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), rect(0.0, 0.0, 100.0, 50.0, 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + let spans = |pieces: &[Shape], key: u64| { + let mut v: Vec<_> = pieces.iter().filter(|l| l.key == key).filter_map(|l| l.path.bounds().map(|b| (b.x0, b.x1))).collect(); + v.sort_by(|a, b| a.0.total_cmp(&b.0)); + v + }; + assert_eq!(spans(&lines, 1), [(100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 1), [(0.0, 100.0)], "{lines_under:?}"); + assert_eq!(spans(&lines, 0), [], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Without the rectangle, both lines are cut where the line across them crosses. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), line((100.0, 0.0), (100.0, 100.0), 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + assert_eq!(spans(&lines, 1), [(0.0, 100.0), (100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Live Paint's edges stay one per stretch, the front line's. + assert_eq!(live_paint(&s).1.iter().filter(|e| e.key == 0).count(), 0); +} + #[test] fn shape_builder_merges_adjacent_gap_closed_faces_without_keeping_bridges() { let outline = Shape::new( diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index ddcbcb310e..b1ccfa949d 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -81,8 +81,9 @@ impl BuilderMap { }) .collect() }; - // A line keeps its pieces under the outline of a closed path in front of it, so a merge - // or an erase removes them as it does the rest of the line. + // A line keeps its pieces under the outline of a closed path or along a line in front of + // it, so a merge or an erase removes them as it does the rest of the line. The pieces in + // front come first, so a hit where pieces lie on each other takes the one in front. let lines = arr.lines.into_iter().chain(arr.lines_under).collect(); Self { shapes, regions: faces_of(arr.regions), lines: bounded(lines), edges: bounded(arr.edges) } } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 2104609cf7..fc3ed294c3 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -363,6 +363,30 @@ fn shape_builder_keeps_a_line_under_an_edge_in_front_and_alt_click_there_takes_t assert!(matches!(map.hit(Point::new(150.0, 51.0), Some(4.0)), Some(Hit::Line(_)))); } +#[test] +fn shape_builder_alt_click_on_coincident_lines_takes_the_front_one() { + // Two lines from (0, 50) to (200, 50), crossed by a line at x = 100: each keeps its own + // pieces, and a hit where they lie on each other takes the piece of the line in front. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut s = Selection::default(); + let line = |a: (f64, f64), b: (f64, f64)| PathData::new(vec![SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)]); + let paths = [line((0.0, 50.0), (200.0, 50.0)), line((0.0, 50.0), (200.0, 50.0)), line((100.0, 0.0), (100.0, 100.0))]; + for (k, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), k, Node::path(id, path, Appearance::default_art())).unwrap(); + s.add(id); + } + let map = map_of(&d, &s); + for key in [0, 1] { + assert_eq!(map.lines.iter().filter(|(piece, _)| piece.key == key).count(), 2, "line {key}: {:?}", map.lines); + } + for x in [50.0, 150.0] { + let Some(Hit::Line(i)) = map.hit(Point::new(x, 51.0), Some(4.0)) else { panic!("no line hit at {x}") }; + assert_eq!(map.lines.get(i).map(|(piece, _)| piece.key), Some(1), "at {x}"); + } +} + #[test] fn shape_builder_erase_drag_across_an_overlap_narrower_than_twice_the_tolerance_touches_it() { let (d, s) = sliver_rects(); From e9be911c9b8d1f2315126fc7c9fbf26ede529d43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:41:09 -0800 Subject: [PATCH 007/105] MCP: pointer_gesture rejects a backquote that is not a boolean A `backquote` given as a string or a number, on the request or on an event, was read as absent, so `"true"` moved the object's geometry instead of its pattern. `pointer_gesture` and `ui.pointer`, headless and desktop, now answer with an error before any event runs. --- crates/mcp/src/headless.rs | 6 +++--- crates/mcp/src/tests.rs | 28 ++++++++++++++++++++++++++++ crates/mcp/src/tools/dispatch.rs | 6 ++++++ crates/tools/src/input.rs | 16 ++++++++++++++++ crates/ui-egui/src/control.rs | 9 +++++++-- crates/ui-egui/src/control/tests.rs | 23 +++++++++++++++++++++++ docs/mcp.md | 1 + 7 files changed, 84 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 64a7f0ea1f..0a81bb127f 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -181,9 +181,11 @@ impl Headless { fn pointer(&mut self, p: &Value) -> Result { let events = p.get("events").and_then(Value::as_array).ok_or("missing `events`")?; let base: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); + let default = PointerEvent::json_backquote(p, false)?; + let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::, _>>()?; self.ensure_document(); let mut requests = vec![]; - for e in events { + for (e, backquote) in events.iter().zip(held) { let kind = s(e, "kind").unwrap_or(""); let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; if s(e, "space") == Some("screen") { @@ -192,8 +194,6 @@ impl Headless { let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?; let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?; let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base); - let backquote = - e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); let ev = PointerEvent { kind, pos: Point::new(x, y), diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 2e153b62b7..90df3349ec 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1431,6 +1431,34 @@ fn pointer_gesture_forwards_backquote_on_each_event() { assert_eq!(rect["bounds"]["x"], 100.0, "{doc}"); } +/// A `backquote` that is not a boolean is an error, and none of the gesture's events runs. +#[test] +fn pointer_gesture_rejects_a_backquote_that_is_not_a_boolean() { + let mut s = server(); + let made = call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 50, "height": 50, "fill": "#ff0000"})); + let id = serde_json::from_str::(&text_of(&made)).unwrap()["id"].as_u64().unwrap(); + let drag = |top: Option, first: Option| { + let mut down = json!({"kind": "down", "x": 300, "y": 300}); + if let Some(b) = first { + down["backquote"] = b; + } + let mut a = json!({"tool": "rectangle", "events": [down, {"kind": "drag", "x": 350, "y": 350}, {"kind": "up", "x": 350, "y": 350}]}); + if let Some(b) = top { + a["backquote"] = b; + } + a + }; + for (n, args) in [drag(Some(json!("true")), None), drag(None, Some(json!(1)))].into_iter().enumerate() { + let r = call(&mut s, 2 + n as u64, "pointer_gesture", args); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains("`backquote` must be a boolean"), "{r}"); + } + let inspected = call(&mut s, 4, "inspect_document", json!({})); + let doc = serde_json::from_str::(&text_of(&inspected)).unwrap(); + let children = doc["layers"][0]["children"].as_array().unwrap(); + assert_eq!(children.iter().map(|n| n["id"].as_u64()).collect::>(), vec![Some(id)], "{doc}"); +} + /// A Shift-drag marquee reaches agents (#483): `pointer_gesture` with `mods.shift` toggles the /// objects it reaches, so a selected one leaves the selection and an unselected one joins it. #[test] diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 9e3af3dbaa..f9d768eaa5 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -125,6 +125,12 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result f64 { e.get("holdMs").and_then(Value::as_f64).filter(|f| f.is_finite()).map_or(0.0, |ms| ms.clamp(0.0, 60_000.0) / 1000.0) } + /// Whether backquote is held, from the `backquote` of a JSON pointer event or request (control + /// channel, MCP): `default` when the key is absent, an error when it is not a boolean. + pub fn json_backquote(v: &Value, default: bool) -> Result { + v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned())) + } } #[cfg(test)] @@ -119,6 +124,17 @@ mod tests { value["backquote"] = serde_json::json!(true); assert!(serde_json::from_value::(value).unwrap().backquote); } + + #[test] + fn json_backquote_takes_the_default_only_when_absent() { + use serde_json::json; + assert_eq!(PointerEvent::json_backquote(&json!({}), true), Ok(true)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": false}), true), Ok(false)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": true}), false), Ok(true)); + for bad in [json!("true"), json!(1), json!(null)] { + assert!(PointerEvent::json_backquote(&json!({"backquote": bad}), false).is_err(), "{bad}"); + } + } } /// Keys tools care about. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 045ad97328..3734be480b 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -540,7 +540,13 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); let view = app.view_info(); let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v)); - for e in events { + let held = + PointerEvent::json_backquote(p, false).and_then(|d| events.iter().map(|e| PointerEvent::json_backquote(e, d)).collect::, _>>()); + let held = match held { + Ok(held) => held, + Err(e) => return err(e), + }; + for (e, backquote) in events.iter().zip(held) { let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") { "down" => PointerKind::Down, "drag" => PointerKind::Drag, @@ -566,7 +572,6 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe Some(xf) if screen => crate::canvas::pose_on_page(q, &xf), _ => q, }); - let backquote = e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); crate::canvas::dispatch(app, &PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen }, view); let hold = PointerEvent::json_hold(e); if hold > 0.0 { diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index d084d7ee04..e587c0489f 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -293,6 +293,29 @@ fn synthetic_pointer_backquote_keeps_solid_object_in_place() { assert_eq!(xf.as_coeffs()[4], 20.0, "synthetic backquote drag changes pattern paint"); } +/// `ui.pointer` rejects a `backquote` that is not a boolean, given for the request or for any +/// event, before any of the events runs. +#[test] +fn synthetic_pointer_rejects_a_backquote_that_is_not_a_boolean() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(input_request(&mut app, "ui.tool.select", json!({"tool": "selection"}))["ok"], true); + let before = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let down = json!({"kind": "down", "x": 125, "y": 125}); + let drag = json!({"kind": "drag", "x": 145, "y": 125}); + for params in [ + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125}], "backquote": "true"}), + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125, "backquote": 1}]}), + ] { + let r = input_request(&mut app, "ui.pointer", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("`backquote` must be a boolean")), "{r}"); + assert_eq!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(), &before, "{params}"); + } +} + /// `ui.pointer` replies with the key object: a click on one of two selected objects makes it /// the key, and a click on the key again lets it go. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index fcbb492fdc..da1c1658e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -426,6 +426,7 @@ opens the picker through `run_command` with the remote backend. | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | | `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. | | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. `line`: `x1,y1,x2,y2`. | From 2038dc7849f051c2fbae925e4b69e3ab80a9090d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 22:51:22 -0800 Subject: [PATCH 008/105] SVG export: numbers are written from integers, not through the exact float formatter push_num formatted every number with write!("{:.*}"), which runs the exact decimal float formatter, then scanned and trimmed the text. That formatter was about 95% of the time to export a path of 200,000 anchors. At 9 decimals or fewer, push_num now scales the value by 10^decimals and writes the digits of the rounded integer when that rounding is certain: the scaled value is below 2^53 and further from a half than the scaling's rounding error. Ties and larger values still go through the formatter, so the output is the same byte for byte. Exporting one path of 200,000 anchors takes a median of 43.4 ms instead of 167.0 ms, and 20,000 rectangles 81.4 ms instead of 141.4 ms (Windows 11, release build). --- crates/svg/src/lib.rs | 90 +++++++++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 2 files changed, 91 insertions(+) diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ccc154a383..58cb434ed2 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -624,6 +624,49 @@ pub fn xml_escape(s: &str) -> String { o } +/// [`push_num`] through integer arithmetic, for the values it writes the same as the decimal +/// formatter: `decimals` of at most 9, and `v` scaled by 10^`decimals` below 2^53 and further from +/// halfway between two integers than the scaling's rounding error. Returns false, writing nothing, +/// for any other value. +fn push_num_scaled(out: &mut String, v: f64, decimals: u8) -> bool { + const SCALE: [f64; 10] = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + let Some(&scale) = SCALE.get(usize::from(decimals)) else { return false }; + // Each power of ten here is exact, so `x` is within half an ulp (`x * EPSILON / 2`) of |v| × 10^decimals. + let x = v.abs() * scale; + if x.is_nan() || x >= 9.0e15 { + return false; + } + let whole = x.floor(); + let frac = x - whole; + if (frac - 0.5).abs() <= x * f64::EPSILON { + return false; + } + let mut n = whole as u64 + u64::from(frac > 0.5); + let places = usize::from(decimals); + // The digits of `n` from the last one, at least one more than `places` of them. + let mut digits = [0u8; 24]; + let mut len = 0; + for d in digits.iter_mut() { + if n == 0 && len > places { + break; + } + *d = b'0' + (n % 10) as u8; + n /= 10; + len += 1; + } + let Some((fraction, int)) = digits.get(..len).and_then(|d| d.split_at_checked(places)) else { return false }; + let zeros = fraction.iter().take_while(|&&d| d == b'0').count(); + if v < 0.0 && (zeros < places || int.iter().any(|&d| d != b'0')) { + out.push('-'); + } + out.extend(int.iter().rev().map(|&d| char::from(d))); + if zeros < places { + out.push('.'); + out.extend(fraction.iter().skip(zeros).rev().map(|&d| char::from(d))); + } + true +} + /// Format a number with at most `decimals` places, trimming trailing zeros. pub fn fmt_num(v: f64, decimals: u8) -> String { let mut s = String::new(); @@ -635,6 +678,9 @@ pub fn fmt_num(v: f64, decimals: u8) -> String { pub fn push_num(out: &mut String, v: f64, decimals: u8) { use std::fmt::Write as _; let v = if v.is_finite() { v } else { 0.0 }; + if push_num_scaled(out, v, decimals) { + return; + } let start = out.len(); let _ = write!(out, "{:.*}", decimals as usize, v); // writing to a String can't fail let s = out.get(start..).unwrap_or_default(); @@ -674,4 +720,48 @@ mod tests { fn escaping() { assert_eq!(xml_escape("a&\"'"), "a<b>&"'"); } + + /// `v` at `decimals` places by the decimal formatter, trailing zeros trimmed. + fn formatted(v: f64, decimals: u8) -> String { + let s = format!("{:.*}", usize::from(decimals), if v.is_finite() { v } else { 0.0 }); + let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.') } else { &s }; + if matches!(s, "-0" | "") { "0".into() } else { s.into() } + } + + #[test] + fn numbers_match_the_decimal_formatter() { + let mut values = + vec![0.0, -0.0, 0.5, -0.5, 2.5, 0.0005, -0.0005, 1.0005, 0.125, 1e-12, 9.0e15, 4503599627370495.5, 1e20, f64::NAN, f64::INFINITY]; + // Coordinates of every size, and values on and just off the halfway points between written numbers. + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + for _ in 0..20_000 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let unit = (seed >> 11) as f64 / (1u64 << 53) as f64; + let v = (unit - 0.5) * 10f64.powi((seed % 13) as i32 - 3); + let tie = ((v * 1000.0).trunc() + 0.5) / 1000.0; + values.extend([v, tie, f64::from_bits(tie.to_bits() + 1), f64::from_bits(tie.to_bits() - 1)]); + } + for v in values { + for d in 0..=12 { + assert_eq!(fmt_num(v, d), formatted(v, d), "{v:e} at {d} decimals"); + } + } + } + + #[test] + fn coordinates_are_written_through_integers() { + for (v, d, want) in [(123.4567, 3, "123.457"), (-0.25, 3, "-0.25"), (-0.0004, 3, "0"), (1600.0, 3, "1600"), (7.0, 0, "7")] { + let mut s = String::new(); + assert!(push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert_eq!(s, want); + } + // Halfway as stored, too large, or too many places: the decimal formatter writes them. + for (v, d) in [(0.5, 0), (0.125, 2), (1e16, 0), (1.0, 10)] { + let mut s = String::new(); + assert!(!push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert!(s.is_empty()); + } + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3051202252..a1b4194126 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1169,6 +1169,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the `